text stringlengths 14 6.51M |
|---|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit DispatcherImpl;
interface
{$MODE OBJFPC}
uses
DispatcherIntf,
DependencyIntf,
EnvironmentIntf,
ResponseIntf,
ResponseFactoryIntf,
RequestIntf,
RequestFactoryIntf,
RequestHandlerIntf,
RouteHandlerIntf,
RouteMatcherIntf,
MiddlewareChainIntf,
MiddlewareCollectionIntf,
MiddlewareChainFactoryIntf,
MiddlewareCollectionAwareIntf;
type
(*!---------------------------------------------------
* Request dispatcher class having capability dispatch
* request and return response and with middleware support
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------------------*)
TDispatcher = class(TInterfacedObject, IDispatcher, IDependency)
private
routeCollection : IRouteMatcher;
responseFactory : IResponseFactory;
requestFactory : IRequestFactory;
appBeforeMiddlewareList : IMiddlewareCollection;
appAfterMiddlewareList : IMiddlewareCollection;
middlewareChainFactory : IMiddlewareChainFactory;
public
constructor create(
const appBeforeMiddlewares : IMiddlewareCollection;
const appAfterMiddlewares : IMiddlewareCollection;
const chainFactory : IMiddlewareChainFactory;
const routes : IRouteMatcher;
const respFactory : IResponseFactory;
const reqFactory : IRequestFactory
);
destructor destroy(); override;
function dispatchRequest(const env: ICGIEnvironment) : IResponse;
end;
implementation
uses
sysutils,
MiddlewareIntf;
constructor TDispatcher.create(
const appBeforeMiddlewares : IMiddlewareCollection;
const appAfterMiddlewares : IMiddlewareCollection;
const chainFactory : IMiddlewareChainFactory;
const routes : IRouteMatcher;
const respFactory : IResponseFactory;
const reqFactory : IRequestFactory
);
begin
appBeforeMiddlewareList := appBeforeMiddlewares;
appAfterMiddlewareList := appAfterMiddlewares;
middlewareChainFactory := chainFactory;
routeCollection := routes;
responseFactory := respFactory;
requestFactory := reqFactory;
end;
destructor TDispatcher.destroy();
begin
inherited destroy();
appBeforeMiddlewareList := nil;
appAfterMiddlewareList := nil;
middlewareChainFactory := nil;
routeCollection := nil;
responseFactory := nil;
requestFactory := nil;
end;
function TDispatcher.dispatchRequest(const env: ICGIEnvironment) : IResponse;
var routeHandler : IRouteHandler;
method : string;
uriParts : TStringArray;
middlewareChain : IMiddlewareChain;
routeMiddlewares : IMiddlewareCollectionAware;
begin
try
method := env.requestMethod();
//remove any query string parts
uriParts := env.requestUri().split('?');
routeHandler := routeCollection.match(method, uriParts[0]);
routeMiddlewares := routeHandler.getMiddlewares();
middlewareChain := middlewareChainFactory.build(
appBeforeMiddlewareList,
appAfterMiddlewareList,
routeMiddlewares.getBefore(),
routeMiddlewares.getAfter()
);
result := middlewareChain.execute(
requestFactory.build(env),
responseFactory.build(env),
routeHandler
);
finally
routeHandler := nil;
middlewareChain := nil;
routeMiddlewares := nil;
uriParts := nil;
end;
end;
end.
|
{$mode objfpc}
unit List;
interface
type EListEmpty = class
end;
type generic TListNode<_T> = class
_Data: _T;
_Next: TListNode;
_Prev: TListNode;
public
constructor Create( d : _T );
destructor Free;
procedure SetNext( n : TListNode );
procedure SetPrev( p : TListNode );
function GetNext : TListNode;
function GetPrev : TListNode;
procedure SetHead;
procedure SetTail;
function GetData : _T;
end;
type generic TConstIterator<_T> = class
type TNode = specialize TListNode<_T>;
private
_currentNode : TNode;
_position : integer;
public
constructor CreateFromNode( n : TNode );
function HasNext : boolean;
function GetNext : _T;
function Peek : _T;
function StepBack : boolean;
function GetPosition : integer;
end;
type generic TList<_T> = class
type TNode = specialize TListNode<_T>;
type TCIterator = specialize TConstIterator<_T>;
private
_Head: TNode;
_Tail: TNode;
_Count: integer;
public
constructor Create;
destructor Free;
procedure PushBack ( Item : _T );
procedure PushFront( Item : _T );
function PopFront : _T ;
function PopBack : _T ;
function GetCount : integer;
function GetConstIterator : TCIterator;
private
function CreateNode( Item : _T) : TNode;
end;
implementation
constructor TConstIterator.CreateFromNode( n : TNode );
begin
_currentNode := n;
_position := 1;
end;
function TConstIterator.HasNext : boolean;
begin
// WriteLn('Iterator.HasNext -> ', _currentNode <> nil);
Result := _currentNode <> nil;
end;
function TConstIterator.GetNext : _T;
begin
Result := _currentNode.GetData;
_currentNode := _currentNode.GetNext;
_position := _position + 1;
end;
function TConstIterator.Peek : _T;
begin
Result := _currentNode.GetData;
end;
function TConstIterator.GetPosition : integer;
begin
Result := _position;
end;
function TConstIterator.StepBack : boolean;
begin
if _currentNode.GetPrev <> nil then begin
_currentNode := _currentNode.GetPrev;
_position := _position - 1;
Result := true;
end else begin
Result := false;
end;
end;
constructor TList.Create;
begin
_Count := 0;
_Head := nil;
_Tail := nil;
end;
destructor TList.Free;
var node : TNode;
begin
while _Head <> nil do begin
node := _Head;
_Head := _Head.GetNext;
node.Free;
end
end;
function TList.GetConstIterator : TCIterator;
begin
Result := TCIterator.CreateFromNode( _Head );
end;
function TList.CreateNode( Item : _T ) : TNode;
var node : TNode;
begin
node := TNode.Create ( Item );
Result := node;
end;
procedure TList.PushBack ( Item : _T );
var newNode : TNode;
begin
newNode := CreateNode( Item );
if _Head = nil then begin
_Head := newNode;
_Tail := newNode;
end else begin
_Tail.SetNext( newNode );
_Tail := newNode;
end;
_Count := _Count + 1;
end;
procedure TList.PushFront ( Item : _T );
var newNode : TNode;
begin
newNode := CreateNode( Item );
if _Tail = nil then begin
_Head := newNode;
_Tail := newNode;
end else begin
_Head.SetPrev( newNode );
_Head := newNode;
end;
_Count := _Count + 1;
end;
function TList.PopFront : _T;
var node : TNode;
begin
if _Count = 0 then
raise EListEmpty.Create
else begin
if _Head = _Tail then begin
node := _Head;
_Head := nil;
_Tail := nil;
end else begin
node := _Head;
_Head := _Head.GetNext;
_Head.SetHead;
end;
Result := node.GetData;
_Count := _Count - 1;
node.Free;
end
end;
function TList.PopBack : _T;
var node : TNode;
begin
if _Count = 0 then
raise EListEmpty.Create
else begin
if _Head = _Tail then begin
node := _Head;
_Head := nil;
_Tail := nil;
end else begin
node := _Tail;
_Tail := _Tail.GetPrev;
_Tail.SetTail;
end;
Result := node.GetData;
_Count := _Count - 1;
node.Free;
end
end;
function TList.GetCount : integer;
begin
Result := _Count;
end;
{ * * * * * * * * * * * * * * * * * * * * * }
constructor TListNode.Create ( d : _T );
begin
_Data := d;
_Next := nil;
_Prev := nil;
end;
destructor TListNode.Free;
begin
end;
procedure TListNode.SetNext( n : TListNode );
begin
_Next := n;
n._Prev := self;
end;
procedure TListNode.SetPrev( p : TListNode );
begin
_Prev := p;
p._Next := self;
end;
procedure TListNode.SetHead;
begin
_Prev := nil;
end;
procedure TListNode.SetTail;
begin
_Next := nil;
end;
function TListNode.GetNext : TListNode;
begin
Result := _Next;
end;
function TListNode.GetPrev : TListNode;
begin
Result := _Prev;
end;
function TListNode.GetData : _T;
begin
Result := _Data;
end;
end.
|
unit vr_intfs;
{$mode delphi}{$H+}
{$I vrode.inc}
interface
uses SysUtils, Classes, vr_types{$IFDEF WINDOWS}, windows{$ENDIF};
type
TOsEvent = vr_types.TOSEvent;
ICustomData = interface
['{1B8A37FB-94FF-48D6-80B2-AB2C6E64515B}']
end;
IVariantObject = interface //inherit to work IVariant assignment operator overloading
['{7528DBB4-8E67-4B7C-A1E0-31B687128060}']
end;
IFPObject = interface
['{76937C07-A0E0-41B2-A8BC-DAE634D3FF5D}']
function GetFPObject: TObject;
end;
{ IFPStringBuilder }
IFPStringBuilder = interface
['{D6DA0F34-6A4D-4472-A549-5CF0E11D0E5B}']
function GetCount: Integer;
procedure Add(const S: string); overload;
procedure Add(const AStrings: array of string); overload;
function ToString: string;
procedure Clear;
property Count: Integer read GetCount;
end;
IFPTimer = interface
['{39F38883-F916-4EB6-A126-91012AC8DEB7}']
function GetEnabled: Boolean;
function GetInterval: Cardinal;
function GetOnTimer: TNotifyEvent;
procedure SetEnabled(AValue: Boolean);
procedure SetInterval(AValue: Cardinal);
procedure SetOnTimer(AValue: TNotifyEvent);
property Enabled: Boolean read GetEnabled write SetEnabled;
property Interval: Cardinal read GetInterval write SetInterval;
property OnTimer: TNotifyEvent read GetOnTimer write SetOnTimer;
end;
{ IFPInterfaceList }
IFPInterfaceList = interface(IInterfaceList)
['{03DC6BB5-6F3B-43EA-A6E9-161CE5D7539B}']
function GetFPObject: TObject;
procedure Assign(const AList: IFPInterfaceList);
function AddUnique(const AItem: IUnknown) : Integer;
function ExportToArray: TInterfaceArray;
end;
{ IFPStream }
IFPStream = interface(IFPObject)
['{72C74C0C-F0EB-4786-8A5F-48BC851E9320}']
function GetPosition: Int64;
function GetSize: Int64;
function Read(var Buffer; Count: Longint): Longint;
procedure SetPosition(const AValue: Int64);
procedure SetSize64(const AValue: Int64);
function Write(const Buffer; Count: Longint): Longint;
function Seek(Offset: Longint; Origin: Word): Longint; overload;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload;
procedure ReadBuffer(var Buffer; Count: Longint);
procedure WriteBuffer(const Buffer; Count: Longint);
//function CopyFrom(Source: TStream; Count: Int64): Int64;
//function ReadComponent(Instance: TComponent): TComponent;
//function ReadComponentRes(Instance: TComponent): TComponent;
//procedure WriteComponent(Instance: TComponent);
//procedure WriteComponentRes(const ResName: string; Instance: TComponent);
//procedure WriteDescendent(Instance, Ancestor: TComponent);
//procedure WriteDescendentRes(const ResName: string; Instance, Ancestor: TComponent);
procedure WriteResourceHeader(const ResName: string; {!!!:out} var FixupInfo: Integer);
procedure FixupResourceHeader(FixupInfo: Integer);
procedure ReadResHeader;
function ReadByte : Byte;
function ReadWord : Word;
function ReadDWord : Cardinal;
function ReadQWord : QWord;
function ReadAnsiString : String;
procedure WriteByte(b : Byte);
procedure WriteWord(w : Word);
procedure WriteDWord(d : Cardinal);
procedure WriteQWord(q : QWord);
Procedure WriteAnsiString (const S : String);
property Position: Int64 read GetPosition write SetPosition;
property Size: Int64 read GetSize write SetSize64;
end;
IFPFileStream = interface(IFPStream)
['{C0A60D1F-A92C-4701-828F-56E028A3F656}']
end;
{ IFPStringStream }
IFPStringStream = interface(IFPStream)
['{C0A60D1F-A92C-4701-828F-56E028A3F656}']{$IF FPC_FULLVERSION >= 030200}
function GetUnicodeDataString: UnicodeString;
function GetOwnsEncoding: Boolean;
function GetEncoding: TEncoding;{$ENDIF}
function GetDataString: string;
function ReadString(Count: Longint): string;
procedure WriteString(const AString: string);{$IF FPC_FULLVERSION >= 030200}
function ReadUnicodeString(Count: Longint): UnicodeString;
procedure WriteUnicodeString(const AString: UnicodeString);
property UnicodeDataString: UnicodeString read GetUnicodeDataString;
property OwnsEncoding: Boolean read GetOwnsEncoding;
property Encoding: TEncoding read GetEncoding;
{$ENDIF}
property DataString: string read GetDataString;
end;
IFPStack = interface(IFPObject)
['{E05DAE44-5BCC-41CD-BC07-5691EDE488D0}']
function Count: Integer;
function AtLeast(ACount: Integer): Boolean;
function Push(AItem: Pointer): Pointer;
function Pop: Pointer;
function Peek: Pointer;
end;
{ IFPList }
IFPList = interface(IFPObject)
['{8274F86E-389D-4E6D-80FB-169CB348C253}']
procedure AddList(const AList: IFPList);
function Add(Item: Pointer): Integer;
procedure Clear;
procedure Delete(Index: Integer);
//class procedure Error(const Msg: string; Data: PtrInt); virtual;
procedure Exchange(Index1, Index2: Integer);
//function Expand: TList;
function Extract(item: Pointer): Pointer;
function First: Pointer;
function Get(Index: Integer): Pointer;
function GetCapacity: Integer;
function GetCount: Integer;
//function GetEnumerator: TListEnumerator;
function IndexOf(Item: Pointer): Integer;
procedure Insert(Index: Integer; Item: Pointer);
function Last: Pointer;
procedure Move(CurIndex, NewIndex: Integer);
procedure Put(Index: Integer; AValue: Pointer);
//procedure Assign (ListA: TList; AOperator: TListAssignOp=laCopy; ListB: TList=nil);
function Remove(Item: Pointer): Integer;
procedure Pack;
procedure SetCapacity(AValue: Integer);
procedure SetCount(AValue: Integer);
procedure Sort(Compare: TListSortCompare);
property Capacity: Integer read GetCapacity write SetCapacity;
property Count: Integer read GetCount write SetCount;
property Items[Index: Integer]: Pointer read Get write Put; default;
//property List: PPointerList read GetList;
function AddUnique(AItem: Pointer): Integer;
end;
{ IFPIntegerList }
IFPIntegerList = interface(IFPObject)
['{55B2725F-54F6-4819-A80E-1ACBA9D68BC2}']
//procedure AddList(const AList: IFPIntegerList);
function Add(AItem: PtrInt): Integer;
procedure Clear;
procedure Delete(Index: Integer);
//class procedure Error(const Msg: string; Data: PtrInt); virtual;
procedure Exchange(Index1, Index2: Integer);
//function Expand: TList;
function Extract(AItem: PtrInt): Boolean;
function First: PtrInt;
function GetCapacity: Integer;
function GetCommaText: string;
function GetCount: Integer;
function GetItem(Index: Integer): PtrInt;
//function GetEnumerator: TListEnumerator;
function IndexOf(const Item: PtrInt): Integer;
procedure Insert(Index: Integer; Item: PtrInt);
function Last: PtrInt;
procedure Move(CurIndex, NewIndex: Integer);
//procedure Assign (ListA: TList; AOperator: TListAssignOp=laCopy; ListB: TList=nil);
function Remove(Item: PtrInt): Integer;
procedure Pack;
procedure SetCapacity(AValue: Integer);
procedure SetCommaText(const AValue: string);
procedure SetCount(AValue: Integer);
procedure SetItem(Index: Integer; const AValue: PtrInt);
procedure Sort;//(Compare: TListSortCompare);
function LoadFromIntegerArray(const arr: TIntArray): Boolean;
procedure SaveToIntegerArray(var arr: TIntArray);
property Capacity: Integer read GetCapacity write SetCapacity;
property Count: Integer read GetCount write SetCount;
property Items[Index: Integer]: PtrInt read GetItem write SetItem; default;
//property List: PPointerList read GetList;
property CommaText: string read GetCommaText write SetCommaText;
end;
IGenList<T> = interface(IFPObject)
function GetCapacity: Integer;
function GetFirst: T;
function GetLast: T;
procedure SetCapacity(AValue: Integer);
procedure SetFirst(const AValue: T);
procedure SetLast(const AValue: T);
function Add(const AItem: T): Integer;
procedure Clear;
procedure Delete(Index: Integer);
procedure Exchange(Index1, Index2: Integer);
//function Expand: TList;
function Extract(const Item: T): T;
function IndexOf(const Item: T): Integer;
procedure Insert(Index: Integer; const Item: T);
procedure Move(CurIndex, NewIndex: Integer);
//procedure Assign (ListA: TList; AOperator: TListAssignOp=laCopy; ListB: TList=nil);
function Remove(const Item: T): Integer;
procedure Pack;
property First: T read GetFirst write SetFirst;
property Last: T read GetLast write SetLast;
property Capacity: Integer read GetCapacity write SetCapacity;
end;
IGenThreadList<T> = interface(IGenList<T>)
end;
{ IGenNumberListBase }
IGenNumberListBase<T> = interface(IGenList<T>)
['{6624B15B-CA96-4B61-8D88-1F36688FD3AC}']
function GetDuplicates: TDuplicates;
function GetSorted: Boolean;
procedure SetDuplicates(AValue: TDuplicates);
function GetCommaText: string;
procedure SetCommaText(const AValue: string);
procedure SetSorted(AValue: Boolean);
procedure Sort;
function LoadFromStream(const AStream: TStream): Boolean;
procedure SaveToStream(const AStream: TStream);
function LoadFromArray(const arr: array of T): Boolean;
procedure SaveToArray(var arr: TGArray<T>);
property CommaText: string read GetCommaText write SetCommaText;
property Sorted: Boolean read GetSorted write SetSorted;
property Duplicates: TDuplicates read GetDuplicates write SetDuplicates;
end;
IGenNumberList<T> = interface(IGenNumberListBase<T>)
['{D9D4026E-7C28-40D3-9322-597CB4727A5F}']
function Get(Index: Integer): T;
function GetCount: Integer;
procedure Put(Index: Integer; const AValue: T);
procedure SetCount(AValue: Integer);
//function GetEnumerator: TListEnumerator;
procedure AddList(const AList: IGenNumberList<T>);
//property List: PPointerList read GetList;
property Count: Integer read GetCount write SetCount;
property Items[Index: Integer]: T read Get write Put; default;
end;
IGenThreadNumberList<T> = interface(IGenNumberListBase<T>)
['{1222AE27-E24C-443A-9A9D-4236081394B7}']
end;
{ IFPStrings }
IFPStrings = interface(IFPObject)
['{E2F15AED-5C47-4620-8DCE-E808E154F0D7}']
function Add(const S: string): Integer;
function AddObject(const S: string; AObject: TObject): Integer;
//procedure AddStrings(const TheStrings: array of string); overload;
Procedure AddText(Const S : String);
procedure Clear;
procedure Delete(Index: Integer);
function GetStrictDelimiter: Boolean;
function Remove(const S: string): Boolean;
procedure Exchange(Index1, Index2: Integer);
function Get(Index: Integer): string;
function GetCapacity: Integer;
function GetCommaText: string;
function GetCount: Integer;
function GetDelimitedText: string;
function GetLBS: TTextLineBreakStyle;
function GetName(Index: Integer): string;
function GetObject(Index: Integer): TObject;
function GetText: PChar;
function GetTextStr: string;
function GetValue(const Name: string): string;
function GetValueFromIndex(Index: Integer): string;
function IndexOf(const S: string): Integer;
function IndexOfName(const Name: string): Integer;
function IndexOfObject(AObject: TObject): Integer;
procedure Insert(Index: Integer; const S: string);
procedure InsertObject(Index: Integer; const S: string; AObject: TObject);
procedure LoadFromFile(const FileName: string);
//procedure LoadFromStream(Stream: IFPStream);
procedure Move(CurIndex, NewIndex: Integer);
procedure Put(Index: Integer; const AValue: string);
procedure PutObject(Index: Integer; AValue: TObject);
procedure SaveToFile(const FileName: string);
procedure SetCapacity(AValue: Integer);
procedure SetCommaText(const AValue: string);
procedure SetDelimitedText(const AValue: string);
procedure SetLBS(AValue: TTextLineBreakStyle);
procedure SetStrictDelimiter(AValue: Boolean);
//procedure SaveToStream(Stream: IFPStream);
procedure SetText(TheText: PChar);
procedure GetNameValue(Index : Integer; Out AName,AValue : String);
function ExtractName(Const S:String):String;
procedure SetTextStr(const AValue: string);
procedure SetValue(const Name: string; const AValue: string);
procedure SetValueFromIndex(Index: Integer; const AValue: string);
property TextLineBreakStyle : TTextLineBreakStyle Read GetLBS Write SetLBS;
//property Delimiter: Char read FDelimiter write SetDelimiter;
property DelimitedText: string read GetDelimitedText write SetDelimitedText;
Property StrictDelimiter : Boolean Read GetStrictDelimiter Write SetStrictDelimiter;
//property QuoteChar: Char read FQuoteChar write SetQuoteChar;
//Property NameValueSeparator : Char Read FNameValueSeparator Write SetNameValueSeparator;
property ValueFromIndex[Index: Integer]: string read GetValueFromIndex write SetValueFromIndex;
property Capacity: Integer read GetCapacity write SetCapacity;
property CommaText: string read GetCommaText write SetCommaText;
property Count: Integer read GetCount;
property Names[Index: Integer]: string read GetName;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property Values[const Name: string]: string read GetValue write SetValue;
property Strings[Index: Integer]: string read Get write Put; default;
property Text: string read GetTextStr write SetTextStr;
procedure AddStrings(const AStrings: IFPStrings; const AClearFirst: Boolean = False);
end;
{ IFPStringListUTF8 }
IFPStringListUTF8 = interface(IFPStrings)
['{A7A625C7-888D-439A-B334-48C34F670841}']
function GetCaseSensitive: Boolean;
function GetSorted: Boolean;{$IF FPC_FULLVERSION >= 030000}
function GetSortStyle: TStringsSortStyle;{$ENDIF}
procedure SetCaseSensitive(AValue: Boolean);
procedure SetSorted(AValue: Boolean);{$IF FPC_FULLVERSION >= 030000}
procedure SetSortStyle(AValue: TStringsSortStyle);{$ENDIF}
function AddIfNotFind(const S: string; const AObject: TObject = nil): Boolean;
function Remove(const AIndex: Integer; out S: string): Boolean; overload;
function RemoveEx(const AIndex: Integer; out S: string; out AObject: TObject): Boolean;
procedure RemoveName(const AName: string);
procedure RemoveAllObjects(const AObject: TObject);
function Find(const S: string; Out Index: Integer): Boolean;
function FindObject(const S: string; Out AObject: TObject): Boolean;
procedure Sort;
function ExportToArray: TStringArray;
function ExportByObject(const AObject: TObject): TStringArray;
procedure ImportArray(const AValue: TStringArray);
//procedure CustomSort(CompareFn: TStringListSortCompare);
//property Duplicates: TDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read GetSorted write SetSorted;
property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive;{$IF FPC_FULLVERSION >= 030000}
property SortStyle : TStringsSortStyle read GetSortStyle write SetSortStyle;{$ENDIF}
end;
IFPStringList = IFPStringListUTF8;
IFPFileNameList = interface(IFPStringListUTF8)
['{45BEDB7C-0861-42FE-87FE-19BD1D1841BE}']
procedure ClearNotExistFiles(const ACheckDirs: Boolean = False);
end;
{ IDataStringList }
IFPDataStringList = interface(IFPStringListUTF8)
['{F1C9B9A7-A5AA-4FB1-AEA9-8BE46C3AAB35}']
function GetData(const Index: Integer): Pointer;
function IndexOfData(AData: Pointer): Integer;
property Data[Index: Integer]: Pointer read GetData;
//property OnFreeData: TNotifyPointer read FOnFreeData write FOnFreeData;
end;
{ IFPThreadStrings }
IFPThreadStrings = interface
['{7B569584-0104-4178-80F7-1303D455BEBE}']
function Get(Index: Integer): string;
function GetObject(Index: Integer): TObject;
function GetOwnsObjects: Boolean;
function GetSorted: Boolean;
function GetValue(const AName: string): string;
procedure Put(Index: Integer; const AValue: string);
procedure PutObject(Index: Integer; const AValue: TObject);
procedure SetOwnsObjects(AValue: Boolean);
procedure SetSorted(AValue: Boolean);
procedure SetValue(const AName: string; const AValue: string);
function Add(const S: string): Integer;
procedure Remove(const S: string); overload;
function Remove(const AIndex: Integer; out S: string): Boolean; overload;
function RemoveLast(out S: string): Boolean;
procedure RemoveName(const AName: string);
procedure RemoveAllObjects(const AObject: TObject);
function AddObject(const S: string; AObject: TObject): Integer;
procedure Insert(AIndex: Integer; const S: string);
procedure InsertObject(AIndex: Integer; const S: string; AObject: TObject);
procedure Delete(AIndex: Integer);
function IsEmpty: Boolean;
function Count: Integer;
procedure SetCount(const ASize: Integer);
procedure Clear;
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
procedure AddStrings(const AStrings: IFPStrings; const AClearFirst: Boolean = False);
procedure CopyToStrings(const AStrings: IFPStrings);
function ExportToArray: TStringArray;
function ExportByObject(const AObject: TObject): TStringArray;
procedure ImportArray(const AValue: TStringArray);
function Find(const S: string; Out AIndex: Integer): Boolean;
function IndexOf(const S: string): Integer;
function FindObject(const S: string; Out AObject: TObject): Boolean;
function IndexOfObject(const AObject: TObject): Integer;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property Strings[Index: Integer]: string read Get write Put; default;
property Values[const AName: string]: string read GetValue write SetValue;
property Sorted: Boolean read GetSorted write SetSorted;
property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects;
end;
IFPThreadStringList = interface(IFPThreadStrings)
['{529C0F4A-9A0F-4A11-983E-C465F84D29B2}']
function LockList: IFPStringList;
procedure UnlockList;
end;
IFPThreadFileNameList = interface(IFPThreadStrings)
['{719E62EC-1F99-4B6A-B9FA-2B86E2205AEC}']
function LockList: IFPFileNameList;
procedure UnlockList;
end;
{ IFPThreadDataStringList }
IFPThreadDataStringList = interface(IFPThreadStrings)
['{3B508A20-5C30-4E9E-873E-BB984CE2B6A8}']
function GetData(Index: Integer): Pointer;
function LockList: IFPDataStringList;
procedure UnlockList;
property Data[Index: Integer]: Pointer read GetData;
end;
{ IFPCustomIniFile }
IFPCustomIniFile = interface(IFPObject)
['{9554624F-1C01-4855-9FC9-FB59DF8100B2}']
function SectionExists(const Section: string): Boolean;
function ReadString(const Section, Ident: string; const ADefault: string = ''): string;
procedure WriteString(const Section, Ident, Value: String);
function ReadInteger(const Section, Ident: string; ADefault: Longint): Longint;
procedure WriteInteger(const Section, Ident: string; Value: Longint);
function ReadInt64(const Section, Ident: string; ADefault: Int64): {$IF FPC_FULLVERSION >= 030000}Int64{$ELSE}Longint{$ENDIF};
procedure WriteInt64(const Section, Ident: string; Value: Int64);
function ReadBool(const Section, Ident: string; ADefault: Boolean): Boolean;
procedure WriteBool(const Section, Ident: string; Value: Boolean);
function ReadDate(const Section, Ident: string; ADefault: TDateTime): TDateTime;
function ReadDateTime(const Section, Ident: string; ADefault: TDateTime): TDateTime;
function ReadFloat(const Section, Ident: string; ADefault: Double): Double;
function ReadTime(const Section, Ident: string; ADefault: TDateTime): TDateTime;
//function ReadBinaryStream(const Section, Name: string; Value: IFPStream): Integer;
procedure WriteDate(const Section, Ident: string; Value: TDateTime);
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
procedure WriteFloat(const Section, Ident: string; Value: Double);
procedure WriteTime(const Section, Ident: string; Value: TDateTime);
//procedure WriteBinaryStream(const Section, Name: string; Value: IFPStream);
procedure EraseSection(const Section: string);
procedure DeleteKey(const Section, Ident: String);
procedure UpdateFile;
function ValueExists(const Section, Ident: string): Boolean;
procedure ReadSections(const AStrings: IFPStrings);
//without comments name
procedure ReadSection(const ASection: string; const AStrings: IFPStrings);
//without comments name=value
procedure ReadSectionRaw(const ASection: string; const AStrings: IFPStrings);
//with comments name=value
procedure ReadSectionValues(const ASection: string; const AStrings: IFPStrings);
procedure GetSection(const ASection: string; out AStrings: IFPStringListUTF8);
procedure GetSections(out AStrings: IFPStringListUTF8);
procedure GetSectionValues(const ASection: string; out AStrings: IFPStringListUTF8);
procedure GetSectionRaw(const ASection: string; out AStrings: IFPStringListUTF8);
end;
{ IFPIniFileUTF8 }
IFPIniFileUTF8 = interface(IFPCustomIniFile)
['{7C11338A-C8DD-4612-A66E-5D30E5886CF8}']
procedure WriteDeleteString(const ASection, AIdent, AValue, ADefault: String;
AToQuote: Boolean = False; ACaseSensetive: Boolean = False);
procedure WriteDeleteBool(const ASection, AIdent: string;
AValue, ADefault: Boolean);
procedure WriteDeleteInteger(const ASection, AIdent: string;
AValue, ADefault: Integer);
procedure WriteSection(const ASection: string; const AValues: IFPStrings;
const AIsClearFirst: Boolean = True);
procedure ClearSection(const ASection: string);//not erase [Section]
procedure AddSection(const ASection: string);//add empty [ASection] if not exists
function CopySection(const ASourceSect, ADestSect: string): Boolean;
function RenameSection(const OldSect, NewSect: string): Boolean;
procedure BeginUpdateFile;
procedure EndUpdateFile;
procedure Clear;
end;
IFPIniFile = IFPIniFileUTF8;
IFPThreadIniFileUTF8 = interface(IFPObject)
['{73467F72-0F1C-45C9-B80B-971FF484C3CE}']
function SectionExists(const Section: string): Boolean;
function ReadString(const Section, Ident: string; const ADefault: string = ''): string;
procedure WriteString(const Section, Ident, Value: String);
function ReadInteger(const Section, Ident: string; ADefault: Longint): Longint;
procedure WriteInteger(const Section, Ident: string; Value: Longint);
function ReadInt64(const Section, Ident: string; ADefault: Int64): {$IF FPC_FULLVERSION >= 030100}Int64{$ELSE}Longint{$ENDIF};
procedure WriteInt64(const Section, Ident: string; Value: Int64);
function ReadBool(const Section, Ident: string; ADefault: Boolean): Boolean;
procedure WriteBool(const Section, Ident: string; Value: Boolean);
function ReadDateTime(const Section, Ident: string; ADefault: TDateTime): TDateTime;
function ReadFloat(const Section, Ident: string; ADefault: Double): Double;
procedure WriteDate(const Section, Ident: string; Value: TDateTime);
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
procedure WriteFloat(const Section, Ident: string; Value: Double);
procedure WriteTime(const Section, Ident: string; Value: TDateTime);
procedure EraseSection(const Section: string);
procedure DeleteKey(const Section, Ident: String);
procedure UpdateFile;
function ValueExists(const Section, Ident: string): Boolean;
procedure ReadSections(const AStrings: IFPStrings);
//without comments name
procedure ReadSection(const ASection: string; const AStrings: IFPStrings);
//without comments name=value
procedure ReadSectionRaw(const ASection: string; const AStrings: IFPStrings);
//with comments name=value
procedure ReadSectionValues(const ASection: string; const AStrings: IFPStrings);
procedure GetSection(const ASection: string; out AStrings: IFPStringListUTF8);
procedure GetSections(out AStrings: IFPStringListUTF8);
procedure GetSectionValues(const ASection: string; out AStrings: IFPStringListUTF8);
procedure GetSectionRaw(const ASection: string; out AStrings: IFPStringListUTF8);
procedure WriteDeleteString(const ASection, AIdent, AValue, ADefault: String;
AToQuote: Boolean = False; ACaseSensetive: Boolean = False);
procedure WriteDeleteBool(const ASection, AIdent: string;
AValue, ADefault: Boolean);
procedure WriteDeleteInt(const ASection, AIdent: string;
AValue, ADefault: Integer);
function CopySection(const ASourceSect, ADestSect: string): Boolean;
function RenameSection(const OldSect, NewSect: string): Boolean;
procedure Clear;
function Lock: IFPIniFileUTF8;
procedure Unlock;
end;
IFPThreadIniFile = IFPThreadIniFileUTF8;
{$IFDEF CACHED_INI_NOT_THREAD}
IFPIniTestCachedFile = interface(IFPIniFileUTF8)
['{87131744-FF14-4E4D-8CE5-1FDEB2C74D4C}']
function Lock: IFPIniFileUTF8;
procedure Unlock;
end;
IFPIniCachedFile = IFPIniTestCachedFile;
{$ELSE}
IFPIniCachedFile = IFPThreadIniFileUTF8;
{$ENDIF}
TOnBeforeLoad = procedure(Sender: TObject; var AUrl: string; var ACancel: Boolean) of object;
TOnShowContextMenu = procedure(Sender: TObject; constref APoint: TPoint; var ADone: Boolean) of object;
TWBKeyEvent = procedure(Sender: TObject; var Key: Word; Shift: TShiftState; const AOSEvent: TOSEvent) of Object;
{ IWebBrowser }
IWebBrowser = interface
['{48EA1A18-F87C-4156-A0E5-03BC77E0E2D3}']
function GetEnabled: Boolean;
function GetInitialized: Boolean;
function GetOnKeyDown: TWBKeyEvent;
procedure SetEnabled(AValue: Boolean);
procedure SetOnKeyDown(AValue: TWBKeyEvent);
function GetOnBeforeLoad: TOnBeforeLoad;
procedure SetOnBeforeLoad(AValue: TOnBeforeLoad);
function GetOnLoad: TNotifyEvent;
procedure SetOnLoad(AValue: TNotifyEvent);
function GetOnShowContextMenu: TOnShowContextMenu;
procedure SetOnShowContextMenu(AValue: TOnShowContextMenu);
function GetOnFocused: TNotifyEvent;
procedure SetOnFocused(AValue: TNotifyEvent);
procedure Navigate(const AUrl: string);
procedure Refresh(const AIgnoreCache: Boolean = False);
function LoadFromString(const S : string): Integer;
function SaveToString: string;
procedure PrintToPDF(const AFileName: string);
function Focused: Boolean;
function ClearSelection: Boolean;
//function SelText: string;
function SelectAll: Boolean;
procedure ExecuteJavaScript(const ACode: string);
property OnKeyDown: TWBKeyEvent read GetOnKeyDown write SetOnKeyDown;//may be not In MainThread (Chromium Embedded)
property OnBeforeLoad: TOnBeforeLoad read GetOnBeforeLoad write SetOnBeforeLoad;
property OnLoad: TNotifyEvent read GetOnLoad write SetOnLoad;
property OnShowContextMenu: TOnShowContextMenu read GetOnShowContextMenu write SetOnShowContextMenu;
property OnFocused: TNotifyEvent read GetOnFocused write SetOnFocused;
property Initialized: Boolean read GetInitialized;
property Enabled: Boolean read GetEnabled write SetEnabled;
function IsEnabled: Boolean;//check Parent
//property Visible: Boolean read GetVisible write SetVisible;
function IsVisible: Boolean;//check Parent
end;
IFPHttpClient = interface(IFPObject)
['{A80BF710-0E74-4918-9A4F-BF2035256918}']
end;
implementation
end.
|
unit IdUDPClient;
interface
uses
IdUDPBase;
type
//TODO: The send methods cause Host to be resolved each time
// change this to cache the resolution locally.
TIdUDPClient = class(TIdUDPBase)
protected
public
procedure Send(AData: string); overload;
procedure SendBuffer(var ABuffer; const AByteCount: integer); overload;
published
property Host: string read FHost write FHost;
property Port: Integer read FPort write FPort;
property ReceiveTimeout;
end;
implementation
{ TIdUDPClient }
procedure TIdUDPClient.Send(AData: string);
begin
Send(Host, Port, AData);
end;
procedure TIdUDPClient.SendBuffer(var ABuffer; const AByteCount: integer);
begin
SendBuffer(Host, Port, ABuffer, AByteCount);
end;
end.
|
unit iaExample.CDE.ControllerThread;
interface
uses
System.Classes,
System.SyncObjs,
Vcl.StdCtrls;
type
TExampleControllerThread = class(TThread)
private const
WorkerThreadCount = 3;
private
fCDE:TCountdownEvent;
fCallBackMemo:TMemo;
protected
procedure Execute(); override;
procedure CallBack(const pText:string);
procedure Fork();
procedure Join();
public
constructor Create(const pCallbackTo:TMemo);
destructor Destroy(); override;
end;
implementation
uses
System.SysUtils,
iaExample.CDE.ParallelTask;
constructor TExampleControllerThread.Create(const pCallbackTo:TMemo);
begin
fCDE := TCountdownEvent.Create(1);
fCallBackMemo := pCallbackTo;
FreeOnTerminate := True;
inherited Create(False);
end;
destructor TExampleControllerThread.Destroy();
begin
fCDE.Free();
inherited;
end;
procedure TExampleControllerThread.Execute();
begin
NameThreadForDebugging('ExampleCDEControllerThread');
CallBack('Creating worker threads');
Fork();
CallBack('Controller waiting for workers to finish');
Join();
CallBack('Work completed');
end;
(*
Alternate, AddCount for each task
procedure TExampleControllerThread.Fork();
begin
for var i := 1 to WorkerThreadCount do
begin
fCDE.AddCount;
TExampleParallelTask.Create(fCDE);
end;
end;
*)
//spin up some child threads
procedure TExampleControllerThread.Fork();
begin
fCDE.AddCount(WorkerThreadCount);
for var i := 1 to WorkerThreadCount do
begin
TExampleParallelTask.Create(fCDE);
end;
end;
//wait for the children to be done with their work
procedure TExampleControllerThread.Join();
begin
fCDE.Signal();
fCDE.WaitFor();
end;
procedure TExampleControllerThread.CallBack(const pText:string);
begin
Synchronize(procedure()
begin
fCallBackMemo.Lines.Add(FormatDateTime('hh:nn:ss.zzzz', Now) + ' ' + pText);
end);
end;
end.
|
unit ncaFrmZerarTempo;
{
ResourceString: Dario 11/03/13
Nada pra fazer
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, cxRadioGroup,
cxControls, cxContainer, cxEdit, cxLabel, cxGraphics, cxLookAndFeels;
type
TFrmZeraTempo = class(TForm)
cxLabel1: TcxLabel;
rbClienteAtual: TcxRadioButton;
rbTodos: TcxRadioButton;
cxLabel2: TcxLabel;
btnZerar: TcxButton;
btnCancelar: TcxButton;
procedure btnZerarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCancelarClick(Sender: TObject);
private
FResultado : Integer;
{ Private declarations }
public
function Zerar(aCliente: String): Integer; // -1 Cancelar, 0 cliente atual, 1 todos
{ Public declarations }
end;
var
FrmZeraTempo: TFrmZeraTempo;
implementation
{$R *.dfm}
procedure TFrmZeraTempo.btnCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TFrmZeraTempo.btnZerarClick(Sender: TObject);
begin
if rbClienteAtual.Checked then
FResultado := 0 else
FResultado := 1;
Close;
end;
procedure TFrmZeraTempo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
function TFrmZeraTempo.Zerar(aCliente: String): Integer;
begin
FResultado := -1;
rbClienteAtual.Caption := aCliente;
ShowModal;
Result := FResultado;
end;
end.
|
{$DEFINE HASCANVAS}
unit LuaShape;
interface
Uses Classes, Controls, StdCtrls, ComCtrls, ExtCtrls, FileCtrl, EditBtn, Buttons, Forms, Spin, ActnList, CheckLst, TypInfo, LuaPas, LuaControl, LuaCanvas;
function CreateShape(L: Plua_State): Integer; cdecl;
type
TRotateShape = class(TShape)
private
fAngle: extended;
fRotateMinSize: Boolean;
procedure SetAngle(const Value: extended);
procedure SetRotateMinSize(const Value: Boolean);
function CalcR(WInt,HInt: Integer; radA: Extended): Extended;
public
constructor Create(aOwner: TComponent); override;
procedure Paint; override;
published
property Angle: extended read fAngle write SetAngle; {in degrees}
property RotateMinSize: Boolean read fRotateMinSize write SetRotateMinSize;
end;
type
TLuaShape = class(TRotateShape)
LuaCtl: TLuaControl;
{$IFDEF HASCANVAS}
LuaCanvas: TLuaCanvas;
{$ENDIF}
public
destructor Destroy; override;
end;
implementation
Uses LuaProperties, Lua, LCLClasses, Windows, Math;
{ TRotateShape }
constructor TRotateShape.Create(aOwner: TComponent);
begin
fAngle := 0;
fRotateMinSize := False;
inherited;
end;
function TRotateShape.CalcR(WInt,HInt: Integer; radA: Extended): Extended;
var
radA0 :Extended;
W,H :Extended;
begin
W := WInt;
H := HInt;
if radA > 3*Pi/2 then
radA := 2*Pi - radA
else if radA > Pi then
radA := radA - Pi
else if radA > Pi/2 then
radA := Pi - radA;
radA0 := arctan(W / H);
Result := 1 / (Sqrt(1 + IntPower(W/H,2)) * Cos(radA0 - radA));
end;
function Min(a, b: Extended): Extended;inline;overload;
begin
if a < b then
Result := a
else
Result := b;
end;
function Max(a, b: Extended): Extended;inline;overload;
begin
if a > b then
Result := a
else
Result := b;
end;
procedure TRotateShape.Paint;
var
xForm,xFormOld: TXForm;
gMode: DWORD;
r: Extended;
radA,radA0: Extended;
begin
if Shape = stCircle then
begin
inherited;
Exit;
end;
radA := frac(fAngle / 360) * 2 * Pi;
case Shape of
stSquaredDiamond:
r := 1;
stSquare,stRoundSquare:
if fRotateMinSize then
r := 1 / Sqrt(2)
else
r := CalcR(Min(Width,Height),Min(Width,Height),radA);
else
if fRotateMinSize then
begin
if Shape in [stDiamond,stEllipse] then
r := Min(Width,Height) / Max(Width,Height)
else
r := 1 / (Sqrt(1 + IntPower(Max(Width,Height)/Min(Height,Width),2)))
end
else
begin
r := Min(CalcR(Width,Height,radA), CalcR(Height,Width,radA))
end;
end;
gMode:= SetGraphicsMode(Canvas.Handle,GM_ADVANCED);
try
XForm.eM11 := Cos(radA) * r * (Width-1)/Width;
XForm.eM12 := Sin(radA) * r * (Height-1)/Height;
XForm.eM21 := - Sin(radA) * r * (Width-1)/Width;
XForm.eM22 := Cos(radA) * r * (Height-1)/Height;
XForm.eDx := (((Width-1)/2)-(Cos(radA)*((Width-1)/2))*r)+((Sin(radA)*((Height-1)/2))*r);
XForm.eDy := (((Height-1)/2)-(Sin(radA)*((Width-1)/2))*r)-((Cos(radA)*((Height-1)/2))*r);
if GetWorldTransform(Canvas.Handle,xFormOld) then
try
SetWorldTransform(Canvas.Handle,XForm);
inherited;
finally
SetWorldTransform(Canvas.Handle,XFormOld);
end;
finally
SetGraphicsMode(Canvas.Handle,gMode);
end;
end;
procedure TRotateShape.SetAngle(const Value: extended);
begin
if fAngle <> Value then
begin
fAngle := Value;
Repaint;
end;
end;
procedure TRotateShape.SetRotateMinSize(const Value: Boolean);
begin
if fRotateMinSize <> Value then
begin
fRotateMinSize := Value;
Repaint;
end;
end;
{ TLuaShape }
destructor TLuaShape.Destroy;
begin
{$IFDEF HASCANVAS}
if (LuaCanvas<>nil) then LuaCanvas.Free;
{$ENDIF}
inherited Destroy;
end;
{$IFDEF HASCANVAS}
function ShapeGetCanvas(L: Plua_State): Integer; cdecl;
var lShape:TLuaShape;
begin
lShape := TLuaShape(GetLuaObject(L, 1));
lShape.LuaCanvas.ToTable(L, -1, lShape.Canvas);
result := 1;
end;
{$ENDIF}
function SendToBack(L: Plua_State): Integer; cdecl;
var lC:TShape;
begin
lC := TShape(GetLuaObject(L, 1));
lC.SendToBack;
Result := 0;
end;
function BringToFront(L: Plua_State): Integer; cdecl;
var lC:TShape;
begin
lC := TShape(GetLuaObject(L, 1));
lC.BringToFront;
Result := 0;
end;
procedure ShapeToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L,Index,Sender);
{$IFDEF HASCANVAS}
if (Sender.InheritsFrom(TCustomControl) or Sender.InheritsFrom(TGraphicControl) or
Sender.InheritsFrom(TLCLComponent)) then
LuaSetTableFunction(L, Index, 'GetCanvas', ShapeGetCanvas);
{$ENDIF}
LuaSetTableFunction(L, Index, 'SendToBack',@SendToBack);
LuaSetTableFunction(L, Index, 'BringToFront',@BringToFront);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function CreateShape(L: Plua_State): Integer; cdecl;
var
lShape:TLuaShape;
Parent:TComponent;
Name:String;
begin
GetControlParents(L,Parent,Name);
lShape := TLuaShape.Create(Parent);
lShape.Parent := TWinControl(Parent);
lShape.LuaCtl := TLuaControl.Create(lShape,L,@ShapeToTable);
if (lua_gettop(L)>0) and (GetLuaObject(L, -1) = nil) then
SetPropertiesFromLuaTable(L, TObject(lShape),-1)
else
lShape.Name := Name;
{$IFDEF HASCANVAS}
if (lShape.InheritsFrom(TCustomControl) or lShape.InheritsFrom(TGraphicControl) or
lShape.InheritsFrom(TLCLComponent)) then
lShape.LuaCanvas := TLuaCanvas.Create;
{$ENDIF}
ShapeToTable(L, -1, lShape);
Result := 1;
end;
end.
|
(*
Implementation of typical Observable.
Before deciding to implement your own Observable,
check here.
--- Implicit infrastructure ---
There are principles that may not be obvious in the code.
One of the most important is that no event will be issued
after the sequence is complete (onError or onCompleted).
The implementation of the subject 'respects these principles.
Security can not be guaranteed wherever Rx is used,
so you better be aware and not violate this principle,
as this can lead to vague consequences.
*)
unit Rx.Subjects;
interface
uses Rx, Rx.Implementations, Generics.Collections;
type
/// <summary>
/// The simplest implementation of Subject. When data is transmitted to
/// PublishSubject, it issues them to all subscribers who are subscribed to
/// him at the moment.
/// </summary>
TPublishSubject<T> = class(TObservableImpl<T>)
public
procedure OnNext(const Data: T); override;
end;
/// <summary>
/// Has a special ability to cache all the incoming data.
/// When he has a new subscriber, the sequence is given to him
/// since the beginning. All subsequent received data will be provided
/// subscribers as usual.
/// </summary>
TReplaySubject<T> = class(TPublishSubject<T>)
type
TValue = TSmartVariable<T>;
TVaueDescr = record
Value: TValue;
Stamp: TDateTime;
end;
strict private
FCache: TList<TVaueDescr>;
FLimitBySize: Boolean;
FLimitSize: LongWord;
FLimitByTime: Boolean;
FLimitDelta: TDateTime;
FLimitFrom: TDateTime;
protected
procedure OnSubscribe(Subscriber: ISubscriber<T>); override;
public
constructor Create;
/// <summary>
/// <para>
/// Caching everything is not always the best idea, because
/// sequences can be long or even infinite.
/// </para>
/// <para>
/// CreateWithSize limits the size of the buffer, and discards the oldest item
/// CreateWithTime time that objects will remain in the cache.
/// internally tags each observed item with a timestamp value supplied by the
/// scheduler and keeps only those whose age is less than the supplied time value
/// </para>
/// </summary>
constructor CreateWithSize(Size: LongWord);
constructor CreateWithTime(Time: LongWord;
TimeUnit: TimeUnit = Rx.TimeUnit.MILLISECONDS; From: TDateTime=Rx.StdSchedulers.IMMEDIATE);
destructor Destroy; override;
procedure OnNext(const Data: T); override;
procedure OnCompleted; override;
end;
/// <summary>
/// BehaviorSubject stores only the last value. This is the same as
/// and ReplaySubject, but with a buffer of size 1. During creation, it can
/// to be assigned an initial value, thus ensuring that the data
/// will always be available to new subscribers.
/// </summary>
TBehaviorSubject<T> = class(TPublishSubject<T>)
strict private
FValue: TSmartVariable<T>;
FValueExists: Boolean;
protected
procedure OnSubscribe(Subscriber: ISubscriber<T>); override;
public
constructor Create(const Value: T); overload;
procedure OnNext(const Data: T); override;
end;
/// <summary>
/// Also stores the last value. The difference is that it does not issue data
/// until the sequence ends. It is used when
/// you need to give a single value and immediately end.
/// </summary>
TAsyncSubject<T> = class(TObservableImpl<T>)
type
TValue = TSmartVariable<T>;
strict private
FCache: TList<TValue>;
protected
property Cache: TList<TValue> read FCache;
public
constructor Create;
destructor Destroy; override;
procedure OnNext(const Data: T); override;
procedure OnCompleted; override;
end;
implementation
uses {$IFDEF DEBUG}Windows, {$ENDIF} SysUtils, Rx.Schedulers, DateUtils;
{ TPublishSubject<T> }
procedure TPublishSubject<T>.OnNext(const Data: T);
var
Contract: IContract;
Ref: TSmartVariable<T>;
begin
inherited;
Ref := Data;
if Supports(Scheduler, StdSchedulers.ICurrentThreadScheduler) then
for Contract in Freeze do
Contract.GetSubscriber.OnNext(TSmartVariable<T>.Create(Data))
else
for Contract in Freeze do
Scheduler.Invoke(TOnNextAction<T>.Create(Data, Contract))
end;
{ TReplaySubject<T> }
constructor TReplaySubject<T>.Create;
begin
inherited Create;
FCache := TList<TVaueDescr>.Create;
end;
constructor TReplaySubject<T>.CreateWithSize(Size: LongWord);
begin
if Size = 0 then
raise ERangeError.Create('Size must be not equal zero!');
FLimitBySize := True;
FLimitSize := Size;
Create;
end;
constructor TReplaySubject<T>.CreateWithTime(Time: LongWord; TimeUnit: TimeUnit;
From: TDateTime);
var
Hours, Minutes, Seconds, Millisecs: Word;
begin
FLimitByTime := True;
Hours := 0; Minutes := 0; Seconds := 0; Millisecs := 0;
case TimeUnit of
Rx.TimeUnit.MILLISECONDS: begin
Millisecs := Time mod MSecsPerSec;
Seconds := (Time div MSecsPerSec) mod SecsPerMin;
Minutes := (Time div (MSecsPerSec*SecsPerMin)) mod MinsPerHour;
Hours := Time div (MSecsPerSec*SecsPerMin*MinsPerHour);
end;
Rx.TimeUnit.SECONDS: begin
Seconds := Time mod SecsPerMin;
Minutes := (Time div SecsPerMin) mod MinsPerHour;
Hours := Time div (SecsPerMin*MinsPerHour);
end;
Rx.TimeUnit.MINUTES: begin
Minutes := Time mod MinsPerHour;
Hours := Time div MinsPerHour;
end
else
raise ERangeError.Create('Unknown TimeUnit value');
end;
FLimitDelta := EncodeTime(Hours, Minutes, Seconds, Millisecs);
FLimitFrom := From;
Create;
end;
destructor TReplaySubject<T>.Destroy;
begin
FCache.Free;
inherited;
end;
procedure TReplaySubject<T>.OnCompleted;
begin
inherited;
Lock;
try
FCache.Clear;
finally
Unlock
end;
end;
procedure TReplaySubject<T>.OnNext(const Data: T);
var
Descr: TVaueDescr;
CountToDelete: Integer;
I: Integer;
LastStamp: TDateTime;
begin
inherited OnNext(Data);
Descr.Value := Data;
Descr.Stamp := Now;
Lock;
try
if FLimitBySize then begin
if LongWord(FCache.Count) >= FLimitSize then
FCache.DeleteRange(0, FCache.Count-Integer(FLimitSize)+1);
FCache.Add(Descr);
end
else if FLimitByTime then begin
if FLimitFrom <= Now then begin
if FCache.Count > 0 then begin
LastStamp := Now;
CountToDelete := 0;
for I := 0 to FCache.Count-1 do begin
if (LastStamp - FCache[I].Stamp) > FLimitDelta then
Inc(CountToDelete)
else
Break;
end;
if CountToDelete > 0 then
FCache.DeleteRange(0, CountToDelete);
end;
FCache.Add(Descr);
end
end
else
FCache.Add(Descr);
finally
Unlock
end;
end;
procedure TReplaySubject<T>.OnSubscribe(Subscriber: ISubscriber<T>);
var
Descr: TVaueDescr;
A: TArray<TVaueDescr>;
begin
inherited;
Lock;
try
A := FCache.ToArray;
finally
Unlock;
end;
for Descr in A do
Subscriber.OnNext(Descr.Value);
end;
{ TBehaviorSubject<T> }
constructor TBehaviorSubject<T>.Create(const Value: T);
begin
inherited Create;
FValue := Value;
FValueExists := True;
end;
procedure TBehaviorSubject<T>.OnNext(const Data: T);
begin
inherited;
FValue := Data;
FValueExists := True;
end;
procedure TBehaviorSubject<T>.OnSubscribe(Subscriber: ISubscriber<T>);
begin
inherited;
if FValueExists then
Subscriber.OnNext(FValue);
end;
{ TAsyncSubject<T> }
constructor TAsyncSubject<T>.Create;
begin
inherited Create;
FCache := TList<TValue>.Create;
end;
destructor TAsyncSubject<T>.Destroy;
begin
FCache.Free;
inherited;
end;
procedure TAsyncSubject<T>.OnCompleted;
var
Value: TValue;
Contract: IContract;
begin
if Supports(Scheduler, StdSchedulers.ICurrentThreadScheduler) then
for Contract in Freeze do
for Value in FCache do
Contract.GetSubscriber.OnNext(Value)
else
for Contract in Freeze do
for Value in FCache do
Scheduler.Invoke(TOnNextAction<T>.Create(Value, Contract));
inherited;
end;
procedure TAsyncSubject<T>.OnNext(const Data: T);
begin
inherited;
FCache.Add(Data);
end;
end.
|
unit VA508AccessibilityCompileInfo;
interface
{$UNDEF DELAY_BEFORE_SHOW}
{$DEFINE DELAY_BEFORE_SHOW}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, DateUtils, StrUtils;
type
TfrmProgress = class(TForm)
pnlMain: TPanel;
pnlProject: TPanel;
lblProj: TLabel;
lblProject: TLabel;
pnlFile: TPanel;
lblComp: TLabel;
lblFile: TLabel;
pnlErrorData: TPanel;
pnlErrors: TPanel;
lblNumErrors: TLabel;
lblErrors: TLabel;
pnlWarnings: TPanel;
lblNumWarnings: TLabel;
lblWarnings: TLabel;
btnRelease: TButton;
Panel1: TPanel;
lblTotal: TLabel;
lblTotalLines: TLabel;
Panel2: TPanel;
Label1: TLabel;
lblBuilt: TLabel;
Panel3: TPanel;
Label2: TLabel;
lblCached: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnReleaseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TStopCompileProc = procedure of object;
procedure StartMonitor(ProjectText: string; StopProc: TStopCompileProc);
procedure StopMonitor;
procedure Update508Monitor(FileName: String; TotalLines,
Warnings, Errors, Cached, Built: integer; ForceDisplay: boolean = false);
implementation
uses VAUtils;
{$R *.dfm}
const
{$IFDEF DELAY_BEFORE_SHOW}
SECONDS_BEFORE_SHOW = 3;
{$ENDIF}
UPDATE_FREQUENCY = 50;
var
frmProgress: TfrmProgress = nil;
uProjectText: string;
uStopProc: TStopCompileProc;
uRunning: boolean = false;
uLastUpdate: TDateTime;
{$IFDEF DELAY_BEFORE_SHOW}
uStartTime: TDateTime;
{$ENDIF}
procedure Hookup;
begin
if not assigned(frmProgress) then
frmProgress := TfrmProgress.Create(nil);
frmProgress.lblProject.Caption := GetFileWithShortenedPath(uProjectText, frmProgress.lblProject.Width, frmProgress.Canvas);
frmProgress.lblFile.Caption := '';
frmProgress.Show;
Application.ProcessMessages;
end;
procedure StartMonitor(ProjectText: string; StopProc: TStopCompileProc);
begin
uLastUpdate := 0;
uProjectText := ProjectText;
uStopProc := StopProc;
{$IFDEF DELAY_BEFORE_SHOW}
if assigned(frmProgress) then
Hookup
else
uStartTime := Now;
{$ELSE}
Hookup;
{$ENDIF}
end;
procedure StopMonitor;
begin
if assigned(frmProgress) then
FreeAndNil(frmProgress);
end;
procedure Update508Monitor(FileName: String; TotalLines,
Warnings, Errors, Cached, Built: integer; ForceDisplay: boolean = false);
begin
{$IFDEF DELAY_BEFORE_SHOW}
if not assigned(frmProgress) then
begin
if ForceDisplay or (SecondSpan(Now, uStartTime) > SECONDS_BEFORE_SHOW) then
Hookup;
end;
{$ENDIF}
if assigned(frmProgress) then
begin
frmProgress.lblFile.Caption := FileName;
frmProgress.lblTotalLines.Caption := IntToStr(TotalLines);
frmProgress.lblWarnings.Caption := IntToStr(Warnings);
frmProgress.lblErrors.Caption := IntToStr(Errors);
frmProgress.lblCached.Caption := IntToStr(Cached);
frmProgress.lblBuilt.Caption := IntToStr(Built);
if MilliSecondSpan(Now, uLastUpdate) > UPDATE_FREQUENCY then
begin
Application.ProcessMessages;
uLastUpdate := Now;
end;
end;
end;
procedure TfrmProgress.btnReleaseClick(Sender: TObject);
begin
btnRelease.Enabled := False;
if assigned(uStopProc) then
uStopProc;
Close;
end;
procedure TfrmProgress.FormCreate(Sender: TObject);
begin
Left := (Screen.Width - Width) div 2;
Top := (Screen.Height - Height) div 3;
end;
initialization
finalization
if assigned(frmProgress) then
FreeAndNil(frmProgress);
end.
|
unit CRSSHIOHandler;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Types, SysUtils, Classes, ScTypes, MemUtils,
ScVio, {$IFNDEF SBRIDGE}CRVio, {$ENDIF}
ScBridge, ScSSHClient, ScSSHChannel;
{$I SecureBridgeVer.inc}
type
{$IFDEF VER16P}
[ComponentPlatformsAttribute({$IFDEF STD}pidDevartWinPlatforms{$ELSE}pidDevartAllPlatforms{$ENDIF})]
{$ENDIF}
TCRSSHIOHandler = class (TCRIOHandler)
protected
FClient: TScSSHClient;
//FChannel: TScSSHChannel;
procedure CheckClient;
procedure SetClient(Value: TScSSHClient);
procedure ConnectChange(Sender: TObject; Connecting: boolean);
procedure Notification(Component: TComponent; Operation: TOperation); override;
function GetHandlerType: string; override;
procedure DoServerKeyValidate(Sender: TObject;
NewServerKey: TScKey; var Accept: Boolean);
procedure DoAuthenticationPrompt(Sender: TObject;
const Name, Instruction: string; const Prompts: TStringDynArray;
var Responses: TStringDynArray);
public
destructor Destroy; override;
function Connect(const Server: string; const Port: integer;
HttpOptions: THttpOptions; ProxyOptions: TProxyOptions;
SSLOptions: TSSLOptions; SSHOptions: TSSHOptions;
IPVersion: TIPVersion = ivIPv4): TCRIOHandle; override;
procedure Disconnect(Handle: TCRIOHandle); override;
class function ReadNoWait(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function Read(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function Write(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function WaitForData(Handle: TCRIOHandle; Timeout: integer = -1): boolean; override;
class function GetTimeout(Handle: TCRIOHandle): integer; override;
class procedure SetTimeout(Handle: TCRIOHandle; Value: integer); override;
published
property Client: TScSSHClient read FClient write SetClient;
end;
implementation
uses
ScConsts, ScUtils, CRAccess, DBAccess, CRFunctions,
ScSSHUtils;
const
KEY_GUID = '861690563F1B';
{ TCRSSHIOHandler }
destructor TCRSSHIOHandler.Destroy;
{$IFNDEF SBRIDGE}
{$IFNDEF ODBC_DRIVER}
var
con: TCRConnection;
i: integer;
{$ENDIF}
{$ENDIF}
begin
{$IFNDEF SBRIDGE}
{$IFNDEF ODBC_DRIVER}
for i := 0 to FList.Count - 1 do begin
if IsClass(TObject(FList[i]), TCRConnection) then begin
con := TCRConnection(FList[i]);
if con.GetConnected then
con.Disconnect;
end;
end;
{$ENDIF}
{$ENDIF}
if Assigned(Client) then
TScClientUtils.UnregisterClient(Client, Self);
inherited;
end;
function TCRSSHIOHandler.GetHandlerType: string;
begin
Result := 'ssh';
end;
procedure TCRSSHIOHandler.CheckClient;
begin
if FClient = nil then
raise EScError.Create(SClientNotDefined);
if not Assigned(FClient.OnServerKeyValidate) then
FClient.OnServerKeyValidate := DoServerKeyValidate;
if not Assigned(FClient.OnAuthenticationPrompt) then
FClient.OnAuthenticationPrompt := DoAuthenticationPrompt;
try
FClient.Connect;
except
on E: EScError do begin
if (FClient.Authentication = atPassword) and (E.ErrorCode = seAuthenticationFailed) then begin
FClient.Authentication := atKeyboardInteractive;
FClient.Connect;
end
else
raise;
end;
end;
end;
function TCRSSHIOHandler.Connect(const Server: string; const Port: integer;
HttpOptions: THttpOptions; ProxyOptions: TProxyOptions;
SSLOptions: TSSLOptions; SSHOptions: TSSHOptions;
IPVersion: TIPVersion = ivIPv4): TCRIOHandle;
var
Channel: TScSSHChannel;
begin
// set default Username for Oracle
if (SSHOptions <> nil) and (Client.User = '') then
Client.User := SSHOptions.Username;
CheckClient;
Channel := TScSSHChannel.Create(Self);
try
Channel.Direct := True;
Channel.Client := FClient;
//FClient.Options.IPVersion := IPVersion; //ODBC
Channel.DestHost := Server;
Channel.DestPort := Port;
Channel.Timeout := FClient.Timeout;
Channel.Connect;
except
Channel.Free;
raise;
end;
Result := Channel;
end;
procedure TCRSSHIOHandler.Disconnect(Handle: TCRIOHandle);
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
Channel.Connected := False;
end;
class function TCRSSHIOHandler.ReadNoWait(Handle: TCRIOHandle;
const buffer: TValueArr; offset, count: integer): integer;
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
Result := Channel.ReadNoWait(buffer[offset], count);
end;
class function TCRSSHIOHandler.Read(Handle: TCRIOHandle;
const buffer: TValueArr; offset, count: integer): integer;
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
Result := Channel.ReadBuffer(buffer[offset], count);
end;
class function TCRSSHIOHandler.Write(Handle: TCRIOHandle;
const buffer: TValueArr; offset, count: integer): integer;
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
Result := Channel.WriteBuffer(buffer[offset], count);
end;
class function TCRSSHIOHandler.WaitForData(Handle: TCRIOHandle;
Timeout: integer = -1): boolean;
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
if Timeout = -1 then
Timeout := MaxInt;
Result := TScSSHChannelUtils.Readable(Channel, 1, Timeout);
end;
class function TCRSSHIOHandler.GetTimeout(Handle: TCRIOHandle): integer;
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
Result := Channel.Timeout;
end;
class procedure TCRSSHIOHandler.SetTimeout(Handle: TCRIOHandle; Value: integer);
var
Channel: TScSSHChannel;
begin
Channel := Handle as TScSSHChannel;
if Value = 0 then
Value := MaxInt;
Channel.Timeout := Value;
end;
procedure TCRSSHIOHandler.Notification(Component: TComponent; Operation: TOperation);
begin
if (Component = FClient) and (Operation = opRemove) then
Client := nil;
inherited;
end;
procedure TCRSSHIOHandler.SetClient(Value: TScSSHClient);
begin
if Value <> FClient then begin
if FClient <> nil then begin
TScClientUtils.UnregisterClient(FClient, Self);
FClient.RemoveFreeNotification(Self);
end;
FClient := Value;
if Value <> nil then begin
TScClientUtils.RegisterClient(Value, Self, ConnectChange);
Value.FreeNotification(Self);
end;
end;
end;
procedure TCRSSHIOHandler.ConnectChange(Sender: TObject; Connecting: boolean);
var
i: integer;
Conn: TCustomDAConnection;
begin
if not Connecting then
for i := 0 to FList.Count - 1 do begin
if IsClass(TObject(FList[i]), TCustomDAConnection) then begin
Conn := TCustomDAConnection(FList[i]);
if not Conn.Pooling and not Conn.Options.DisconnectedMode then
Conn.Disconnect;
end;
end;
end;
procedure TCRSSHIOHandler.DoAuthenticationPrompt(Sender: TObject;
const Name, Instruction: string; const Prompts: TStringDynArray;
var Responses: TStringDynArray);
begin
if Length(Responses) > 0 then
Responses[0] := TScSSHClient(Sender).Password;
end;
procedure TCRSSHIOHandler.DoServerKeyValidate(Sender: TObject;
NewServerKey: TScKey; var Accept: Boolean);
var
HostKeyName: string;
Key: TScKey;
begin
if TScSSHClient(Sender).HostKeyName = '' then begin
HostKeyName := TScSSHClient(Sender).HostName + KEY_GUID;
Key := TScSSHClient(Sender).KeyStorage.Keys.FindKey(HostKeyName);
if Key = nil then begin
Key := TScKey.Create(nil);
try
Key.Assign(NewServerKey);
Key.KeyName := HostKeyName;
TScSSHClient(Sender).KeyStorage.Keys.Add(Key);
except
Key.Free;
raise;
end;
Accept := True;
end
else
Accept := Key.Equals(NewServerKey);
end;
end;
end.
|
{***************************************************************
*
* Project : UDPClient
* Unit Name: UDPClientMain
* Purpose : UDP demo - client project
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:44:24
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit UDPClientMain;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, IdWinsock, stdctrls,
{$ENDIF}
SysUtils, Classes, IdBaseComponent, IdAntiFreezeBase, IdAntiFreeze,
IdComponent, IdUDPBase, IdUDPClient, IdStack;
type
TUDPMainForm = class(TForm)
SourceGroupBox: TGroupBox;
HostNameLabel: TLabel;
HostAddressLabel: TLabel;
HostName: TLabel;
HostAddress: TLabel;
UDPAntiFreeze: TIdAntiFreeze;
PortLabel: TLabel;
Port: TLabel;
DestinationLabel: TLabel;
DestinationAddress: TLabel;
BufferSizeLabel: TLabel;
BufferSize: TLabel;
UDPMemo: TMemo;
SendButton: TButton;
UDPClient: TIdUDPClient;
procedure FormCreate(Sender: TObject);
procedure SendButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
UDPMainForm: TUDPMainForm;
implementation
const
HOSTNAMELENGTH = 80;
RECIEVETIMEOUT = 5000; // milliseconds
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TUDPMainForm.FormCreate(Sender: TObject);
begin
Randomize; // remove if you want reproducible results.
HostName.Caption := UDPClient.LocalName;
HostAddress.Caption := GStack.LocalAddress;
Port.Caption := IntToStr(UDPClient.Port);
DestinationAddress.Caption := UDPClient.Host;
BufferSize.Caption := IntToStr(UDPClient.BufferSize);
UDPClient.ReceiveTimeout := RECIEVETIMEOUT;
end;
procedure TUDPMainForm.SendButtonClick(Sender: TObject);
var
MessageID: Integer;
ThisMessage: String;
ReceivedString: String;
begin
MessageID := Random(MAXINT);
ThisMessage := 'Message: ' + IntToStr(MessageID);
UDPMemo.Lines.Add('Sending ' + ThisMessage);
UDPClient.Send(ThisMessage);
ReceivedString := UDPClient.ReceiveString();
if ReceivedString = '' then
UDPMemo.Lines.Add('No response received from the server after ' + IntToStr(UDPClient.ReceiveTimeout) + ' millseconds.')
else
UDPMemo.Lines.Add('Received: ' + ReceivedString)
end;
end.
|
unit Vawrgrid;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Grids;
type
TVAWrapGrid = class(TStringGrid)
private
{ Private declarations }
fHiddenCols: string;
fHiddenColMap: string[255];
procedure SetHiddenCols(Value:string);
protected
{ Protected declarations }
{ This DrawCell procedure wraps text in the grid cell }
procedure DrawCell(Col, Row : Longint; Rect : TRect; State : TGridDrawState); override ;
public
constructor Create(AOwner : TComponent); override ;
published
{ Published declarations }
property HiddenCols: string read fHiddenCols write SetHiddenCols;
end;
procedure Register;
implementation
constructor TVAWrapGrid.Create(AOwner : TComponent);
begin
{ Create a TStringGrid }
inherited Create(AOwner);
HiddenCols:='';
{change to bit map someday}
fHiddenColMap:='';
end;
procedure TVAWrapGrid.SetHiddenCols(value:string);
var
v,old:string;
j:integer;
procedure SetCol(val:string);
var
i:integer;
begin
i:=strtoint(val) + 1; {offset for 1 based string index}
if (i in [1..255]) then fHiddenColMap[i]:='1';
end;
begin
old := String(fHiddenColMap); {save oldmap image}
fHiddenCols:=Value;
fHiddenColMap:=''; {reset the map}
for j:=1 to 255 do
fHiddenColMap:=fHiddenColMap + '0';
while pos(',',value)>0 do
begin
v:=copy(value,1,pos(',',value)-1);
SetCol(v);
Delete(value,1,pos(',',value));
end;
if value <> '' then
begin
SetCol(value); {get the last piece}
if not (csDesigning in componentstate) then
invalidate;
end;
if old='' then exit;
if (old <> String(fHiddenColMap)) and (not (csDesigning in componentState)) then
begin
j:=pos('1',old);
while j > 0 do
begin
if fHiddenColMap[j]='0' then
if pred(j) < colcount then colwidths[pred(j)]:=defaultcolwidth;
old[j]:='0'; {get rid of hit}
j:=pos('1',old);
end;
end;
end;
{ This DrawCell procedure wraps text in the grid cell }
procedure TVAWrapGrid.DrawCell(Col,Row: Longint; Rect: TRect; State: TGridDrawState);
var
i, MaxRowHeight, CurrRowHeight, hgt, CellLen :integer;
CellValue :PChar;
begin
{don't display hidden cols}
if RowHeights[Row] = 0 then exit;
if (fHiddenColMap[succ(col)] = '1') and (not (csDesigning in componentstate)) then
{disappear the column}
begin
if colwidths[col] > 0 then colwidths[col] := 0;
exit;
end;
with Canvas do {not a hidden col}
begin
if colwidths[col]=0 then ColWidths[col] := defaultcolwidth;
{ Initialize the font to be the control's font }
Canvas.Font := Font;
Canvas.Font.Color := Font.Color;
{If this is a fixed cell, then use the fixed color }
if gdFixed in State then
begin
Pen.Color := FixedColor;
Brush.Color := FixedColor;
font.color := self.font.color;
end
{if highlighted cell}
else if (gdSelected in State) and
(not (gdFocused in State) or
([goDrawFocusSelected, goRowSelect] * Options <> [])) then
begin
Brush.Color := clHighlight;
Font.Color := clHighlightText;
end
{else, use the normal color }
else
begin
Pen.Color := Color;
Brush.Color := Color;
font.color := self.font.color;
end;
{Prepaint cell in cell color }
FillRect(rect);
end;
CellValue := PChar(cells[col,row]);
CellLen := strlen(CellValue);
{get cell size}
Drawtext(canvas.handle,CellValue,CellLen,rect,DT_LEFT or DT_WORdbreak or DT_CALCRECT or DT_NOPREFIX);
{Draw text in cell}
Drawtext(canvas.handle,CellValue,CellLen,rect,DT_LEFT or DT_WORdbreak or DT_NOPREFIX);
{adjust row heights up OR DOWN}
MaxRowHeight := DefaultRowHeight;
CurrRowHeight := RowHeights[row];
for i := pred(colcount) downto 0 do
begin
if (not (gdFixed in state)) then
begin
rect := cellrect(i,row);
hgt := Drawtext(canvas.handle,PChar(cells[i,row]),length(cells[i,row]),rect,DT_LEFT or
DT_WORdbreak or DT_CALCRECT or DT_NOPREFIX);
if hgt > MaxRowHeight then MaxRowHeight := hgt;
end;
end;
if MaxRowHeight <> CurrRowHeight then rowheights[row] := MaxRowHeight;
end;
procedure Register;
begin
{ You can change Samples to whichever part of the Component Palette you want
to install this component to }
RegisterComponents('CPRS', [TVAWrapGrid]);
end;
end.
|
unit pTaxBillNameAddress;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, DBCtrls, StdCtrls, ExtCtrls, Mask, DB, DBTables, Buttons,
Types, DBLookup, Wwtable, Wwdatsrc, wwdblook;
type
TfmTaxBillAddress = class(TForm)
Panel1: TPanel;
TitleLabel: TLabel;
YearLabel: TLabel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
ParcelDataSource: TDataSource;
ParcelTable: TTable;
Label9: TLabel;
Label10: TLabel;
InactiveLabel: TLabel;
OppositeYearParcelTable: TTable;
Label3: TLabel;
Label53: TLabel;
Label55: TLabel;
TotalAVLabel: TLabel;
LandAVLabel: TLabel;
SetFocusTimer: TTimer;
AssessmentYearControlTable: TTable;
OldParcelIDLabel: TLabel;
PartialAssessmentLabel: TLabel;
Panel3: TPanel;
SaveButton: TBitBtn;
CancelButton: TBitBtn;
CloseButton: TBitBtn;
Panel4: TPanel;
Label4: TLabel;
EditSBL: TMaskEdit;
Label6: TLabel;
EditLocation: TEdit;
Label12: TLabel;
Label5: TLabel;
EditName: TDBEdit;
EditLastChangeDate: TDBEdit;
Label13: TLabel;
EditLastChangeByName: TDBEdit;
GroupBox1: TGroupBox;
Label11: TLabel;
Label1: TLabel;
Label2: TLabel;
Label14: TLabel;
Label15: TLabel;
SwisLabel: TLabel;
Label17: TLabel;
Label7: TLabel;
Label28: TLabel;
edName1: TDBEdit;
EditName2: TDBEdit;
EditAddress: TDBEdit;
EditAddress2: TDBEdit;
EditStreet: TDBEdit;
EditCity: TDBEdit;
EditState: TDBEdit;
EditZip: TDBEdit;
EditZipPlus4: TDBEdit;
SwisCodeTable: TTable;
tbTaxBillAddress: TTable;
dsTaxBillAddress: TDataSource;
edDesignation: TDBEdit;
Label8: TLabel;
btnCopyAddress: TBitBtn;
Label16: TLabel;
DBEdit1: TDBEdit;
btnClearAddress: TBitBtn;
procedure SaveButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TaxBillAddressTableAfterEdit(DataSet: TDataset);
procedure TaxBillAdressTableAfterPost(DataSet: TDataset);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SetFocusTimerTimer(Sender: TObject);
procedure tbTaxBillAddressNewRecord(DataSet: TDataSet);
procedure btnCopyAddressClick(Sender: TObject);
procedure ParcelTableAfterEdit(DataSet: TDataSet);
procedure ParcelTableAfterPost(DataSet: TDataSet);
procedure tbTaxBillAddressBeforePost(DataSet: TDataSet);
procedure btnClearAddressClick(Sender: TObject);
procedure ParcelTableBeforePost(DataSet: TDataSet);
{override method of parent object so we can set parent and style of}
{this 'nested' forms}
protected
procedure CreateParams(var Params: TCreateParams); override;
private
{ private declarations }
public
{ public declarations }
UnitName : String; {For use with error dialog box.}
{These will be set in the ParcelTabForm.}
EditMode : Char; {A = Add; M = Modify; V = View}
TaxRollYr : String;
SwisSBLKey : String;
ProcessingType : Integer; {NextYear, ThisYear, History}
FieldTraceInformationList : TList;
FieldTraceInformationList_Parcel : TList;
{Have there been any changes?}
ParcelChanged : Boolean;
FormAccessRights : Integer; {Read only or read write, based on security level?}
{Values = raReadOnly, raReadWrite}
FormIsInitializing,
FormIsClosing : Boolean;
OrigVillageRelevy,
OrigSchoolRelevy : Extended;
{CHG10281997-1: Dual mode processing.}
OppositeProcessingType : Integer;
OppositeTaxYear : String;
OriginalFieldValues,
NewFieldValues : TStringList;
OriginalFieldValues_Parcel,
NewFieldValues_Parcel : TStringList;
Procedure InitializeForm;
Procedure SetFocusToFirstField;
end;
implementation
{$R *.DFM}
Uses Glblvars, PASUTILS, UTILEXSD, PASTypes, WinUtils, Utilitys,
GlblCnst, DataAccessUnit;
{===========================================================================}
Procedure TfmTaxBillAddress.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
WndParent := Application.Mainform.Handle;
Style := (Style or WS_Child) and not WS_Popup;
end;
end; {CreateParams}
{===========================================================================}
Procedure TfmTaxBillAddress.InitializeForm;
{This procedure opens the tables for this form and synchronizes
them to this parcel. Also, we set the title and year
labels.
Note that this code is in this seperate procedure rather
than any of the OnShow events so that we could have
complete control over when this procedure is run.
The problem with any of the OnShow events is that when
the form is created, they are called, but it is not possible to
have the SwisSBLKey, etc. set.
This way, we can call InitializeForm after we know that
the SwisSBLKey, etc. has been set.}
var
SBLRec : SBLRecord;
Quit, Found : Boolean;
I : Integer;
begin
FormIsInitializing := True;
FormIsClosing := False;
UnitName := 'PTaxBillNameAddress.pas';
ParcelChanged := False;
If (Deblank(SwisSBLKey) <> '')
then
begin
OriginalFieldValues := TStringList.Create;
NewFieldValues := TStringList.Create;
OriginalFieldValues_Parcel := TStringList.Create;
NewFieldValues_Parcel := TStringList.Create;
{This string lists will hold the labels and values of each field and will be used
to insert changes into the trace file.}
(* FieldValuesList := TStringList.Create;
FieldLabelsList := TStringList.Create;*)
FieldTraceInformationList := TList.Create;
FieldTraceInformationList_Parcel := TList.Create;
{If this is the history file, or they do not have read access,
then we want to set the files to read only.}
If not ModifyAccessAllowed(FormAccessRights)
then ParcelTable.ReadOnly := True;
{If this is inquire mode or the processing type is not the main type
(i.e. GlblTaxYearFlg), let's open it in readonly mode.}
If ((EditMode = 'V') or
(ProcessingType <> DetermineProcessingType(GlblTaxYearFlg)))
then ParcelTable.ReadOnly := True;
If GlblNameAddressUpdateOnly
then ParcelTable.ReadOnly := False;
OpenTablesForForm(Self, ProcessingType);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
Found := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode',
'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[TaxRollYr, SwisCode, Section,
SubSection, Block, Lot, Sublot,
Suffix]);
If not Found
then SystemSupport(003, ParcelTable, 'Error finding key in parcel table.', UnitName, GlblErrorDlgBox);
{Set the location label.}
EditLocation.Text := GetLegalAddressFromTable(ParcelTable);
{Now set the year label.}
SetTaxYearLabelForProcessingType(YearLabel, ProcessingType);
{Also, set the title label to reflect the mode.
We will then center it in the panel.}
{FXX12151997-1: Make sure that the tital does not overlap the
assessed values.}
TitleLabel.Caption := 'Tax Bill Address';
(* case EditMode of
'A' : TitleLabel.Caption := 'Parcel Add';
'M' : TitleLabel.Caption := 'Parcel Modify';
'V' : TitleLabel.Caption := 'Parcel View';
end; {case EditMode of} *)
TitleLabel.Left := (Panel1.Width - TitleLabel.Width) DIV 2;
{Now, for some reason the table is marked as
Modified after we look it up (in modify mode).
So, we will cancel the modify and set it in
the proper mode.}
If ((not ParcelTable.ReadOnly) and
ParcelTable.Modified and
(EditMode = 'M'))
then
begin
ParcelTable.Edit;
ParcelTable.Cancel;
end;
If ParcelTable.ReadOnly
then
begin
SaveButton.Visible := False;
CancelButton.Visible := False;
btnCopyAddress.Visible := False;
end;
EditSBL.Text := ConvertSwisSBLToDashDot(SwisSBLKey);
If (ParcelTable.FieldByName('ActiveFlag').Text = InactiveParcelFlag)
then InactiveLabel.Visible := True;
{CHG10091997-1: Should zeroes be blanks or '0'?}
SetDisplayFormatForCurrencyFields(Self, False);
{CHG10281997-1: Dual mode processing.
Note that there is only edit for parcel pg2,
no delete or insert.}
(* If (ProcessingType = ThisYear)
then OppositeProcessingType := NextYear
else OppositeProcessingType := ThisYear;
OppositeTaxYear := GetTaxRollYearForProcessingType(OppositeProcessingType);
OpenTableForProcessingType(OppositeYearParcelTable,
ParcelTableName,
OppositeProcessingType, Quit); *)
{FXX11131997-7: Refresh the drop downs when come in.}
(*RefreshDropdownsAndLabels(Self, ParcelTable,
DescriptionIndexedLookups); *)
{FXX03031998-2: Set focus to the first field. Note that we must
do this on a timer so that the form is showing
by the time we try to set focus. Otherwise,
we get an error trying to set focus in an invisible
window.}
SetFocusTimer.Enabled := True;
end; {If (Deblank(SwisSBLKey) <> '')}
FormIsInitializing := False;
If not _Locate(tbTaxBillAddress, [TaxRollYr, SwisSBLKey], '', [])
then tbTaxBillAddress.Insert;
{CHG11162004-7(2.8.0.21): Option to make the close button locate.}
If GlblCloseButtonIsLocate
then MakeCloseButtonLocate(CloseButton);
end; {InitializeForm}
{===========================================================}
Procedure TfmTaxBillAddress.SetFocusToFirstField;
{FXX03031998-2: Set focus to the first field after insert, any post,
and upon coming into the form.}
begin
with edName1 do
begin
SetFocus;
SelectAll;
end;
end; {SetFocusToFirstField}
{===========================================================}
Procedure TfmTaxBillAddress.SetFocusTimerTimer(Sender: TObject);
{FXX03031998-2: Set focus to the first field. Note that we must
do this on a timer so that the form is showing
by the time we try to set focus. Otherwise,
we get an error trying to set focus in an invisible
window.}
begin
SetFocusTimer.Enabled := False;
SetFocusToFirstField;
end; {SetFocusTimerTimer}
{=====================================================================================}
Procedure TfmTaxBillAddress.btnCopyAddressClick(Sender: TObject);
begin
with tbTaxBillAddress do
try
If (State = dsBrowse)
then Edit;
FieldByName('Name1').AsString := ParcelTable.FieldByName('Name1').AsString;
FieldByName('Name2').AsString := ParcelTable.FieldByName('Name2').AsString;
FieldByName('Address1').AsString := ParcelTable.FieldByName('Address1').AsString;
FieldByName('Address2').AsString := ParcelTable.FieldByName('Address2').AsString;
FieldByName('Street').AsString := ParcelTable.FieldByName('Street').AsString;
FieldByName('City').AsString := ParcelTable.FieldByName('City').AsString;
FieldByName('State').AsString := ParcelTable.FieldByName('State').AsString;
FieldByName('Zip').AsString := ParcelTable.FieldByName('Zip').AsString;
FieldByName('ZipPlus4').AsString := ParcelTable.FieldByName('ZipPlus4').AsString;
except
end;
end; {btnCopyAddressClick}
{=====================================================================================}
Procedure TfmTaxBillAddress.btnClearAddressClick(Sender: TObject);
begin
with tbTaxBillAddress do
try
If (State = dsBrowse)
then Edit;
FieldByName('Name1').AsString := '';
FieldByName('Name2').AsString := '';
FieldByName('Address1').AsString := '';
FieldByName('Address2').AsString := '';
FieldByName('Street').AsString := '';
FieldByName('City').AsString := '';
FieldByName('State').AsString := '';
FieldByName('Zip').AsString := '';
FieldByName('ZipPlus4').AsString := '';
Post;
except
end;
end; {btnClearAddressClick}
{======================================================================}
Procedure TfmTaxBillAddress.tbTaxBillAddressNewRecord(DataSet: TDataSet);
begin
with tbTaxBillAddress do
try
FieldByName('TaxRollYr').AsString := TaxRollYr;
FieldByName('SwisSBLKey').AsString := SwisSBLKey;
except
end;
end; {tbTaxBillAddressNewRecord}
{=====================================================================================}
Procedure TfmTaxBillAddress.TaxBillAddressTableAfterEdit(DataSet: TDataset);
{We will initialize the field values for this record. This will be used in the trace
logic. In the AfterPost event, we will pass the values into the Record Changes procedure
in PASUTILS and a record will be inserted into the trace file if any differences exist.
Note that this is a shared event handler with the AfterInsert event.
Also note that we can not pass in the form variable (i.e. BaseParcelPg1Form) since
it is not initialized. Instead, we have to pass in the Self var.}
var
I : Integer;
begin
If not FormIsInitializing
then
begin
CreateFieldValuesAndLabels(Self, tbTaxBillAddress, FieldTraceInformationList);
OriginalFieldValues.Clear;
with tbTaxBillAddress do
For I := 0 to (FieldCount - 1) do
OriginalFieldValues.Add(Fields[I].Text);
end; {If not FormIsInitializing}
end; {TaxBillAddressTableAfterEdit}
{=====================================================================================}
Procedure TfmTaxBillAddress.tbTaxBillAddressBeforePost(DataSet: TDataSet);
begin
with tbTaxBillAddress do
try
FieldByName('LastChangeUser').AsString := GlblUserName;
FieldByName('LastChangeDate').AsString := DateToStr(Date);
except
end;
If (ParcelTable.State = dsBrowse)
then ParcelTable.Edit;
ParcelTable.Post;
end; {tbTaxBillAddressBeforePost}
{=====================================================================================}
Procedure TfmTaxBillAddress.TaxBillAdressTableAfterPost(DataSet: TDataset);
{Now let's call RecordChanges which will insert a record into the trace file if any differences
exist.
Note that RecordChanges returns an integer saying how many changes there
were. If this number is greater than 0, then we will update the
name and date changed fields of the parcel record.}
var
Quit, Found : Boolean;
SBLRec : SBLRecord;
ChangedFields : TStringList;
NewSchoolRelevy, NewVillageRelevy : Extended;
TempParcelTable : TTable;
NumChanges, I : Integer;
FieldName : String;
begin
{FXX11101997-3: Pass the screen name into RecordChanges so
the screen names are more readable.}
{FXX12301999-3: Make sure to always carry changes forward if they want them.}
NumChanges := RecordChanges(Self, 'Tax Bill Address', tbTaxBillAddress, SwisSBLKey,
FieldTraceInformationList);
If (NumChanges > 0)
then ParcelChanged := True;
If GlblModifyBothYears
then
begin
{FXX01202000-2: Copy information forward for parcel record on a field
by field basis only.}
NewFieldValues.Clear;
with tbTaxBillAddress do
For I := 0 to (FieldCount - 1) do
NewFieldValues.Add(Fields[I].Text);
{Now go through the list and compare on a field by field basis
any changes.}
ChangedFields := TStringList.Create;
For I := 0 to (OriginalFieldValues.Count - 1) do
If (NewFieldValues[I] <> OriginalFieldValues[I])
then ChangedFields.Add(ParcelTable.Fields[I].FieldName);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
(* with SBLRec do
Found := FindKeyOld(OppositeYearParcelTable,
['TaxRollYr', 'SwisCode',
'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[OppositeTaxYear,
SwisCode, Section, SubSection,
Block, Lot, Sublot, Suffix]);
If Found
then OppositeYearParcelTable.Edit;
CreateFieldValuesAndLabels(Self, OppositeYearParcelTable,
FieldTraceInformationList);
{Copy the fields from the main table to the new table, but make
sure that we do not copy the tax roll year.}
{FXX06222001-1: Don't move changes forward if NY parcel is inactive.}
{FXX01172002-1: The code said the information should only move forward if it WAS inactive.}
If (Found and
(OppositeYearParcelTable.FieldByName('ActiveFlag').Text <> InactiveParcelFlag))
then
begin
{Never copy the school and village relevies forward.}
{FXX03101999-1: Also, don't copy the arrears flag forward.}
{FXX01202000-2: Copy information forward for parcel record on a field
by field basis only.}
For I := 0 to (ChangedFields.Count - 1) do
begin
FieldName := ChangedFields[I];
OppositeYearParcelTable.FieldByName(FieldName).Text :=
ParcelTable.FieldByName(FieldName).Text;
end; {For I := 0 to (ChangedFields.Count - 1) do}
If (RecordChanges(Self, 'Tax Bill Address',
OppositeYearParcelTable, SwisSBLKey,
FieldTraceInformationList) > 0)
then
with OppositeYearParcelTable do
begin
end;
try
OppositeYearParcelTable.Post;
except
SystemSupport(050, OppositeYearParcelTable,
'Error posting opposite year record.', UnitName,
GlblErrorDlgBox);
end;
end; {If Found} *)
ChangedFields.Free;
end; {If GlblModifyBothYears}
{FXX03021998-2: Set focus back to the first field after post,.}
SetFocusToFirstField;
end; {TaxBillAdressTableAfterPost}
{======================================================================}
Procedure TfmTaxBillAddress.ParcelTableAfterEdit(DataSet: TDataSet);
var
I : Integer;
begin
If not FormIsInitializing
then
begin
CreateFieldValuesAndLabels(Self, ParcelTable, FieldTraceInformationList_Parcel);
OriginalFieldValues_Parcel.Clear;
with ParcelTable do
For I := 0 to (FieldCount - 1) do
OriginalFieldValues_Parcel.Add(Fields[I].Text);
end; {If not FormIsInitializing}
end; {ParcelTableAfterEdit}
{===========================================================================}
Procedure TfmTaxBillAddress.ParcelTableBeforePost(DataSet: TDataSet);
begin
with ParcelTable do
try
FieldByName('LastChangeUser').AsString := GlblUserName;
FieldByName('LastChangeDate').AsString := DateToStr(Date);
except
end;
end; {ParcelTableBeforePost}
{===========================================================================}
Procedure TfmTaxBillAddress.ParcelTableAfterPost(DataSet: TDataSet);
var
Quit, Found : Boolean;
SBLRec : SBLRecord;
ChangedFields : TStringList;
NewSchoolRelevy, NewVillageRelevy : Extended;
TempParcelTable : TTable;
NumChanges, I : Integer;
FieldName : String;
begin
NumChanges := RecordChanges(Self, 'Base Information', ParcelTable, SwisSBLKey,
FieldTraceInformationList_Parcel);
If (NumChanges > 0)
then ParcelChanged := True;
If GlblModifyBothYears
then
begin
{FXX01202000-2: Copy information forward for parcel record on a field
by field basis only.}
NewFieldValues.Clear;
with ParcelTable do
For I := 0 to (FieldCount - 1) do
NewFieldValues_Parcel.Add(Fields[I].Text);
{Now go through the list and compare on a field by field basis
any changes.}
ChangedFields := TStringList.Create;
For I := 0 to (OriginalFieldValues.Count - 1) do
If (NewFieldValues_Parcel[I] <> OriginalFieldValues_Parcel[I])
then ChangedFields.Add(ParcelTable.Fields[I].FieldName);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
(* with SBLRec do
Found := FindKeyOld(OppositeYearParcelTable,
['TaxRollYr', 'SwisCode',
'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[OppositeTaxYear,
SwisCode, Section, SubSection,
Block, Lot, Sublot, Suffix]);
If Found
then OppositeYearParcelTable.Edit;
CreateFieldValuesAndLabels(Self, OppositeYearParcelTable,
FieldTraceInformationList);
{Copy the fields from the main table to the new table, but make
sure that we do not copy the tax roll year.}
{FXX06222001-1: Don't move changes forward if NY parcel is inactive.}
{FXX01172002-1: The code said the information should only move forward if it WAS inactive.}
If (Found and
(OppositeYearParcelTable.FieldByName('ActiveFlag').Text <> InactiveParcelFlag))
then
begin
{Never copy the school and village relevies forward.}
{FXX03101999-1: Also, don't copy the arrears flag forward.}
{FXX01202000-2: Copy information forward for parcel record on a field
by field basis only.}
For I := 0 to (ChangedFields.Count - 1) do
begin
FieldName := ChangedFields[I];
OppositeYearParcelTable.FieldByName(FieldName).Text :=
ParcelTable.FieldByName(FieldName).Text;
end; {For I := 0 to (ChangedFields.Count - 1) do}
If (RecordChanges(Self, 'Tax Bill Address',
OppositeYearParcelTable, SwisSBLKey,
FieldTraceInformationList) > 0)
then
with OppositeYearParcelTable do
begin
end;
try
OppositeYearParcelTable.Post;
except
SystemSupport(050, OppositeYearParcelTable,
'Error posting opposite year record.', UnitName,
GlblErrorDlgBox);
end;
end; {If Found} *)
ChangedFields.Free;
end; {If GlblModifyBothYears}
end; {ParcelTableAfterPost}
{===========================================================================}
Procedure TfmTaxBillAddress.SaveButtonClick(Sender: TObject);
{FXX10291997-2: Set the last change name and date in before post, not
on save click since can save without clicking save.}
begin
If (tbTaxBillAddress.Modified and {Table is modified.}
(tbTaxBillAddress.State <> dsBrowse) and
((not GlblAskSave) or {We should not confirm a save or...}
(GlblAskSave and {We should confirm a save and...}
(MessageDlg('Do you want to save this tax bill address change?', mtConfirmation,
[mbYes, mbCancel], 0) = mrYes)))) {They want to save it.}
then tbTaxBillAddress.Post;
If (ParcelTable.State = dsEdit)
then ParcelTable.Post;
end; {SaveButtonClick}
{===========================================================================}
Procedure TfmTaxBillAddress.CancelButtonClick(Sender: TObject);
begin
If (tbTaxBillAddress.Modified and
(MessageDlg('Warning! You will lose all changes.' + #13 +
'Cancel anyway?', mtWarning, [mbYes, mbNo], 0) = mrYes))
then tbTaxBillAddress.Cancel;
end; {CancelButtonClick}
{===========================================================================}
Procedure TfmTaxBillAddress.CloseButtonClick(Sender: TObject);
{Note that the close button is a close for the whole
parcel maintenance.}
{To close the whole parcel maintenance, we will once again use
the base popup menu. We will simulate a click on the
"Exit Parcel Maintenance" of the BasePopupMenu which will
then call the Close of ParcelTabForm. See the locate button
click above for more information on how this works.}
var
I : Integer;
CanClose : Boolean;
begin
{Search for the name of the menu item that has "Exit"
in it, and click it.}
For I := 0 to (PopupMenu.Items.Count - 1) do
If (Pos('Exit', PopupMenu.Items[I].Name) <> 0)
then
begin
{FXX06141999-5: Ask if person wants to save before exiting
to locate dialog.}
FormCloseQuery(Sender, CanClose);
If CanClose
then PopupMenu.Items[I].Click;
end; {If (Pos('Exit', ...}
end; {CloseButtonClick}
{===========================================================================}
Procedure TfmTaxBillAddress.FormCloseQuery( Sender: TObject;
var CanClose: Boolean);
var
ReturnCode : Integer;
begin
GlblParcelPageCloseCancelled := False;
CanClose := True;
{First see if anything needs to be saved. In order to
determine if there are any changes, we need to sychronize
the fields with what is in the DB edit boxes. To do this,
we call the UpdateRecord. Then, if there are any changes,
the Modified flag will be set to True.}
If (tbTaxBillAddress.State in [dsInsert, dsEdit])
then tbTaxBillAddress.UpdateRecord;
{Now, if they are closing the table, let's see if they want to
save any changes. However, we won't check this if
they are in inquire mode. Note that sometimes a record can be marked even
if there were no changes if a person clicks on a drop down box (even without changing
the value). So, since we are recording field values before any changes, we
will compare them to now and if there are no changes, we will cancel this
edit or insert.}
{FXX05151998-3: Don't ask save on close form if don't want to see save.}
If (((not tbTaxBillAddress.ReadOnly) and
(tbTaxBillAddress.State in [dsEdit, dsInsert]) and
tbTaxBillAddress.Modified) or
((not ParcelTable.ReadOnly) and
(ParcelTable.State in [dsEdit, dsInsert]) and
ParcelTable.Modified))
then
If ((NumRecordChanges(Self, tbTaxBillAddress, FieldTraceInformationList) = 0) and
(NumRecordChanges(Self, ParcelTable, FieldTraceInformationList_Parcel) = 0))
then
begin
try
tbTaxBillAddress.Cancel;
ParcelTable.Cancel;
except
end;
end
else
If GlblAskSave
then
begin
ReturnCode := MessageDlg('Do you want to save your tax bill address changes?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0);
case ReturnCode of
idYes :
begin
tbTaxBillAddress.Post;
If (ParcelTable.State = dsEdit)
then ParcelTable.Post;
end;
idNo :
begin
tbTaxBillAddress.Cancel;
If (ParcelTable.State = dsEdit)
then ParcelTable.Cancel;
end;
idCancel : begin
GlblParcelPageCloseCancelled := True;
CanClose := False;
end;
end; {case ReturnCode of}
end
else tbTaxBillAddress.Post;
end; {FormCloseQuery}
{===========================================================================}
Procedure TfmTaxBillAddress.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
FormIsClosing := True;
CloseTablesForForm(Self);
{Free up the trace lists.}
(* FieldValuesList.Free;
FieldLabelsList.Free; *)
FreeTList(FieldTraceInformationList, SizeOf(FieldTraceInformationRecord));
OriginalFieldValues.Free;
NewFieldValues.Free;
FreeTList(FieldTraceInformationList_Parcel, SizeOf(FieldTraceInformationRecord));
OriginalFieldValues_Parcel.Free;
NewFieldValues_Parcel.Free;
Action := caFree;
end; {FormClose}
end.
|
unit AppGlobals;
interface
uses
StdCtrls;
const
APP_BETA_BUILD = -1;
STD_BUFFER_SIZE = 1024*1024*1; // 1 MB
resourcestring
EXTN_IMG_NORMAL = 'img';
EXTN_IMG_COMPRESSED = 'gz';
DOT_EXTN_IMG_COMPRESSED = '.gz';
// Open/Save file filters...
FILE_FILTER_FLT_IMAGES = 'All image files (*.img, *.gz)|*.img;*.gz|Uncompressed image files (*.img)|*.img|Compressed image files (*.gz)|*.gz|All files|*.*';
const
FILE_FILTER_DFLT_IDX_ALL = 1;
FILE_FILTER_DFLT_IDX_UNCOMPRESSED = 2;
FILE_FILTER_DFLT_IDX_COMPRESSED = 3;
// Default filename to be used for compressed file stored within .gz
// Note: This is an arbitary filename
COMPRESSED_FILE = 'image.img';
procedure PopulateRemovableDrives(cbDrive: TComboBox);
implementation
uses
{$WARNINGS OFF} // Useless warning about platform - don't care about it
FileCtrl,
{$WARNINGS ON}
Windows,
SDUGeneral;
procedure PopulateRemovableDrives(cbDrive: TComboBox);
var
DriveType: TDriveType;
drive: char;
item: string;
volTitle: string;
partSize: ULONGLONG;
strSize: string;
begin
cbDrive.Items.Clear();
// Skip "A" and "B"; typically floppy drives
// Note: *Uppercase* letters
for drive:='C' to 'Z' do
begin
DriveType := TDriveType(GetDriveType(PChar(drive + ':\')));
if (
(DriveType = dtFloppy) or
(DriveType = dtUnknown)
) then
begin
item := drive+':';
volTitle := SDUVolumeID(drive);
partSize := SDUGetPartitionSize(drive);
if (partSize >= 0) then
begin
strSize := SDUFormatUnits(
partSize,
['bytes', 'KB', 'MB', 'GB', 'TB'],
1024,
0
);
item := item + ' ['+strSize+']';
end;
if (volTitle <> '') then
begin
item := item+' '+volTitle;
end;
cbDrive.Items.Add(item);
end;
end;
end;
END.
|
{ Модуль с описанием узла дерева }
unit UNode;
interface
uses
ComCtrls, SysUtils, Math;
const
{ Минимально возможный элемент }
MinElem = 0;
{ Максимально возможный элемент }
MaxElem = 100;
type
{ Тип Элемент дерева }
TElem = MinElem..MaxElem;
{ Тип "Указатель на узел дерева"}
TPtr = ^TNode;
{ Класс Узел дерева }
TNode = class
private
{ Информационная часть }
FInf: TElem;
{ Указатели на левое и правое поддеревья }
FLeft, FRight: TNode;
public
{ Создание узла дерева }
constructor Create(el : TElem = MinElem);
{ Разрушение узла дерева }
destructor Destroy; override;
{ Построить рандомно }
constructor BuildRandom(n: integer);
{ Обход дерева }
procedure View(TV:TTreeView; ParentNode: TTreeNode);
// Поиск элемента el в дереве
function CountNumber(el: TElem): integer;
property Info : Telem read FInf;
property Left : TNode read FLeft write FLeft;
property Right : TNode read FRight write FRight;
end;
implementation
{ Создание узла дерева }
constructor TNode.Create(el:TElem = MinElem);
begin
inherited Create;
FInf:= el;
FLeft:= nil;
FRight:= nil;
end;
{ Разрушение узла дерева }
destructor TNode.Destroy;
begin
FreeAndNil(FLeft);
FreeAndNil(FRight);
end;
{ Построить рандомно }
constructor TNode.BuildRandom(n: integer);
var
nl: integer;
begin
Create(Random(10));
n:= n - 1;
if n>0 then
begin
nl:= Random(n+1);
if nl>0 then
FLeft:= TNode.BuildRandom(nl);
nl:=n - nl;
if nl>0 then
FRight:= TNode.BuildRandom(nl);
end;
end;
{ Обход дерева }
procedure TNode.View(TV: TTreeView; ParentNode: TTreeNode);
var node: TTreeNode;
begin
if Self = nil then
TV.Items.AddChild(ParentNode, 'x')
else
begin
node:= TV.Items.AddChild(ParentNode, IntToStr(FInf));
if (FLeft<>nil) or(FRight<>nil) then
begin
FLeft.View(TV, node);
FRight.View(TV, node);
end;
end;
end;
// Поиск элемента el в дереве
function TNode.CountNumber(el: TElem): integer;
begin
Result:=ord(self.FInf = el);
if Fleft<>nil then
Result:=Result+FLeft.CountNumber(el);
if Fright<>nil then
Result:=Result+FRight.CountNumber(el);
end;
end.
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls,
Grids, ShellCtrls, ListViewFilterEdit, JvTabBar, JvPageList,
JvTabBarXPPainter;
type
{ TMainForm }
TMainForm = class(TForm)
cbCloseButton: TCheckBox;
cbAllowTabMoving: TCheckBox;
cbTabHotTracking: TCheckBox;
cmbPainter: TComboBox;
cmbOrientation: TComboBox;
Image1: TImage;
ImageList1: TImageList;
JvModernTabBarPainter1: TJvModernTabBarPainter;
JvPageList1: TJvPageList;
JvStandardPage1: TJvStandardPage;
JvStandardPage2: TJvStandardPage;
JvStandardPage3: TJvStandardPage;
JvStandardPage4: TJvStandardPage;
JvTabBar1: TJvTabBar;
JvTabBarXPPainter1: TJvTabBarXPPainter;
lblPainter: TLabel;
lblOrientation: TLabel;
Memo1: TMemo;
Panel1: TPanel;
ShellListView1: TShellListView;
ShellTreeView1: TShellTreeView;
Splitter1: TSplitter;
StringGrid1: TStringGrid;
procedure cbCloseButtonChange(Sender: TObject);
procedure cbAllowTabMovingChange(Sender: TObject);
procedure cbTabHotTrackingChange(Sender: TObject);
procedure cmbPainterChange(Sender: TObject);
procedure cmbOrientationChange(Sender: TObject);
procedure JvTabBar1TabCloseQuery(Sender: TObject; Item: TJvTabBarItem;
var CanClose: Boolean);
private
public
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.cbCloseButtonChange(Sender: TObject);
begin
JvTabBar1.CloseButton := cbCloseButton.Checked;
end;
procedure TMainForm.cbTabHotTrackingChange(Sender: TObject);
begin
JvTabBar1.HotTracking := cbTabHotTracking.Checked;
end;
procedure TMainForm.cbAllowTabMovingChange(Sender: TObject);
begin
JvTabBar1.AllowTabMoving := cbAllowTabMoving.Checked;
end;
procedure TMainForm.cmbPainterChange(Sender: TObject);
begin
case cmbPainter.ItemIndex of
0: JvTabBar1.Painter := JvModernTabBarPainter1;
1: JvTabBar1.Painter := JvTabBarXPPainter1;
end;
end;
procedure TMainForm.JvTabBar1TabCloseQuery(Sender: TObject;
Item: TJvTabBarItem; var CanClose: Boolean);
begin
CanClose := MessageDlg('Do you really want to close tab ' + Item.Caption + '?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
procedure TMainForm.cmbOrientationChange(Sender: TObject);
begin
case cmbOrientation.ItemIndex of
0: begin
JvTabBar1.Orientation := toTop;
JvTabBar1.Align := alTop;
end;
1: begin
JvTabBar1.Orientation := toBottom;
JvTabBar1.Align := alBottom;
end;
end;
end;
end.
|
unit BrickCamp.Repositories.IAnswer;
interface
uses
System.JSON,
BrickCamp.Model.TAnswer;
type
IAnswerRepository = interface(IInterface)
['{A8CEDDFF-9337-4317-9864-D6FE771937B4}']
function GetOne(const Id: Integer): TAnswer;
function GetList: TJSONArray;
procedure Insert(const Answer: TAnswer);
procedure Update(const Answer: TAnswer);
procedure Delete(const Id: Integer);
function GetListByQuestionId(const ProductId: Integer): TJSONArray;
end;
implementation
end.
|
unit form_Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,
form_BackupRestore;
type
TfrmMain = class(TForm)
pbBackup: TButton;
pbRestore: TButton;
pbSecDelete: TButton;
pbVerify: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
pbAdvanced: TButton;
Label6: TLabel;
pnlPanel1: TPanel;
pbClose: TButton;
pbAbout: TButton;
procedure pbVerifyClick(Sender: TObject);
procedure pbSecDeleteClick(Sender: TObject);
procedure pbRestoreClick(Sender: TObject);
procedure pbBackupClick(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbAdvancedClick(Sender: TObject);
procedure pbAboutClick(Sender: TObject);
private
procedure DoBackupRestore(backupRestore: TBackupRestoreDlgType);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
About_U,
form_AdvancedCopy, form_SecureErase, form_VerifyCapacity;
procedure TfrmMain.FormShow(Sender: TObject);
begin
self.caption := Application.Title;
pnlPanel1.Caption := '';
pnlPanel1.BevelInner := bvLowered;
pnlPanel1.BevelOuter := bvNone;
end;
procedure TfrmMain.pbAboutClick(Sender: TObject);
begin
ShowAboutDialog();
end;
procedure TfrmMain.pbAdvancedClick(Sender: TObject);
var
dlg: Tfrm_AdvancedCopy;
begin
dlg:= Tfrm_AdvancedCopy.Create(nil);
try
dlg.ShowModal();
finally
dlg.Free();
end;
end;
procedure TfrmMain.pbBackupClick(Sender: TObject);
begin
DoBackupRestore(opBackup);
end;
procedure TfrmMain.pbRestoreClick(Sender: TObject);
begin
DoBackupRestore(opRestore);
end;
procedure TfrmMain.pbSecDeleteClick(Sender: TObject);
var
dlg: TfrmSecureErase;
begin
dlg:= TfrmSecureErase.Create(nil);
try
dlg.ShowModal();
finally
dlg.Free();
end;
end;
procedure TfrmMain.pbVerifyClick(Sender: TObject);
var
dlg: TfrmVerifyCapacity;
begin
dlg:= TfrmVerifyCapacity.Create(nil);
try
dlg.ShowModal();
finally
dlg.Free();
end;
end;
procedure TfrmMain.DoBackupRestore(backupRestore: TBackupRestoreDlgType);
var
dlg: TfrmBackupRestore;
begin
dlg:= TfrmBackupRestore.Create(nil);
try
dlg.DlgType := backupRestore;
dlg.ShowModal();
finally
dlg.Free();
end;
end;
procedure TfrmMain.pbCloseClick(Sender: TObject);
begin
Close();
end;
END.
|
unit VCLClientMainForm;
interface
{$POINTERMATH ON}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.FileCtrl, Vcl.Grids,
DateUtils,IOUtils,Registry,
tgputtylib,tgputtysftp, Vcl.ComCtrls;
type
TVCLSFTPClientDemoForm = class(TForm)
DirectoryListBox1: TDirectoryListBox;
DriveComboBox1: TDriveComboBox;
FileListBox1: TFileListBox;
Label1: TLabel;
Label2: TLabel;
edURL: TEdit;
Label3: TLabel;
edPort: TEdit;
Label4: TLabel;
edUserName: TEdit;
Label5: TLabel;
edPassword: TEdit;
Label6: TLabel;
edFolderPath: TEdit;
Label7: TLabel;
sgRemoteFiles: TStringGrid;
Label8: TLabel;
btConnect: TButton;
btDisconnect: TButton;
Label9: TLabel;
cbVerbose: TCheckBox;
memLog: TMemo;
btUpload: TButton;
btDownload: TButton;
cbSavePassword: TCheckBox;
ProgressBar1: TProgressBar;
btDeleteLocal: TButton;
btDeleteRemote: TButton;
btMkDir: TButton;
btRemoveDir: TButton;
btMove: TButton;
FileOpenDialog1: TFileOpenDialog;
edKeyFile: TEdit;
Label10: TLabel;
btnSelectKeyFile: TButton;
procedure btConnectClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
function ListingCallback(const names:Pfxp_names):Boolean;
procedure MessageCallback(const Msg:AnsiString;const isstderr:Boolean);
function ProgressCallback(const bytescopied:Int64;const isupload:Boolean):Boolean;
function GetInputCallback(var cancel:Boolean):AnsiString;
function VerifyHostKeyCallback(const host:PAnsiChar;const port:Integer;const fingerprint:PAnsiChar;const verificationstatus:Integer;var storehostkey:Boolean):Boolean;
procedure btDisconnectClick(Sender: TObject);
procedure sgRemoteFilesDblClick(Sender: TObject);
procedure btDownloadClick(Sender: TObject);
procedure btUploadClick(Sender: TObject);
procedure edFolderPathExit(Sender: TObject);
procedure btDeleteLocalClick(Sender: TObject);
procedure btDeleteRemoteClick(Sender: TObject);
procedure DirectoryListBox1Change(Sender: TObject);
procedure btMkDirClick(Sender: TObject);
procedure btRemoveDirClick(Sender: TObject);
procedure btMoveClick(Sender: TObject);
procedure btnSelectKeyFileClick(Sender: TObject);
procedure cbVerboseClick(Sender: TObject);
private
{ Private declarations }
PSFTP:TTGPuttySFTP;
FTotalToCopy:Int64;
FInLoadSettings:Boolean;
procedure SaveSettings;
procedure LoadSettings;
procedure GetListing;
public
{ Public declarations }
end;
var
VCLSFTPClientDemoForm: TVCLSFTPClientDemoForm;
implementation
{$R *.dfm}
procedure TVCLSFTPClientDemoForm.btConnectClick(Sender: TObject);
begin
SaveSettings;
with PSFTP do begin
HostName:=Utf8Encode(edURL.Text);
UserName:=Utf8Encode(edUserName.Text);
if edKeyFile.Text='' then
Password:=Utf8Encode(edPassword.Text)
else begin
Keyfile:=Utf8Encode(edKeyFile.Text);
KeyPassword:=Utf8Encode(edPassword.Text);
end;
Port:=StrToIntDef(edPort.Text,22);
Connect;
if edFolderPath.Text<>'' then
ChangeDir(Utf8Encode(edFolderPath.Text));
edFolderPath.Text:=Utf8ToString(WorkDir);
end;
GetListing;
end;
procedure TVCLSFTPClientDemoForm.btDeleteLocalClick(Sender: TObject);
var i,count:Integer;
APath:string;
begin
count:=0;
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then
Inc(count);
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' file locally (left side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then begin
APath:=DirectoryListBox1.Directory+PathDelim+FileListBox1.Items[i];
DeleteFile(APath);
end;
FileListBox1.Update;
end;
end;
procedure TVCLSFTPClientDemoForm.btDisconnectClick(Sender: TObject);
begin
PSFTP.Disconnect;
sgRemoteFiles.RowCount:=0;
sgRemoteFiles.ColCount:=0;
end;
procedure TVCLSFTPClientDemoForm.btDownloadClick(Sender: TObject);
var i:Integer;
DownloadStream:TStream;
APath:UnicodeString;
begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do begin
if sgRemoteFiles.Cells[2,i]<>'<dir>' then begin
APath:=DirectoryListBox1.Directory+PathDelim+sgRemoteFiles.Cells[0,i];
DownloadStream:=TFileStream.Create(APath,fmCreate);
try
FTotalToCopy:=StrToInt64Def(sgRemoteFiles.Cells[2,i],0);
ProgressBar1.Min:=0;
ProgressBar1.Max:=FTotalToCopy div 1024;
ProgressBar1.Position:=0;
ProgressBar1.Visible:=true;
Application.ProcessMessages;
PSFTP.DownloadStream(Utf8Encode(sgRemoteFiles.Cells[0,i]),
DownloadStream,
false);
FileListBox1.Update;
finally
ProgressBar1.Visible:=false;
FreeAndNil(DownloadStream);
end;
end;
end;
end;
procedure TVCLSFTPClientDemoForm.btMkDirClick(Sender: TObject);
var AName:string;
begin
AName:=InputBox('Make Directory','Enter new Directory Name:','');
if AName<>'' then begin
PSFTP.MakeDir(Utf8Encode(AName));
GetListing;
end;
end;
procedure TVCLSFTPClientDemoForm.btMoveClick(Sender: TObject);
var count,i:Integer;
AName:string;
begin
AName:=InputBox('Renaem / Move','Enter new name and/or destination directory:','');
if AName<>'' then begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm moving '+IntToStr(count)+' item(s) remotely (right side)'),
'Confirm Moving',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]<>'<dir>' then
PSFTP.Move(Utf8Encode(sgRemoteFiles.Cells[0,i]),Utf8Encode(AName));
end;
GetListing;
end;
end;
procedure TVCLSFTPClientDemoForm.btUploadClick(Sender: TObject);
var i:Integer;
APath:string;
UploadStream:TStream;
LDateTime:TDateTimeInfoRec;
begin
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then begin
APath:=DirectoryListBox1.Directory+PathDelim+FileListBox1.Items[i];
FileGetDateTimeInfo(APath,LDateTime);
UploadStream:=TFileStream.Create(APath,fmOpenRead);
try
FTotalToCopy:=UploadStream.Size;
ProgressBar1.Min:=0;
ProgressBar1.Max:=FTotalToCopy div 1024;
ProgressBar1.Position:=0;
ProgressBar1.Visible:=true;
Application.ProcessMessages;
PSFTP.UploadStream(Utf8Encode(FileListBox1.Items[i]),UploadStream,false);
PSFTP.SetModifiedDate(Utf8Encode(FileListBox1.Items[i]),LDateTime.TimeStamp,false);
GetListing;
finally
FreeAndNil(UploadStream);
ProgressBar1.Visible:=false;
end;
end;
end;
procedure TVCLSFTPClientDemoForm.cbVerboseClick(Sender: TObject);
begin
PSFTP.Verbose:=cbVerbose.Checked;
end;
procedure TVCLSFTPClientDemoForm.btRemoveDirClick(Sender: TObject);
var count,i:Integer;
begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' directory remotely (right side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]='<dir>' then
PSFTP.RemoveDir(Utf8Encode(sgRemoteFiles.Cells[0,i]));
end;
GetListing;
end;
procedure TVCLSFTPClientDemoForm.DirectoryListBox1Change(Sender: TObject);
begin
if not FInLoadSettings then
SaveSettings;
end;
procedure TVCLSFTPClientDemoForm.btDeleteRemoteClick(Sender: TObject);
var count,i:Integer;
begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' file(s) remotely (right side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]<>'<dir>' then
PSFTP.DeleteFile(Utf8Encode(sgRemoteFiles.Cells[0,i]));
end;
GetListing;
end;
procedure TVCLSFTPClientDemoForm.btnSelectKeyFileClick(Sender: TObject);
begin
if FileOpenDialog1.Execute then begin
edKeyFile.Text := FileOpenDialog1.FileName;
end;
end;
procedure TVCLSFTPClientDemoForm.edFolderPathExit(Sender: TObject);
begin
if PSFTP.Connected then begin
try
if edFolderPath.Text<>'' then
PSFTP.ChangeDir(Utf8Encode(edFolderPath.Text));
edFolderPath.Text:=Utf8ToString(PSFTP.WorkDir);
GetListing;
except
on E:Exception do
Application.MessageBox(PWideChar(E.Message),'Error');
end;
end;
end;
procedure TVCLSFTPClientDemoForm.FormCreate(Sender: TObject);
begin
PSFTP:=TTGPuttySFTP.Create(true);
PSFTP.OnListing:=ListingCallback;
PSFTP.OnMessage:=MessageCallback;
PSFTP.OnProgress:=ProgressCallback;
PSFTP.OnGetInput:=GetInputCallback;
PSFTP.OnVerifyHostKey:=VerifyHostKeyCallback;
end;
procedure TVCLSFTPClientDemoForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(PSFTP);
end;
procedure TVCLSFTPClientDemoForm.FormShow(Sender: TObject);
begin
LoadSettings;
ProgressBar1.Visible:=false;
memLog.Lines.Add('Library version: '+string(PSFTP.LibVersion));
end;
function TVCLSFTPClientDemoForm.GetInputCallback(var cancel: Boolean): AnsiString;
begin
Result:=''; // this event will not normally fire
cancel:=false;
memLog.Lines.Add('Replying with empty line.');
end;
procedure TVCLSFTPClientDemoForm.GetListing;
begin
sgRemoteFiles.RowCount:=1;
sgRemoteFiles.ColCount:=3;
sgRemoteFiles.ColWidths[0]:=480;
sgRemoteFiles.ColWidths[1]:=300;
sgRemoteFiles.ColWidths[2]:=150;
sgRemoteFiles.Cells[0,0]:='Name';
sgRemoteFiles.Cells[1,0]:='Timestamp';
sgRemoteFiles.Cells[2,0]:='Size';
PSFTP.ListDir('');
if sgRemoteFiles.RowCount>1 then
sgRemoteFiles.FixedRows:=1;
sgRemoteFiles.FixedCols:=0;
end;
function TVCLSFTPClientDemoForm.ListingCallback(const names: Pfxp_names): Boolean;
var StartRow,i:Integer;
begin
StartRow:=sgRemoteFiles.RowCount;
sgRemoteFiles.RowCount:=StartRow+names.nnames;
for i:=0 to names.nnames-1 do begin
sgRemoteFiles.Cells[0,StartRow+i]:=Utf8ToString(names.names[i].filename);
sgRemoteFiles.Cells[1,StartRow+i]:=DateTimeToStr(TTimeZone.Local.ToLocalTime(UnixToDateTime(names.names[i].attrs.mtime)));
if names.names[i].attrs.permissions and $F000 = $4000 then
sgRemoteFiles.Cells[2,StartRow+i]:='<dir>'
else
sgRemoteFiles.Cells[2,StartRow+i]:=IntToStr(names.names[i].attrs.size);
end;
Result:=true;
end;
procedure TVCLSFTPClientDemoForm.LoadSettings;
var Reg:TRegistry;
begin
Reg:=TRegistry.Create;
FInLoadSettings:=true;
try
with Reg do begin
RootKey:=HKEY_CURRENT_USER;
if OpenKey('SOFWARE\tgputty',true) then begin
edURL.Text:=ReadString('URL');
edUserName.Text:=ReadString('UserName');
edPassword.Text:=ReadString('Password');
cbSavePassword.Checked:=edPassword.Text<>'';
try
edPort.Text:=IntToStr(ReadInteger('Port'));
except
edPort.Text:='22';
end;
edFolderPath.Text:=ReadString('FolderPath');
DirectoryListBox1.Directory:=ReadString('LocalPath');
edKeyFile.Text:=ReadString('PrivateKey');
end;
end;
finally
FreeAndNil(Reg);
FInLoadSettings:=false;
end;
end;
procedure TVCLSFTPClientDemoForm.MessageCallback(const Msg: AnsiString;const isstderr: Boolean);
begin
memLog.Lines.Add(Utf8ToString(Msg));
end;
function TVCLSFTPClientDemoForm.ProgressCallback(const bytescopied: Int64;const isupload: Boolean): Boolean;
begin
ProgressBar1.Position:=bytescopied div 1024;
Application.ProcessMessages;
Result:=true;
end;
procedure TVCLSFTPClientDemoForm.SaveSettings;
var Reg:TRegistry;
begin
Reg:=TRegistry.Create;
try
with Reg do begin
RootKey:=HKEY_CURRENT_USER;
if OpenKey('SOFWARE\tgputty',true) then begin
WriteString('URL',edURL.Text);
WriteString('UserName',edUserName.Text);
if cbSavePassword.Checked then
WriteString('Password',edPassword.Text)
else
DeleteValue('Password');
WriteInteger('Port',StrToIntDef(edPort.Text,22));
WriteString('FolderPath',edFolderPath.Text);
WriteString('LocalPath',DirectoryListBox1.Directory);
WriteString('PrivateKey', edKeyFile.Text);
end;
end;
finally
FreeAndNil(Reg);
end;
end;
procedure TVCLSFTPClientDemoForm.sgRemoteFilesDblClick(Sender: TObject);
begin
if sgRemoteFiles.Selection.Top=sgRemoteFiles.Selection.Bottom then begin
if sgRemoteFiles.Cells[2,sgRemoteFiles.Selection.Top]='<dir>' then begin
PSFTP.ChangeDir(Utf8Encode(sgRemoteFiles.Cells[0,sgRemoteFiles.Selection.Top]));
edFolderPath.Text:=Utf8ToString(PSFTP.WorkDir);
SaveSettings;
GetListing;
end;
end;
end;
function TVCLSFTPClientDemoForm.VerifyHostKeyCallback(const host: PAnsiChar; const port: Integer;
const fingerprint: PAnsiChar;
const verificationstatus:Integer;
var storehostkey: Boolean): Boolean;
begin
if verificationstatus=0 then begin
Result:=true;
Exit;
end;
Result:=Application.MessageBox(PWideChar(WideString(
'Please confirm the SSH host key fingerprint for '+Utf8ToString(AnsiString(host))+
', port '+IntToStr(port)+':'+sLineBreak+
Utf8ToString(AnsiString(fingerprint)))),
'Server Verification',
MB_YESNO or MB_ICONQUESTION) = IDYES;
storehostkey:=Result;
end;
end.
|
unit RakNetStatistics;
interface
type
IRakNetStatistics = Interface(IInterface)
// /// For each type in RNSPerSecondMetrics, what is the value over the last 1 second?
// uint64_t valueOverLastSecond[RNS_PER_SECOND_METRICS_COUNT];
//
// /// For each type in RNSPerSecondMetrics, what is the total value over the lifetime of the connection?
// uint64_t runningTotal[RNS_PER_SECOND_METRICS_COUNT];
//
// /// When did the connection start?
// /// \sa RakNet::GetTimeUS()
// RakNet::TimeUS connectionStartTime;
//
// /// Is our current send rate throttled by congestion control?
// /// This value should be true if you send more data per second than your bandwidth capacity
// bool isLimitedByCongestionControl;
//
// /// If \a isLimitedByCongestionControl is true, what is the limit, in bytes per second?
// uint64_t BPSLimitByCongestionControl;
//
// /// Is our current send rate throttled by a call to RakPeer::SetPerConnectionOutgoingBandwidthLimit()?
// bool isLimitedByOutgoingBandwidthLimit;
//
// /// If \a isLimitedByOutgoingBandwidthLimit is true, what is the limit, in bytes per second?
// uint64_t BPSLimitByOutgoingBandwidthLimit;
//
// /// For each priority level, how many messages are waiting to be sent out?
// unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES];
//
// /// For each priority level, how many bytes are waiting to be sent out?
// double bytesInSendBuffer[NUMBER_OF_PRIORITIES];
//
// /// How many messages are waiting in the resend buffer? This includes messages waiting for an ack, so should normally be a small value
// /// If the value is rising over time, you are exceeding the bandwidth capacity. See BPSLimitByCongestionControl
// unsigned int messagesInResendBuffer;
//
// /// How many bytes are waiting in the resend buffer. See also messagesInResendBuffer
// uint64_t bytesInResendBuffer;
//
// /// Over the last second, what was our packetloss? This number will range from 0.0 (for none) to 1.0 (for 100%)
// float packetlossLastSecond;
//
// /// What is the average total packetloss over the lifetime of the connection?
// float packetlossTotal;
//
// RakNetStatistics& operator +=(const RakNetStatistics& other)
// {
// unsigned i;
// for (i=0; i < NUMBER_OF_PRIORITIES; i++)
// {
// messageInSendBuffer[i]+=other.messageInSendBuffer[i];
// bytesInSendBuffer[i]+=other.bytesInSendBuffer[i];
// }
//
// for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++)
// {
// valueOverLastSecond[i]+=other.valueOverLastSecond[i];
// runningTotal[i]+=other.runningTotal[i];
// }
//
// return *this;
// }
// };
end;
implementation
end.
|
unit Report_Sold_Day;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorReport, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData,
cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, dsdGuides, cxButtonEdit, dxBarExtItems,
dsdAddOn, ChoicePeriod, Vcl.Menus, dxBar, cxClasses, dsdDB, Datasnap.DBClient,
dsdAction, Vcl.ActnList, cxPropertiesStore, cxLabel, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomView,
cxGrid, cxPC, cxCurrencyEdit, cxCheckBox, cxPivotGridChartConnection,
cxCustomPivotGrid, cxDBPivotGrid, cxGridChartView, cxGridDBChartView,
cxSplitter, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter,
dxSkinsdxBarPainter;
type
TReport_Sold_DayForm = class(TAncestorReportForm)
dxBarControlContainerItem1: TdxBarControlContainerItem;
dxBarControlContainerItem2: TdxBarControlContainerItem;
cxLabel3: TcxLabel;
dxBarControlContainerItem3: TdxBarControlContainerItem;
ceUnit: TcxButtonEdit;
UnitGuides: TdsdGuides;
rdUnit: TRefreshDispatcher;
dxBarControlContainerItem4: TdxBarControlContainerItem;
PlanDate: TcxGridDBColumn;
UnitName: TcxGridDBColumn;
PlanAmount: TcxGridDBColumn;
PlanAmountAccum: TcxGridDBColumn;
FactAmount: TcxGridDBColumn;
FactAmountAccum: TcxGridDBColumn;
DiffAmount: TcxGridDBColumn;
DiffAmountAccum: TcxGridDBColumn;
PercentMake: TcxGridDBColumn;
PercentMakeAccum: TcxGridDBColumn;
tsPivot: TcxTabSheet;
cxSplitter1: TcxSplitter;
grChart: TcxGrid;
grChartDBChartView1: TcxGridDBChartView;
dgDate: TcxGridDBChartDataGroup;
dgUnit: TcxGridDBChartDataGroup;
serPlanAmount: TcxGridDBChartSeries;
serPlanAmountAccum: TcxGridDBChartSeries;
serFactAmount: TcxGridDBChartSeries;
serFactAmountAccum: TcxGridDBChartSeries;
grChartLevel1: TcxGridLevel;
cxDBPivotGrid1: TcxDBPivotGrid;
pcolPlanDate: TcxDBPivotGridField;
pcolWeek: TcxDBPivotGridField;
pcolUnitName: TcxDBPivotGridField;
pcolPlanAmount: TcxDBPivotGridField;
pcolFactAmount: TcxDBPivotGridField;
pcolDiffAmount: TcxDBPivotGridField;
pcolDayOfWeek: TcxDBPivotGridField;
spGet_UserUnit: TdsdStoredProc;
actGet_UserUnit: TdsdExecStoredProc;
actRefreshStart: TdsdDataSetRefresh;
actQuasiSchedule: TBooleanStoredProcAction;
bbQuasiSchedule: TdxBarButton;
actGridToExcelPivot: TdsdGridToExcel;
bbGridToExcelPivot: TdxBarButton;
UnitJuridical: TcxGridDBColumn;
pcolUnitJuridical: TcxDBPivotGridField;
ProvinceCityName: TcxGridDBColumn;
dxBarControlContainerItem5: TdxBarControlContainerItem;
actNoStaticCodes: TBooleanStoredProcAction;
bbNoStaticCodes: TdxBarButton;
actSP: TBooleanStoredProcAction;
dxBarButton1: TdxBarButton;
FactAmountSale: TcxGridDBColumn;
pcolFactAmountSale: TcxDBPivotGridField;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Report_Sold_DayForm: TReport_Sold_DayForm;
implementation
{$R *.dfm}
initialization
RegisterClass(TReport_Sold_DayForm);
end.
|
unit Broker_s;
{This file was generated on 11 Aug 2000 20:13:59 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file broker.idl. }
{Delphi Pascal unit : Broker_s }
{derived from IDL module : Broker }
interface
uses
CORBA,
Broker_i,
Broker_c;
type
TMoneyMarketSkeleton = class;
TMarginAccountSkeleton = class;
TInvestmentAccountSkeleton = class;
TMoneyMarketSkeleton = class(CORBA.TCorbaObject, Broker_i.MoneyMarket)
private
FImplementation : MoneyMarket;
public
constructor Create(const InstanceName: string; const Impl: MoneyMarket);
destructor Destroy; override;
function GetImplementation : MoneyMarket;
function interest_rate : Single;
published
procedure _interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
TMarginAccountSkeleton = class(CORBA.TCorbaObject, Broker_i.MarginAccount)
private
FImplementation : MarginAccount;
public
constructor Create(const InstanceName: string; const Impl: MarginAccount);
destructor Destroy; override;
function GetImplementation : MarginAccount;
function margin_rate : Single;
published
procedure _margin_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
TInvestmentAccountSkeleton = class(Broker_s.TMoneyMarketSkeleton, Broker_i.InvestmentAccount)
private
FImplementation : InvestmentAccount;
public
constructor Create(const InstanceName: string; const Impl: InvestmentAccount);
destructor Destroy; override;
function GetImplementation : InvestmentAccount;
function balance : Single;
function interest_rate : Single;
function margin_rate : Single;
published
procedure _balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _margin_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TMoneyMarketSkeleton.Create(const InstanceName : string; const Impl : Broker_i.MoneyMarket);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'MoneyMarket', 'IDL:Broker/MoneyMarket:1.0');
FImplementation := Impl;
end;
destructor TMoneyMarketSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TMoneyMarketSkeleton.GetImplementation : Broker_i.MoneyMarket;
begin
result := FImplementation as Broker_i.MoneyMarket;
end;
function TMoneyMarketSkeleton.interest_rate : Single;
begin
Result := FImplementation.interest_rate;
end;
procedure TMoneyMarketSkeleton._interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := interest_rate;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
constructor TMarginAccountSkeleton.Create(const InstanceName : string; const Impl : Broker_i.MarginAccount);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'MarginAccount', 'IDL:Broker/MarginAccount:1.0');
FImplementation := Impl;
end;
destructor TMarginAccountSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TMarginAccountSkeleton.GetImplementation : Broker_i.MarginAccount;
begin
result := FImplementation as Broker_i.MarginAccount;
end;
function TMarginAccountSkeleton.margin_rate : Single;
begin
Result := FImplementation.margin_rate;
end;
procedure TMarginAccountSkeleton._margin_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := margin_rate;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
constructor TInvestmentAccountSkeleton.Create(const InstanceName : string; const Impl : Broker_i.InvestmentAccount);
begin
inherited CreateSkeleton(InstanceName, 'InvestmentAccount', 'IDL:Broker/InvestmentAccount:1.0');
FImplementation := Impl;
end;
destructor TInvestmentAccountSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TInvestmentAccountSkeleton.GetImplementation : Broker_i.InvestmentAccount;
begin
result := FImplementation as Broker_i.InvestmentAccount;
end;
function TInvestmentAccountSkeleton.balance : Single;
begin
Result := FImplementation.balance;
end;
function TInvestmentAccountSkeleton.interest_rate : Single;
begin
Result := FImplementation.interest_rate;
end;
function TInvestmentAccountSkeleton.margin_rate : Single;
begin
Result := FImplementation.margin_rate;
end;
procedure TInvestmentAccountSkeleton._balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := balance;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
procedure TInvestmentAccountSkeleton._interest_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := interest_rate;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
procedure TInvestmentAccountSkeleton._margin_rate(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := margin_rate;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
initialization
end. |
unit SIP_Action;
interface
uses Classes;
type
TSIPOperation=(OP_NONE,OP_RING,OP_DELAY,OP_PLAY,OP_DTMF,OP_JUMP,OP_CALL,OP_HANGUP,OP_SMS,OP_Mail);
TSIPAction=class(TObject)
private
OperandsArray:array of String;
function GetOperand(Index: Integer): String;
procedure SetOperands(const Value: String);
procedure SetAction(const Value: String);
function GetAction: String;
function GetOperands: String;
public
OpCode:TSIPOperation;
property Operand[Index:Integer]:String read GetOperand;
property Operands:String read GetOperands write SetOperands;
published
property Action:String read GetAction write SetAction;
end;
implementation
uses TypInfo, SysUtils;
{ TSIPAction }
function TSIPAction.GetAction: String;
begin
Result:=GetEnumName(TypeInfo(TSIPOperation),Integer(OpCode));
if Pos('OP_',Result)=1 then Delete(Result,1,3);
Result:=LowerCase(Result)+'('+Operands+')';
end;
function TSIPAction.GetOperand(Index: Integer): String;
begin
if (Index<=0) or (Index>Length(OperandsArray)) then Result:='' else Result:=OperandsArray[Index-1];
end;
function TSIPAction.GetOperands: String;
var
I: Integer;
S:TStringList;
begin
Result:='';
S:=TStringList.Create;
try
for I := 0 to Length(OperandsArray) - 1 do
S.Add(OperandsArray[I]);
S.QuoteChar:='''';
Result:=S.DelimitedText;
finally
S.Free;
end;
end;
procedure TSIPAction.SetAction(const Value: String);
var I,O:Integer;
Code,OP:String;
begin
I:=Pos('(',Value);
Code:=Value;
if I>0 then
begin
Op:=Copy(Value,I+1,Length(Value));
while (Length(Op)>0) and (Ord(Op[Length(Op)])<=32) do Delete(Op,Length(Op),1);
if (Length(Op)>0) and (Op[Length(Op)]=')') then Delete(Op,Length(Op),1);
Operands:=Op;
Delete(Code,I,Length(Code));
end;
O:=GetEnumValue(TypeInfo(TSIPOperation),'OP_'+UpperCase(Code));
if O<0 then OpCode:=OP_NONE else OpCode:=TSIPOperation(O);
end;
procedure TSIPAction.SetOperands(const Value: String);
var SLine:TStringList;
I: Integer;
begin
SLine:=TStringList.Create;
try
SLine.QuoteChar:='''';
SLine.DelimitedText:=Value;
SetLength(OperandsArray,SLine.Count);
for I := 0 to SLine.Count - 1 do
OperandsArray[I]:=SLine[I];
finally
Sline.Free;
end;
end;
end.
|
unit SpinButtonImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, Spin;
type
TSpinButtonX = class(TActiveXControl, ISpinButtonX)
private
{ Private declarations }
FDelphiControl: TSpinButton;
FEvents: ISpinButtonXEvents;
procedure DownClickEvent(Sender: TObject);
procedure UpClickEvent(Sender: TObject);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DownNumGlyphs: Smallint; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_UpNumGlyphs: Smallint; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DownNumGlyphs(Value: Smallint); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_UpNumGlyphs(Value: Smallint); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About29;
{ TSpinButtonX }
procedure TSpinButtonX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_SpinButtonXPage); }
end;
procedure TSpinButtonX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as ISpinButtonXEvents;
end;
procedure TSpinButtonX.InitializeControl;
begin
FDelphiControl := Control as TSpinButton;
FDelphiControl.OnDownClick := DownClickEvent;
FDelphiControl.OnUpClick := UpClickEvent;
end;
function TSpinButtonX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TSpinButtonX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TSpinButtonX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TSpinButtonX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TSpinButtonX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TSpinButtonX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TSpinButtonX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TSpinButtonX.Get_DownNumGlyphs: Smallint;
begin
Result := Smallint(FDelphiControl.DownNumGlyphs);
end;
function TSpinButtonX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TSpinButtonX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TSpinButtonX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TSpinButtonX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TSpinButtonX.Get_UpNumGlyphs: Smallint;
begin
Result := Smallint(FDelphiControl.UpNumGlyphs);
end;
function TSpinButtonX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TSpinButtonX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TSpinButtonX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TSpinButtonX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TSpinButtonX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TSpinButtonX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TSpinButtonX.AboutBox;
begin
ShowSpinButtonXAbout;
end;
procedure TSpinButtonX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TSpinButtonX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TSpinButtonX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TSpinButtonX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TSpinButtonX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TSpinButtonX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TSpinButtonX.Set_DownNumGlyphs(Value: Smallint);
begin
FDelphiControl.DownNumGlyphs := TNumGlyphs(Value);
end;
procedure TSpinButtonX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TSpinButtonX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TSpinButtonX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TSpinButtonX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TSpinButtonX.Set_UpNumGlyphs(Value: Smallint);
begin
FDelphiControl.UpNumGlyphs := TNumGlyphs(Value);
end;
procedure TSpinButtonX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TSpinButtonX.DownClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDownClick;
end;
procedure TSpinButtonX.UpClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnUpClick;
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TSpinButtonX,
TSpinButton,
Class_SpinButtonX,
29,
'{695CDBB6-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit uCidade;
interface
uses
uPaiControle, uEstado;
type
TCidade = class(TControle)
private
FIdCidade: Integer;
FNome: string;
FIdEstado: integer;
FEstado: TEstado;
function GetEstado: TEstado;
public
destructor Destroy; override;
property IdCidade: Integer read FIdCidade write FIdCidade;
property Nome: string read FNome write FNome;
property IdEstado: integer read FIdEstado write FIdEstado;
property Estado: TEstado read GetEstado;
end;
implementation
uses
SysUtils;
{ TCidade }
destructor TCidade.Destroy;
begin
if FEstado <> nil then
FreeAndNil(FEstado);
inherited;
end;
{$REGION 'Getters'}
function TCidade.GetEstado: TEstado;
begin
if FEstado = nil then
FEstado := TEstado.Create(FIdEstado)
else
FEstado.PesquisarPorCodigo(FEstado.IdEstado, FIdEstado);
Result := FEstado;
end;
{$ENDREGION}
end.
|
unit RakPeerInterface;
interface
uses
RakNetTypes,
RakNetTime,
RakNetSocket2,
PacketPriority,
System.Generics.Collections;
type
IRakPeerInterface = Interface(IInterface)
///Destructor
// destructor Destroy;
// --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users--------------------------------------------------------------------------------------------
/// \brief Starts the network threads, opens the listen port.
/// \details You must call this before calling Connect().
/// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown().
/// \note Call SetMaximumIncomingConnections if you want to accept incoming connections
/// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections
/// \param[in] localPort The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility.
/// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP
/// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass.
/// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application.
/// \return RAKNET_STARTED on success, otherwise appropriate failure enumeration.
function Startup(maxConnections: Word; socketDescriptors: TSocketDescriptor; socketDescriptorCount: Word; threadPriority: Integer = 99999): TStartupResult;
/// If you accept connections, you must call this or else security will not be enabled for incoming connections.
/// This feature requires more round trips, bandwidth, and CPU time for the connection handshake
/// x64 builds require under 25% of the CPU time of other builds
/// See the Encryption sample for example usage
/// \pre Must be called while offline
/// \pre LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect
/// \param[in] publicKey A pointer to the public key for accepting new connections
/// \param[in] privateKey A pointer to the private key for accepting new connections
/// \param[in] bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection
function InitializeSecurity(const publicKey: PChar; const privateKey: PChar; bRequireClientKey: Boolean = false): Boolean;
/// Disables security for incoming connections.
/// \note Must be called while offline
procedure DisableSecurity;
/// If secure connections are on, do not use secure connections for a specific IP address.
/// This is useful if you have a fixed-address internal server behind a LAN.
/// \note Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect.
/// \param[in] ip IP address to add. * wildcards are supported.
procedure AddToSecurityExceptionList(ip: PChar);
/// Remove a specific connection previously added via AddToSecurityExceptionList
/// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported.
procedure RemoveFromSecurityExceptionList(ip: PChar);
/// Checks to see if a given IP is in the security exception list
/// \param[in] IP address to check.
function IsInSecurityExceptionList(ip: PChar): Boolean;
/// Sets how many incoming connections are allowed. If this is less than the number of players currently connected,
/// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed,
/// it will be reduced to the maximum number of peers allowed.
/// Defaults to 0, meaning by default, nobody can connect to you
/// \param[in] numberAllowed Maximum number of incoming connections allowed.
procedure SetMaximumIncomingConnections(numberAllowed: Word);
/// Returns the value passed to SetMaximumIncomingConnections()
/// \return the maximum number of incoming connections, which is always <= maxConnections
function GetMaximumIncomingConnections(): Word;
/// Returns how many open connections there are at this time
/// \return the number of open connections
function NumberOfConnections(): Word;
/// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password
/// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections
/// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data
/// \param[in] passwordDataLength The length in bytes of passwordData
procedure SetIncomingPassword(const passwordData: PChar; passwordDataLength: Integer);
/// Gets the password passed to SetIncomingPassword
/// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword()
/// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written
procedure GetIncomingPassword(passwordData: PChar; passwordDataLength: Integer);
/// \brief Connect to the specified host (ip or domain name) and server port.
/// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client.
/// Calling both acts as a true peer. This is a non-blocking connection.
/// You know the connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED.
/// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen.
/// \pre Requires that you first call Startup()
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
/// \param[in] publicKey The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
/// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect.
/// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth.
/// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS);
/// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure.
/// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected!
/// \note It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed.
function Connect(const host: PChar; remotePort: Word; const passwordData: PChar; passwordDataLength: Integer; publicKey: TPublicKey; connectionSocketIndex: Word = 0; sendConnectionAttemptCount: Word = 12; timeBetweenSendConnectionAttemptsMS: Word = 500; timeoutTime: TimeMS = 0): TConnectionAttemptResult;
/// \brief Connect to the specified host (ip or domain name) and server port, using a shared socket from another instance of RakNet
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
/// \param[in] socket A bound socket returned by another instance of RakPeerInterface
/// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect.
/// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth.
/// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS);
/// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure.
/// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected!
function ConnectWithSocket(const host: PChar; remotePort: Word; const passwordData: PChar; passwordDataLength: Integer; socket: TRakNetSocket2; publicKey: TPublicKey; sendConnectionAttemptCount: Word = 12; timeBetweenSendConnectionAttemptsMS: Word = 500; timeoutTime: TimeMS = 0): TConnectionAttemptResult;
/// \brief Connect to the specified network ID (Platform specific console function)
/// \details Does built-in NAt traversal
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
//virtual bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength )=0;
/// \brief Stops the network threads and closes all connections.
/// \param[in] blockDuration How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all.
/// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel
/// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on.
/// If you set it to 0 then the disconnection notification won't be sent
procedure Shutdown(blockDuration: Word; orderingChannel: Byte = 0; disconnectionNotificationPriority: TPacketPriority = LOW_PRIORITY);
/// Returns if the network thread is running
/// \return true if the network thread is running, false otherwise
function IsActive(): Boolean;
/// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to
/// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to
/// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array
function GetConnectionList(remoteSystems: TSystemAddress; numberOfSystems: Word): Boolean;
/// Returns the next uint32_t that Send() will return
/// \note If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case.
/// \return The next uint32_t that Send() or SendList will return
function GetNextSendReceipt(): UInt32;
/// Returns the next uint32_t that Send() will return, and increments the value by one
/// \note If using RakPeer from multiple threads, pass this to forceReceipt in the send function
/// \return The next uint32_t that Send() or SendList will return
function IncrementNextSendReceipt(): UInt32;
/// Sends a block of data to the specified system that you are connected to.
/// This function only works while connected
/// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM
/// \param[in] data The block of data to send
/// \param[in] length The size in bytes of the data to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.
/// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number
function Send(const data: PChar; const length: Integer; priority: PacketPriority; reliability: TPacketReliability; orderingChannel: Char; const systemIdentifier: AddressOrGUID; broadcast: Boolean; forceReceiptNumber: UInt32 = 0): UInt32;
/// "Send" to yourself rather than a remote system. The message will be processed through the plugins and returned to the game as usual
/// This function works anytime
/// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM
/// \param[in] data The block of data to send
/// \param[in] length The size in bytes of the data to send
procedure SendLoopback(const data: PChar; const length: Integer);
/// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input.
/// \param[in] bitStream The bitstream to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.
/// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number
/// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration.
function Send(const bitStream: RakNet.IBitStream; priority: TPacketPriority; reliability: TPacketReliability; orderingChannel: Char; const systemIdentifier: AddressOrGUID; broadcast: Boolean; forceReceiptNumber: Uint32 = 0): Uint32;
/// Sends multiple blocks of data, concatenating them automatically.
///
/// This is equivalent to:
/// RakNet::BitStream bs;
/// bs.WriteAlignedBytes(block1, blockLength1);
/// bs.WriteAlignedBytes(block2, blockLength2);
/// bs.WriteAlignedBytes(block3, blockLength3);
/// Send(&bs, ...)
///
/// This function only works while connected
/// \param[in] data An array of pointers to blocks of data
/// \param[in] lengths An array of integers indicating the length of each block of data
/// \param[in] numParameters Length of the arrays data and lengths
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it.
/// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number
function SendList(const data: PChar; const lengths: Integer; const numParameters: Integer; priority: PacketPriority; reliability: PacketReliability; char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ): UInt32;
/// Gets a message from the incoming message queue.
/// Use DeallocatePacket() to deallocate the message after you are done with it.
/// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here.
/// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet.
/// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up.
/// sa RakNetTypes.h contains struct Packet
function Receive(): IPacket;
/// Call this to deallocate a message returned by Receive() when you are done handling it.
/// \param[in] packet The message to deallocate.
function DeallocatePacket(packet: IPacket): Boolean;
/// Return the total number of connections we are allowed
function GetMaximumNumberOfPeers(): Word;
// -------------------------------------------------------------------------------------------- Connection Management Functions--------------------------------------------------------------------------------------------
/// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out).
/// \param[in] target Which system to close the connection to.
/// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently.
/// \param[in] channel Which ordering channel to send the disconnection notification on, if any
/// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on.
procedure CloseConnection(const target: AddressOrGUID; sendDisconnectionNotification: Boolean; orderingChannel: Byte = 0; disconnectionNotificationPriority: PacketPriority = LOW_PRIORITY );
/// Returns if a system is connected, disconnected, connecting in progress, or various other states
/// \param[in] systemIdentifier The system we are referring to
/// \note This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout
/// \return What state the remote system is in
function GetConnectionState(const systemIdentifier: AddressOrGUID): ConnectionState;
/// Cancel a pending connection attempt
/// If we are already connected, the connection stays open
/// \param[in] target Which system to cancel
procedure CancelConnectionAttempt(const target: ISystemAddress);
/// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1.
/// \param[in] systemAddress The SystemAddress we are referring to
/// \return The index of this SystemAddress or -1 on system not found.
function GetIndexFromSystemAddress(const systemAddress: ISystemAddress): Integer;
/// This function is only useful for looping through all systems
/// Given an index, will return a SystemAddress.
/// \param[in] index Index should range between 0 and the maximum number of players allowed - 1.
/// \return The SystemAddress
function GetSystemAddressFromIndex(index: Word): ISystemAddress;
/// Same as GetSystemAddressFromIndex but returns RakNetGUID
/// \param[in] index Index should range between 0 and the maximum number of players allowed - 1.
/// \return The RakNetGUID
function GetGUIDFromIndex(index: Word): RakNetGUID;
/// Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient
/// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system
/// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the list will match the size of the \a guids list.
/// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list.
procedure GetSystemList(addresses: TList<ISystemAddress>; guids: TList<RakNetGUID>);
/// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup.
/// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0
/// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban
procedure AddToBanList(const IP: PChar; milliseconds: RakNet.TimeMS = 0);
/// Allows a previously banned IP to connect.
/// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0
procedure RemoveFromBanList(const IP: PChar);
/// Allows all previously banned IPs to connect.
procedure ClearBanList();
/// Returns true or false indicating if a particular IP is banned.
/// \param[in] IP - Dotted IP address.
/// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise.
function IsBanned(const IP: PChar): Boolean;
/// Enable or disable allowing frequent connections from the same IP adderss
/// This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots
/// \param[in] b True to limit connections from the same ip to at most 1 per 100 milliseconds.
procedure SetLimitIPConnectionFrequency(b: Boolean);
// --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism--------------------------------------------------------------------------------------------
/// Send a ping to the specified connected system.
/// \pre The sender and recipient must already be started via a successful call to Startup()
/// \param[in] target Which system to ping
procedure Ping(const target: ISystemAddress);
/// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(RakNet::TimeMS) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h
/// System should reply with ID_PONG if it is active
/// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast.
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
/// \return true on success, false on failure (unknown hostname)
function Ping(const host: PChar; remotePort: Word; onlyReplyOnAcceptingConnections: Boolean; connectionSocketIndex: Byte = 0): Boolean;
/// Returns the average of all ping times read for the specific system or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The ping time for this system, or -1
function GetAveragePing(const systemIdentifier: AddressOrGUID): Integer;
/// Returns the last ping time read for the specific system or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The last ping time for this system, or -1
function GetLastPing(const systemIdentifier: AddressOrGUID): Integer;
/// Returns the lowest ping time read or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The lowest ping time for this system, or -1
function GetLowestPing(const systemIdentifier: AddressOrGUID): Integer;
/// Ping the remote systems every so often, or not. Can be called anytime.
/// By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets.
/// It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate
/// \param[in] doPing True to start occasional pings. False to stop them.
procedure SetOccasionalPing(doPing: Boolean);
/// Return the clock difference between your system and the specified system
/// Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system
/// Returns 0 if the system is unknown
/// \param[in] systemIdentifier Which system we are referring to
function GetClockDifferential(const systemIdentifier: AddressOrGUID): RakNet.Time;
// --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory--------------------------------------------------------------------------------------------
/// Sets the data to send along with a LAN server discovery or offline ping reply.
/// \a length should be under 400 bytes, as a security measure against flood attacks
/// \param[in] data a block of data to store, or 0 for none
/// \param[in] length The length of data in bytes, or 0 for none
/// \sa Ping.cpp
procedure SetOfflinePingResponse(const data: PChar; const length: Word);
/// Returns pointers to a copy of the data passed to SetOfflinePingResponse
/// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse()
/// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse()
/// \sa SetOfflinePingResponse
procedure GetOfflinePingResponse(data: PChar; length: Word);
//--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general--------------------------------------------------------------------------------------------
/// Return the unique address identifier that represents you or another system on the the network and is based on your local IP / port.
/// \note Not supported by the XBOX
/// \param[in] systemAddress Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address
/// \param[in] index When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1)
/// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy
function GetInternalID(const systemAddress: ISystemAddress = UNASSIGNED_SYSTEM_ADDRESS; const index: Integer = 0): ISystemAddress;
/// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value
/// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string
/// \param[in] index When you have multiple internal IDs, which index to set?
procedure SetInternalID(systemAddress: ISystemAddress; index: Integer = 0);
/// Return the unique address identifier that represents you on the the network and is based on your externalIP / port
/// (the IP / port the specified player uses to communicate with you)
/// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards.
function GetExternalID(const target: SystemAddress): ISystemAddress;
/// Return my own GUID
function GetMyGUID(): RakNetGUID;
/// Return the address bound to a socket at the specified index
function GetMyBoundAddress(const socketIndex: Integer = 0): ISystemAddress;
/// Get a random number (to generate a GUID)
function Get64BitUniqueRandomNumber(): Uint64;
/// Given a connected system, give us the unique GUID representing that instance of RakPeer.
/// This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different
/// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change.
/// Returns UNASSIGNED_RAKNET_GUID if system address can't be found.
/// If \a input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID
/// \pre Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID
/// \param[in] input The system address of the system we are connected to
function GetGuidFromSystemAddress(const input: ISystemAddress): RakNetGUID;
/// Given the GUID of a connected system, give us the system address of that system.
/// The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different
/// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change.
/// If \a input is UNASSIGNED_RAKNET_GUID, will return UNASSIGNED_SYSTEM_ADDRESS
/// \param[in] input The RakNetGUID of the system we are checking to see if we are connected to
function GetSystemAddressFromGuid(const input: RakNetGUID): SystemAddress;
/// Given the SystemAddress of a connected system, get the public key they provided as an identity
/// Returns false if system address was not found or client public key is not known
/// \param[in] input The RakNetGUID of the system
/// \param[in] client_public_key The connected client's public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length.
function GetClientPublicKeyFromSystemAddress(const input: ISystemAddress; client_public_key: PChar): Boolean;
/// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message.
/// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug.
/// Do not set different values for different computers that are connected to each other, or you won't be able to reconnect after ID_CONNECTION_LOST
/// \param[in] timeMS Time, in MS
/// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems.
procedure SetTimeoutTime(timeMS: RakNet.TimeMS; const target: ISystemAddress);
/// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value
/// \return timeoutTime for a given system.
function GetTimeoutTime(const target: ISystemAddress): RakNet.TimeMS;
/// Returns the current MTU size
/// \param[in] target Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default
/// \return The current MTU size
function GetMTUSize(const target: ISystemAddress): Integer;
/// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP()
function GetNumberOfAddresses(): Word;
/// Returns an IP address at index 0 to GetNumberOfAddresses-1
/// \param[in] index index into the list of IP addresses
/// \return The local IP address at this index
function GetLocalIP(index: Word): PChar;
/// Is this a local IP?
/// \param[in] An IP address to check, excluding the port
/// \return True if this is one of the IP addresses returned by GetLocalIP
function IsLocalIP( const char *ip ): Boolean;
/// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary
/// when connecting to servers with multiple IP addresses.
/// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections
procedure AllowConnectionResponseIPMigration(allow: Boolean);
/// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system.
/// This will tell the remote system our external IP outside the LAN along with some user data.
/// \pre The sender and recipient must already be started via a successful call to Initialize
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] data Optional data to append to the packet.
/// \param[in] dataLength length of data in bytes. Use 0 if no data.
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
/// \return false if IsActive()==false or the host is unresolvable. True otherwise
function AdvertiseSystem(const host: PChar; remotePort: Word; const data: PChar; dataLength: Integer; connectionSocketIndex: Word = 0): Boolean;
/// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads.
/// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived
/// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned.
/// Defaults to 0 (never return this notification)
/// \param[in] interval How many messages to use as an interval
procedure SetSplitMessageProgressInterval(int interval);
/// Returns what was passed to SetSplitMessageProgressInterval()
/// \return What was passed to SetSplitMessageProgressInterval(). Default to 0.
function GetSplitMessageProgressInterval(): Integer;
/// Set how long to wait before giving up on sending an unreliable message
/// Useful if the network is clogged up.
/// Set to 0 or less to never timeout. Defaults to 0.
/// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message.
procedure SetUnreliableTimeout(timeoutMS: RakNet.TimeMS);
/// Send a message to host, with the IP socket option TTL set to 3
/// This message will not reach the host, but will open the router.
/// Used for NAT-Punchthrough
procedure SendTTL(const host: PCHar; remotePort: Integer; ttl: Integer; connectionSocketIndex: Integer = 0);
// -------------------------------------------------------------------------------------------- Plugin Functions--------------------------------------------------------------------------------------------
/// \brief Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call.
/// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active.
/// \param[in] messageHandler Pointer to the plugin to attach.
procedure AttachPlugin(plugin: IPluginInterface2);
/// \brief Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to.
/// \details This method disables the plugin code from running automatically on base class's updates or message receipt.
/// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active.
/// \param[in] messageHandler Pointer to a plugin to detach.
procedure DetachPlugin(messageHandler: IPluginInterface2 );
// --------------------------------------------------------------------------------------------Miscellaneous Functions--------------------------------------------------------------------------------------------
/// Put a message back at the end of the receive queue in case you don't want to deal with it immediately
/// \param[in] packet The packet you want to push back.
/// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order)
procedure PushBackPacket(packet: IPacket; pushAtHead: Boolean);
/// \internal
/// \brief For a given system identified by \a guid, change the SystemAddress to send to.
/// \param[in] guid The connection we are referring to
/// \param[in] systemAddress The new address to send to
procedure ChangeSystemAddress(guid: RakNetGUID; const systemAddress: ISystemAddress);
/// \returns a packet for you to write to if you want to create a Packet for some reason.
/// You can add it to the receive buffer with PushBackPacket
/// \param[in] dataSize How many bytes to allocate for the buffer
/// \return A packet you can write to
function AllocatePacket(unsigned dataSize): IPacket;
/// Get the socket used with a particular active connection
/// The smart pointer reference counts the RakNetSocket2 object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection.
/// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so.
/// \param[in] target Which system
/// \return A smart pointer object containing the socket information about the socket. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected
function GetSocket(const target: ISystemAddress): IRakNetSocket2;
/// Get all sockets in use
/// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so.
/// \param[out] sockets List of RakNetSocket2 structures in use. Sockets will not be closed until \a sockets goes out of scope
procedure GetSockets(sockets: TList<RakNetSocket2>);
procedure ReleaseSockets(sockets: TList<RakNetSocket2>);
procedure WriteOutOfBandHeader(bitStream: RakNet.IBitStream);
/// If you need code to run in the same thread as RakNet's update thread, this function can be used for that
/// \param[in] _userUpdateThreadPtr C callback function
/// \param[in] _userUpdateThreadData Passed to C callback function
procedure SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData)=0;
/// Set a C callback to be called whenever a datagram arrives
/// Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram.
/// This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer
/// RNS2RecvStruct will only remain valid for the duration of the call
/// If the incoming datagram is not from your game at all, it is a RakNet packet.
/// If the incoming datagram has an IP address that matches a known address from your game, then check the first byte of data.
/// For RakNet connected systems, the first bit is always 1. So for your own game packets, make sure the first bit is always 0.
virtual void SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) )=0;
// --------------------------------------------------------------------------------------------Network Simulator Functions--------------------------------------------------------------------------------------------
/// Adds simulated ping and packet loss to the outgoing data flow.
/// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each.
/// You can exclude network simulator code with the _RELEASE #define to decrease code size
/// \deprecated Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead.
/// \note Doesn't work past version 3.6201
/// \param[in] packetloss Chance to lose a packet. Ranges from 0 to 1.
/// \param[in] minExtraPing The minimum time to delay sends.
/// \param[in] extraPingVariance The additional random time to delay sends.
procedure ApplyNetworkSimulator(packetloss: single; minExtraPing: Word; extraPingVariance: Word);
/// Limits how much outgoing bandwidth can be sent per-connection.
/// This limit does not apply to the sum of all connections!
/// Exceeding the limit queues up outgoing traffic
/// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again.
procedure SetPerConnectionOutgoingBandwidthLimit(maxBitsPerSecond: Word);
/// Returns if you previously called ApplyNetworkSimulator
/// \return If you previously called ApplyNetworkSimulator
function IsNetworkSimulatorActive(): Boolean;
// --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance--------------------------------------------------------------------------------------------
/// Returns a structure containing a large set of network statistics for the specified system.
/// You can map this data to a string using the C style StatisticsToString() function
/// \param[in] systemAddress: Which connected system to get statistics for
/// \param[in] rns If you supply this structure, it will be written to it. Otherwise it will use a static struct, which is not threadsafe
/// \return 0 on can't find the specified system. A pointer to a set of data otherwise.
/// \sa RakNetStatistics.h
function GetStatistics(const systemAddress: ISystemAddress; rns: IRakNetStatistics = 0): IRakNetStatistics;
/// \brief Returns the network statistics of the system at the given index in the remoteSystemList.
/// \return True if the index is less than the maximum number of peers allowed and the system is active. False otherwise.
function GetStatistics(const index: Word; rns: IRakNetStatistics): Boolean;
/// \brief Returns the list of systems, and statistics for each of those systems
/// Each system has one entry in each of the lists, in the same order
/// \param[out] addresses SystemAddress for each connected system
/// \param[out] guids RakNetGUID for each connected system
/// \param[out] statistics Calculated RakNetStatistics for each connected system
procedure GetStatisticsList(addresses: TList<SystemAddress>; guids: TList<RakNetGUID>; statistics: TList<RakNetStatistics>);
/// \Returns how many messages are waiting when you call Receive()
function GetReceiveBufferSize(): Word;
// --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY--------------------------------------------------------------------------------------------
/// \internal
// Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds.
// updateBitStream should be:
// BitStream updateBitStream( MAXIMUM_MTU_SIZE
// #if LIBCAT_SECURITY==1
// + cat::AuthenticatedEncryption::OVERHEAD_BYTES
// #endif
// );
function RunUpdateCycle(updateBitStream: IBitStream): Boolean;
/// \internal
function SendOutOfBand(const host: PChar; remotePort: Word; const data: PChar; dataLength: BitSize_t; connectionSocketIndex: Word = 0): Boolean;
end;
implementation
end.
|
{1.4. Реликтовая роща (6)
В заповеднике растет роща реликтовых деревьев. Для их защиты требуется обнести рощу
забором. Но для обеспечения доступа к остальной территории заповедника площадь участка,
окруженного забором, должна быть минимальной. Деревья растут точно в узлах координатной
сетки на расстоянии одного метра друг от друга. Любое из деревьев имеет хотя бы одного соседа
(с юга, севера, востока или запада). Забор состоит из блоков длиной в один метр.
По заданной конфигурации рощи найти минимально необходимое число блоков для забора.}
Program Forest;
Const
tree = 1;
step_label = -1;
Var
Map : Array [1..100,1..100] Of Integer;
n, m : Integer;
Function Build_Fence : Integer;
Var
i, j, fence_items_count : Integer;
Begin
fence_items_count := 0;
For i := 2 To n - 1 Do
Begin
For j := 2 To m - 1 Do
Begin
If Map[i,j] = 1 Then
Begin
If Map[i,j+1] = -1 Then Inc(fence_items_count);
If Map[i+1,j] = -1 Then Inc(fence_items_count);
If Map[i,j-1] = -1 Then Inc(fence_items_count);
If Map[i-1,j] = -1 Then Inc(fence_items_count);
End;
End;
End;
Build_Fence := fence_items_count;
End;
Procedure Check_Around_Recurs(x, y : Integer);
Begin
If (x in [1..n]) And (y in [1..m]) Then
Begin
If (y < m) Then
Begin
If (Map[x,y+1] = 0) Then
Begin
Map[x,y+1] := step_label;
Check_Around_Recurs(x,y + 1);
End;
End;
If (x < n) Then
Begin
If (Map[x+1,y] = 0) Then
Begin
Map[x+1,y] := step_label;
Check_Around_Recurs(x + 1,y);
End;
End;
If (x > 1) Then
Begin
If (Map[x-1,y] = 0) Then
Begin
Map[x-1,y] := step_label;
Check_Around_Recurs(x - 1,y);
End;
End;
If (y > 1) Then
Begin
If (Map[x,y-1] = 0) Then
Begin
Map[x,y-1] := step_label;
Check_Around_Recurs(x,y - 1);
End;
End;
End;
End;
Procedure Fill_Map(k, p : Integer);
Var
i, j : Integer;
Begin
For i := 1 To k Do
Begin
For j := 1 To p Do
Begin
Map[i,j] := 0;
End;
End;
End;
Procedure Read_Map;
Var
i, j, k, prom : Integer;
temp : String;
A : Text;
Begin
k := 1;
Assign(A, 'input.txt');
Reset(A);
Read(A, n);
Readln(A, m);
Inc(n);Inc(n);
Inc(m);Inc(m);
Fill_Map(n,m);
While not EOF(A) Do
Begin
For i := 2 to n - 1 Do
Begin
Readln(A, temp);
For j := 2 to m - 1 Do
Begin
prom := Ord(temp[k]) - 48;
Map[i,j] := prom;
Inc(k);
End;
k := 1;
End;
End;
Close(A);
End;
Procedure Write_Out(fence_count : Integer);
Var
text_output : Text;
Begin
Assign(text_output, 'output.txt');
Rewrite(text_output);
Write(text_output, fence_count);
Close(text_output);
End;
Begin
Read_Map;
Map[1,1] := step_label;
Check_Around_Recurs(1,1);
Write_Out(Build_Fence);
End. |
unit UtilsDb2;
interface
USES SysUtils, WinTypes, WinProcs, Classes, Messages, Controls, DateUtils,
Forms, Dialogs, stdCtrls, Grids, DBGrids, DBClient,
Graphics, Db, JPEG, SqlExpr, Provider, StrUtils, Variants;
Function UltimoSequencial(sNomeTab,sCampoId: String): Integer;
Function UltimoID(sNomeTab: String): Integer;
Procedure Logradouros(oEd1,oEd2: TCustomEdit);
Procedure Bairros(oEd1,oEd2: TCustomEdit);
Procedure LocaisDePagto(oEd1,oEd2: TCustomEdit);
Function Pesquisa(sTabela, sCampoPesq, sTextPesq, sCampoRet, sMensagem: String): String;
Procedure AtualizaUltSequencial(sTabela: String; iUltSequencial: Integer);
Procedure MostraDados(sTabela,sCampoId,sCampoDisp1,sCampoDisp2,sTextoPesq: String; oEdit1,oEdit2: TCustomEdit; sMsg: String);
Procedure CancelaTransacao(oTab: TClientDataSet; sNomeTab: String);
Function ProximoNumero(sTabela,sCampoPesq: String; bDigVerificador: Boolean; iTam: Integer): String;
Function SalvaTransacao(oTab: TClientDataSet): Boolean;
Function ExcluiRegistro(oTab: TClientDataSet): Boolean;
Procedure SetIndice(oTab: TClientDataSet; oDbg: TDBGrid; wCol: Word; oFrame1: TFrame);
Procedure PesquisaIncremental(sTexto: String; oTab: TClientDataSet);
Function ProxColGrid(iMaxColGrid,iColAtual: Integer): Integer;
Procedure gsRefreshClient(oCds: TClientDataSet; sNomeCampoPk: String; iId: Integer);
Procedure gsRefreshClient2(oCds: TClientDataSet; sNomeCampoPk1,sNomeCampoPk2,sNomeCampoPk3: String;
iId,iId2,iId3: Integer);
Function NavegaClient2(wKey: Word; cds1: TClientDataSet): Word;
Function MovimEncerradoSUO(sAnoMes,sParcela: String; iSubUndOrcam: Integer): Boolean;
Function MovimEncerradoMesAno(sAnoMes,sParcela: String): Boolean;
function GetFieldValue(Table, Field, WhereClausule: string): string;
function OpenClient(Client: TClientDataSet; CommandText: String): Boolean;
procedure CloseClient(Client: TClientDataSet);
procedure BeforePostClient(Client: TClientDataSet);
function GetDataSet(cdsClient: TClientDataSet): TSQLDataSet; //ult. vs. 2010/05/26
function IncrementGenerator(Generator_: String; N_: Integer): String;
procedure CancelGenerator(oDataSetState: TDataSetState; sTab, sIdGen: String;
iIdCancel: integer);
Function UnidGestoraPermiteUsuario(iIdUnidGestora,iIdSubUnidOrcam,
iIdServidor: Integer; sPesq,sAnoMes: String): Boolean;
function CNPJ_Razao_Social_UG(iUnidGestora,iSubUnidOrcam: Integer): TStringList;
Function QtdRegChaveEstrangeira(sPesquisa,sCampo,sTabela: String): Integer;
Function RetiraUnidGestSemPermissao(sMultiUnidGestora: widestring;
sAnoMes: string): widestring;
function ValidaPIS_PASEP_CPF(sId,sCPF,sPIS_PASEP,sOper: string): Boolean;
function UsuarioPermissaoTabela(iUsuario: integer; sTab: string): string;
Function CriaCampoTab(sTab,sCampo,sTipo: string): Boolean;
function OcultaTriggers_e_procs: Boolean;
implementation
uses VarGlobais, udmPrincipal2, gsLib2, uPublicacao;
Function UltimoSequencial(sNomeTab,sCampoId: String): Integer;
Var
oQry1: TSQLQuery;
iSequencial: Integer;
Begin
sNomeTab := UpperCase(sNomeTab);
oQry1:= TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT MAX('+sCampoId+') AS ULT_ID FROM '+sNomeTab);
Try
try
oQry1.Open;
iSequencial := oQry1.FieldByName('ULT_ID').AsInteger+1;
except
iSequencial := 1;
end;
Finally
oQry1.Close;
FreeAndNil(oQry1);
End;
Result := iSequencial;
End;
Function UltimoID(sNomeTab: String): Integer;
Var
oQry1: TSQLQuery;
iId: Integer;
Begin
sNomeTab := UpperCase(sNomeTab);
oQry1:= TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT MAX(ID) AS ULT_ID FROM '+sNomeTab);
Try
try
oQry1.Open;
iId := oQry1.FieldByName('ULT_ID').Value;
except
iId := 0;
end;
Finally
oQry1.Close;
FreeAndNil(oQry1);
Result := iId;
End;
End;
Procedure Logradouros(oEd1,oEd2: TCustomEdit);
Var
oQry1: TSQLQuery;
Begin
oQry1 := TSQLQuery.Create(Nil);
oQry1.SqlConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT ID_LOGRADOURO FROM LOGRADOURO ORDER BY ID_LOGRADOURO');
oQry1.Open;
oEd1.Text := oQry1.FieldByName('ID_LOGRADOURO').Value;
oQry1.Last;
oEd2.Text := oQry1.FieldByName('ID_LOGRADOURO').Value;
oQry1.Close;
oQry1.Free;
End;
Procedure Bairros(oEd1,oEd2: TCustomEdit);
Var
oQry1: TSQLQuery;
Begin
oQry1 := TSQLQuery.Create(Nil);
oQry1.SqlConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT ID_BAIRRO FROM BAIRRO ORDER BY ID_BAIRRO');
oQry1.Open;
oEd1.Text := oQry1.FieldByName('ID_BAIRRO').Value;
oQry1.Last;
oEd2.Text := oQry1.FieldByName('ID_BAIRRO').Value;
oQry1.Close;
oQry1.Free;
End;
Procedure LocaisDePagto(oEd1,oEd2: TCustomEdit);
Var
oQry1: TSQLQuery;
Begin
oQry1 := TSQLQuery.Create(Nil);
oQry1.SqlConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT ID_LOCAL_PAGTO FROM LOCAL_DE_PAGAMENTO ORDER BY ID_LOCAL_PAGTO');
oQry1.Open;
oEd1.Text := oQry1.FieldByName('ID_LOCAL_PAGTO').Value;
oQry1.Last;
oEd2.Text := oQry1.FieldByName('ID_LOCAL_PAGTO').Value;
oQry1.Close;
oQry1.Free;
End;
Function Pesquisa(sTabela, sCampoPesq, sTextPesq, sCampoRet, sMensagem: String): String;
Var
oQry1: TSQLQuery;
Begin
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := fPublicacao.SQLConnection1;
oQry1.SQL.Clear;
oQry1.SQL.Add('SELECT '+UpperCase(sCampoRet)+' FROM '+UpperCase(sTabela)+
' WHERE '+UpperCase(sCampoPesq)+' = :Param1');
oQry1.Params[0].AsString := Trim(sTextPesq);
Try
oQry1.Open;
Try
Result := oQry1.FieldByName(UpperCase(sCampoRet)).AsString;
except
Result := '';
End;
If Result = '' Then
If sMensagem <> '' Then
Mensagem(sMensagem,'E r r o !!!',MB_ICONERROR+MB_OK);
Finally
oQry1.Close;
oQry1.Free;
End;
End;
Procedure AtualizaUltSequencial(sTabela: String; iUltSequencial: Integer);
Var
oQry1: TSQLQuery;
Begin
{
sTabela := UpperCase(sTabela);
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT ULTIMO_SEQUENCIAL, NOME_DA_TABELA FROM CONTROLE_DE_SEQUENCIAL WHERE NOME_DA_TABELA = :sTab');
oQry1.ParamByName('sTab').Value := sTabela;
Try
oQry1.Open;
If oQry1.FieldByName('NOME_DA_TABELA').Value = Null Then
Begin
oQry1.Close;
oQry1.SQL.Clear;
oQry1.SQL.Add('INSERT INTO CONTROLE_DE_SEQUENCIAL (ID_CONTROL_SEQUENCIAL,NOME_DA_TABELA,ULTIMO_SEQUENCIAL');
oQry1.SQL.Add('VALUES (:iIdControlSeq,:sNomeTab,:iUltSeq)');
oQry1.ParamByName('iIdControlSeq').Value:= UltimoSequencial('CONTROLE_DE_SEQUENCIAL')+1;
oQry1.ParamByName('sNomeTab').Value := sTabela;
oQry1.ParamByName('iUltSeq').Value := iUltSequencial;
oQry1.ExecSQL;
End Else
Begin
oQry1.Close;
oQry1.SQL.Clear;
oQry1.SQL.Add('UPDATE CONTROLE_DE_SEQUENCIAL SET ULTIMO_SEQUENCIAL = :iUltSeq WHERE NOME_DA_TABELA = :sTab');
oQry1.ParamByName('iUltSeq').Value := iUltSequencial;
oQry1.ParamByName('sTab').Value := sTabela;
oQry1.ExecSQL;
End;
Finally
oQry1.Close;
oQry1.Free;
End;
}
End;
Procedure MostraDados(sTabela,sCampoId,sCampoDisp1,sCampoDisp2,sTextoPesq: String;
oEdit1,oEdit2: TCustomEdit; sMsg: String);
Var
oQry1 : TSqlQuery;
sCPF_CNPJ : String[14];
sTextoSQL : String;
Begin
oQry1 := TSqlQuery.Create(Nil);
sCPF_CNPJ:= '';
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Clear;
sTextoSQL := 'SELECT '+sCampoDisp1+', '+sCampoDisp2+' '+
'FROM '+sTabela+' '+
'WHERE '+sCampoId+' = :pCodigo';
oQry1.SQL.Add(sTextoSQL);
oQry1.Params[0].Value := sTextoPesq;
oQry1.Open;
Try
If oQry1.FieldByName(sCampoDisp1).IsNull Then
Begin
If sMsg <> '' Then
Mensagem('Código de '+sMsg+' inválido !','E r r o !!!',MB_ICONEXCLAMATION+MB_OK);
Exit;
End;
oEdit1.Text:= oQry1.FieldByName(sCampoDisp1).Value;
If Not oQry1.FieldByName(sCampoDisp2).IsNull Then
oEdit2.Text := oQry1.FieldByName(sCampoDisp2).Value;
Finally
oQry1.Close;
FreeAndNil(oQry1);
End;
End;
Procedure CancelaTransacao(oTab: TClientDataSet; sNomeTab: String);
Var
iSequencial,
iSequencial2: Integer;
lAdd : Boolean;
Begin
lAdd := (oTab.State = dsInsert);
If oTab.State in [dsInsert,dsEdit] Then oTab.Cancel;
oTab.CancelUpdates;
{
If Not lAdd Then Exit;
sNomeTab := UpperCase(sNomeTab);
iSequencial2 := UltimoSequencial(sNomeTab);
If iSequencial = iSequencial2 Then
AtualizaUltSequencial(sNomeTab,iSequencial-1);
}
End;
Function ProximoNumero(sTabela,sCampoPesq: String; bDigVerificador: Boolean; iTam: Integer): String;
Var
iUltSequencial: Integer;
Begin
sTabela := UpperCase(sTabela);
iUltSequencial:= UltimoSequencial(sTabela,sCampoPesq);
Inc(iUltSequencial);
If bDigVerificador = True Then
Begin
Result := IntToStr(iUltSequencial);
Result := PreencheZeros(Result,iTam-1);
If sTabela = 'PROPRIETARIO' Then
Result := Result + CalcDigProprietario(Result)
Else If sTabela = 'UNIDADE_CONSUMIDORA' Then
Result := Result + CalcDigUnidConsumidora(Result)
End Else
Begin
If iTam > 0 Then
Result := PreencheZeros(IntToStr(iUltSequencial),iTam)
Else
Result := IntToStr(iUltSequencial);
End;
//AtualizaUltSequencial(sTabela,iUltSequencial);
End;
Function SalvaTransacao(oTab: TClientDataSet): Boolean;
Begin
Result := True;
If oTab.State in [dsInsert,dsEdit] Then
oTab.Post;
try
oTab.ApplyUpdates(0);
except
on E: Exception do
begin
Mensagem('Não foi possível Gravar essa Transação no Banco de Dados !'+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
oTab.CancelUpdates;
Result := False;
end;
end;
End;
Function ExcluiRegistro(oTab: TClientDataSet): Boolean;
Begin
Result := True;
oTab.Delete;
try
oTab.ApplyUpdates(0);
except
on E: Exception do
begin
Mensagem('Não foi possível Excluir esse Registro do Banco de Dados !'+#13+
'('+E.Message+')','E R R O !!!',MB_OK+MB_ICONERROR);
oTab.CancelUpdates;
Result := False;
end;
end;
End;
Procedure SetIndice(oTab: TClientDataSet; oDbg: TDBGrid; wCol: Word; oFrame1: TFrame);
Var
iConta: Integer;
sCampoIndex: String;
Begin
{
If Trim(oDbg.Columns[wCol].Title.Caption) = '' Then Exit;
sCampoIndex := oDbg.Columns[wCol].FieldName;
For iConta := 0 To oDbg.Columns.Count-1 Do
Begin
oDbg.Columns[iConta].Title.Font.Color:= glb_oCorColTitGrid_Normal; // Normal
oDbg.Columns[iConta].Title.Font.Style:= [fsBold];
End;
oTab.IndexFieldNames := sCampoIndex;
oDbg.Columns[wCol].Title.Font.Color:= glb_oCorColTitGrid_Destacada; // Destacado
oDbg.Columns[wCol].Title.Font.Style:= [fsBold];
If oFrame1 <> Nil Then
Begin
For iConta := 0 To oFrame1.ComponentCount - 1 Do
Begin
If oFrame1.Components[iConta] Is TEdit Then
TEdit(oFrame1.Components[iConta]).MaxLength := oTab.FieldByName(sCampoIndex).Size
Else If oFrame1.Components[iConta] Is TGroupBox Then
TGroupBox(oFrame1.Components[iConta]).Caption := ' '+oDbg.Columns[wCol].Title.Caption+': ( [F3] -> Muda Ordem ... ) ';
End;
End;
}
End;
Procedure PesquisaIncremental(sTexto: String; oTab: TClientDataSet);
Var
sCampoPesq: String;
iTemp : Integer;
crTemp : Currency;
Begin
With oTab Do
Begin
If Empty(sTexto) Then
Begin
First;
Exit;
End;
iTemp := 0;
crTemp:= 0;
sCampoPesq := oTab.IndexFieldNames;
{
if (oTab.FieldByName(sCampoPesq) Is TIntegerField) then
begin
try
iTemp := StrToInt(sTexto);
finally
iTemp := -1;
end;
end else
if (oTab.FieldByName(sCampoPesq) Is TCurrencyField) then
begin
try
crTemp := StrToCurr(sTexto);
finally
iTemp := -1;
end;
end;
if (iTemp=-1) or (crTemp=-1) then exit;
}
DisableControls;
Try
Locate(sCampoPesq,sTexto,[loPartialKey]);
Except
End;
EnableControls;
End;
End;
Function ProxColGrid(iMaxColGrid,iColAtual: Integer): Integer;
Begin
Result := iColAtual+1;
If Result > iMaxColGrid Then
Result := 0;
End;
Procedure gsRefreshClient(oCds: TClientDataSet; sNomeCampoPk: String; iId: Integer);
begin
ocds.DisableControls;
ocds.Close;
ocds.Open;
oCds.Locate(sNomeCampoPk,IntToStr(iId),[]);
ocds.EnableControls;
end;
Procedure gsRefreshClient2(oCds: TClientDataSet; sNomeCampoPk1,sNomeCampoPk2,sNomeCampoPk3: String;
iId,iId2,iId3: Integer);
Var
sIndexSave: string;
begin
sIndexSave := ocds.IndexFieldNames;
ocds.DisableControls;
ocds.Close;
if sNomeCampoPk3 <> '' then
ocds.IndexFieldNames := sNomeCampoPK1+';'+sNomeCampoPK2+';'+sNomeCampoPK3
else
ocds.IndexFieldNames := sNomeCampoPK1+';'+sNomeCampoPK2;
ocds.Open;
if sNomeCampoPk3 <> '' then
ocds.FindKey([iId,iId2,iId3])
else
ocds.FindKey([iId,iId2]);
ocds.IndexFieldNames := sIndexSave;
ocds.EnableControls;
end;
Function NavegaClient2(wKey: Word; cds1: TClientDataSet): Word;
Begin
If wKey in [VK_END,VK_HOME,VK_UP,VK_DOWN] Then
Begin
Case wKey of
VK_END : cds1.Last;
VK_HOME: cds1.First;
VK_UP : cds1.Prior;
VK_DOWN: cds1.Next;
End;
Result := 0;
End Else
Result := wKey;
End;
Function MovimEncerradoSUO(sAnoMes,sParcela: String; iSubUndOrcam: Integer): Boolean;
Var
oQry1: TSQLQuery;
begin
Result := False;
oQry1:= TSQLQuery.Create(nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('select ENCERRADO from CTRL_PROCES_SUB_UND_ORCAM');
oQry1.SQL.Add('where (ano_mes = :pAnoMes) and ');
oQry1.SQL.Add('(parcela = :pParcela) and ');
oQry1.SQL.Add('(id_sub_unid_orcam = :pIdSubUndOrcam)');
oQry1.ParamByName('pAnoMes').Value:= sAnoMes;
oQry1.ParamByName('pParcela').Value:= sParcela;
oQry1.ParamByName('pIdSubUndOrcam').Value:= iSubUndOrcam;
try
try
oQry1.Open;
if oQry1.FieldByName('ENCERRADO').Value = 'S' then
Result := True;
except
end;
finally
oQry1.Close;
FreeAndNil(oQry1);
end;
end;
Function MovimEncerradoMesAno(sAnoMes,sParcela: String): Boolean;
Var
oQry1: TSQLQuery;
begin
Result := False;
oQry1:= TSQLQuery.Create(nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('select ENCERRADO from CTRL_PROCESS_GERAL');
oQry1.SQL.Add('where (ano_mes = :pAnoMes) and ');
oQry1.SQL.Add('(parcela = :pParcela)');
oQry1.ParamByName('pAnoMes').Value:= sAnoMes;
oQry1.ParamByName('pParcela').Value:= sParcela;
try
try
oQry1.Open;
if oQry1.FieldByName('ENCERRADO').Value = 'S' then
Result := True;
except
end;
finally
oQry1.Close;
FreeAndNil(oQry1);
end;
end;
function IncrementGenerator(Generator_: String; N_: Integer): String;
Var
oQry1: TSQLQuery;
begin
//GetFieldValue('CRIA_GERADOR('''+Generator_+''')', 'OK', EmptyStr);
//FinishTransaction(True);
//StartTransaction;
Result := '0';
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('select gen_id('+Generator_+',1) as NewId from RDB$DATABASE');
try
try
oQry1.Open;
Result := oQry1.FieldByName('NewId').AsString;
except
Mensagem('Não foi possível incrementar o Gerador '+#13+Generator_,
'Erro !!!',MB_OK+MB_ICONERROR);
end;
finally
oQry1.Close;
FreeAndNil(oQry1);
end;
//Result := GetFieldValue('RDB$DATABASE', 'gen_id('+Generator_+', '+IntToStr(N_)+')', EmptyStr);
end;
procedure CancelGenerator(oDataSetState: TDataSetState;
sTab, sIdGen: String; iIdCancel: integer);
Var
oSP1: TSQLStoredProc;
iUltId: Integer;
sUltId: string;
sNomeGen: string;
begin
if (oDataSetState <> dsInsert) or
(sTab = '') or (sIdGen = '') then exit;
oSP1:= TSQLStoredProc.Create(Nil);
oSP1.SQLConnection := dmPrincipal.SConPrincipal;
oSP1.StoredProcName := 'SP_ATUALIZA_GEN';
iUltId := UltimoID(sTab);
if iUltId > 0 then
if (sTab = 'SERVIDOR') or
(sTab = 'PRESTADOR_SERVICO') or
(sTab = 'BOLSA_BENEFICIARIO') then
begin
sUltId := IntToStr(iUltId);
sUltId := LeftStr(sUltId,Length(sUltId)-1);
iUltId := StrToInt(sUltId);
end;
try
if iIdCancel > iUltId then
begin
if UpperCase(sTab) = UpperCase('hist_transf_sub_und_orcam') then
sNomeGen := 'GEN_ID_HIST_TRANSF_SUB_UND_ORC'
else
sNomeGen := 'GEN_'+sIdGen+'_'+sTab;
oSP1.ParamByName('pe_nome_gen').Value := sNomeGen;
oSP1.ParamByName('pe_id').Value := iUltId;
try
oSP1.ExecProc;
except
on E: Exception do
begin
Mensagem('('+E.Message+')','E R R O !!!',MB_OK+MB_ICONERROR);
end;
end;
end;
finally
oSP1.Close;
FreeAndNil(oSP1);
end;
end;
function GetFieldValue(Table, Field, WhereClausule: string): string;
var
DataSet: TSQLDataSet;
Provider: TDataSetProvider;
Client: TClientDataSet;
begin
DataSet := TSQLDataSet.Create(Nil);
DataSet.Name := 'sdsGetFieldValue';
DataSet.SQLConnection := dmPrincipal.SConPrincipal;
DataSet.GetMetadata := False;
Provider := TDataSetProvider.Create(Nil);
Provider.Name := 'dspGetFieldValue';
Provider.DataSet := DataSet;
Provider.Exported := False;
Provider.Options := [poAllowCommandText,poUseQuoteChar];
Provider.UpdateMode := upWhereKeyOnly;
Client := TClientDataSet.Create(Nil);
Client.Name := 'cdsGetFieldValue';
Client.ProviderName := Provider.Name;
Client.Filtered := True;
OpenClient(Client,
IfThen((Field<>EmptyStr) and (Table<>EmptyStr), 'select '+Field+' from '+
Table+' ', '')+WhereClausule);
if (Client.Active)and(not Client.Fields[0].IsNull) then
begin
Result := Client.Fields[0].AsString;
end
else
begin
Result := '';
end;
CloseClient(Client);
Client.Free;
Provider.Free;
DataSet.Free;
end;
function OpenClient(Client: TClientDataSet; CommandText: String): Boolean;
begin
Client.CommandText := IfThen(CommandText = EmptyStr, Client.CommandText,
CommandText);
try
Client.Open;
except
on E: Exception do
begin
Mensagem('Erro $002'+#13+Client.Name+#13+E.Message+#13+
Client.CommandText, 'Erro', MB_ICONERROR+MB_OK);
end;
end;
Result := Client.Active;
end;
procedure CloseClient(Client: TClientDataSet);
begin
Client.Close;
Client.Filter := '';
end;
procedure BeforePostClient(Client: TClientDataSet);
var
Count: integer;
begin
for Count := 0 to (Client.Fields.Count - 1) do
begin
if (Client.Fields[Count].Required) and
(Client.Fields[Count].IsNull) then
begin
Mensagem('O campo '+Client.Fields[Count].DisplayLabel+
' é obrigatório(a)', 'Aviso', MB_ICONINFORMATION+MB_OK);
Client.Fields[Count].FocusControl;
SysUtils.Abort;
end;
end;
if Client.State = dsEdit then
for Count := 0 to (Client.Fields.Count - 1) do
begin
if
(Client.Fields[Count].Tag = 1) then
begin
if (Client.Fields[Count].NewValue) <>
(Client.Fields[Count].OldValue) then
GetDataSet(Client).Fields[Count].ProviderFlags := [pfInUpdate]
else
GetDataSet(Client).Fields[Count].ProviderFlags := []
end;
end;
end;
function GetDataSet(cdsClient: TClientDataSet): TSQLDataSet; //ult. vs. 2010/05/26
//retorna o sqldataset associado ao clientdataset
begin
//procuro no proprietário do clientdataset o componente com o nome
//configurado na propriedade providername do clientdataset
//e retorno a propriedade dataset
if
TDataSetProvider(
cdsClient.Owner.FindComponent(cdsClient.ProviderName)
) = nil //se não encontrar nenhum componente
then
Result := nil
else
Result :=
TSQLDataSet(
TDataSetProvider(
cdsClient.Owner.FindComponent(cdsClient.ProviderName)
).DataSet
);
{
Elaborado por:
BRUNO MAJORICO FREITAS SANTIAGO
E-mail e MSN: contato@brunosantiago.net
Mais informações acesse: http://brunosantiago.net
}
end;
Function UnidGestoraPermiteUsuario(iIdUnidGestora,iIdSubUnidOrcam,
iIdServidor: Integer; sPesq,sAnoMes: String): Boolean;
Var
oQry1: TSQLQuery;
oQry2: TSQLQuery;
begin
Result := False;
if (iIdUnidGestora = 0) and (iIdSubUnidOrcam = 0) and (iIdServidor = 0)
then exit;
if iIdServidor <> 0 then
begin
if sPesq = '1' then // Cadastro do Servidor
iIdSubUnidOrcam := StrToInt(Pesquisa('SERVIDOR','ID',
IntToStr(iIdServidor),'ID_SUB_UNID_ORCAMENT',''))
else begin // na tabela de inicialização
oQry2:= TSQLQuery.Create(Nil);
oQry2.SQLConnection := dmPrincipal.SConPrincipal;
oQry2.SQL.Add('SELECT ID_SUB_UNID_ORCAMENT FROM INICIALIZA_MES_SERVIDOR ');
oQry2.SQL.Add('WHERE (ID_SERVIDOR = :pServidor) AND (ANO_MES = :pAnoMes)');
oQry2.ParamByName('pServidor').Value:= iIdServidor;
oQry2.ParamByName('pAnoMes').Value := sAnoMes;
try
oQry2.Open;
if not oQry2.IsEmpty then
iIdSubUnidOrcam := oQry2.FieldByName('ID_SUB_UNID_ORCAMENT').Value;
finally
oQry2.Close;
FreeAndNil(oQry2);
end;
end;
iIdUnidGestora :=
(StrToInt(Pesquisa('SUB_UNID_ORCAMENT','ID',IntToStr(iIdSubUnidOrcam),
'ID_UNID_GESTORA','')));
end else
if iIdUnidGestora = 0 then
iIdUnidGestora :=
(StrToInt(Pesquisa('SUB_UNID_ORCAMENT','ID',IntToStr(iIdSubUnidOrcam),
'ID_UNID_GESTORA','')));
oQry1:= TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT * FROM USUARIO_UNID_GESTORA WHERE ');
oQry1.SQL.Add('(ID_USUARIO = :pUsuario) AND (ID_UNID_GESTORA = :pUnidGestora)');
oQry1.ParamByName('pUsuario').Value := glb_iIdOperExecut;
oQry1.ParamByName('pUnidGestora').Value := iIdUnidGestora;
try
oQry1.Open;
if not oQry1.IsEmpty then
Result := True;
finally
oQry1.Close;
FreeAndNil(oQry1);
end;
end;
function CNPJ_Razao_Social_UG(iUnidGestora,iSubUnidOrcam: Integer): TStringList;
Var
oQry1: TSQLQuery;
sRazaoSocialPrincipal,
sRazaoSocialUG: String[60];
sCNPJPrincipal,
sCNPJUnidGestora: String[14];
slRet: TStringList;
begin
slRet := TStringList.Create;
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT RAZAO_SOCIAL, CNPJ FROM CONFIG_ORGAO WHERE ID = 1');
oQry1.Open;
sRazaoSocialPrincipal:= Criptografa(oQry1.FieldByName('RAZAO_SOCIAL').Value,
'2',60);
sCNPJPrincipal:= Criptografa(oQry1.FieldByName('CNPJ').Value,'2',14);
oQry1.Close;
oQry1.SQL.Clear;
if iSubUnidOrcam <> 0 then
begin
oQry1.SQL.Add('SELECT ID_UNID_GESTORA FROM SUB_UNID_ORCAMENT '+
'WHERE ID = :pS_U_O');
oQry1.ParamByName('pS_U_O').Value := iSubUnidOrcam;
oQry1.Open;
iUnidGestora := oQry1.FieldByName('ID_UNID_GESTORA').Value;
oQry1.Close;
oQry1.SQL.Clear;
end;
oQry1.SQL.Add('SELECT RAZAO_SOCIAL, CNPJ FROM UNID_GESTORA WHERE ID = :pId_UG');
oQry1.ParamByName('pId_UG').Value := iUnidGestora;
oQry1.Open;
sRazaoSocialUG := '';
sCNPJUnidGestora:= '';
if not oQry1.FieldByName('RAZAO_SOCIAL').IsNull then
sRazaoSocialUG := oQry1.FieldByName('RAZAO_SOCIAL').Value;
if not oQry1.FieldByName('CNPJ').IsNull then
sCNPJUnidGestora:= oQry1.FieldByName('CNPJ').Value;
oQry1.Close;
FreeAndNil(oQry1);
if sCNPJUnidGestora <> sCNPJPrincipal then
begin
slRet.Add(sCNPJUnidGestora);
slRet.Add(sRazaoSocialUG);
end else
begin
slRet.Add(sCNPJPrincipal);
slRet.Add(sRazaoSocialPrincipal);
end;
Result := slRet;
end;
Function QtdRegChaveEstrangeira(sPesquisa,sCampo,sTabela: String): Integer;
Var
oQry: TSQLQuery;
Begin
Screen.Cursor:= crHourGlass;
oQry := TSQLQuery.Create(Nil);
oQry.SQLConnection:= dmPrincipal.SConPrincipal;
oQry.SQL.Add('SELECT '+sCampo);
oQry.SQL.Add('FROM '+sTabela);
oQry.SQL.Add('WHERE '+sCampo+' = :sTexto');
oQry.ParamByName('sTexto').Value := sPesquisa;
oQry.Open;
Result := oQry.RecordCount;
oQry.Free;
Screen.Cursor:= crDefault;
End;
Function RetiraUnidGestSemPermissao(sMultiUnidGestora: WideString;
sAnoMes: string): WideString;
Var
sIdUGTemp: string;
iConta: integer;
sMultiUGRet: WideString;
sTemp: string;
begin
sMultiUGRet:= ';';
sIdUGTemp := '';
for iConta := 1 to Length(sMultiUnidGestora) do
begin
sTemp := sMultiUnidGestora[iConta];
if sTemp = ';' then
begin
if (iConta > 1) then
begin
if UnidGestoraPermiteUsuario(StrToInt(sIdUGTemp),0,0,'',sAnoMes) then
sMultiUGRet:= sMultiUGRet + sIdUGTemp + ';';
sIdUGTemp := '';
end;
end else
sIdUGTemp := sIdUGTemp + sTemp;
end;
Result := sMultiUGRet;
end;
// ;1;
function ValidaPIS_PASEP_CPF(sId,sCPF,sPIS_PASEP,sOper: string): Boolean;
Var
oQry1: TSQLQuery;
iErro: integer;
begin
Result := True;
{
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('SELECT ID, NOME_SERVIDOR, PIS_PASEP_PF FROM SERVIDOR ');
oQry1.SQL.Add('WHERE CPF_PF = :pCPF');
oQry1.ParamByName('pCPF').Value := sCPF;
iErro:= 0;
try
try
oQry1.Open;
except
on E: Exception do
begin
Mensagem('Não foi possível executar essas instruções ...'+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
iErro := 1;
end;
end;
finally
if iErro = 0 then
begin
Result := True;
if sOper = '1' then
begin
if sPIS_PASEP = oQry1.FieldByName('PIS_PASEP_PF').Value then
if not Confirma('JÁ EXISTE UM SERVIDOR COM ESTE CPF E PIS_PASEP:'+#13+
'ID. :'+FormatString('99999-9',oQry1.FieldByName('ID').AsString)+
' - NOME: '+oQry1.FieldByName('NOME_SERVIDOR').AsString+'.'+#13+
'DESEJA CONTINUAR ASSIM MESMO ?') then
Result := False;
end else
begin
if sId <> oQry1.FieldByName('ID').AsString then
if sPIS_PASEP = oQry1.FieldByName('PIS_PASEP_PF').Value then
if not Confirma('JÁ EXISTE UM SERVIDOR COM ESTE CPF E PIS_PASEP:'+#13+
'ID. :'+FormatString('99999-9',oQry1.FieldByName('ID').AsString)+
' - NOME: '+oQry1.FieldByName('NOME_SERVIDOR').AsString+'.'+#13+
'DESEJA CONTINUAR ASSIM MESMO ?') then
Result := False;
end;
end;
oQry1.Close;
FreeAndNil(oQry1);
end
}
end;
function UsuarioPermissaoTabela(iUsuario: integer; sTab: string): string;
Var
oQry1: TSQLQuery;
begin
oQry1 := TSQLQuery.Create(Nil);
oQry1.SQLConnection := dmPrincipal.SConPrincipal;
oQry1.SQL.Add('select incluir, alterar, excluir');
oQry1.SQL.Add('from usuario_permissao_tabela');
oQry1.SQL.Add('where (id_usuario = :pUsuario) and');
oQry1.SQL.Add(' (nome_tabela = :pTab)');
oQry1.ParamByName('pUsuario').Value := iUsuario;
oQry1.ParamByName('pTab').Value := sTab;
try
try
oQry1.Open;
try
Result := iIf(oQry1.FieldByName('incluir').Value='S','S','N');
except
Result := 'N';
end;
try
Result := Result + iIf(oQry1.FieldByName('alterar').Value='S','S','N');
except
Result := Result + 'N';
end;
try
Result := Result + iIf(oQry1.FieldByName('excluir').Value='S','S','N');
except
Result := Result + 'N';
end;
except
Result := 'NNN';
end;
finally
oQry1.Close;
FreeAndNil(oQry1);
end;
end;
Function CriaCampoTab(sTab,sCampo,sTipo: string): Boolean;
begin
Result := True;
try
dmPrincipal.SConPrincipal.ExecuteDirect('ALTER TABLE '+sTab+' ADD '+sCampo+' '+
sTipo);
except
on E: Exception do
begin
Result := False;
Mensagem('Não foi possível executar essas instruções ...'+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
end;
end;
end;
function OcultaTriggers_e_procs: Boolean;
Var
iErro: Integer;
begin
iErro := 0;
try
dmPrincipal.SConPrincipal.ExecuteDirect(
'update rdb$triggers set RDB$TRIGGER_SOURCE = null'+
' where RDB$SYSTEM_FLAG = 0');
except
on E: Exception do
begin
iErro := 1;
Mensagem('Não foi possível ocultar as Triggers ...'+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
end;
end;
if iErro = 0 then
begin
try
dmPrincipal.SConPrincipal.ExecuteDirect(
'update rdb$procedures set RDB$PROCEDURE_SOURCE = null'+
' where RDB$SYSTEM_FLAG = 0');
except
on E: Exception do
begin
iErro := 1;
Mensagem('Não foi possível ocultar as Procedures ...'+#13+
'('+E.Message+')',
'E R R O !!!',MB_OK+MB_ICONERROR);
end;
end;
end;
Result := (iErro=0);
end;
end.
|
unit caTextStore;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Sysutils,
Classes,
// ca units
caConsts,
caUtils,
caLog,
caIni;
type
//```````````````````````````````````````````````````````````````````````````
// TcaTextItem
//```````````````````````````````````````````````````````````````````````````
TcaTextItem = class(TComponent)
private
// Property fields
FText: string;
published
// Published properties
property Text: string read FText write FText;
end;
//```````````````````````````````````````````````````````````````````````````
// TcaTextList
//```````````````````````````````````````````````````````````````````````````
TcaTextList = class(TObject)
private
// Private fields
FList: TList;
FOwner: TComponent;
// Property methods
function GetCount: Integer;
function GetItem(Index: Integer): TcaTextItem;
public
// Create/Destroy
constructor Create(AOwner: TComponent);
destructor Destroy; override;
// Public methods
function FindText(const AName: string): TcaTextItem;
procedure AddItem(AItem: TcaTextItem);
procedure AddText(const AName, AText: string);
procedure Clear;
// Properties
property Count: Integer read GetCount;
property Items[Index: Integer]: TcaTextItem read GetItem; default;
end;
//```````````````````````````````````````````````````````````````````````````
// TcaTextStore
//```````````````````````````````````````````````````````````````````````````
TcaTextStore = class(TComponent)
private
// Private fields
FStrings: TStrings;
FTextList: TcaTextList;
// Private methods
procedure UpdateFromStrings;
procedure UpdateStrings;
procedure UpdateTextList;
// Property methods
function GetStrings: TStrings;
function GetText(const AName: string): string;
procedure SetStrings(const Value: TStrings);
public
// Create/Destroy
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// Properties
property Strings: TStrings read GetStrings write SetStrings;
property Text[const AName: string]: string read GetText; default;
end;
implementation
//---------------------------------------------------------------------------
// TcaTextList
//---------------------------------------------------------------------------
// Create/Destroy
constructor TcaTextList.Create(AOwner: TComponent);
begin
inherited Create;
FOwner := AOwner;
FList := TList.Create;
end;
destructor TcaTextList.Destroy;
begin
FList.Free;
inherited;
end;
// Public methods
function TcaTextList.FindText(const AName: string): TcaTextItem;
var
Index: Integer;
Item: TcaTextItem;
begin
Result := nil;
for Index := 0 to Pred(FList.Count) do
begin
Item := GetItem(Index);
if AnsiSameText(Item.Name, AName) then
begin
Result := Item;
Break;
end;
end;
end;
procedure TcaTextList.AddItem(AItem: TcaTextItem);
begin
FList.Add(AItem);
end;
procedure TcaTextList.AddText(const AName, AText: string);
var
Item: TcaTextItem;
begin
Item := TcaTextItem.Create(FOwner);
Item.Name := AName;
Item.Text := AText;
FList.Add(Item);
end;
procedure TcaTextList.Clear;
begin
FList.Clear;
end;
// Property methods
function TcaTextList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TcaTextList.GetItem(Index: Integer): TcaTextItem;
begin
Result := TcaTextItem(FList[Index]);
end;
//---------------------------------------------------------------------------
// TcaTextStore
//---------------------------------------------------------------------------
// Create/Destroy
constructor TcaTextStore.Create(AOwner: TComponent);
begin
inherited;
FStrings := TStringList.Create;
FTextList := TcaTextList.Create(AOwner);
end;
destructor TcaTextStore.Destroy;
begin
FStrings.Free;
FreeAndNil(FTextList);
inherited;
end;
// Private methods
procedure TcaTextStore.UpdateFromStrings;
var
Index: Integer;
TextName: string;
TextValue: string;
TextItem: TcaTextItem;
begin
for Index := 0 to Pred(FStrings.Count) do
begin
TextName := FStrings.Names[Index];
TextValue := FStrings.Values[TextName];
TextItem := FTextList.FindText(TextName);
if not Assigned(TextItem) then
FTextList.AddText(TextName, TextValue);
end;
for Index := 0 to Pred(FTextList.Count) do
begin
TextItem := FTextList[Index];
if FStrings.IndexOfName(TextItem.Name) < 0 then
TextItem.Free;
end;
end;
procedure TcaTextStore.UpdateStrings;
var
Index: Integer;
TextItem: TcaTextItem;
begin
FStrings.Clear;
for Index := 0 to Pred(FTextList.Count) do
begin
TextItem := FTextList[Index];
FStrings.Values[TextItem.Name] := TextItem.Text;
end;
end;
procedure TcaTextStore.UpdateTextList;
var
Index: Integer;
TextItem: TcaTextItem;
begin
if Assigned(Owner) then
begin
FTextList.Clear;
for Index := 0 to Pred(Owner.ComponentCount) do
begin
if Owner.Components[Index] is TcaTextItem then
begin
TextItem := TcaTextItem(Owner.Components[Index]);
FTextList.AddItem(TextItem);
end;
end;
end;
end;
// Property methods
function TcaTextStore.GetStrings: TStrings;
begin
UpdateTextList;
UpdateStrings;
Result := FStrings;
end;
function TcaTextStore.GetText(const AName: string): string;
var
TextItem: TcaTextItem;
begin
Result := '';
UpdateTextList;
UpdateStrings;
TextItem := FTextList.FindText(AName);
if Assigned(TextItem) then
Result := TextItem.Text;
end;
procedure TcaTextStore.SetStrings(const Value: TStrings);
begin
FStrings.Assign(Value);
UpdateFromStrings;
end;
initialization
RegisterClass(TcaTextItem);
finalization
UnRegisterClass(TcaTextItem);
end.
|
unit uReservaModel;
interface
uses FireDac.Comp.Client, uEnumerado, System.SysUtils;
type
TReservaModel = class
private
FAcao: TAcao;
FIdLivro: string;
FIdUsuario: string;
FInicio: string;
FFim: string;
FHora: string;
procedure setAcao(const Value: TAcao);
procedure setFim(const Value: string);
procedure setInicio(const Value: string);
procedure setLivro(const Value: string);
procedure setUsuario(const Value: string);
procedure setHora(const Value: string);
public
function Obter: TFDQuery;
function ObterSelecionadas(Cpf: string): TFDQuery;
function Salvar: Boolean;
property IdLivro: string read FIdLivro write setLivro;
property IdUsuario: string read FIdUsuario write setUsuario;
property Inicio: string read FInicio write setInicio;
property Fim: string read FFim write setFim;
property Hora: string read FHora write setHora;
property Acao: TAcao read FAcao write SetAcao;
end;
implementation
uses
uReservaDao, uUsuarioModel, uReservaControl;
{ TReservaModel }
function TReservaModel.Obter: TFDQuery;
var
Dao: TReservaDao;
begin
Dao := TReservaDao.Create;
try
Result := Dao.Obter;
finally
Dao.Free;
end;
end;
function TReservaModel.ObterSelecionadas(Cpf: string): TFDQuery;
var
Dao: TReservaDao;
begin
Dao := TReservaDao.Create;
try
Result := Dao.ObterSelecionadas(Cpf);
finally
Dao.Free;
end;
end;
function TReservaModel.Salvar: Boolean;
var
Dao: TReservaDao;
begin
Result := False;
Dao := TReservaDao.Create;
try
case FAcao of
uEnumerado.tacIncluir:
Result := Dao.Incluir(Self);
uEnumerado.tacAlterar:
Result := Dao.Alterar(Self);
uEnumerado.tacExcluir:
Result := Dao.Excluir(Self);
end;
finally
Dao.Free;
end;
end;
procedure TReservaModel.setAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TReservaModel.setFim(const Value: string);
begin
FFim := Value;
end;
procedure TReservaModel.setHora(const Value: string);
begin
FHora := Value;
end;
procedure TReservaModel.setInicio(const Value: string);
begin
FInicio := Value;
end;
procedure TReservaModel.setLivro(const Value: string);
begin
FIdLivro := Value;
end;
procedure TReservaModel.setUsuario(const Value: string);
begin
FIdUsuario := Value;
end;
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriButtons;
interface
uses
Windows, SysUtils, Types, Classes, Messages, Controls, Graphics, ImgList,
Menus, StdCtrls, Forms, LCLType,
OriControlsBase//, OriUtils
;
type
{ TOriCustomButton }
TOriButtonOption = (boAllowAllUnchecked, boNoDrawFocus, boNoAutoDropDownMenu,
boDropDownAlignRight, boDropDownArrow, boDropDownAsEllipsis, boDropDownHoriz);
TOriButtonOptions = set of TOriButtonOption;
TOriButtonLook = (blDefault, blDefaultSys, blFlat, blSoft, blTransparent,
blTransparentSys);
TOriCustomButton = class(TButton)
private
IFocused: Boolean;
IMouseOver: Boolean;
FCanvas: TCanvas;
FChecked: Boolean;
FPaintInfo: TButtonPaintInfo;
FGroupIndex: Integer;
FOptions: TOriButtonOptions;
FLook: TOriButtonLook;
FImages: TCustomImageList;
FImageIndex: TImageIndex;
FImageChangeLink: TChangeLink;
FDropDownMenu: TPopupMenu;
procedure SetOptions(Value: TOriButtonOptions);
procedure SetLook(Value: TOriButtonLook);
procedure SetImages(Value: TCustomImageList);
procedure SetImageIndex(Value: TImageIndex);
procedure ImageListChange(Sender: TObject);
procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM;
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure SetButtonStyle(ADefault: Boolean);
procedure SetChecked(Value: Boolean); override;
function GetChecked: Boolean; override;
procedure PaintShape; virtual;
procedure PaintImage; virtual;
procedure PaintText; virtual;
procedure PaintFocus; virtual;
procedure PaintDropDownArrow; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Click; override;
property Images: TCustomImageList read FImages write SetImages;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default -1;
property DropDownMenu: TPopupMenu read FDropDownMenu write FDropDownMenu;
published
property GroupIndex: Integer read FGroupIndex write FGroupIndex default 0;
property Options: TOriButtonOptions read FOptions write SetOptions default [];
property Look: TOriButtonLook read FLook write SetLook default blDefault;
property Action;
property Anchors;
property BiDiMode;
property Cancel;
property Checked;
property Constraints;
property Default;
property Enabled;
property ModalResult;
property ParentShowHint;
property ParentBiDiMode;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnEnter;
property OnExit;
end;
TOriImgButton = class(TOriCustomButton)
private
FMonoGlyph: TOriButtonMonoGlyph;
procedure SetMonoGlyph(Value: TOriButtonMonoGlyph);
protected
procedure PaintImage; override;
procedure PaintText; override;
public
constructor Create(AOwner: TComponent); override;
published
property MonoGlyph: TOriButtonMonoGlyph read FMonoGlyph write SetMonoGlyph default bgNone;
property DropDownMenu;
property Images;
property ImageIndex;
property Height default 25;
property Width default 25;
end;
{ TOriButton }
TOriButton = class(TOriCustomButton)
published
property DropDownMenu;
property Images;
property ImageIndex;
property Caption;
end;
{ TOriRadioCheckBox }
TOriRadioCheckBoxOption = (rcoRadioButton, rcoRadioAsCheck);
TOriRadioCheckBoxOptions = set of TOriRadioCheckBoxOption;
TOriRadioCheckBoxLook = (rclDefault, rclFlat);
TOriRadioCheckPaintText = procedure(Sender: TObject; Canvas: TCanvas;
const AText: String; var ARect: TRect; Flags: Cardinal;
var PaintDefault: Boolean) of object;
TOriRadioCheckBox = class(TButtonControl)
private
_MouseOver: Boolean;
FCanvas: TCanvas;
FLayout: TTextLayout;
FAlignment: TAlignment;
FCheckPosition: TLeftRight;
FAutoSize: Boolean;
FGroupIndex: Integer;
FState: TCheckBoxState;
FAllowGrayed: Boolean;
FLook: TOriRadioCheckBoxLook;
FOptions: TOriRadioCheckBoxOptions;
FOnPaintText: TOriRadioCheckPaintText;
procedure SetLook(Value: TOriRadioCheckBoxLook);
procedure SetOptions(Value: TOriRadioCheckBoxOptions);
procedure SetCheckPosition(Value: TLeftRight);
procedure SetLayout(Value: TTextLayout);
procedure SetAlignment(Value: TAlignment);
procedure SetState(Value: TCheckBoxState);
procedure DrawItem(const DrawItemStruct: TDrawItemStruct);
procedure AdjustBounds;
procedure UncheckSiblings;
procedure DoDrawText(var Rect: TRect; Flags: Longint);
procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM;
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure WMSize(var Message: TMessage); message WM_SIZE;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
procedure CNCtlColorBtn(var Message: TWMCtlColorBtn); message CN_CTLCOLORBTN;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
protected
procedure SetAutoSize(Value: Boolean); override;
procedure CreateParams(var Params: TCreateParams); override;
procedure SetParent(AParent: TWinControl); override;
procedure Toggle;
procedure Loaded; override;
procedure Click; override;
procedure SetChecked(Value: Boolean); override;
function GetChecked: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ClicksDisabled;
published
property Layout: TTextLayout read FLayout write SetLayout default tlCenter;
property CheckPosition: TLeftRight read FCheckPosition write SetCheckPosition default taLeftJustify;
property Look: TOriRadioCheckBoxLook read FLook write SetLook default rclDefault;
property Options: TOriRadioCheckBoxOptions read FOptions write SetOptions default [];
property AutoSize: Boolean read FAutoSize write SetAutoSize default True;
property OnPaintText: TOriRadioCheckPaintText read FOnPaintText write FOnPaintText;
property GroupIndex: Integer read FGroupIndex write FGroupIndex default 0;
property State: TCheckBoxState read FState write SetState default cbUnchecked;
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False;
property Align;
property Action;
property Anchors;
property BiDiMode;
property Caption;
property Checked;
property Color nodefault;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
{ TOriDialogPanel }
TDialogButton = (dbutOk, dbutCancel, dbutApply, dbutHelp);
TDialogButtons = set of TDialogButton;
TDialogPanelOption = (dpoSizeGrip, dpoSeparator, dpoHelpLabel, dpoHelpLabelOpposite,
dpoCatchF1);
TDialogPanelOptions = set of TDialogPanelOption;
TOriDlgButton = TButton;
TOriDialogPanel = class(TCustomControl)
private
FButtonOk: TOriDlgButton;
FButtonCancel: TOriDlgButton;
FButtonApply: TOriDlgButton;
FButtonHelp: TOriDlgButton;
FHorzMargin: Integer;
FVertMargin: Integer;
FButtonWidth: Integer;
FButtonHeight: Integer;
FButtonSpace: Integer;
FButtons: TDialogButtons;
FOnClickOK: TNotifyEvent;
FOnClickCancel: TNotifyEvent;
FOnClickApply: TNotifyEvent;
FOnClickHelp: TNotifyEvent;
FOptions: TDialogPanelOptions;
FHelpLabel: TLabel;
FHelpTopic: String;
procedure SetSize(Index: Integer; Value: Integer);
procedure SetButtons(Value: TDialogButtons);
procedure SetEvent(Index: Integer; Value: TNotifyEvent);
procedure SetOptions(const Value: TDialogPanelOptions);
procedure PaintDesignTime;
procedure PaintSizeGrip;
procedure PaintSeparator;
procedure RemoveButtons;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
protected
procedure RecreateButtons;
procedure RecreateHelpLabel;
procedure ArrangeButtons; virtual;
function GetButtonCaption(Value: TDialogButton): String; virtual;
procedure InternalHelpClick(Sender: TObject);
procedure Paint; override;
procedure SetParent(AParent: TWinControl); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ButtonOk: TOriDlgButton read FButtonOk;
property ButtonCancel: TOriDlgButton read FButtonCancel;
property ButtonApply: TOriDlgButton read FButtonApply;
property ButtonHelp: TOriDlgButton read FButtonHelp;
published
property HelpTopic: String read FHelpTopic write FHelpTopic;
property HorzMargin: Integer index 0 read FHorzMargin write SetSize default 6;
property VertMargin: Integer index 1 read FVertMargin write SetSize default 6;
property ButtonWidth: Integer index 2 read FButtonWidth write SetSize default 75;
property ButtonHeight: Integer index 3 read FButtonHeight write SetSize default 25;
property ButtonSpace: Integer index 4 read FButtonSpace write SetSize default 6;
property Buttons: TDialogButtons read FButtons write SetButtons default [dbutOk, dbutCancel];
property Options: TDialogPanelOptions read FOptions write SetOptions default [];
property OnClickOK: TNotifyEvent index 0 read FOnClickOK write SetEvent;
property OnClickCancel: TNotifyEvent index 1 read FOnClickCancel write SetEvent;
property OnClickApply: TNotifyEvent index 2 read FOnClickApply write SetEvent;
property OnClickHelp: TNotifyEvent index 3 read FOnClickHelp write SetEvent;
//property Align; TODO, see ArrangeButtons
property BiDiMode;
property BorderWidth;
property Color default clBtnFace;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
{$ifdef USE_TBX}
type
TTBXComboItem = class(TTBXItem)
protected
function GetItemViewerClass(AView: TTBView): TTBItemViewerClass; override;
end;
// нужен только чтобы подогнать ширину меню к ширине кнопки
TTBXComboItemViewer = class(TTBXItemViewer)
procedure CalcSize(const Canvas: TCanvas; var AWidth, AHeight: Integer); override;
end;
TOriComboButton = class(TOriCustomButton)
private
FItemIndex: Integer;
FOnChange: TNotifyEvent;
procedure ItemClick(Sender: TObject);
procedure SetItemIndex(Value: Integer);
function GetItemsCount: Integer;
protected
procedure DoChange;
public
constructor Create(AOwner: TComponent); override;
procedure AddItem(const Value: TOriString; Tag: Integer = 0);
property ItemsCount: Integer read GetItemsCount;
published
property ItemIndex: Integer read FItemIndex write SetItemIndex;
property Options default [boDropDownArrow];
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TOriBrushButton = class;
TOriSelectPenBrush = (bstBrush, bstPen);
TOriColorButton = class(TOriCustomButton)
private
FItemRoot: TTBXPopupMenu;
FShowCaption: Boolean;
FColorSelector: TTBXOriColorSelector;
FColorPosition: TLeftRight;
procedure SetShowCaption(Value: Boolean);
procedure SetColorPosition(Value: TLeftRight);
procedure SetSelectedColor(Value: TColor);
function GetSelectedColor: TColor;
procedure SetOnColorChange(Value: TNotifyEvent);
function GetOnColorChange: TNotifyEvent;
protected
procedure DoPopup(Sender: TObject);
procedure PaintText; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property SelectedColor: TColor read GetSelectedColor write SetSelectedColor;
published
property ColorSelector: TTBXOriColorSelector read FColorSelector write FColorSelector;
property ShowCaption: Boolean read FShowCaption write SetShowCaption default False;
property ColorPosition: TLeftRight read FColorPosition write SetColorPosition default taLeftJustify;
property OnColorChange: TNotifyEvent read GetOnColorChange write SetOnColorChange;
property Caption;
property Options default [boDropDownArrow];
end;
TOriBrushButton = class(TOriCustomButton)
private
FButtonStyle: TOriSelectPenBrush;
FPenStyle: TPenStyle;
FBrushStyle: TBrushStyle;
FSmallDots: Boolean; // for TeeChartPen
FUseSmallDots: Boolean; // for TeeChartPen
FItemRoot: TTBXPopupMenu;
FOnStyleChanged: TNotifyEvent;
FImageList: TCustomImageList;
FPopupWidth: Integer;
protected
procedure SetPenStyle(Value: TPenStyle);
procedure SetBrushStyle(Value: TBrushStyle);
procedure SetSmallDots(Value: Boolean);
procedure ItemPenClick(Sender: TObject);
procedure ItemBrushClick(Sender: TObject);
procedure DoPopup(Sender: TObject);
procedure DrawPenImage(Item: TTBCustomItem; Viewer: TTBItemViewer;
Canvas: TCanvas; ImageRect: TRect; ImageOffset: TPoint; StateFlags: Integer);
procedure DrawBrushImage(Item: TTBCustomItem; Viewer: TTBItemViewer;
Canvas: TCanvas; ImageRect: TRect; ImageOffset: TPoint; StateFlags: Integer);
procedure PaintText; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property PenStyle: TPenStyle read FPenStyle write SetPenStyle default psSolid;
property BrushStyle: TBrushStyle read FBrushStyle write SetBrushStyle default bsSolid;
property SmallDots: Boolean read FSmallDots write SetSmallDots default False;
property OnStyleChanged: TNotifyEvent read FOnStyleChanged write FOnStyleChanged;
property UseSmallDots: Boolean read FUseSmallDots write FUseSmallDots default False; // for design-time (or before first click)
property ButtonStyle: TOriSelectPenBrush read FButtonStyle write FButtonStyle nodefault; // for design-time (or before first click)
property PopupWidth: Integer read FPopupWidth write FPopupWidth nodefault; // for design-time (or before first click)
end;
{$endif}
{$ifdef USE_DKLANG}
{$ifdef UNIT_TEST}
procedure UnitTest_OriButtons_DKLang;
{$endif}
{$endif}
implementation
uses
Themes, Math, Dialogs
{$ifdef USE_DKLANG}, DKLang{$endif}
{$ifdef USE_TBX}, TBXUtils {$ifdef TBX_22A_UP}, TBXGraphics{$endif}{$endif};
{$ifdef USE_DKLANG}
{$ifdef UNIT_TEST}
// Проверяет наличие всех DKLang-констант, необходимых для работы модуля.
procedure UnitTest_OriButtons_DKLang;
begin
LangManager.ConstantValue['OriDialog_OK'];
LangManager.ConstantValue['OriDialog_Cancel'];
LangManager.ConstantValue['OriDialog_Apply'];
LangManager.ConstantValue['OriDialog_Help'];
end;
{$endif}
{$endif}
//------------------------------------------------------------------------------
{ TOriCustomButton }
constructor TOriCustomButton.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csReflector];
DoubleBuffered := True;
FCanvas := TCanvas.Create;
FLook := blDefault;
FImageIndex := -1;
FImages := nil;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := @ImageListChange;
end;
destructor TOriCustomButton.Destroy;
begin
FCanvas.Free;
FImageChangeLink.Free;
inherited;
end;
procedure TOriCustomButton.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do Style := Style or BS_OWNERDRAW;
end;
procedure TOriCustomButton.SetButtonStyle(ADefault: Boolean);
begin
if ADefault <> IFocused then
begin
IFocused := ADefault;
Refresh;
end;
end;
procedure TOriCustomButton.CMFontChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TOriCustomButton.CMEnabledChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TOriCustomButton.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
Perform(WM_LBUTTONDOWN, Message.Keys, Longint(Message.Pos));
end;
procedure TOriCustomButton.CMMouseEnter(var Message: TMessage);
begin
inherited;
if csDesigning in ComponentState then Exit;
case FLook of
blDefault:
if IsThemesEnabled and not IMouseOver then
begin
IMouseOver := True;
Repaint;
end;
blTransparent, blTransparentSys:
if not IMouseOver then
begin
IMouseOver := True;
Repaint;
end;
end;
end;
procedure TOriCustomButton.CMMouseLeave(var Message: TMessage);
begin
inherited;
case FLook of
blDefault:
if IsThemesEnabled and IMouseOver then
begin
IMouseOver := False;
Repaint;
end;
blTransparent, blTransparentSys:
if IMouseOver then
begin
IMouseOver := False;
Repaint;
end;
end;
end;
procedure TOriCustomButton.CNMeasureItem(var Message: TWMMeasureItem);
begin
with Message.MeasureItemStruct^ do
begin
itemWidth := Width;
itemHeight := Height;
end;
end;
procedure TOriCustomButton.CNDrawItem(var Message: TWMDrawItem);
begin
with Message.DrawItemStruct^ do
begin
FCanvas.Handle := hDC;
FCanvas.Font.Assign(Self.Font);
FPaintInfo.Canvas := FCanvas;
FPaintInfo.Parent := Self.Parent;
FPaintInfo.Window := Self.Handle;
FPaintInfo.Rect := ClientRect;
FPaintInfo.Pressed := itemState and ODS_SELECTED <> 0;
FPaintInfo.Default := itemState and ODS_FOCUS <> 0;
FPaintInfo.Disabled := itemState and ODS_DISABLED <> 0;
FPaintInfo.Focused := IFocused;
FPaintInfo.Hover := IMouseOver;
FPaintInfo.Checked := FChecked;
end;
PaintShape;
if boDropDownArrow in FOptions then PaintDropDownArrow;
PaintImage;
PaintText;
with FPaintInfo do
if Default and Focused and not (boNoDrawFocus in FOptions) then
PaintFocus;
FPaintInfo.Canvas.Handle := 0;
end;
procedure TOriCustomButton.PaintShape;
begin
case FLook of
blDefault:
if IsThemesEnabled
then PaintButtonShape_Themed(FPaintInfo)
else PaintButtonShape_Default(FPaintInfo);
blDefaultSys:
if IsThemesEnabled
then PaintButtonShape_ThemedSys(FPaintInfo)
else PaintButtonShape_DefaultSys(FPaintInfo);
blFlat: PaintButtonShape_Flat(FPaintInfo);
blSoft: PaintButtonShape_Soft(FPaintInfo);
blTransparent: PaintButtonShape_Transparent(FPaintInfo);
blTransparentSys: PaintButtonShape_TransparentSys(FPaintInfo);
end;
end;
procedure TOriCustomButton.PaintFocus;
begin
case FLook of
blDefault: PaintButtonFocus_Default(FPaintInfo);
blFlat: PaintButtonFocus_Flat(FPaintInfo);
blSoft: PaintButtonFocus_Default(FPaintInfo);
blTransparent, blTransparentSys: PaintButtonFocus_Default(FPaintInfo);
end;
end;
procedure TOriCustomButton.PaintImage;
begin
if (FImages <> nil) and (FImageIndex > -1)
and (FImageIndex < FImages.Count) then
with FPaintInfo, FPaintInfo.Rect do
begin
FImages.Draw(Canvas,
Left + 4 + Ord(Pressed),
(Top + Bottom - FImages.Height) div 2 + Ord(Pressed),
FImageIndex, Enabled);
Left := Left + FImages.Width + 6;
end;
end;
procedure TOriCustomButton.PaintText;
var
Flags: Cardinal;
Text: TOriString;
begin
Text := Caption;
Flags := DT_CENTER or DT_VCENTER or DT_SINGLELINE;
FCanvas.Brush.Style := bsClear;
if Enabled
then FCanvas.Font.Color := clBtnText
else FCanvas.Font.Color := clBtnShadow;
DrawText(FCanvas.Handle, POriChar(Text), Length(Text), FPaintInfo.Rect, DrawTextBiDiModeFlags(Flags));
end;
procedure TOriCustomButton.PaintDropDownArrow;
var
C: TColor;
procedure PaintDropDownArrowNormal(X, Y: Integer);
begin
with FCanvas do
begin
Pixels[X, Y] := C;
Pixels[X+1, Y] := C;
Pixels[X+2, Y] := C;
Pixels[X+3, Y] := C;
Pixels[X+4, Y] := C;
Pixels[X+5, Y] := C;
Pixels[X+6, Y] := C;
Pixels[X+1, Y+1] := C;
Pixels[X+2, Y+1] := C;
Pixels[X+3, Y+1] := C;
Pixels[X+4, Y+1] := C;
Pixels[X+5, Y+1] := C;
Pixels[X+2, Y+2] := C;
Pixels[X+3, Y+2] := C;
Pixels[X+4, Y+2] := C;
Pixels[X+3, Y+3] := C;
end;
end;
procedure PaintDropDownArrowHoriz(X, Y: Integer);
begin
with FCanvas do
begin
Pixels[X, Y] := C;
Pixels[X, Y+1] := C;
Pixels[X, Y+2] := C;
Pixels[X, Y+3] := C;
Pixels[X, Y+4] := C;
Pixels[X, Y+5] := C;
Pixels[X, Y+6] := C;
Pixels[X+1, Y+1] := C;
Pixels[X+1, Y+2] := C;
Pixels[X+1, Y+3] := C;
Pixels[X+1, Y+4] := C;
Pixels[X+1, Y+5] := C;
Pixels[X+2, Y+2] := C;
Pixels[X+2, Y+3] := C;
Pixels[X+2, Y+4] := C;
Pixels[X+3, Y+3] := C;
end;
end;
procedure PaintDropDownArrowEllipsis(X, Y: Integer);
begin
with FCanvas do
begin
Pixels[X, Y+1] := C; Pixels[X+1, Y+1] := C;
Pixels[X, Y+2] := C; Pixels[X+1, Y+2] := C;
Pixels[X+3, Y+1] := C; Pixels[X+4, Y+1] := C;
Pixels[X+3, Y+2] := C; Pixels[X+4, Y+2] := C;
Pixels[X+6, Y+1] := C; Pixels[X+7, Y+1] := C;
Pixels[X+6, Y+2] := C; Pixels[X+7, Y+2] := C;
end;
end;
var
X, Y: Integer;
begin
X := FPaintInfo.Rect.Right - 7 - 4;
Y := (FPaintInfo.Rect.Top + FPaintInfo.Rect.Bottom) div 2 - 2;
FPaintInfo.Rect.Right := FPaintInfo.Rect.Right - 12;
if Enabled
then C := clBtnText
else C := clBtnShadow;
if boDropDownHoriz in FOptions then
PaintDropDownArrowHoriz(X, Y-2)
else if boDropDownAsEllipsis in FOptions then
PaintDropDownArrowEllipsis(X-1, Y)
else PaintDropDownArrowNormal(X, Y);
end;
procedure TOriCustomButton.SetChecked(Value: Boolean);
begin
if Value <> FChecked then
begin
FChecked := Value;
Invalidate;
end;
end;
function TOriCustomButton.GetChecked: Boolean;
begin
Result := FChecked;
end;
procedure TOriCustomButton.SetOptions(Value: TOriButtonOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
Invalidate;
end;
end;
procedure TOriCustomButton.Click;
var
i: Integer;
pt: TPoint;
begin
if GroupIndex > 0 then
begin
if not Checked then
begin
Checked := True;
with Parent do
for i := 0 to ControlCount-1 do
if (Controls[i] is TOriCustomButton) and (Controls[i] <> Self) then
with TOriCustomButton(Controls[i]) do
if Checked and (GroupIndex = Self.GroupIndex) then
Checked := False;
end
else
if boAllowAllUnchecked in Options then Checked := False;
end;
if Assigned(FDropDownMenu) and not (boNoAutoDropDownMenu in Options) then
begin
if boDropDownAlignRight in Options then pt.X := Width else pt.X := 0;
pt.Y := Height;
pt := ClientToScreen(pt);
FDropDownMenu.PopupComponent := Self;
FDropDownMenu.Popup(pt.X, pt.Y);
end;
inherited;
end;
procedure TOriCustomButton.SetLook(Value: TOriButtonLook);
begin
if FLook <> Value then
begin
FLook := Value;
Invalidate;
end;
end;
procedure TOriCustomButton.SetImages(Value: TCustomImageList);
begin
if FImages <> nil then
FImages.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if FImages <> nil then
begin
FImages.RegisterChanges(FImageChangeLink);
FImages.FreeNotification(Self);
end;
Invalidate;
end;
procedure TOriCustomButton.SetImageIndex(Value: TImageIndex);
begin
if Value <> FImageIndex then
begin
FImageIndex := Value;
Invalidate;
end;
end;
procedure TOriCustomButton.ImageListChange(Sender: TObject);
begin
if Sender = Images then Invalidate;
end;
//------------------------------------------------------------------------------
{ TOriImgButton }
constructor TOriImgButton.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle - [csSetCaption];
Width := 25;
Height := 25;
FMonoGlyph := bgNone;
end;
procedure TOriImgButton.PaintImage;
var OffsetX, OffsetY: Integer;
begin
if FMonoGlyph <> bgNone then
with FPaintInfo, FPaintInfo.Rect do
begin
if Pressed and (Width > MonoGlyphW * 2) then OffsetX := 1 else OffsetX := 0;
if Pressed and (Height > MonoGlyphH * 2) then OffsetY := 1 else OffsetY := 0;
DrawMonoGlyph(Canvas.Handle,
(Left + Right - MonoGlyphW) div 2 + OffsetX,
(Top + Bottom - MonoGlyphH) div 2 + OffsetY,
FMonoGlyph, IfThen(Enabled, clWindowText, clBtnShadow));
end
else // paint image centered
if (FImages <> nil) and (FImageIndex > -1)
and (FImageIndex < FImages.Count) then
with FPaintInfo, FPaintInfo.Rect do
FImages.Draw(Canvas,
(Left + Right - FImages.Width) div 2 + Ord(Pressed),
(Top + Bottom - FImages.Height) div 2 + Ord(Pressed),
FImageIndex, Enabled);
end;
procedure TOriImgButton.PaintText;
begin
// do nothing
end;
procedure TOriImgButton.SetMonoGlyph(Value: TOriButtonMonoGlyph);
begin
if Value <> FMonoGlyph then
begin
FMonoGlyph := Value;
Invalidate;
end;
end;
//------------------------------------------------------------------------------
{ TOriRadioCheckBox }
const
CheckSize = 13;
CheckIndent = 5;
constructor TOriRadioCheckBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csSetCaption, csDoubleClicks];
FCanvas := TCanvas.Create;
DoubleBuffered := True;
TabStop := True;
FLayout := tlCenter;
FLook := rclDefault;
FCheckPosition := taLeftJustify;
FAlignment := taLeftJustify;
FAutoSize := True;
FState := cbUnchecked;
end;
destructor TOriRadioCheckBox.Destroy;
begin
FCanvas.Free;
inherited Destroy;
end;
procedure TOriRadioCheckBox.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
CreateSubClass(Params, 'BUTTON');
with Params do
begin
Style := Style or BS_OWNERDRAW;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
procedure TOriRadioCheckBox.Loaded;
begin
inherited Loaded;
if FAutoSize then AdjustBounds;
end;
procedure TOriRadioCheckBox.SetParent(AParent: TWinControl);
begin
inherited;
if Assigned(Parent) and FAutoSize then AdjustBounds;
end;
procedure TOriRadioCheckBox.SetAutoSize(Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
AdjustBounds;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.SetOptions(Value: TOriRadioCheckBoxOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
if (rcoRadioButton in FOptions) and (FState = cbGrayed) then
FState := cbUnchecked; // radio button can't be grayed
AdjustBounds;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.SetLook(Value: TOriRadioCheckBoxLook);
begin
if Value <> FLook then
begin
FLook := Value;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.SetCheckPosition(Value: TLeftRight);
begin
if FCheckPosition <> Value then
begin
FCheckPosition := Value;
AdjustBounds;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.SetLayout(Value: TTextLayout);
begin
if Value <> FLayout then
begin
FLayout := Value;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.SetAlignment(Value: TAlignment);
begin
if Value <> FAlignment then
begin
FAlignment := Value;
AdjustBounds;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.CNMeasureItem(var Message: TWMMeasureItem);
begin
with Message.MeasureItemStruct^ do
begin
itemWidth := Width;
itemHeight := Height;
end;
end;
procedure TOriRadioCheckBox.CNDrawItem(var Message: TWMDrawItem);
begin
DrawItem(Message.DrawItemStruct^);
end;
procedure TOriRadioCheckBox.CMMouseEnter(var Message: TMessage);
begin
inherited;
if (FLook = rclDefault) and IsThemesEnabled and
not _MouseOver and not (csDesigning in ComponentState) then
begin
_MouseOver := True;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.CMMouseLeave(var Message: TMessage);
begin
inherited;
if (FLook = rclDefault) and IsThemesEnabled and _MouseOver then
begin
_MouseOver := False;
Invalidate;
end;
end;
procedure TOriRadioCheckBox.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
Invalidate;
end;
procedure TOriRadioCheckBox.CMEnabledChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TOriRadioCheckBox.CMTextChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
Invalidate;
end;
procedure TOriRadioCheckBox.WMSize(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TOriRadioCheckBox.CMDialogChar(var Message: TCMDialogChar);
begin
with Message do
if IsAccel(CharCode, Caption) and CanFocus then
begin
SetFocus;
if Focused then Toggle;
Result := 1;
end
else inherited;
end;
procedure TOriRadioCheckBox.CNCommand(var Message: TWMCommand);
begin
case Message.NotifyCode of
BN_CLICKED,
BN_DOUBLECLICKED: Toggle;
end;
end;
procedure TOriRadioCheckBox.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
if IsThemesEnabled then
Message.Result := 1
else
DefaultHandler(Message);
end;
procedure TOriRadioCheckBox.CNCtlColorBtn(var Message: TWMCtlColorBtn);
begin
with OriGraphics.ThemeServices do
if IsThemesEnabled then
begin
DrawParentBackground(Handle, Message.ChildDC, nil, False);
// Return an empty brush to prevent Windows
// from overpainting we just have created.
Message.Result := GetStockObject(NULL_BRUSH);
end
else
inherited;
end;
procedure TOriRadioCheckBox.AdjustBounds;
const
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
VAlignments: array[Boolean] of Word = (DT_VCENTER, DT_TOP);
var
DC: HDC;
Rect: TRect;
// Align: TAlignment;
begin
if not (csReading in ComponentState) and FAutoSize and Assigned(Parent) then
begin
DC := GetDC(0);
try
FCanvas.Handle := DC;
Rect := ClientRect;
Inc(Rect.Right, CheckSize + CheckIndent + 3);
DoDrawText(Rect, DT_EXPANDTABS or DT_CALCRECT or WordWraps[WordWrap] or VAlignments[WordWrap]);
FCanvas.Handle := 0;
finally
ReleaseDC(0, DC);
end;
// Align := FAlignment;
// if UseRightToLeftAlignment then ChangeBiDiModeAlignment(Align);
SetBounds(Left, Top, Rect.Right + CheckSize + CheckIndent + 3, Rect.Bottom + 4);
end;
end;
procedure TOriRadioCheckBox.DoDrawText(var Rect: TRect; Flags: Longint);
var
Text: TOriString;
PaintDefault: Boolean;
begin
Text := Caption;
if (Flags and DT_CALCRECT <> 0) and ((Text = '') or (Text[1] = '&') and (Text[2] = #0))
then Text := Text + ' ';
Flags := DrawTextBiDiModeFlags(Flags);
// it is true painting, not measuring
if Flags and DT_CALCRECT = 0 then
begin
// reserve place for focus frame, during measurement this
// additional place are taken into account in SetBounds
if Flags and DT_VCENTER = 0 then Rect.Top := Rect.Top + 1;
PaintDefault := True;
if Assigned(FOnPaintText) then
FOnPaintText(Self, FCanvas, Text, Rect, Flags, PaintDefault);
if not PaintDefault then Exit;
end;
with FCanvas do
begin
Font.Assign(Self.Font);
Brush.Style := bsClear;
case Flook of
rclDefault:
if not Enabled then
begin
OffsetRect(Rect, 1, 1);
Font.Color := clBtnHighlight;
OriGraphics.DrawText(Handle, POriChar(Text), Length(Text), Rect, Flags);
OffsetRect(Rect, -1, -1);
Font.Color := clBtnShadow;
OriGraphics.DrawText(Handle, POriChar(Text), Length(Text), Rect, Flags);
end
else
OriGraphics.DrawText(Handle, POriChar(Text), Length(Text), Rect, Flags);
rclFlat:
begin
if not Enabled then Font.Color := clBtnShadow;
OriGraphics.DrawText(Handle, POriChar(Text), Length(Text), Rect, Flags);
end;
end;
end;
end;
procedure TOriRadioCheckBox.DrawItem(const DrawItemStruct: TDrawItemStruct);
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
VAlignments: array[Boolean] of Word = (DT_VCENTER, DT_TOP);
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
IsDown, IsFocused: Boolean;
PaintDefault: Boolean;
R, CheckRect, TxtRect: TRect;
Flags: Longint;
Details: TThemedElementDetails;
Button: TThemedButton;
DrawStyle: Longint;
{$ifdef DXE2_UP}
DrawTextFmt: TTextFormat;
{$endif}
begin
R := ClientRect;
with DrawItemStruct do
begin
FCanvas.Handle := hDC;
FCanvas.Font.Assign(Self.Font);
IsDown := itemState and ODS_SELECTED <> 0;
IsFocused := itemState and ODS_FOCUS <> 0;
end;
if CheckPosition = taLeftJustify then
begin
case Layout of
tlTop: CheckRect := Classes.Rect(R.Left, R.Top, R.Left+CheckSize, R.Top+CheckSize);
tlBottom: CheckRect := Classes.Rect(R.Left, R.Bottom, R.Left+CheckSize, R.Bottom-CheckSize);
tlCenter: CheckRect := Classes.Rect(R.Left, (R.Bottom+R.Top-CheckSize) div 2, R.Left+CheckSize, (R.Bottom+R.Top+CheckSize) div 2);
end;
Inc(R.Left, CheckSize + CheckIndent);
end
else
begin
case Layout of
tlTop: CheckRect := Classes.Rect(R.Right-CheckSize, R.Top, R.Right, R.Top+CheckSize);
tlBottom: CheckRect := Classes.Rect(R.Right-CheckSize, R.Bottom, R.Right, R.Bottom-CheckSize);
tlCenter: CheckRect := Classes.Rect(R.Right-CheckSize, (R.Bottom+R.Top-CheckSize) div 2, R.Right, (R.Bottom+R.Top+CheckSize) div 2);
end;
Dec(R.Right, CheckSize + CheckIndent);
end;
// DoDrawText takes care of BiDi alignments
DrawStyle := DT_EXPANDTABS or WordWraps[WordWrap] or
Alignments[FAlignment] or VAlignments[WordWrap];
TxtRect := R;
DoDrawText(TxtRect, DrawStyle or DT_CALCRECT);
OffsetRect(TxtRect, 0, (Height-TxtRect.Bottom) div 2);
case FLook of
rclDefault:
if IsThemesEnabled then
begin
if (rcoRadioButton in Options) and not (rcoRadioAsCheck in Options) then
if not Enabled then
case State of
cbChecked: Button := tbRadioButtonCheckedDisabled;
else Button := tbRadioButtonUncheckedDisabled;
end
else if IsDown then
case State of
cbChecked: Button := tbRadioButtonCheckedPressed;
else Button := tbRadioButtonUncheckedPressed;
end
else if _MouseOver then
case State of
cbChecked: Button := tbRadioButtonCheckedHot;
else Button := tbRadioButtonUncheckedHot;
end
else
case State of
cbChecked: Button := tbRadioButtonCheckedNormal;
else Button := tbRadioButtonUncheckedNormal;
end
else
begin
if not Enabled then
case State of
cbChecked: Button := tbCheckBoxCheckedDisabled;
cbUnchecked: Button := tbCheckBoxUncheckedDisabled;
else Button := tbCheckBoxMixedDisabled;
end
else if IsDown then
case State of
cbChecked: Button := tbCheckBoxCheckedPressed;
cbUnchecked: Button := tbCheckBoxUncheckedPressed;
else Button := tbCheckBoxMixedPressed;
end
else if _MouseOver then
case State of
cbChecked: Button := tbCheckBoxCheckedHot;
cbUnchecked: Button := tbCheckBoxUncheckedHot;
else Button := tbCheckBoxMixedHot;
end
else
case State of
cbChecked: Button := tbCheckBoxCheckedNormal;
cbUnchecked: Button := tbCheckBoxUncheckedNormal;
else Button := tbCheckBoxMixedNormal;
end;
end;
Details := OriGraphics.ThemeServices.GetElementDetails(Button);
OriGraphics.ThemeServices.DrawParentBackground(Parent.Handle, DrawItemStruct.hDC, @Details, True);
OriGraphics.ThemeServices.DrawElement(FCanvas.Handle, Details, CheckRect);
PaintDefault := True;
if Assigned(FOnPaintText) then
FOnPaintText(Self, FCanvas, Caption,
TxtRect, DrawTextBiDiModeFlags(DrawStyle), PaintDefault);
if PaintDefault then
begin
{$ifdef DXE2_UP}
DrawTextFmt := [tfExpandTabs];
if WordWrap then
DrawTextFmt := DrawTextFmt + [tfWordBreak, tfTop]
else
Include(DrawTextFmt, tfVerticalCenter);
case FAlignment of
taLeftJustify: Include(DrawTextFmt, tfLeft);
taRightJustify: Include(DrawTextFmt, tfRight);
taCenter: Include(DrawTextFmt, tfCenter);
end;
if UseRightToLeftAlignment then
Include(DrawTextFmt, tfRtlReading);
OriGraphics.ThemeServices.DrawText(DrawItemStruct.hDC, Details, Caption,
TxtRect, DrawTextFmt, 0);
{$else}
OriGraphics.ThemeServices.DrawText(DrawItemStruct.hDC, Details, Caption,
TxtRect, DrawTextBiDiModeFlags(DrawStyle), 0);
{$endif}
end;
end
else
begin
if (rcoRadioButton in Options) and not (rcoRadioAsCheck in Options)
then Flags := DFCS_BUTTONRADIO
else Flags := DFCS_BUTTONCHECK;
if Checked then Flags := Flags or DFCS_CHECKED;
if IsDown then Flags := Flags or DFCS_PUSHED;
if DrawItemStruct.itemState and ODS_DISABLED <> 0 then
Flags := Flags or DFCS_INACTIVE;
DrawFrameControl(DrawItemStruct.hDC, CheckRect, DFC_BUTTON, Flags);
DoDrawText(TxtRect, DrawStyle);
if IsFocused then
with FCanvas do
begin
Pen.Color := clWindowFrame;
Brush.Color := clWindow;
Font.Color := clWindowText;
InflateRect(TxtRect, 2, 2);
case FCheckPosition of
// если текст слева, то он начинается с нуля
// и focus-rect вылезет за пределы компонента
taRightJustify: TxtRect.Left := 0;
end;
Windows.DrawFocusRect(FCanvas.Handle, TxtRect);
end;
end;
rclFlat:
with FCanvas do
begin
if (rcoRadioButton in Options) and not (rcoRadioAsCheck in Options) then
begin
DrawRadioCircle(FCanvas.Handle, CheckRect, IsDown, Checked, Enabled);
end
else
begin
Pen.Color := clBtnShadow;
if IsDown or not Enabled or (State = cbGrayed)
then Brush.Color := clBtnFace
else Brush.Color := clBtnHighlight;
Rectangle(CheckRect); // check rect
if Checked then
DrawMonoGlyph(Handle, CheckRect.Left+2, CheckRect.Top+1,
bgCheck, IfThen(Enabled, clWindowText, clBtnShadow));
end;
DoDrawText(TxtRect, DrawStyle);
if IsFocused then
begin
Pen.Color := clWindowFrame;
Brush.Color := clWindow;
Font.Color := clWindowText;
InflateRect(TxtRect, 2, 2);
case FCheckPosition of
// если текст слева, то он начинается с нуля
// и focus-rect вылезет за пределы компонента
taRightJustify: TxtRect.Left := 0;
end;
Windows.DrawFocusRect(FCanvas.Handle, TxtRect);
end;
end;
end;
FCanvas.Handle := 0;
end;
function TOriRadioCheckBox.GetChecked: Boolean;
begin
Result := State = cbChecked;
end;
procedure TOriRadioCheckBox.SetChecked(Value: Boolean);
begin
if Value then State := cbChecked else State := cbUnchecked;
end;
procedure TOriRadioCheckBox.SetState(Value: TCheckBoxState);
begin
if FState <> Value then
begin
FState := Value;
Invalidate;
if (rcoRadioButton in FOptions) and (FState = cbChecked) then
UncheckSiblings;
if not ClicksDisabled then Click;
end;
end;
procedure TOriRadioCheckBox.Toggle;
begin
case State of
cbUnchecked:
if FAllowGrayed and not (rcoRadioButton in FOptions)
then State := cbGrayed
else State := cbChecked;
cbChecked:
if rcoRadioButton in FOptions
then Exit // user can't switch radio button to off
else State := cbUnchecked;
cbGrayed: State := cbChecked;
end;
end;
procedure TOriRadioCheckBox.UncheckSiblings;
var i: Integer;
begin
for i := 0 to Parent.ControlCount-1 do
if (Parent.Controls[i] <> Self)
and (Parent.Controls[i] is TOriRadioCheckBox) then
with TOriRadioCheckBox(Parent.Controls[i]) do
if Checked and (rcoRadioButton in Options)
and (GroupIndex = Self.GroupIndex)
then Checked := False;
end;
procedure TOriRadioCheckBox.Click;
begin
inherited Changed;
inherited Click;
end;
//------------------------------------------------------------------------------
{ TOriDialogPanel }
constructor TOriDialogPanel.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csAcceptsControls, csParentbackGround] - [csOpaque];
FButtons := [dbutOk, dbutCancel];
FHorzMargin := 6;
FVertMargin := 6;
FButtonWidth := 75;
FButtonHeight := 25;
FButtonSpace := 6;
Align := alBottom;
Height := FButtonHeight + 2*FVertMargin;
BevelInner := bvNone;
BevelOuter := bvNone;
ParentBackground := True;
// if default value then create buttons,
// else buttons will be created in SetButtons during loading
if FButtons = [dbutOk, dbutCancel] then RecreateButtons;
end;
destructor TOriDialogPanel.Destroy;
begin
RemoveButtons;
inherited;
end;
{
var
HookHandle: HHOOK;
function GetMsgHookProc(code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
msg: PMsg;
begin
msg := PMsg(Pointer(lParam));
case msg.message of
// This undocumented message is a precursor to WM_HELP and catching
$4D: if wParam = PM_REMOVE then MsgBox('F1');
end;
Result := CallNextHookEx(HookHandle, code, wParam, lParam);
end;
}
procedure TOriDialogPanel.SetParent(AParent: TWinControl);
begin
inherited;
// HookHandle := SetWindowsHookEx(WH_GETMESSAGE, GetMsgHookProc, 0, GetCurrentThreadId);
end;
function TOriDialogPanel.GetButtonCaption(Value: TDialogButton): TOriString;
{$ifdef USE_DKLANG}
function GetItemName(const AKey: String; const ADefault: TOriString): TOriString;
begin
try
Result := LangManager.ConstantValue[AKey]
except
Result := ADefault;
end;
end;
{$endif}
const
SCaptionOK = 'OK';
SCaptionCancel = 'Cancel';
SCaptionApply = 'Apply';
SCaptionHelp = 'Help';
begin
{$ifdef USE_DKLANG}
try
case Value of
dbutOk: Result := GetItemName('OriDialog_OK', SCaptionOK);
dbutCancel: Result := GetItemName('OriDialog_Cancel', SCaptionCancel);
dbutApply: Result := GetItemName('OriDialog_Apply', SCaptionApply);
dbutHelp: Result := GetItemName('OriDialog_Help', SCaptionHelp);
end;
except
// TODO: убрать, когда старые имена констант (SDialog...)
// будут исправлены во всех проектах на новые
case Value of
dbutOk: Result := GetItemName('SDialogPanelOK', SCaptionOK);
dbutCancel: Result := GetItemName('SDialogPanelCancel', SCaptionCancel);
dbutApply: Result := GetItemName('SDialogPanelApply', SCaptionApply);
dbutHelp: Result := GetItemName('SDialogPanelHelp', SCaptionHelp);
end;
end;
{$else}
case Value of
dbutOk: Result := SCaptionOK;
dbutCancel: Result := SCaptionCancel;
dbutApply: Result := SCaptionApply;
dbutHelp: Result := SCaptionHelp;
end;
{$endif}
end;
procedure TOriDialogPanel.RemoveButtons;
begin
FreeAndNil(FButtonOk);
FreeAndNil(FButtonCancel);
FreeAndNil(FButtonApply);
FreeAndNil(FButtonHelp);
end;
procedure TOriDialogPanel.RecreateButtons;
begin
RemoveButtons;
if dbutOk in FButtons then
begin
FButtonOk := TOriDlgButton.Create(Self);
with FButtonOk do
begin
Parent := Self;
ModalResult := mrOk;
Default := True;
Caption := GetButtonCaption(dbutOk);
OnClick := FOnClickOK;
end;
end;
if dbutCancel in FButtons then
begin
FButtonCancel := TOriDlgButton.Create(Self);
with FButtonCancel do
begin
Parent := Self;
ModalResult := mrCancel;
Cancel := True;
Caption := GetButtonCaption(dbutCancel);
OnClick := FOnClickCancel;
end;
end;
if dbutApply in FButtons then
begin
FButtonApply := TOriDlgButton.Create(Self);
with FButtonApply do
begin
Parent := Self;
Caption := GetButtonCaption(dbutApply);
OnClick := FOnClickApply;
end;
end;
if dbutHelp in FButtons then
begin
FButtonHelp := TOriDlgButton.Create(Self);
with FButtonHelp do
begin
Parent := Self;
Caption := GetButtonCaption(dbutHelp);
OnClick := InternalHelpClick;
end;
end;
end;
procedure TOriDialogPanel.RecreateHelpLabel;
begin
FreeAndNil(FHelpLabel);
if dpoHelpLabel in FOptions then
begin
FHelpLabel := TLabel.Create(Self);
with FHelpLabel do
begin
Parent := Self;
Caption := GetButtonCaption(dbutHelp);
Font.Color := clBlue;
Font.Style := Font.Style + [fsUnderline];
Cursor := crHandPoint;
OnClick := InternalHelpClick;
end;
end;
end;
procedure TOriDialogPanel.ArrangeButtons;
var w: Integer;
begin
// TODO: remaining aligns will be coded as needed
//case Align of
//alBottom:
begin
if Assigned(FButtonHelp) then
begin
FButtonHelp.Height := FButtonHeight;
FButtonHelp.Width := FButtonWidth;
FButtonHelp.Top := Height - FButtonHeight - FVertMargin;
FButtonHelp.Left := FHorzMargin;
end;
w := 0;
if Assigned(FButtonApply) then
begin
Inc(w, FButtonWidth);
FButtonApply.Height := FButtonHeight;
FButtonApply.Width := FButtonWidth;
FButtonApply.Top := Height - FVertMargin - FButtonHeight;
FButtonApply.Left := Width - FHorzMargin - w;
Inc(w, FButtonSpace);
end;
if Assigned(FButtonCancel) then
begin
Inc(w, FButtonWidth);
FButtonCancel.Height := FButtonHeight;
FButtonCancel.Width := FButtonWidth;
FButtonCancel.Top := Height - FVertMargin - FButtonHeight;
FButtonCancel.Left := Width - FHorzMargin - w;
Inc(w, FButtonSpace);
end;
if Assigned(FButtonOK) then
begin
Inc(w, FButtonWidth);
FButtonOK.Height := FButtonHeight;
FButtonOK.Width := FButtonWidth;
FButtonOK.Top := Height - FVertMargin - FButtonHeight;
FButtonOK.Left := Width - FHorzMargin - w;
end;
if Assigned(FHelpLabel) then
begin
FHelpLabel.Left := FHorzMargin;
if dpoHelpLabelOpposite in FOptions then
FHelpLabel.Top := Height - FVertMargin - FHelpLabel.Height
else
FHelpLabel.Top := 0;
end;
end;
//end;
end;
procedure TOriDialogPanel.SetSize(Index: Integer; Value: Integer);
begin
case Index of
0:
if Value <> FHorzMargin then
begin
FHorzMargin := Value;
ArrangeButtons;
end;
1:
if Value <> FVertMargin then
begin
FVertMargin := Value;
ArrangeButtons;
end;
2:
if Value <> FButtonWidth then
begin
FButtonWidth := Value;
ArrangeButtons;
end;
3:
if Value <> FButtonHeight then
begin
FButtonHeight := Value;
ArrangeButtons;
end;
4:
if Value <> FButtonSpace then
begin
FButtonSpace := Value;
ArrangeButtons;
end;
end;
end;
procedure TOriDialogPanel.SetButtons(Value: TDialogButtons);
begin
if Value <> FButtons then
begin
FButtons := Value;
RecreateButtons;
ArrangeButtons;
end;
end;
procedure TOriDialogPanel.WMSize(var Message: TWMSize);
begin
inherited;
ArrangeButtons;
end;
procedure TOriDialogPanel.SetEvent(Index: Integer; Value: TNotifyEvent);
begin
case Index of
0:
begin
FOnClickOK := Value;
if Assigned(FButtonOK) then FButtonOK.OnClick := Value;
end;
1:
begin
FOnClickCancel := Value;
if Assigned(FButtonCancel) then FButtonCancel.OnClick := Value;
end;
2:
begin
FOnClickApply := Value;
if Assigned(FButtonApply) then FButtonApply.OnClick := Value;
end;
3:
begin
FOnClickHelp := Value;
end;
end;
end;
procedure TOriDialogPanel.InternalHelpClick(Sender: TObject);
begin
if FHelpTopic <> '' then ShowHelp(FHelpTopic);
if Assigned(FOnClickHelp) then FOnClickHelp(Self);
end;
procedure TOriDialogPanel.SetOptions(const Value: TDialogPanelOptions);
begin
if FOptions <> Value then
begin
FOptions := Value;
RecreateHelpLabel;
ArrangeButtons;
Invalidate;
end;
end;
procedure TOriDialogPanel.PaintDesignTime;
var
R: TRect;
DC: HDC;
begin
DC := Canvas.Handle;
R := ClientRect;
SaveDC(DC);
ExcludeClipRect(DC, R.Left+1, R.Top+1, R.Right-1, R.Bottom-1);
DitherRect(DC, R, clBtnFace, clBtnShadow);
RestoreDC(DC, -1);
end;
procedure TOriDialogPanel.PaintSizeGrip;
var
D, Sz, I: Integer;
DC: HDC;
R: TRect;
procedure DiagLine(C: TColor);
var
Pen, OldPen: HPEN;
begin
if C < 0 then C := GetSysColor(C and $000000FF);
Pen := CreatePen(PS_SOLID, 1, C);
OldPen := SelectObject(DC, Pen);
with R do
begin
Windows.MoveToEx(DC, Right - 1 - D, Bottom - 1, nil);
Windows.LineTo(DC, Right, Bottom - D - 2);
end;
SelectObject(DC, OldPen);
DeleteObject(Pen);
Inc(D);
end;
begin
D := 0;
R := ClientRect;
DC := Canvas.Handle;
Sz := Min(R.Right - R.Left, R.Bottom - R.Top);
// code borrwed from TTBXOfficeXPTheme.PaintStatusBar
for I := 1 to 3 do
case Sz of
0..8:
begin
DiagLine(clBtnShadow);
DiagLine(clBtnHighlight);
end;
9..11:
begin
DiagLine(clBtnFace);
DiagLine(clBtnShadow);
DiagLine(clBtnHighlight);
end;
12..14:
begin
DiagLine(clBtnShadow);
DiagLine(clBtnShadow);
DiagLine(clBtnHighlight);
end;
else
DiagLine(clBtnFace);
DiagLine(clBtnShadow);
DiagLine(clBtnShadow);
DiagLine(clBtnHighlight);
end;
end;
procedure TOriDialogPanel.PaintSeparator;
begin
Canvas.Pen.Color := clBtnShadow;
case Align of
alBottom:
begin
Canvas.MoveTo(0, 0);
Canvas.LineTo(Width, 0);
end;
// TODO: остальные по необходимости
end;
end;
procedure TOriDialogPanel.Paint;
begin
if not IsThemesEnabled or not ParentBackground then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(ClientRect);
end;
if csDesigning in ComponentState then PaintDesignTime;
if dpoSizeGrip in FOptions then PaintSizeGrip;
if dpoSeparator in FOptions then PaintSeparator;
end;
//------------------------------------------------------------------------------
{$ifdef USE_TBX}
{ TOriColorButton }
constructor TOriColorButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Include(FOptions, boDropDownArrow);
FItemRoot := TTBXPopupMenu.Create(Self);
FItemRoot.OnPopup := DoPopup;
FItemRoot.Options := FItemRoot.Options + [tboToolbarStyle];
DropDownMenu := FItemRoot;
FColorPosition := taLeftJustify;
FColorSelector := TTBXOriColorSelector.Create(Self);
end;
destructor TOriColorButton.Destroy;
begin
FItemRoot.Free;
FColorSelector.Free;
inherited;
end;
procedure TOriColorButton.DoPopup(Sender: TObject);
begin
FColorSelector.InitItems(FItemRoot.Items);
end;
procedure TOriColorButton.SetShowCaption(Value: Boolean);
begin
if FShowCaption <> Value then
begin
FShowCaption := Value;
Invalidate;
end;
end;
procedure TOriColorButton.SetColorPosition(Value: TLeftRight);
begin
if FColorPosition <> Value then
begin
FColorPosition := Value;
Invalidate;
end;
end;
procedure TOriColorButton.SetSelectedColor(Value: TColor);
begin
FColorSelector.SelectedColor := Value;
end;
function TOriColorButton.GetSelectedColor: TColor;
begin
Result := FColorSelector.SelectedColor;
end;
procedure TOriColorButton.SetOnColorChange(Value: TNotifyEvent);
begin
FColorSelector.OnColorChange := Value;
end;
function TOriColorButton.GetOnColorChange: TNotifyEvent;
begin
Result := FColorSelector.OnColorChange;
end;
procedure TOriColorButton.PaintText;
var
Rect: TRect;
begin
if FShowCaption then
begin
Rect := FPaintInfo.Rect;
if FColorPosition = taLeftJustify then
begin
Rect.Right := Rect.Left + Rect.Bottom - Rect.Top;
FPaintInfo.Rect.Left := Rect.Right;
end
else
begin
Rect.Left := Rect.Right - Rect.Bottom + Rect.Top;
FPaintInfo.Rect.Right := Rect.Left;
end;
end
else Rect := FPaintInfo.Rect;
if FPaintInfo.Pressed and (FLook <> blFlat) then
OffsetRect(Rect, 1, 1);
InflateRect(Rect, -4, -4);
// paint rect with selected color
FCanvas.Pen.Color := clGray;
FCanvas.Brush.Color := FColorSelector.SelectedColor;
FCanvas.Rectangle(Rect);
if FShowCaption then inherited;
end;
//------------------------------------------------------------------------------
{ TOriBrushButton }
constructor TOriBrushButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Include(FOptions, boDropDownArrow);
FButtonStyle := bstBrush;
FPenStyle := psSolid;
FBrushStyle := bsSolid;
FSmallDots := False;
FUseSmallDots := False;
FPopupWidth := 80;
FItemRoot := TTBXPopupMenu.Create(Self);
FItemRoot.OnPopup := DoPopup;
FItemRoot.Options := FItemRoot.Options + [tboToolbarStyle];
DropDownMenu := FItemRoot;
end;
destructor TOriBrushButton.Destroy;
begin
FItemRoot.Free;
inherited;
end;
procedure TOriBrushButton.SetPenStyle(Value: TPenStyle);
begin
if Value <> FPenStyle then
begin
FPenStyle := Value;
Invalidate;
end;
end;
procedure TOriBrushButton.SetBrushStyle(Value: TBrushStyle);
begin
if Value <> FBrushStyle then
begin
FBrushStyle := Value;
Invalidate;
end;
end;
procedure TOriBrushButton.SetSmallDots(Value: Boolean);
begin
if Value <> FSmallDots then
begin
FSmallDots := Value;
Invalidate;
end;
end;
procedure TOriBrushButton.ItemPenClick(Sender: TObject);
begin
FSmallDots := TPenStyle((Sender as TTBXItem).Tag) = psInsideFrame;
PenStyle := TPenStyle((Sender as TTBXItem).Tag);
if Assigned(OnStyleChanged) then OnStyleChanged(Self);
end;
procedure TOriBrushButton.ItemBrushClick(Sender: TObject);
begin
BrushStyle := TBrushStyle((Sender as TTBXItem).Tag);
if Assigned(OnStyleChanged) then OnStyleChanged(Self);
end;
procedure TOriBrushButton.DrawPenImage(Item: TTBCustomItem;
Viewer: TTBItemViewer; Canvas: TCanvas; ImageRect: TRect;
ImageOffset: TPoint; StateFlags: Integer);
var
X1, X2, Y: Integer;
R: TRect;
begin
R := ImageRect;
with Canvas do
begin
Brush.Color := clWhite;
Pen.Color := clDkGray;
Pen.Style := psSolid;
Rectangle(R);
Y := (R.Top + R.Bottom) div 2;
X1 := R.Left + 1;
X2 := R.Right - 1;
if TPenStyle(Item.Tag) = psInsideFrame then begin
while X1 < X2 do begin
Pixels[X1, Y] := clDkGray;
Pixels[X1+1, Y] := clDkGray;
Pixels[X1, Y+1] := clDkGray;
Pixels[X1+1, Y+1] := clDkGray;
Inc(X1, 4);
end;
end
else begin
Pen.Style := TPenStyle(Item.Tag);
MoveTo(X1, Y);
LineTo(X2, Y);
MoveTo(X1, Y-1);
LineTo(X2, Y-1);
MoveTo(X1, Y+1);
LineTo(X2, Y+1);
end;
end;
end;
procedure TOriBrushButton.DrawBrushImage(Item: TTBCustomItem;
Viewer: TTBItemViewer; Canvas: TCanvas; ImageRect: TRect;
ImageOffset: TPoint; StateFlags: Integer);
begin
with Canvas do
begin
Pen.Color := clDkGray;
Brush.Style := bsSolid;
Brush.Color := clWhite;
Rectangle(ImageRect);
if TBrushStyle(Item.Tag) <> bsClear then
begin
Brush.Style := TBrushStyle(Item.Tag);
Brush.Color := clDkGray;
Rectangle(ImageRect);
end;
end;
end;
procedure TOriBrushButton.DoPopup(Sender: TObject);
var
i: Integer;
it: TTBXItem;
bmp: TBitmap;
begin
if FItemRoot.Items.Count = 0 then
begin
bmp := TBitmap.Create;
bmp.Height := 16;
bmp.Width := FPopupWidth;
FImageList := TCustomImageList.Create(Self);
FImageList.Height := 16;
FImageList.Width := FPopupWidth;
FImageList.Add(bmp, bmp);
FItemRoot.Images := FImageList;
bmp.Free;
if FButtonStyle = bstPen then
begin
if UseSmallDots then i := 6 else i := 5;
for i := 0 to i do
begin
it := TTBXItem.Create(FItemRoot);
it.Tag := i;
it.OnClick := ItemPenClick;
it.OnDrawImage := DrawPenImage;
it.ImageIndex := 0;
FItemRoot.Items.Add(it);
end;
end
else
for i := 0 to 7 do
begin
it := TTBXItem.Create(FItemRoot);
it.Tag := i;
it.OnClick := ItemBrushClick;
it.OnDrawImage := DrawBrushImage;
it.ImageIndex := 0;
FItemRoot.Items.Add(it);
end;
end;
end;
procedure TOriBrushButton.PaintText;
var
Y, X1, X2: Integer;
C: TColor;
Rect: TRect;
begin
Rect := FPaintInfo.Rect;
if Enabled
then C := clBtnText
else C := clBtnShadow;
if FPaintInfo.Pressed and (FLook <> blFlat) then
OffsetRect(Rect, 1, 1);
InflateRect(Rect, -4, -4);
if ButtonStyle = bstPen then
begin
// draw thick line with selected pen
Y := (Rect.Top + Rect.Bottom) div 2;
X1 := Rect.Left + 1;
X2 := Rect.Right - 1;
with FCanvas do
begin
Pen.Color := clBtnShadow;
Pen.Style := psSolid;
Brush.Color := clWhite;
Rectangle(Rect);
if SmallDots then
while X1 < X2 do
begin
Pixels[X1, Y] := C;
Pixels[X1+1, Y] := C;
Pixels[X1, Y+1] := C;
Pixels[X1+1, Y+1] := C;
Inc(X1, 4);
end
else
begin
Pen.Color := C;
Pen.Style := FPenStyle;
MoveTo(X1, Y);
LineTo(X2, Y);
MoveTo(X1, Y-1);
LineTo(X2, Y-1);
MoveTo(X1, Y+1);
LineTo(X2, Y+1);
Pen.Style := psSolid;
end;
end;
end
else
// draw rect with selected brush
with FCanvas do
begin
Pen.Color := clDkGray;
Brush.Style := bsSolid;
Brush.Color := clWhite;
Rectangle(Rect);
if FBrushStyle <> bsClear then
begin
Brush.Style := FBrushStyle;
Brush.Color := clDkGray;
Rectangle(Rect);
end;
end;
end;
//------------------------------------------------------------------------------
{ TOriComboButton }
function TTBXComboItem.GetItemViewerClass(AView: TTBView): TTBItemViewerClass;
begin
Result := TTBXComboItemViewer;
end;
procedure TTBXComboItemViewer.CalcSize(const Canvas: TCanvas; var AWidth, AHeight: Integer);
begin
inherited CalcSize(Canvas, AWidth, AHeight);
with TOriComboButton(Item.Owner) do
if AWidth < Width then AWidth := Width;
end;
constructor TOriComboButton.Create(AOwner: TComponent);
begin
inherited;
Include(FOptions, boDropDownArrow);
FItemIndex := -1;
DropDownMenu := TTBXPopupMenu.Create(Self);
end;
procedure TOriComboButton.AddItem(const Value: TOriString; Tag: Integer);
var
it: TTBXItem;
begin
it := TTBXComboItem.Create(Self);
it.Caption := Value;
it.OnClick := ItemClick;
it.Tag := Tag;
TTBXPopupMenu(DropDownMenu).Items.Add(it);
end;
procedure TOriComboButton.ItemClick(Sender: TObject);
begin
FItemIndex := TTBXPopupMenu(DropDownMenu).Items.IndexOf(TTBCustomItem(Sender));
Caption := TTBXItem(Sender).Caption;
DoChange;
end;
procedure TOriComboButton.DoChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TOriComboButton.SetItemIndex(Value: Integer);
begin
if Value <> FItemIndex then
begin
if (Value < -1) or (Value >= TTBXPopupMenu(DropDownMenu).Items.Count)
then FItemIndex := -1
else FItemIndex := Value;
if FItemIndex = -1
then Caption := ''
else Caption := TTBXPopupMenu(DropDownMenu).Items[FItemIndex].Caption;
DoChange;
end;
end;
function TOriComboButton.GetItemsCount: Integer;
begin
Result := TTBXPopupMenu(DropDownMenu).Items.Count;
end;
{$endif}
end.
|
unit Soccer.Voting.Domain;
interface
uses
System.SysUtils,
System.Generics.Collections,
System.RegularExpressions,
Soccer.Exceptions,
Soccer.Domain.Abstract,
Soccer.Domain.Factory,
Soccer.Voting.Actions,
Soccer.Voting.RulesDict,
Soccer.Voting.RulePreferenceList,
Soccer.Voting.Preferences,
Soccer.Voting.RuleChooser;
type
TSoccerVotingDomain = class(TInterfacedObject, ISoccerDomain)
private
FRulePreferenceList: TSoccerVotingRulePreferenceList;
FVotersPreferenceProfile: TSoccerVotingVotersPreferences;
FOutput: TList<string>;
function GetOutput: System.Generics.Collections.TList<string>;
procedure SetOutput(AValue: TList<string>);
public
procedure Initialize;
function AmIStarted(AWhatIsStarted: string): Boolean;
function GetActionForCommand(ACommand: string): ISoccerAction;
function SupportsCommand(ACommand: string): Boolean;
property Output: TList<string> read GetOutput write SetOutput;
procedure DeInitialize;
end;
implementation
{ TVotingDomain }
function TSoccerVotingDomain.AmIStarted(AWhatIsStarted: string): Boolean;
begin
Result := AWhatIsStarted = 'voting';
end;
procedure TSoccerVotingDomain.DeInitialize;
begin
if Assigned(FRulePreferenceList) then
FreeAndNil(FRulePreferenceList);
if Assigned(FVotersPreferenceProfile) then
FreeAndNil(FVotersPreferenceProfile);
end;
function TSoccerVotingDomain.GetActionForCommand(ACommand: string)
: ISoccerAction;
begin
Result := nil;
if TRegEx.IsMatch(ACommand, 'IMPORT\[(.*)\]') then
Result := TSoccerVotingImportAction.Create(GlobalVotingRulesDict,
FRulePreferenceList);
if TRegEx.IsMatch(ACommand, 'VOTE\((.*)\)') then
Result := TSoccerVoteAction.Create(FVotersPreferenceProfile);
if ACommand = 'DECIDE!' then
begin
Result := TSoccerDecideAction.Create(FVotersPreferenceProfile,
FRulePreferenceList, Self, GetDefaultRuleChooser);
end;
end;
function TSoccerVotingDomain.GetOutput
: System.Generics.Collections.TList<string>;
begin
if not Assigned(FOutput) then
raise ESoccerParserException.Create('No "DECIDE!" command found');
Result := FOutput;
end;
procedure TSoccerVotingDomain.Initialize;
begin
FRulePreferenceList := TSoccerVotingRulePreferenceList.Create
(GetPreferenceFilePath);
FVotersPreferenceProfile := TSoccerVotingVotersPreferences.Create;
FOutput := nil;
end;
procedure TSoccerVotingDomain.SetOutput(AValue: TList<string>);
begin
FOutput := AValue;
end;
function TSoccerVotingDomain.SupportsCommand(ACommand: string): Boolean;
begin
Result := TRegEx.IsMatch(ACommand, 'IMPORT\[(.*)\]') or
TRegEx.IsMatch(ACommand, 'VOTE\((.*)\)') or (ACommand = 'DECIDE!');
end;
initialization
GlobalDomainFactory.Domains.Add(TSoccerVotingDomain.Create);
end.
|
unit RecordsTestForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
TMyDate = packed record
Year: Integer;
Month: Byte;
Day: Byte;
end;
function MyDateToString (MyDate: TMyDate): string;
begin
Result := MyDate.Year.ToString + '.' +
MyDate.Month.ToString + '.' +
MyDate.Day.ToString;
end;
procedure IncreaseYear (var MyDate: TMyDate);
begin
Inc (MyDate.Year);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
BirthDay: TMyDate;
begin
BirthDay.Year := 1997;
BirthDay.Month := 2;
BirthDay.Day := 14;
Show ('Born in year ' + BirthDay.Year.ToString);
Show ('Record size is ' + SizeOf (BirthDay).ToString);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
BirthDay: TMyDate;
ADay: TMyDate;
begin
BirthDay.Year := 1997;
BirthDay.Month := 2;
BirthDay.Day := 14;
ADay := Birthday;
ADay.Year := 2008;
Show (MyDateToString (BirthDay));
Show (MyDateToString (ADay));
end;
procedure TForm1.Button3Click(Sender: TObject);
var
ADay: TMyDate;
begin
ADay.Year := 2016;
ADay.Month := 3;
ADay.Day := 18;
Increaseyear (ADay);
Show (MyDateToString (ADay));
end;
procedure TForm1.Button4Click(Sender: TObject);
var
DatesList: array of TMyDate;
I: Integer;
begin
// allocate array elements
SetLength (DatesList, 5);
// assign random values
for I := Low(DatesList) to High(DatesList) do
begin
DatesList[I].Year := 2000 + Random (50);
DatesList[I].Month := 1 + Random (12);
DatesList[I].Day := 1 + Random (27);
end;
// display the values
for I := Low(DatesList) to High(DatesList) do
Show (I.ToString + ': ' +
MyDateToString (DatesList[I]));
end;
procedure TForm1.Show(const msg: string);
begin
Memo1.Lines.Add(msg);
end;
initialization
Randomize;
end.
|
unit rhlKeccak;
interface
uses
rhlCore;
type
{ TrhlKeccak }
TrhlKeccak = class abstract(TrhlHash)
private
m_state: array[0..24] of QWord;
protected
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
{ TrhlKeccak224 }
TrhlKeccak224 = class(TrhlKeccak)
constructor Create; override;
end;
{ TrhlKeccak256 }
TrhlKeccak256 = class(TrhlKeccak)
constructor Create; override;
end;
{ TrhlKeccak384 }
TrhlKeccak384 = class(TrhlKeccak)
constructor Create; override;
end;
{ TrhlKeccak512 }
TrhlKeccak512 = class(TrhlKeccak)
constructor Create; override;
end;
implementation
{ TrhlKeccak512 }
constructor TrhlKeccak512.Create;
begin
HashSize := 512 div 8;
inherited Create;
end;
{ TrhlKeccak384 }
constructor TrhlKeccak384.Create;
begin
HashSize := 384 div 8;
inherited Create;
end;
{ TrhlKeccak256 }
constructor TrhlKeccak256.Create;
begin
HashSize := 256 div 8;
inherited Create;
end;
{ TrhlKeccak224 }
constructor TrhlKeccak224.Create;
begin
HashSize := 224 div 8;
inherited Create;
end;
{ TrhlKeccak }
procedure TrhlKeccak.UpdateBlock(const AData);
const
FC: array[0..23] of QWord = (
$0000000000000001,$0000000000008082,$800000000000808a,$8000000080008000,
$000000000000808b,$0000000080000001,$8000000080008081,$8000000000008009,
$000000000000008a,$0000000000000088,$0000000080008009,$000000008000000a,
$000000008000808b,$800000000000008b,$8000000000008089,$8000000000008003,
$8000000000008002,$8000000000000080,$000000000000800a,$800000008000000a,
$8000000080008081,$8000000000008080,$0000000080000001,$8000000080008008);
var
data: array[0..0] of QWord absolute AData;
j: Integer;
Aba, Abe, Abi, Abo, Abu,
Aga, Age, Agi, Ago, Agu,
Aka, Ake, Aki, Ako, Aku,
Ama, Ame, Ami, Amo, Amu,
Asa, Ase, Asi, Aso, Asu,
Bba, Bbe, Bbi, Bbo, Bbu,
Bga, Bge, Bgi, Bgo, Bgu,
Bka, Bke, Bki, Bko, Bku,
Bma, Bme, Bmi, Bmo, Bmu,
Bsa, Bse, Bsi, Bso, Bsu,
Ca, Ce, Ci, Co, Cu,
Da, De, Di, Doo, Du,
Eba, Ebe, Ebi, Ebo, Ebu,
Ega, Ege, Egi, Ego, Egu,
Eka, Eke, Eki, Eko, Eku,
Ema, Eme, Emi, Emo, Emu,
Esa, Ese, Esi, Eso, Esu: QWord;
begin
for j := 0 to (BlockSize div 8) - 1 do
m_state[j] := m_state[j] xor data[j];
Aba := m_state[0];
Abe := m_state[1];
Abi := m_state[2];
Abo := m_state[3];
Abu := m_state[4];
Aga := m_state[5];
Age := m_state[6];
Agi := m_state[7];
Ago := m_state[8];
Agu := m_state[9];
Aka := m_state[10];
Ake := m_state[11];
Aki := m_state[12];
Ako := m_state[13];
Aku := m_state[14];
Ama := m_state[15];
Ame := m_state[16];
Ami := m_state[17];
Amo := m_state[18];
Amu := m_state[19];
Asa := m_state[20];
Ase := m_state[21];
Asi := m_state[22];
Aso := m_state[23];
Asu := m_state[24];
Ca := Aba xor Aga xor Aka xor Ama xor Asa;
Ce := Abe xor Age xor Ake xor Ame xor Ase;
Ci := Abi xor Agi xor Aki xor Ami xor Asi;
Co := Abo xor Ago xor Ako xor Amo xor Aso;
Cu := Abu xor Agu xor Aku xor Amu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor FC[0];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor Fc[1];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[2];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[3];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[4];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[5];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[6];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[7];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[8];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[9];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[10];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[11];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[12];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[13];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[14];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[15];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[16];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[17];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[18];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[19];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[20];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[21];
Ca := Aba;
Abe := Bbe xor (not Bbi or Bbo);
Ce := Abe;
Abi := Bbi xor (Bbo and Bbu);
Ci := Abi;
Abo := Bbo xor (Bbu or Bba);
Co := Abo;
Abu := Bbu xor (Bba and Bbe);
Cu := Abu;
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Ca := Ca xor Aga;
Age := Bge xor (Bgi and Bgo);
Ce := Ce xor Age;
Agi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Agi;
Ago := Bgo xor (Bgu or Bga);
Co := Co xor Ago;
Agu := Bgu xor (Bga and Bge);
Cu := Cu xor Agu;
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ca := Ca xor Aka;
Ake := Bke xor (Bki and Bko);
Ce := Ce xor Ake;
Aki := Bki xor (not Bko and Bku);
Ci := Ci xor Aki;
Ako := (not Bko) xor (Bku or Bka);
Co := Co xor Ako;
Aku := Bku xor (Bka and Bke);
Cu := Cu xor Aku;
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ca := Ca xor Ama;
Ame := Bme xor (Bmi or Bmo);
Ce := Ce xor Ame;
Ami := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Ami;
Amo := not Bmo xor (Bmu and Bma);
Co := Co xor Amo;
Amu := Bmu xor (Bma or Bme);
Cu := Cu xor Amu;
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Asa;
Ase := not Bse xor (Bsi or Bso);
Ce := Ce xor Ase;
Asi := Bsi xor (Bso and Bsu);
Ci := Ci xor Asi;
Aso := Bso xor (Bsu or Bsa);
Co := Co xor Aso;
Asu := Bsu xor (Bsa and Bse);
Cu := Cu xor Asu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Aba := Aba xor Da;
Bba := Aba;
Age := Age xor De;
Bbe := (Age shl 44) xor (Age shr (64 - 44));
Aki := Aki xor Di;
Bbi := (Aki shl 43) xor (Aki shr (64 - 43));
Amo := Amo xor Doo;
Bbo := (Amo shl 21) xor (Amo shr (64 - 21));
Asu := Asu xor Du;
Bbu := (Asu shl 14) xor (Asu shr (64 - 14));
Eba := Bba xor (Bbe or Bbi);
Eba := Eba xor fc[22];
Ca := Eba;
Ebe := Bbe xor (not Bbi or Bbo);
Ce := Ebe;
Ebi := Bbi xor (Bbo and Bbu);
Ci := Ebi;
Ebo := Bbo xor (Bbu or Bba);
Co := Ebo;
Ebu := Bbu xor (Bba and Bbe);
Cu := Ebu;
Abo := Abo xor Doo;
Bga := (Abo shl 28) xor (Abo shr (64 - 28));
Agu := Agu xor Du;
Bge := (Agu shl 20) xor (Agu shr (64 - 20));
Aka := Aka xor Da;
Bgi := (Aka shl 3) xor (Aka shr (64 - 3));
Ame := Ame xor De;
Bgo := (Ame shl 45) xor (Ame shr (64 - 45));
Asi := Asi xor Di;
Bgu := (Asi shl 61) xor (Asi shr (64 - 61));
Ega := Bga xor (Bge or Bgi);
Ca := Ca xor Ega;
Ege := Bge xor (Bgi and Bgo);
Ce := Ce xor Ege;
Egi := Bgi xor (Bgo or not Bgu);
Ci := Ci xor Egi;
Ego := Bgo xor (Bgu or Bga);
Co := Co xor Ego;
Egu := Bgu xor (Bga and Bge);
Cu := Cu xor Egu;
Abe := Abe xor De;
Bka := (Abe shl 1) xor (Abe shr (64 - 1));
Agi := Agi xor Di;
Bke := (Agi shl 6) xor (Agi shr (64 - 6));
Ako := Ako xor Doo;
Bki := (Ako shl 25) xor (Ako shr (64 - 25));
Amu := Amu xor Du;
Bko := (Amu shl 8) xor (Amu shr (64 - 8));
Asa := Asa xor Da;
Bku := (Asa shl 18) xor (Asa shr (64 - 18));
Eka := Bka xor (Bke or Bki);
Ca := Ca xor Eka;
Eke := Bke xor (Bki and Bko);
Ce := Ce xor Eke;
Eki := Bki xor (not Bko and Bku);
Ci := Ci xor Eki;
Eko := (not Bko) xor (Bku or Bka);
Co := Co xor Eko;
Eku := Bku xor (Bka and Bke);
Cu := Cu xor Eku;
Abu := Abu xor Du;
Bma := (Abu shl 27) xor (Abu shr (64 - 27));
Aga := Aga xor Da;
Bme := (Aga shl 36) xor (Aga shr (64 - 36));
Ake := Ake xor De;
Bmi := (Ake shl 10) xor (Ake shr (64 - 10));
Ami := Ami xor Di;
Bmo := (Ami shl 15) xor (Ami shr (64 - 15));
Aso := Aso xor Doo;
Bmu := (Aso shl 56) xor (Aso shr (64 - 56));
Ema := Bma xor (Bme and Bmi);
Ca := Ca xor Ema;
Eme := Bme xor (Bmi or Bmo);
Ce := Ce xor Eme;
Emi := Bmi xor (not Bmo or Bmu);
Ci := Ci xor Emi;
Emo := not Bmo xor (Bmu and Bma);
Co := Co xor Emo;
Emu := Bmu xor (Bma or Bme);
Cu := Cu xor Emu;
Abi := Abi xor Di;
Bsa := (Abi shl 62) xor (Abi shr (64 - 62));
Ago := Ago xor Doo;
Bse := (Ago shl 55) xor (Ago shr (64 - 55));
Aku := Aku xor Du;
Bsi := (Aku shl 39) xor (Aku shr (64 - 39));
Ama := Ama xor Da;
Bso := (Ama shl 41) xor (Ama shr (64 - 41));
Ase := Ase xor De;
Bsu := (Ase shl 2) xor (Ase shr (64 - 2));
Esa := Bsa xor (not Bse and Bsi);
Ca := Ca xor Esa;
Ese := not Bse xor (Bsi or Bso);
Ce := Ce xor Ese;
Esi := Bsi xor (Bso and Bsu);
Ci := Ci xor Esi;
Eso := Bso xor (Bsu or Bsa);
Co := Co xor Eso;
Esu := Bsu xor (Bsa and Bse);
Cu := Cu xor Esu;
Da := Cu xor (Ce shl 1) xor (Ce shr (64 - 1));
De := Ca xor (Ci shl 1) xor (Ci shr (64 - 1));
Di := Ce xor (Co shl 1) xor (Co shr (64 - 1));
Doo := Ci xor (Cu shl 1) xor (Cu shr (64 - 1));
Du := Co xor (Ca shl 1) xor (Ca shr (64 - 1));
Eba := Eba xor Da;
Bba := Eba;
Ege := Ege xor De;
Bbe := (Ege shl 44) xor (Ege shr (64 - 44));
Eki := Eki xor Di;
Bbi := (Eki shl 43) xor (Eki shr (64 - 43));
Emo := Emo xor Doo;
Bbo := (Emo shl 21) xor (Emo shr (64 - 21));
Esu := Esu xor Du;
Bbu := (Esu shl 14) xor (Esu shr (64 - 14));
Aba := Bba xor (Bbe or Bbi);
Aba := Aba xor fc[23];
Abe := Bbe xor (not Bbi or Bbo);
Abi := Bbi xor (Bbo and Bbu);
Abo := Bbo xor (Bbu or Bba);
Abu := Bbu xor (Bba and Bbe);
Ebo := Ebo xor Doo;
Bga := (Ebo shl 28) xor (Ebo shr (64 - 28));
Egu := Egu xor Du;
Bge := (Egu shl 20) xor (Egu shr (64 - 20));
Eka := Eka xor Da;
Bgi := (Eka shl 3) xor (Eka shr (64 - 3));
Eme := Eme xor De;
Bgo := (Eme shl 45) xor (Eme shr (64 - 45));
Esi := Esi xor Di;
Bgu := (Esi shl 61) xor (Esi shr (64 - 61));
Aga := Bga xor (Bge or Bgi);
Age := Bge xor (Bgi and Bgo);
Agi := Bgi xor (Bgo or not Bgu);
Ago := Bgo xor (Bgu or Bga);
Agu := Bgu xor (Bga and Bge);
Ebe := Ebe xor De;
Bka := (Ebe shl 1) xor (Ebe shr (64 - 1));
Egi := Egi xor Di;
Bke := (Egi shl 6) xor (Egi shr (64 - 6));
Eko := Eko xor Doo;
Bki := (Eko shl 25) xor (Eko shr (64 - 25));
Emu := Emu xor Du;
Bko := (Emu shl 8) xor (Emu shr (64 - 8));
Esa := Esa xor Da;
Bku := (Esa shl 18) xor (Esa shr (64 - 18));
Aka := Bka xor (Bke or Bki);
Ake := Bke xor (Bki and Bko);
Aki := Bki xor (not Bko and Bku);
Ako := not Bko xor (Bku or Bka);
Aku := Bku xor (Bka and Bke);
Ebu := Ebu xor Du;
Bma := (Ebu shl 27) xor (Ebu shr (64 - 27));
Ega := Ega xor Da;
Bme := (Ega shl 36) xor (Ega shr (64 - 36));
Eke := Eke xor De;
Bmi := (Eke shl 10) xor (Eke shr (64 - 10));
Emi := Emi xor Di;
Bmo := (Emi shl 15) xor (Emi shr (64 - 15));
Eso := Eso xor Doo;
Bmu := (Eso shl 56) xor (Eso shr (64 - 56));
Ama := Bma xor (Bme and Bmi);
Ame := Bme xor (Bmi or Bmo);
Ami := Bmi xor (not Bmo or Bmu);
Amo := not Bmo xor (Bmu and Bma);
Amu := Bmu xor (Bma or Bme);
Ebi := Ebi xor Di;
Bsa := (Ebi shl 62) xor (Ebi shr (64 - 62));
Ego := Ego xor Doo;
Bse := (Ego shl 55) xor (Ego shr (64 - 55));
Eku := Eku xor Du;
Bsi := (Eku shl 39) xor (Eku shr (64 - 39));
Ema := Ema xor Da;
Bso := (Ema shl 41) xor (Ema shr (64 - 41));
Ese := Ese xor De;
Bsu := (Ese shl 2) xor (Ese shr (64 - 2));
Asa := Bsa xor (not Bse and Bsi);
Ase := not Bse xor (Bsi or Bso);
Asi := Bsi xor (Bso and Bsu);
Aso := Bso xor (Bsu or Bsa);
Asu := Bsu xor (Bsa and Bse);
m_state[0] := Aba;
m_state[1] := Abe;
m_state[2] := Abi;
m_state[3] := Abo;
m_state[4] := Abu;
m_state[5] := Aga;
m_state[6] := Age;
m_state[7] := Agi;
m_state[8] := Ago;
m_state[9] := Agu;
m_state[10] := Aka;
m_state[11] := Ake;
m_state[12] := Aki;
m_state[13] := Ako;
m_state[14] := Aku;
m_state[15] := Ama;
m_state[16] := Ame;
m_state[17] := Ami;
m_state[18] := Amo;
m_state[19] := Amu;
m_state[20] := Asa;
m_state[21] := Ase;
m_state[22] := Asi;
m_state[23] := Aso;
m_state[24] := Asu;
end;
constructor TrhlKeccak.Create;
begin
BlockSize := 200 - (HashSize * 2);
end;
procedure TrhlKeccak.Init;
begin
inherited Init;
FillChar(m_state, SizeOf(m_state), 0);
m_state[1] := $FFFFFFFFFFFFFFFF;
m_state[2] := $FFFFFFFFFFFFFFFF;
m_state[8] := $FFFFFFFFFFFFFFFF;
m_state[12] := $FFFFFFFFFFFFFFFF;
m_state[17] := $FFFFFFFFFFFFFFFF;
m_state[20] := $FFFFFFFFFFFFFFFF;
end;
procedure TrhlKeccak.Final(var ADigest);
var
buffer_pos: Integer;
block: TBytes;
begin
buffer_pos := FBuffer.Pos;
FBuffer.SetZeroPadded;
block := FBuffer.Bytes;
block[buffer_pos] := 1;
block[BlockSize - 1] := block[BlockSize - 1] or 128;
UpdateBlock(block[0]);
m_state[1] := not m_state[1];
m_state[2] := not m_state[2];
m_state[8] := not m_state[8];
m_state[12] := not m_state[12];
m_state[17] := not m_state[17];
Move(m_state[0], ADigest, HashSize);
end;
end.
|
unit Vigilante.Build.Model.Impl;
interface
uses
Model.Base.Impl, Vigilante.Build.Model, Vigilante.Aplicacao.SituacaoBuild,
Module.ValueObject.URL;
type
TBuildModel = class(TModelBase, IBuildModel)
private
FNome: string;
FURL: string;
FSituacao: TSituacaoBuild;
FBuilding: Boolean;
FBuildAtual: integer;
FUltimoBuildFalha: integer;
FUltimoBuildSucesso: integer;
FURLUltimoBuild: IURL;
protected
function GetBuilding: Boolean;
function GetNome: string;
function GetSituacao: TSituacaoBuild;
function GetURL: string;
function GetBuildAtual: integer;
function GetUltimoBuildFalha: integer;
function GetUltimoBuildSucesso: integer;
function GetURLUltimoBuild: IURL;
public
constructor Create(const ANome: string; const AURL: string;
const ASituacao: TSituacaoBuild; const ABuilding: Boolean;
const ABuildAtual, AUltimoBuildFalha, AUltimoBuildSucesso: integer;
const AURLUltimoBuild: IURL);
function Equals(const BuildModel: IBuildModel): Boolean; reintroduce;
end;
implementation
uses
System.SysUtils;
constructor TBuildModel.Create(const ANome: string; const AURL: string;
const ASituacao: TSituacaoBuild; const ABuilding: Boolean;
const ABuildAtual, AUltimoBuildFalha, AUltimoBuildSucesso: integer;
const AURLUltimoBuild: IURL);
begin
FNome := ANome;
FURL := AURL;
FSituacao := ASituacao;
FBuilding := ABuilding;
FBuildAtual := ABuildAtual;
FUltimoBuildFalha := AUltimoBuildFalha;
FUltimoBuildSucesso := AUltimoBuildSucesso;
FURLUltimoBuild := AURLUltimoBuild;
end;
function TBuildModel.Equals(const BuildModel: IBuildModel): Boolean;
begin
Result := false;
if not BuildModel.Nome.Equals(Self.FNome) then
Exit;
if BuildModel.BuildAtual <> Self.FBuildAtual then
Exit;
if BuildModel.UltimoBuildSucesso <> Self.FUltimoBuildSucesso then
Exit;
if BuildModel.UltimoBuildFalha <> Self.FUltimoBuildFalha then
Exit;
if not BuildModel.URLUltimoBuild.AsString.Equals(Self.FURLUltimoBuild.AsString)
then
Exit;
if BuildModel.Situacao.AsInteger <> Self.GetSituacao.AsInteger then
Exit;
if BuildModel.Building <> Self.GetBuilding then
Exit;
if not BuildModel.Id.ToString.Equals(GetId.ToString) then
Exit;
Result := True;
end;
function TBuildModel.GetBuildAtual: integer;
begin
Result := FBuildAtual;
end;
function TBuildModel.GetBuilding: Boolean;
begin
Result := FBuilding;
end;
function TBuildModel.GetNome: string;
begin
Result := FNome;
end;
function TBuildModel.GetSituacao: TSituacaoBuild;
begin
Result := FSituacao;
end;
function TBuildModel.GetUltimoBuildFalha: integer;
begin
Result := FUltimoBuildFalha;
end;
function TBuildModel.GetUltimoBuildSucesso: integer;
begin
Result := FUltimoBuildSucesso;
end;
function TBuildModel.GetURL: string;
begin
Result := FURL;
end;
function TBuildModel.GetURLUltimoBuild: IURL;
begin
Result := FURLUltimoBuild;
end;
end.
|
unit wb_mobile_app;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils,
vr_utils, vr_JsonRpcClasses, vr_json_conf, vr_transport;
type
{ TCustomWBMobileApp }
{$M+}
TCustomWBMobileApp = class(TComponent)
private
FRpc: TJsonRpcClient;
FWB: IWebBrowser;
procedure OnWBShowContextMenu(Sender: TObject; constref {%H-}APoint: TPoint; var ADone: Boolean);
protected
function GetJsonConfigFile: string; virtual; abstract;
procedure DoLoadConfig(const {%H-}ACfg: TJSONConfig); virtual;
procedure DoSaveConfig(const {%H-}ACfg: TJSONConfig); virtual;
public
constructor {%H-}Create(const ATransport: TCustomTransport; const ABrowser: IWebBrowser;
const AOwnTransport: Boolean = True); virtual;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
destructor Destroy; override;
procedure LoadConfig;
procedure SaveConfig;
property Rpc: TJsonRpcClient read FRpc;
property WB: IWebBrowser read FWB;
end;
{$M-}
implementation
{ TCustomWBMobileApp }
procedure TCustomWBMobileApp.OnWBShowContextMenu(Sender: TObject; constref
APoint: TPoint; var ADone: Boolean);
begin
ADone := True;
end;
procedure TCustomWBMobileApp.DoLoadConfig(const ACfg: TJSONConfig);
begin
end;
procedure TCustomWBMobileApp.DoSaveConfig(const ACfg: TJSONConfig);
begin
end;
constructor TCustomWBMobileApp.Create(const ATransport: TCustomTransport;
const ABrowser: IWebBrowser; const AOwnTransport: Boolean);
begin
inherited Create(nil);
FWB := ABrowser;
FRpc := TJsonRpcClient.Create(ATransport, AOwnTransport, True);
FRpc.AddPublishedMethods(Self);
//FWb.ChromiumBrowser.OnConsoleMessage := OnWBConsoleMessage;
FWb.OnShowContextMenu := OnWBShowContextMenu;
//FWb.OnKeyDown := OnWbOnKeyDown;
//FWb.OnBeforeLoad := OnWBBeforeLoad;
//FWb.OnLoad := OnWBLoad;
end;
procedure TCustomWBMobileApp.AfterConstruction;
begin
LoadConfig;
end;
procedure TCustomWBMobileApp.BeforeDestruction;
begin
SaveConfig;
inherited BeforeDestruction;
end;
destructor TCustomWBMobileApp.Destroy;
begin
FreeAndNil(FRpc);
inherited Destroy;
end;
procedure TCustomWBMobileApp.LoadConfig;
var
cfg: TJSONConfig = nil;
begin
inherited AfterConstruction;
try
cfg := TJSONConfig.Create(GetJsonConfigFile);
DoLoadConfig(cfg);
finally
cfg.Free;
end;
end;
procedure TCustomWBMobileApp.SaveConfig;
var
cfg: TJSONConfig = nil;
begin
try
cfg := TJSONConfig.Create(GetJsonConfigFile);
DoSaveConfig(cfg);
finally
cfg.Free;
end;
end;
end.
|
(*
unit Owner: D10.Mofen, qdac.swish
welcome to report bug: 185511468(qq), 185511468@qq.com
Web site : https://github.com/ymofen/msgpack-delphi
* Delphi 2007 (tested)
* XE5, XE7 (tested)
+ first release
2014-08-15 13:05:13
+ add array support
2014-08-19 12:18:47
+ add andriod support
2014-09-08 00:45:27
* fixed int32, int64 parse bug< integer, int64 parse zero>
2014-11-09 22:35:27
+ add EncodeToFile/DecodeFromFile
2014-11-13 12:30:58
* fix asVariant = null (thanks for cyw(26890954))
2014-11-14 09:05:52
* fix AsInteger = -1 bug (thanks for cyw(26890954))
2014-11-14 12:15:52
* fix AsInteger = -127 bug
check int64/integer/cardinal/word/shortint/smallint/byte assign, encode,decode, read
2014-11-14 12:30:38
* fix AsFloat = 2.507182 bug
thanks fo [珠海]-芒果 1939331207
2014-11-21 12:37:04
* add AddArrayChild func
2015-03-25 17:47:28
* add remove/removeFromParent/Delete function
2015-08-29 22:37:48
samples:
lvMsgPack:=TSimpleMsgPack.Create;
lvMsgPack.S['root.child01'] := 'abc';
//save to stream
lvMsgPack.EncodeToStream(pvStream);
Copyright (c) 2014, ymofen, swish
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{
* add free pascal support by cpicanco
2017-08-29 13:34:00
}
unit SimpleMsgPack;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
classes, SysUtils
{$IFDEF UNICODE}, Generics.Collections{$ELSE}, Contnrs{$ENDIF}
{$IFDEF MSWINDOWS}, Windows{$ENDIF}
,Variants;
{$IFDEF FPC}
{$I fpc.inc}
type
PBOOLEAN = ^ByteBool;
{$ENDIF}
type
{$IF RTLVersion<25}
IntPtr=Integer;
{$IFEND IntPtr}
{$if CompilerVersion < 18} //before delphi 2007
TBytes = array of Byte;
{$ifend}
TMsgPackType = (mptUnknown, mptNull, mptMap, mptArray, mptString, mptInteger,
mptBoolean, mptFloat, mptSingle, mptDateTime, mptBinary);
// reserved
IMsgPack = interface
['{37D3E479-7A46-435A-914D-08FBDA75B50E}']
end;
// copy from qmsgPack
TMsgPackValue= packed record
ValueType:Byte;
case Integer of
0:(U8Val:Byte);
1:(I8Val:Shortint);
2:(U16Val:Word);
3:(I16Val:Smallint);
4:(U32Val:Cardinal);
5:(I32Val:Integer);
6:(U64Val:UInt64);
7:(I64Val:Int64);
//8:(F32Val:Single);
//9:(F64Val:Double);
10:(BArray:array[0..16] of Byte);
end;
TMsgPackSetting = class(TObject)
private
FCaseSensitive: Boolean;
public
property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive;
end;
TSimpleMsgPack = class(TObject)
private
FParent:TSimpleMsgPack;
FLowerName:String;
FName:String;
FValue:TBytes;
FDataType:TMsgPackType;
{$IFDEF UNICODE}
FChildren: TList<TSimpleMsgPack>;
{$ELSE}
FChildren: TList;
{$ENDIF}
procedure InnerAddToChildren(pvDataType: TMsgPackType; obj: TSimpleMsgPack);
function InnerAdd(pvDataType: TMsgPackType): TSimpleMsgPack; overload;
function InnerAdd():TSimpleMsgPack; overload;
function GetCount: Integer;
procedure InnerEncodeToStream(pvStream:TStream);
procedure InnerParseFromStream(pvStream: TStream);
procedure setName(pvName:string);
private
function getAsString: String;
procedure setAsString(pvValue:string);
function getAsInteger: Int64;
procedure setAsInteger(pvValue:Int64);
function GetAsBoolean: Boolean;
procedure SetAsBoolean(const Value: Boolean);
procedure SetAsFloat(const Value: Double);
function GetAsFloat: Double;
procedure SetAsDateTime(const Value: TDateTime);
function GetAsDateTime: TDateTime;
function GetAsVariant: Variant;
procedure SetAsVariant(const Value: Variant);
procedure SetAsSingle(const Value: Single);
function GetAsSingle: Single;
procedure SetAsBytes(const Value: TBytes);
function GetAsBytes: TBytes;
procedure checkObjectDataType(ANewType: TMsgPackType);
function findObj(pvName:string): TSimpleMsgPack;
function indexOf(pvName:string): Integer;
function indexOfCaseSensitive(pvName:string): Integer;
function indexOfIgnoreSensitive(pvLowerCaseName: string): Integer;
private
/// <summary>
/// 通过路径查找子对象
/// </summary>
/// <param name="pvPath">要查找的子对象路径 比如: 'p1.age' </param>
/// <param name="vParent">查找到的子对象的父对象</param>
/// <param name="vIndex">查找到的子对象所在父对象的索引值</param>
/// <returns>返回找到的子对象</returns>
function InnerFindPathObject(pvPath: string; var vParent: TSimpleMsgPack; var
vIndex: Integer): TSimpleMsgPack;
function GetO(pvPath: String): TSimpleMsgPack;
procedure SetO(pvPath: String; const Value: TSimpleMsgPack);
function GetS(pvPath: String): string;
procedure SetS(pvPath: String; const Value: string);
function GetI(pvPath: String): Int64;
procedure SetI(pvPath: String; const Value: Int64);
function GetB(pvPath: String): Boolean;
procedure SetB(pvPath: String; const Value: Boolean);
function GetD(pvPath: String): Double;
procedure SetD(pvPath: String; const Value: Double);
function GetItems(AIndex: Integer): TSimpleMsgPack;
/// <summary>
/// 释放所有子对象,并清空子对象列表
/// </summary>
procedure ClearAndFreeAllChildren;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 清空子对象以及本身值(null)
/// </summary>
procedure Clear;
property Count: Integer read GetCount;
procedure LoadBinaryFromStream(pvStream: TStream; pvLen: cardinal = 0);
procedure SaveBinaryToStream(pvStream:TStream);
procedure LoadBinaryFromFile(pvFileName:String);
procedure SaveBinaryToFile(pvFileName:String);
procedure EncodeToStream(pvStream:TStream);
procedure EncodeToFile(pvFileName:string);
procedure DecodeFromStream(pvStream:TStream);
procedure DecodeFromFile(pvFileName:string);
function EncodeToBytes: TBytes;
procedure DecodeFromBytes(pvBytes:TBytes);
function Add(pvNameKey, pvValue: string): TSimpleMsgPack; overload;
function Add(pvNameKey: string; pvValue: Int64): TSimpleMsgPack; overload;
function Add(pvNameKey: string; pvValue: TBytes): TSimpleMsgPack; overload;
function Add(pvNameKey: String): TSimpleMsgPack; overload;
function Add():TSimpleMsgPack; overload;
/// <summary>
/// 添加一个子对象,并负责对象的生命周期
/// </summary>
function Add(pvNameKey: string; pvValue:TSimpleMsgPack): TSimpleMsgPack;
overload;
function AddArrayChild():TSimpleMsgPack; overload;
/// <summary>
/// 添加一个子对象,并负责对象的生命周期
/// </summary>
function AddArrayChild(pvValue:TSimpleMsgPack): TSimpleMsgPack; overload;
function ForcePathObject(pvPath:string): TSimpleMsgPack;
/// <summary>
/// 移除并释放对象
/// </summary>
/// <param name="pvPath">要移除的对象路径, 比如: 'p1.age' </param>
/// <returns>如果移除成功返回true, 否则返回false(对象不存在)</returns>
function DeleteObject(pvPath:String):Boolean;
/// <summary>
/// 根据索引值删除并释放对象
/// </summary>
/// <param name="pvIndex">子对象的索引值</param>
/// <returns>如果移除成功返回true, 否则返回false(超出索引范围)</returns>
function Delete(pvIndex:Integer):Boolean;
/// <summary>
/// 移除子对象,并不释放子对象
/// </summary>
/// <param name="pvPath">要移除的对象路径, 比如: 'p1.age' </param>
/// <returns>如果移除成功返回移除的子对象, 否则返回nil(对象不存在)</returns>
function Remove(pvPath:string): TSimpleMsgPack; overload;
/// <summary>
/// 移除子对象,并不释放子对象
/// </summary>
/// <param name="pvIndex">子对象的索引值</param>
/// <returns>如果移除成功返回移除的子对象, 否则返回nil(索引超出范围)</returns>
function Remove(pvIndex:Integer): TSimpleMsgPack; overload;
/// <summary>
/// 移除子对象,并不释放子对象
/// </summary>
/// <param name="pvChild">要移除的对象</param>
/// <returns>如果移除成功返回true, 否则返回false(对象不是该子对象)</returns>
function Remove(pvChild:TSimpleMsgPack): Boolean; overload;
/// <summary>
/// 从父对象中移除
/// </summary>
procedure RemoveFromParent();
property AsInteger:Int64 read getAsInteger write setAsInteger;
property AsString:string read getAsString write setAsString;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsFloat: Double read GetAsFloat write SetAsFloat;
property AsSingle: Single read GetAsSingle write SetAsSingle;
property AsDateTime: TDateTime read GetAsDateTime write SetAsDateTime;
property AsVariant: Variant read GetAsVariant write SetAsVariant;
property AsBytes: TBytes read GetAsBytes write SetAsBytes;
property Key : string read FName; // for Items only
property Value : string read getAsString; // alias for AsString
property O[pvPath: String]: TSimpleMsgPack read GetO write SetO;
property S[pvPath: String]: string read GetS write SetS;
property I[pvPath: String]: Int64 read GetI write SetI;
property B[pvPath: String]: Boolean read GetB write SetB;
property D[pvPath: String]: Double read GetD write SetD;
property Items[AIndex: Integer]: TSimpleMsgPack read GetItems; default;
end;
implementation
resourcestring
SVariantConvertNotSupport = 'type to convert not support!。';
SCannotAddChild = 'Can''t add child in this node!';
function swap16(const v): Word;
begin
// FF, EE : EE->1, FF->2
PByte(@result)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@result) + 1)^ := PByte(@v)^;
end;
function swap32(const v): Cardinal;
begin
// FF, EE, DD, CC : CC->1, DD->2, EE->3, FF->4
PByte(@result)^ := PByte(IntPtr(@v) + 3)^;
PByte(IntPtr(@result) + 1)^ := PByte(IntPtr(@v) + 2)^;
PByte(IntPtr(@result) + 2)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@result) + 3)^ := PByte(@v)^;
end;
function swap64(const v): Int64;
begin
// FF, EE, DD, CC, BB, AA, 99, 88 : 88->1 ,99->2 ....
PByte(@result)^ := PByte(IntPtr(@v) + 7)^;
PByte(IntPtr(@result) + 1)^ := PByte(IntPtr(@v) + 6)^;
PByte(IntPtr(@result) + 2)^ := PByte(IntPtr(@v) + 5)^;
PByte(IntPtr(@result) + 3)^ := PByte(IntPtr(@v) + 4)^;
PByte(IntPtr(@result) + 4)^ := PByte(IntPtr(@v) + 3)^;
PByte(IntPtr(@result) + 5)^ := PByte(IntPtr(@v) + 2)^;
PByte(IntPtr(@result) + 6)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@result) + 7)^ := PByte(@v)^;
end;
// v and outVal is can't the same value
procedure swap64Ex(const v; out outVal);
begin
// FF, EE, DD, CC, BB, AA, 99, 88 : 88->1 ,99->2 ....
PByte(@outVal)^ := PByte(IntPtr(@v) + 7)^;
PByte(IntPtr(@outVal) + 1)^ := PByte(IntPtr(@v) + 6)^;
PByte(IntPtr(@outVal) + 2)^ := PByte(IntPtr(@v) + 5)^;
PByte(IntPtr(@outVal) + 3)^ := PByte(IntPtr(@v) + 4)^;
PByte(IntPtr(@outVal) + 4)^ := PByte(IntPtr(@v) + 3)^;
PByte(IntPtr(@outVal) + 5)^ := PByte(IntPtr(@v) + 2)^;
PByte(IntPtr(@outVal) + 6)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@outVal) + 7)^ := PByte(@v)^;
end;
// v and outVal is can't the same value
procedure swap32Ex(const v; out outVal);
begin
// FF, EE, DD, CC : CC->1, DD->2, EE->3, FF->4
PByte(@outVal)^ := PByte(IntPtr(@v) + 3)^;
PByte(IntPtr(@outVal) + 1)^ := PByte(IntPtr(@v) + 2)^;
PByte(IntPtr(@outVal) + 2)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@outVal) + 3)^ := PByte(@v)^;
end;
// v and outVal is can't the same value
procedure swap16Ex(const v; out outVal);
begin
// FF, EE : EE->1, FF->2
PByte(@outVal)^ := PByte(IntPtr(@v) + 1)^;
PByte(IntPtr(@outVal) + 1)^ := PByte(@v)^;
end;
// overload swap, result type is integer, because single maybe NaN
function swap(v:Single): Integer; overload;
begin
swap32Ex(v, Result);
end;
// overload swap
function swap(v:word): Word; overload;
begin
swap16Ex(v, Result);
end;
// overload swap
function swap(v:Cardinal):Cardinal; overload;
begin
swap32Ex(v, Result);
end;
// swap , result type is Int64, because Double maybe NaN
function swap(v:Double): Int64; overload;
begin
swap64Ex(v, Result);
end;
// copy from qstring
function BinToHex(p: Pointer; l: Integer; ALowerCase: Boolean): string;
const
B2HConvert: array [0 .. 15] of Char = ('0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
B2HConvertL: array [0 .. 15] of Char = ('0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
var
pd: PChar;
pb: PByte;
begin
if SizeOf(Char) = 2 then
begin
SetLength(Result, l shl 1);
end else
begin
SetLength(Result, l);
end;
pd := PChar(Result);
pb := p;
if ALowerCase then
begin
while l > 0 do
begin
pd^ := B2HConvertL[pb^ shr 4];
Inc(pd);
pd^ := B2HConvertL[pb^ and $0F];
Inc(pd);
Inc(pb);
Dec(l);
end;
end
else
begin
while l > 0 do
begin
pd^ := B2HConvert[pb^ shr 4];
Inc(pd);
pd^ := B2HConvert[pb^ and $0F];
Inc(pd);
Inc(pb);
Dec(l);
end;
end;
end;
function getFirst(var strPtr: PChar; splitChars: TSysCharSet): string;
var
oPtr:PChar;
l:Cardinal;
begin
oPtr := strPtr;
Result := '';
while True do
begin
if (strPtr^ in splitChars) then
begin
l := strPtr - oPtr;
if l > 0 then
begin
{$IFDEF UNICODE}
SetLength(Result, l);
Move(oPtr^, PChar(Result)^, l shl 1);
{$ELSE}
SetLength(Result, l);
Move(oPtr^, PChar(Result)^, l);
{$ENDIF}
break;
end;
end else if (strPtr^ = #0) then
begin
l := strPtr - oPtr;
if l > 0 then
begin
{$IFDEF UNICODE}
SetLength(Result, l);
Move(oPtr^, PChar(Result)^, l shl 1);
{$ELSE}
SetLength(Result, l);
Move(oPtr^, PChar(Result)^, l);
{$ENDIF}
end;
break;
end;
Inc(strPtr);
end;
end;
function Utf8DecodeEx(pvValue:{$IFDEF UNICODE}TBytes{$ELSE}AnsiString{$ENDIF}; len:Cardinal):string;
{$IFDEF UNICODE}
var
lvBytes:TBytes;
{$ENDIF}
begin
{$IFDEF UNICODE}
lvBytes := TEncoding.Convert(TEncoding.UTF8, TEncoding.Unicode, pvValue);
SetLength(Result, Length(lvBytes) shr 1);
Move(lvBytes[0], PChar(Result)^, Length(lvBytes));
{$ELSE}
result:= UTF8Decode(pvValue);
{$ENDIF}
end;
function Utf8EncodeEx(pvValue:string):{$IFDEF UNICODE}TBytes{$ELSE}AnsiString{$ENDIF};
{$IFDEF UNICODE}
var
lvBytes:TBytes;
len:Cardinal;
{$ENDIF}
begin
{$IFDEF UNICODE}
len := length(pvValue) shl 1;
SetLength(lvBytes, len);
Move(PChar(pvValue)^, lvBytes[0], len);
Result := TEncoding.Convert(TEncoding.Unicode, TEncoding.UTF8, lvBytes);
{$ELSE}
result:= UTF8Encode(pvValue);
{$ENDIF}
end;
// copy from qmsgPack
procedure writeString(pvValue: string; pvStream: TStream);
var
lvRawData:{$IFDEF UNICODE}TBytes{$ELSE}AnsiString{$ENDIF};
l:Integer;
lvValue:TMsgPackValue;
begin
lvRawData := Utf8EncodeEx(pvValue);
l:=Length(lvRawData);
//
//fixstr stores a byte array whose length is upto 31 bytes:
//+--------+========+
//|101XXXXX| data |
//+--------+========+
//
//str 8 stores a byte array whose length is upto (2^8)-1 bytes:
//+--------+--------+========+
//| 0xd9 |YYYYYYYY| data |
//+--------+--------+========+
//
//str 16 stores a byte array whose length is upto (2^16)-1 bytes:
//+--------+--------+--------+========+
//| 0xda |ZZZZZZZZ|ZZZZZZZZ| data |
//+--------+--------+--------+========+
//
//str 32 stores a byte array whose length is upto (2^32)-1 bytes:
//+--------+--------+--------+--------+--------+========+
//| 0xdb |AAAAAAAA|AAAAAAAA|AAAAAAAA|AAAAAAAA| data |
//+--------+--------+--------+--------+--------+========+
//
//where
//* XXXXX is a 5-bit unsigned integer which represents N
//* YYYYYYYY is a 8-bit unsigned integer which represents N
//* ZZZZZZZZ_ZZZZZZZZ is a 16-bit big-endian unsigned integer which represents N
//* AAAAAAAA_AAAAAAAA_AAAAAAAA_AAAAAAAA is a 32-bit big-endian unsigned integer which represents N
//* N is the length of data
if L<=31 then
begin
lvValue.ValueType:=$A0+Byte(L);
pvStream.WriteBuffer(lvValue.ValueType,1);
end
else if L<=255 then
begin
lvValue.ValueType:=$d9;
lvValue.U8Val:=Byte(L);
pvStream.WriteBuffer(lvValue,2);
end
else if L<=65535 then
begin
lvValue.ValueType:=$da;
lvValue.U16Val:=((L shr 8) and $FF) or ((L shl 8) and $FF00);
pvStream.Write(lvValue,3);
end else
begin
lvValue.ValueType:=$db;
lvValue.BArray[0]:=(L shr 24) and $FF;
lvValue.BArray[1]:=(L shr 16) and $FF;
lvValue.BArray[2]:=(L shr 8) and $FF;
lvValue.BArray[3]:=L and $FF;
pvStream.WriteBuffer(lvValue,5);
end;
{$IFDEF UNICODE}
pvStream.Write(PByte(@lvRawData[0])^, l);
{$ELSE}
pvStream.Write(PByte(lvRawData)^, l);
{$ENDIF};
end;
procedure WriteBinary(p: PByte; l: Integer; pvStream: TStream);
var
lvValue:TMsgPackValue;
begin
if l <= 255 then
begin
lvValue.ValueType := $C4;
lvValue.U8Val := Byte(l);
pvStream.WriteBuffer(lvValue, 2);
end
else if l <= 65535 then
begin
lvValue.ValueType := $C5;
lvValue.BArray[0] := (l shr 8) and $FF;
lvValue.BArray[1] := l and $FF;
pvStream.WriteBuffer(lvValue, 3);
end
else
begin
lvValue.ValueType := $C6;
lvValue.BArray[0] := (l shr 24) and $FF;
lvValue.BArray[1] := (l shr 16) and $FF;
lvValue.BArray[2] := (l shr 8) and $FF;
lvValue.BArray[3] := l and $FF;
pvStream.WriteBuffer(lvValue, 5);
end;
pvStream.WriteBuffer(p^, l);
end;
// copy from qmsgPack
procedure WriteInt(const iVal: Int64; AStream: TStream);
var
lvValue:TMsgPackValue;
begin
if iVal>=0 then
begin
if iVal<=127 then
begin
lvValue.U8Val:=Byte(iVal);
AStream.WriteBuffer(lvValue.U8Val,1);
end
else if iVal<=255 then//UInt8
begin
lvValue.ValueType:=$cc;
lvValue.U8Val:=Byte(iVal);
AStream.WriteBuffer(lvValue,2);
end
else if iVal<=65535 then
begin
lvValue.ValueType:=$cd;
lvValue.BArray[0]:=(iVal shr 8);
lvValue.BArray[1]:=(iVal and $FF);
AStream.WriteBuffer(lvValue,3);
end
else if iVal<=Cardinal($FFFFFFFF) then
begin
lvValue.ValueType:=$ce;
lvValue.BArray[0]:=(iVal shr 24) and $FF;
lvValue.BArray[1]:=(iVal shr 16) and $FF;
lvValue.BArray[2]:=(iVal shr 8) and $FF;
lvValue.BArray[3]:=iVal and $FF;
AStream.WriteBuffer(lvValue,5);
end
else
begin
lvValue.ValueType:=$cf;
lvValue.BArray[0]:=(iVal shr 56) and $FF;
lvValue.BArray[1]:=(iVal shr 48) and $FF;
lvValue.BArray[2]:=(iVal shr 40) and $FF;
lvValue.BArray[3]:=(iVal shr 32) and $FF;
lvValue.BArray[4]:=(iVal shr 24) and $FF;
lvValue.BArray[5]:=(iVal shr 16) and $FF;
lvValue.BArray[6]:=(iVal shr 8) and $FF;
lvValue.BArray[7]:=iVal and $FF;
AStream.WriteBuffer(lvValue,9);
end;
end
else//<0
begin
if iVal<=Low(Integer) then //-2147483648 // 64 bit
begin
lvValue.ValueType:=$d3;
lvValue.BArray[0]:=(iVal shr 56) and $FF;
lvValue.BArray[1]:=(iVal shr 48) and $FF;
lvValue.BArray[2]:=(iVal shr 40) and $FF;
lvValue.BArray[3]:=(iVal shr 32) and $FF;
lvValue.BArray[4]:=(iVal shr 24) and $FF;
lvValue.BArray[5]:=(iVal shr 16) and $FF;
lvValue.BArray[6]:=(iVal shr 8) and $FF;
lvValue.BArray[7]:=iVal and $FF;
AStream.WriteBuffer(lvValue,9);
end
else if iVal<=Low(SmallInt) then // -32768 // 32 bit
begin
lvValue.ValueType:=$d2;
lvValue.BArray[0]:=(iVal shr 24) and $FF;
lvValue.BArray[1]:=(iVal shr 16) and $FF;
lvValue.BArray[2]:=(iVal shr 8) and $FF;
lvValue.BArray[3]:=iVal and $FF;
AStream.WriteBuffer(lvValue,5);
end
else if iVal<=-128 then
begin
lvValue.ValueType:=$d1;
lvValue.BArray[0]:=(iVal shr 8);
lvValue.BArray[1]:=(iVal and $FF);
AStream.WriteBuffer(lvValue,3);
end
else if iVal<-32 then
begin
lvValue.ValueType:=$d0;
lvValue.I8Val:=iVal;
AStream.WriteBuffer(lvValue,2);
end
else
begin
lvValue.I8Val:=iVal;
AStream.Write(lvValue.I8Val,1);
end;
end;//End <0
end;
procedure WriteFloat(pvVal: Double; AStream: TStream);
var
lvValue:TMsgPackValue;
begin
lvValue.i64Val := swap(pvVal);
lvValue.ValueType := $CB;
AStream.WriteBuffer(lvValue, 9);
end;
procedure WriteSingle(pvVal: Single; AStream: TStream);
var
lvValue:TMsgPackValue;
begin
lvValue.I32Val := swap(pvVal);
lvValue.ValueType := $CA;
AStream.WriteBuffer(lvValue, 5);
end;
procedure WriteNull(pvStream:TStream);
var
lvByte:Byte;
begin
lvByte := $C0;
pvStream.Write(lvByte, 1);
end;
procedure WriteBoolean(pvValue:Boolean; pvStream:TStream);
var
lvByte:Byte;
begin
if pvValue then lvByte := $C3 else lvByte := $C2;
pvStream.Write(lvByte, 1);
end;
/// <summary>
/// copy from qmsgpack
/// </summary>
procedure writeArray(obj:TSimpleMsgPack; pvStream:TStream);
var
c, i:Integer;
lvValue:TMsgPackValue;
lvNode:TSimpleMsgPack;
begin
C:=obj.Count;
if C <= 15 then
begin
lvValue.ValueType := $90 + C;
pvStream.WriteBuffer(lvValue.ValueType, 1);
end
else if C <= 65535 then
begin
lvValue.ValueType := $DC;
lvValue.BArray[0] := (C shr 8) and $FF;
lvValue.BArray[1] := C and $FF;
pvStream.WriteBuffer(lvValue, 3);
end
else
begin
lvValue.ValueType := $DD;
lvValue.BArray[0] := (C shr 24) and $FF;
lvValue.BArray[1] := (C shr 16) and $FF;
lvValue.BArray[2] := (C shr 8) and $FF;
lvValue.BArray[3] := C and $FF;
pvStream.WriteBuffer(lvValue, 5);
end;
for I := 0 to C-1 do
begin
lvNode:=TSimpleMsgPack(obj.FChildren[I]);
lvNode.InnerEncodeToStream(pvStream);
end;
end;
procedure writeMap(obj:TSimpleMsgPack; pvStream:TStream);
var
c, i:Integer;
lvValue:TMsgPackValue;
lvNode:TSimpleMsgPack;
begin
C:=obj.Count;
if C<=15 then
begin
lvValue.ValueType:=$80+C;
pvStream.WriteBuffer(lvValue.ValueType,1);
end
else if C<=65535 then
begin
lvValue.ValueType:=$de;
lvValue.BArray[0]:=(C shr 8) and $FF;
lvValue.BArray[1]:=C and $FF;
pvStream.WriteBuffer(lvValue,3);
end
else
begin
lvValue.ValueType:=$df;
lvValue.BArray[0]:=(C shr 24) and $FF;
lvValue.BArray[1]:=(C shr 16) and $FF;
lvValue.BArray[2]:=(C shr 8) and $FF;
lvValue.BArray[3]:=C and $FF;
pvStream.WriteBuffer(lvValue,5);
end;
for I := 0 to C-1 do
begin
lvNode:=TSimpleMsgPack(obj.FChildren[I]);
writeString(lvNode.FName, pvStream);
lvNode.InnerEncodeToStream(pvStream);
end;
end;
function EncodeDateTime(pvVal: TDateTime): string;
var
AValue: TDateTime;
begin
AValue := pvVal;
if AValue - Trunc(AValue) = 0 then // Date
Result := FormatDateTime('yyyy-MM-dd', AValue)
else
begin
if Trunc(AValue) = 0 then
Result := FormatDateTime('hh:nn:ss.zzz', AValue)
else
Result := FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', AValue);
end;
end;
constructor TSimpleMsgPack.Create;
begin
inherited Create;
{$IFDEF UNICODE}
FChildren := TList<TSimpleMsgPack>.Create();
{$ELSE}
FChildren := TList.Create();
{$ENDIF}
end;
procedure TSimpleMsgPack.DecodeFromBytes(pvBytes: TBytes);
var
lvStream:TStream;
begin
lvStream := TMemoryStream.Create;
try
lvStream.Write(pvBytes[0], Length(pvBytes));
lvStream.Position := 0;
DecodeFromStream(lvStream);
finally
lvStream.Free;
end;
end;
procedure TSimpleMsgPack.DecodeFromFile(pvFileName: string);
var
lvFileStream:TFileStream;
begin
if FileExists(pvFileName) then
begin
lvFileStream := TFileStream.Create(pvFileName, fmOpenRead);
try
DecodeFromStream(lvFileStream);
finally
lvFileStream.Free;
end;
end;
end;
procedure TSimpleMsgPack.DecodeFromStream(pvStream: TStream);
begin
InnerParseFromStream(pvStream);
end;
function TSimpleMsgPack.Delete(pvIndex: Integer): Boolean;
begin
if (pvIndex < 0) or (pvIndex >= Count) then
begin
Result := false;
end else
begin
TObject(FChildren[pvIndex]).Free;
FChildren.Delete(pvIndex);
Result := True;
end;
end;
function TSimpleMsgPack.DeleteObject(pvPath: String): Boolean;
var
lvParent, lvObj:TSimpleMsgPack;
j:Integer;
begin
lvObj := InnerFindPathObject(pvPath, lvParent, j);
Result := lvObj <> nil;
if Result then
begin
lvParent.FChildren.Delete(j);
lvObj.Free;
end;
end;
destructor TSimpleMsgPack.Destroy;
begin
ClearAndFreeAllChildren;
FChildren.Free;
FChildren := nil;
inherited Destroy;
end;
function TSimpleMsgPack.Add(pvNameKey, pvValue: string): TSimpleMsgPack;
begin
Result := InnerAdd(mptMap);
Result.setName(pvNameKey);
Result.AsString := pvValue;
end;
function TSimpleMsgPack.Add(pvNameKey: string; pvValue: Int64): TSimpleMsgPack;
begin
Result := InnerAdd(mptMap);
Result.setName(pvNameKey);
Result.AsInteger := pvValue;
end;
function TSimpleMsgPack.Add: TSimpleMsgPack;
begin
Result := InnerAdd(mptMap);
end;
function TSimpleMsgPack.AddArrayChild: TSimpleMsgPack;
begin
if FDataType <> mptArray then
begin
Clear();
FDataType := mptArray;
end;
Result := InnerAdd;
end;
function TSimpleMsgPack.Add(pvNameKey: string; pvValue: TBytes): TSimpleMsgPack;
begin
Result := InnerAdd(mptMap);
Result.setName(pvNameKey);
Result.FDataType := mptBinary;
Result.FValue := pvValue;
end;
function TSimpleMsgPack.Add(pvNameKey:String): TSimpleMsgPack;
begin
Result := InnerAdd(mptMap);
Result.setName(pvNameKey);
end;
function TSimpleMsgPack.Add(pvNameKey: string; pvValue:TSimpleMsgPack):
TSimpleMsgPack;
begin
InnerAddToChildren(mptMap, pvValue);
pvValue.FName := pvNameKey;
Result := pvValue;
end;
function TSimpleMsgPack.AddArrayChild(pvValue:TSimpleMsgPack): TSimpleMsgPack;
begin
InnerAddToChildren(mptArray, pvValue);
Result := pvValue;
end;
procedure TSimpleMsgPack.checkObjectDataType(ANewType: TMsgPackType);
begin
if (FDataType <> ANewType) then
begin
FDataType := ANewType;
end;
end;
procedure TSimpleMsgPack.Clear;
begin
ClearAndFreeAllChildren;
FDataType := mptNull;
SetLength(FValue, 0);
end;
function TSimpleMsgPack.EncodeToBytes: TBytes;
var
lvStream:TStream;
begin
lvStream := TMemoryStream.Create;
try
EncodeToStream(lvStream);
lvStream.Position := 0;
SetLength(Result, lvStream.size);
lvStream.Read(Result[0], lvStream.Size);
finally
lvStream.Free;
end;
end;
procedure TSimpleMsgPack.EncodeToFile(pvFileName: string);
var
lvFileStream:TFileStream;
begin
if FileExists(pvFileName) then
lvFileStream := TFileStream.Create(pvFileName, fmOpenWrite)
else
lvFileStream := TFileStream.Create(pvFileName, fmCreate);
try
lvFileStream.Size := 0;
EncodeToStream(lvFileStream);
finally
lvFileStream.Free;
end;
end;
procedure TSimpleMsgPack.EncodeToStream(pvStream: TStream);
begin
InnerEncodeToStream(pvStream);
end;
function TSimpleMsgPack.findObj(pvName:string): TSimpleMsgPack;
var
i:Integer;
begin
i := indexOfCaseSensitive(pvName);
if i <> -1 then
begin
Result := TSimpleMsgPack(FChildren[i]);
end else
begin
Result := nil;
end;
end;
function TSimpleMsgPack.ForcePathObject(pvPath:string): TSimpleMsgPack;
var
lvName:string;
s:string;
sPtr:PChar;
lvTempObj, lvParent:TSimpleMsgPack;
j:Integer;
begin
Result := nil;
s := pvPath;
lvParent := Self;
sPtr := PChar(s);
while sPtr^ <> #0 do
begin
lvName := getFirst(sPtr, ['.', '/','\']);
if lvName = '' then
begin
Break;
end else
begin
if sPtr^ = #0 then
begin // end
j := lvParent.indexOf(lvName);
if j <> -1 then
begin
Result := TSimpleMsgPack(lvParent.FChildren[j]);
end else
begin
Result := lvParent.Add(lvName);
end;
end else
begin
// find childrean
lvTempObj := lvParent.findObj(lvName);
if lvTempObj = nil then
begin
lvParent := lvParent.Add(lvName);
end else
begin
lvParent := lvTempObj;
end;
end;
end;
if sPtr^ = #0 then Break;
Inc(sPtr);
end;
end;
procedure TSimpleMsgPack.ClearAndFreeAllChildren;
var
i:Integer;
begin
for i := 0 to FChildren.Count - 1 do
begin
TObject(FChildren[i]).Free;
end;
FChildren.Clear;
end;
function TSimpleMsgPack.GetAsBoolean: Boolean;
begin
if FDataType = mptBoolean then
Result := PBoolean(FValue)^
else if FDataType = mptString then
Result := StrToBoolDef(AsString, False)
else if FDataType = mptInteger then
Result := (AsInteger <> 0)
else if FDataType in [mptNull, mptUnknown] then
Result := False
else
Result := False;
end;
function TSimpleMsgPack.GetAsBytes: TBytes;
begin
Result := FValue;
end;
function TSimpleMsgPack.GetAsDateTime: TDateTime;
begin
if FDataType in [mptDateTime, mptFloat] then
Result := PDouble(FValue)^
else if FDataType = mptSingle then
Result := PSingle(FValue)^
else if FDataType = mptString then
begin
Result := StrToDateTimeDef(GetAsString, 0);
end
else if FDataType in [mptInteger] then
Result := AsInteger
else
Result := 0;
end;
function TSimpleMsgPack.GetAsFloat: Double;
begin
if FDataType in [mptFloat, mptDateTime] then
Result := PDouble(FValue)^
else if FDataType = mptSingle then
Result := PSingle(FValue)^
else if FDataType = mptBoolean then
Result := Integer(AsBoolean)
else if FDataType = mptString then
Result := StrToFloatDef(AsString, 0)
else if FDataType = mptInteger then
Result := AsInteger
else
Result := 0;
end;
function TSimpleMsgPack.getAsInteger: Int64;
begin
case FDataType of
mptInteger: Result:=PInt64(FValue)^;
else
Result := 0;
end;
end;
function TSimpleMsgPack.GetAsSingle: Single;
begin
if FDataType in [mptFloat, mptDateTime] then
Result := PDouble(FValue)^
else if FDataType = mptSingle then
Result := PSingle(FValue)^
else if FDataType = mptBoolean then
Result := Integer(AsBoolean)
else if FDataType = mptString then
Result := StrToFloatDef(AsString, 0)
else if FDataType = mptInteger then
Result := AsInteger
else
Result := 0;
end;
function TSimpleMsgPack.getAsString: String;
var
l:Cardinal;
begin
Result := '';
if FDataType = mptString then
begin
l := Length(FValue);
if l = 0 then
begin
Result := '';
end else if SizeOf(Char) = 2 then
begin
SetLength(Result, l shr 1);
Move(FValue[0],PChar(Result)^, l);
end else
begin
SetLength(Result, l);
Move(FValue[0],PChar(Result)^, l);
end;
end else
begin
case FDataType of
mptUnknown, mptNull:
Result := '';
mptInteger:
Result := IntToStr(AsInteger);
mptBoolean:
Result := BoolToStr(AsBoolean, True);
mptFloat:
Result := FloatToStrF(AsFloat, ffGeneral, 15, 0);
mptSingle:
Result := FloatToStrF(AsSingle, ffGeneral, 7, 0);
mptBinary:
Result := BinToHex(@FValue[0], Length(FValue), False);
mptDateTime:
Result := EncodeDateTime(AsDateTime);
// mptArray:
// Result := EncodeArray;
// mptMap:
// Result := EncodeMap;
// mptExtended:
// Result := EncodeExtended;
else
Result := '';
end;
end;
//showMessage(Result);
end;
/// <summary>
/// copy from qdac3
/// </summary>
function TSimpleMsgPack.GetAsVariant: Variant;
var
I: Integer;
procedure BytesAsVariant;
var
L: Integer;
p:PByte;
begin
L := Length(FValue);
Result := VarArrayCreate([0, L - 1], varByte);
p:=VarArrayLock(Result);
Move(FValue[0],p^,L);
VarArrayUnlock(Result);
end;
begin
case FDataType of
mptNull:
Result := null;
mptString:
Result := AsString;
mptInteger:
Result := AsInteger;
mptFloat:
Result := AsFloat;
mptSingle:
Result := AsSingle;
mptDateTime:
Result := AsDateTime;
mptBoolean:
Result := AsBoolean;
mptArray, mptMap:
begin
Result := VarArrayCreate([0, Count - 1], varVariant);
for I := 0 to Count - 1 do
Result[I] := TSimpleMsgPack(FChildren[I]).AsVariant;
end;
mptBinary:
BytesAsVariant;
else
raise Exception.Create(SVariantConvertNotSupport);
end;
end;
function TSimpleMsgPack.GetB(pvPath: String): Boolean;
var
lvObj:TSimpleMsgPack;
begin
lvObj := GetO(pvPath);
if lvObj = nil then
begin
Result := False;
end else
begin
Result := lvObj.AsBoolean;
end;
end;
function TSimpleMsgPack.GetCount: Integer;
begin
Result := FChildren.Count;
end;
function TSimpleMsgPack.GetD(pvPath: String): Double;
var
lvObj:TSimpleMsgPack;
begin
lvObj := GetO(pvPath);
if lvObj = nil then
begin
Result := 0;
end else
begin
Result := lvObj.AsFloat;
end;
end;
function TSimpleMsgPack.GetI(pvPath: String): Int64;
var
lvObj:TSimpleMsgPack;
begin
lvObj := GetO(pvPath);
if lvObj = nil then
begin
Result := 0;
end else
begin
Result := lvObj.AsInteger;
end;
end;
function TSimpleMsgPack.GetItems(AIndex: Integer): TSimpleMsgPack;
begin
Result := TSimpleMsgPack(FChildren[AIndex]);
end;
function TSimpleMsgPack.GetO(pvPath: String): TSimpleMsgPack;
var
lvParent:TSimpleMsgPack;
j:Integer;
begin
Result := InnerFindPathObject(pvPath, lvParent, j);
end;
function TSimpleMsgPack.GetS(pvPath: String): string;
var
lvObj:TSimpleMsgPack;
begin
lvObj := GetO(pvPath);
if lvObj = nil then
begin
Result := '';
end else
begin
Result := lvObj.AsString;
end;
end;
function TSimpleMsgPack.indexOf(pvName:string): Integer;
begin
Result := indexOfIgnoreSensitive(LowerCase(pvName));
end;
function TSimpleMsgPack.indexOfCaseSensitive(pvName:string): Integer;
var
i, l: Integer;
lvObj:TSimpleMsgPack;
begin
Result := -1;
l := Length(pvName);
if l = 0 then exit;
for i := 0 to FChildren.Count-1 do
begin
lvObj := TSimpleMsgPack(FChildren[i]);
if Length(lvObj.FName) = l then
begin
if lvObj.FName = pvName then
begin
Result := i;
break;
end;
end;
end;
end;
function TSimpleMsgPack.indexOfIgnoreSensitive(pvLowerCaseName: string):
Integer;
var
i, l: Integer;
lvObj:TSimpleMsgPack;
begin
Result := -1;
l := Length(pvLowerCaseName);
if l = 0 then exit;
for i := 0 to FChildren.Count-1 do
begin
lvObj := TSimpleMsgPack(FChildren[i]);
if Length(lvObj.FLowerName) = l then
begin
if lvObj.FLowerName = pvLowerCaseName then
begin
Result := i;
break;
end;
end;
end;
end;
function TSimpleMsgPack.InnerAdd(pvDataType: TMsgPackType): TSimpleMsgPack;
begin
Result := TSimpleMsgPack.Create;
Result.FDataType := mptUnknown;
InnerAddToChildren(pvDataType, Result);
end;
function TSimpleMsgPack.InnerAdd: TSimpleMsgPack;
begin
if self.FDataType in [mptMap, mptArray] then
begin
Result := TSimpleMsgPack.Create;
Result.FDataType := mptUnknown;
Result.FParent := self;
FChildren.Add(Result);
end else
begin
raise Exception.Create(SCannotAddChild);
end;
end;
procedure TSimpleMsgPack.InnerAddToChildren(pvDataType: TMsgPackType; obj:
TSimpleMsgPack);
begin
checkObjectDataType(pvDataType);
obj.FParent := self;
FChildren.Add(obj);
end;
procedure TSimpleMsgPack.InnerEncodeToStream(pvStream:TStream);
begin
case FDataType of
mptUnknown, mptNull: WriteNull(pvStream);
mptMap: writeMap(Self, pvStream);
mptArray: writeArray(Self, pvStream);
mptString: writeString(Self.getAsString, pvStream);
mptInteger: WriteInt(self.getAsInteger, pvStream);
mptBoolean: WriteBoolean(self.GetAsBoolean, pvStream);
mptDateTime, mptFloat: WriteFloat(GetAsFloat, pvStream);
mptSingle: WriteSingle(GetAsSingle, pvStream);
mptBinary: WriteBinary(PByte(@FValue[0]), Length(FValue), pvStream);
end;
end;
function TSimpleMsgPack.InnerFindPathObject(pvPath: string; var vParent:
TSimpleMsgPack; var vIndex: Integer): TSimpleMsgPack;
var
lvName:string;
s:string;
sPtr:PChar;
lvTempObj, lvParent:TSimpleMsgPack;
j:Integer;
begin
s := pvPath;
Result := nil;
lvParent := Self;
sPtr := PChar(s);
while sPtr^ <> #0 do
begin
lvName := getFirst(sPtr, ['.', '/','\']);
if lvName = '' then
begin
Break;
end else
begin
if sPtr^ = #0 then
begin // end
j := lvParent.indexOf(lvName);
if j <> -1 then
begin
Result := TSimpleMsgPack(lvParent.FChildren[j]);
vIndex := j;
vParent := lvParent;
end else
begin
Break;
end;
end else
begin
// find childrean
lvTempObj := lvParent.findObj(lvName);
if lvTempObj = nil then
begin
Break;
end else
begin
lvParent := lvTempObj;
end;
end;
end;
if sPtr^ = #0 then Break;
Inc(sPtr);
end;
end;
procedure TSimpleMsgPack.InnerParseFromStream(pvStream: TStream);
var
lvByte:Byte;
lvBData: array[0..15] of Byte;
lvSwapData: array[0..7] of Byte;
lvAnsiStr:{$IFDEF UNICODE}TBytes{$ELSE}AnsiString{$ENDIF};
l, i:Cardinal;
i64 :Int64;
lvObj:TSimpleMsgPack;
begin
pvStream.Read(lvByte, 1);
if lvByte in [$00 .. $7F] then //positive fixint 0xxxxxxx 0x00 - 0x7f
begin
// +--------+
// |0XXXXXXX|
// +--------+
setAsInteger(lvByte);
end else if lvByte in [$80 .. $8F] then //fixmap 1000xxxx 0x80 - 0x8f
begin
FDataType := mptMap;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := lvByte - $80;
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptMap);
// map key
lvObj.InnerParseFromStream(pvStream);
lvObj.setName(lvObj.getAsString);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end else if lvByte in [$90 .. $9F] then //fixarray 1001xxxx 0x90 - 0x9f
begin
FDataType := mptArray;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := lvByte - $90;
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptArray);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end else if lvByte in [$A0 .. $BF] then //fixstr 101xxxxx 0xa0 - 0xbf
begin
l := lvByte - $A0; // str len
if l > 0 then
begin
SetLength(lvAnsiStr, l);
pvStream.Read(PByte(lvAnsiStr)^, l);
setAsString(UTF8DecodeEx(lvAnsiStr, l));
// SetLength(lvBytes, l + 1);
// lvBytes[l] := 0;
// pvStream.Read(lvBytes[0], l);
// setAsString(UTF8Decode(PAnsiChar(@lvBytes[0])));
end else
begin
setAsString('');
end;
end else if lvByte in [$E0 .. $FF] then
begin
// negative fixnum stores 5-bit negative integer
// +--------+
// |111YYYYY|
// +--------+
setAsInteger(Shortint(lvByte));
end else
begin
case lvByte of
$C0: // null
begin
FDataType := mptNull;
SetLength(FValue, 0);
end;
$C1: // (never used)
raise Exception.Create('(never used) type $c1');
$C2: // False
begin
SetAsBoolean(False);
end;
$C3: // True
begin
SetAsBoolean(True);
end;
$C4: // 短二进制,最长255字节
begin
FDataType := mptBinary;
l := 0; // fill zero
pvStream.Read(l, 1);
SetLength(FValue, l);
pvStream.Read(FValue[0], l);
end;
$C5: // 二进制,16位,最长65535B
begin
FDataType := mptBinary;
l := 0; // fill zero
pvStream.Read(l, 2);
l := swap16(l);
SetLength(FValue, l);
pvStream.Read(FValue[0], l);
end;
$C6: // 二进制,32位,最长2^32-1
begin
FDataType := mptBinary;
l := 0; // fill zero
pvStream.Read(l, 4);
l := swap32(l);
SetLength(FValue, l);
pvStream.Read(FValue[0], l);
end;
$c7,$c8,$c9: //ext 8 11000111 0xc7, ext 16 11001000 0xc8, ext 32 11001001 0xc9
begin
raise Exception.Create('(ext8,ext16,ex32) type $c7,$c8,$c9');
end;
$CA: // float 32
begin
pvStream.Read(lvBData[0], 4);
swap32Ex(lvBData[0], lvSwapData[0]);
AsSingle := PSingle(@lvSwapData[0])^;
end;
$cb: // Float 64
begin
pvStream.Read(lvBData[0], 8);
// swap to int64, and lvBData is not valid double value (for IEEE)
i64 := swap64(lvBData[0]);
//
AsFloat := PDouble(@i64)^;
// AsFloat := swap(PDouble(@lvBData[0])^);
end;
$cc: // UInt8
begin
// uint 8 stores a 8-bit unsigned integer
// +--------+--------+
// | 0xcc |ZZZZZZZZ|
// +--------+--------+
l := 0;
pvStream.Read(l, 1);
setAsInteger(l);
end;
$cd:
begin
// uint 16 stores a 16-bit big-endian unsigned integer
// +--------+--------+--------+
// | 0xcd |ZZZZZZZZ|ZZZZZZZZ|
// +--------+--------+--------+
l := 0;
pvStream.Read(l, 2);
l := swap16(l);
SetAsInteger(Word(l));
end;
$ce:
begin
// uint 32 stores a 32-bit big-endian unsigned integer
// +--------+--------+--------+--------+--------+
// | 0xce |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ
// +--------+--------+--------+--------+--------+
l := 0;
pvStream.Read(l, 4);
l := swap32(l);
setAsInteger(Cardinal(l));
end;
$cf:
begin
// uint 64 stores a 64-bit big-endian unsigned integer
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
// | 0xcf |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
i64 := 0;
pvStream.Read(i64, 8);
i64 := swap64(i64);
setAsInteger(i64);
end;
$dc: // array 16
begin
// +--------+--------+--------+~~~~~~~~~~~~~~~~~+
// | 0xdc |YYYYYYYY|YYYYYYYY| N objects |
// +--------+--------+--------+~~~~~~~~~~~~~~~~~+
FDataType := mptArray;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := 0; // fill zero
pvStream.Read(l, 2);
l := swap16(l);
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptArray);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end;
$dd: // Array 32
begin
// +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
// | 0xdd |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N objects |
// +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
FDataType := mptArray;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := 0; // fill zero
pvStream.Read(l, 4);
l := swap32(l);
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptArray);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end;
$d9: //str 8 , 255
begin
// str 8 stores a byte array whose length is upto (2^8)-1 bytes:
// +--------+--------+========+
// | 0xd9 |YYYYYYYY| data |
// +--------+--------+========+
l := 0;
pvStream.Read(l, 1);
if l > 0 then // check is empty ele
begin
SetLength(lvAnsiStr, l);
pvStream.Read(PByte(lvAnsiStr)^, l);
setAsString(UTF8DecodeEx(lvAnsiStr, l));
end else
begin
setAsString('');
end;
// SetLength(lvBytes, l + 1);
// lvBytes[l] := 0;
// pvStream.Read(lvBytes[0], l);
// setAsString(UTF8Decode(PAnsiChar(@lvBytes[0])));
end;
$DE: // Object map 16
begin
// +--------+--------+--------+~~~~~~~~~~~~~~~~~+
// | 0xde |YYYYYYYY|YYYYYYYY| N*2 objects |
// +--------+--------+--------+~~~~~~~~~~~~~~~~~+
FDataType := mptMap;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := 0; // fill zero
pvStream.Read(l, 2);
l := swap16(l);
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptMap);
// map key
lvObj.InnerParseFromStream(pvStream);
lvObj.setName(lvObj.getAsString);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end;
$DF: //Object map 32
begin
// +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
// | 0xdf |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N*2 objects |
// +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
FDataType := mptMap;
SetLength(FValue, 0);
ClearAndFreeAllChildren;
l := 0; // fill zero
pvStream.Read(l, 4);
l := swap32(l);
if l > 0 then // check is empty ele
begin
for I := 0 to l - 1 do
begin
lvObj := InnerAdd(mptMap);
// map key
lvObj.InnerParseFromStream(pvStream);
lvObj.setName(lvObj.getAsString);
// value
lvObj.InnerParseFromStream(pvStream);
end;
end;
end;
$da: // str 16
begin
// str 16 stores a byte array whose length is upto (2^16)-1 bytes:
// +--------+--------+--------+========+
// | 0xda |ZZZZZZZZ|ZZZZZZZZ| data |
// +--------+--------+--------+========+
l := 0; // fill zero
pvStream.Read(l, 2);
l := swap16(l);
if l > 0 then // check is empty ele
begin
SetLength(lvAnsiStr, l);
pvStream.Read(PByte(lvAnsiStr)^, l);
setAsString(UTF8DecodeEx(lvAnsiStr, l));
end else
begin
setAsString('');
end;
// SetLength(lvBytes, l + 1);
// lvBytes[l] := 0;
// pvStream.Read(lvBytes[0], l);
// setAsString(UTF8Decode(PAnsiChar(@lvBytes[0])));
end;
$db: // str 16
begin
// str 32 stores a byte array whose length is upto (2^32)-1 bytes:
// +--------+--------+--------+--------+--------+========+
// | 0xdb |AAAAAAAA|AAAAAAAA|AAAAAAAA|AAAAAAAA| data |
// +--------+--------+--------+--------+--------+========+
l := 0; // fill zero
pvStream.Read(l, 4);
l := swap32(l);
if l > 0 then // check is empty ele
begin
SetLength(lvAnsiStr, l);
pvStream.Read(PByte(lvAnsiStr)^, l);
setAsString(UTF8DecodeEx(lvAnsiStr, l));
end else
begin
setAsString('');
end;
// SetLength(lvBytes, l + 1);
// lvBytes[l] := 0;
// pvStream.Read(lvBytes[0], l);
// setAsString(UTF8Decode(PAnsiChar(@lvBytes[0])));
end;
$d0: //int 8
begin
// int 8 stores a 8-bit signed integer
// +--------+--------+
// | 0xd0 |ZZZZZZZZ|
// +--------+--------+
l := 0;
pvStream.Read(l, 1);
SetAsInteger(ShortInt(l));
end;
$d1:
begin
// int 16 stores a 16-bit big-endian signed integer
// +--------+--------+--------+
// | 0xd1 |ZZZZZZZZ|ZZZZZZZZ|
// +--------+--------+--------+
l := 0;
pvStream.Read(l, 2);
l := swap16(l);
SetAsInteger(SmallInt(l));
end;
$d2:
begin
// int 32 stores a 32-bit big-endian signed integer
// +--------+--------+--------+--------+--------+
// | 0xd2 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
// +--------+--------+--------+--------+--------+
l := 0;
pvStream.Read(l, 4);
l := swap32(l);
setAsInteger(Integer(l));
end;
$d3:
begin
// int 64 stores a 64-bit big-endian signed integer
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
// | 0xd3 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
i64 := 0;
pvStream.Read(i64, 8);
i64 := swap64(i64);
setAsInteger(Int64(i64));
end;
end;
end;
end;
procedure TSimpleMsgPack.LoadBinaryFromFile(pvFileName:String);
var
lvFileStream:TFileStream;
begin
if FileExists(pvFileName) then
begin
lvFileStream := TFileStream.Create(pvFileName, fmOpenRead);
try
LoadBinaryFromStream(lvFileStream);
finally
lvFileStream.Free;
end;
end;
end;
procedure TSimpleMsgPack.LoadBinaryFromStream(pvStream: TStream; pvLen:
cardinal = 0);
begin
FDataType := mptBinary;
if pvLen = 0 then
begin
pvStream.Position := 0;
SetLength(FValue, pvStream.Size);
pvStream.Read(FValue[0], pvStream.Size);
end else
begin
SetLength(FValue, pvLen);
pvStream.ReadBuffer(FValue[0], pvLen);
end;
end;
function TSimpleMsgPack.Remove(pvPath:string): TSimpleMsgPack;
var
lvParent:TSimpleMsgPack;
j:Integer;
begin
Result := InnerFindPathObject(pvPath, lvParent, j);
if Result<>nil then
begin
lvParent.FChildren.Delete(j);
end;
end;
function TSimpleMsgPack.Remove(pvIndex:Integer): TSimpleMsgPack;
begin
if (pvIndex < 0) or (pvIndex >= Count) then
begin
Result := nil;
end else
begin
Result := TSimpleMsgPack(FChildren[pvIndex]);
FChildren.Delete(pvIndex);
end;
end;
function TSimpleMsgPack.Remove(pvChild:TSimpleMsgPack): Boolean;
begin
Result := FChildren.Remove(pvChild) <> -1;
end;
procedure TSimpleMsgPack.RemoveFromParent;
begin
if FParent <> nil then
begin
FParent.FChildren.Remove(Self);
end;
end;
procedure TSimpleMsgPack.SaveBinaryToFile(pvFileName: String);
var
lvFileStream:TFileStream;
begin
if FileExists(pvFileName) then
begin
if not DeleteFile(PChar(pvFileName)) then
RaiseLastOSError;
end;
lvFileStream := TFileStream.Create(pvFileName, fmCreate);
try
lvFileStream.WriteBuffer(FValue[0], Length(FValue));
finally
lvFileStream.Free;
end;
end;
procedure TSimpleMsgPack.SaveBinaryToStream(pvStream: TStream);
begin
pvStream.WriteBuffer(FValue[0], Length(FValue));
end;
procedure TSimpleMsgPack.SetAsBoolean(const Value: Boolean);
begin
FDataType := mptBoolean;
SetLength(FValue, 1);
PBoolean(@FValue[0])^ := Value;
end;
procedure TSimpleMsgPack.SetAsBytes(const Value: TBytes);
begin
FDataType := mptBinary;
FValue := Value;
end;
procedure TSimpleMsgPack.SetAsDateTime(const Value: TDateTime);
begin
FDataType := mptDateTime;
SetLength(FValue, SizeOf(TDateTime));
PDouble(@FValue[0])^ := Value;
end;
procedure TSimpleMsgPack.SetAsFloat(const Value: Double);
begin
FDataType := mptFloat;
SetLength(FValue, SizeOf(Double));
PDouble(@FValue[0])^ := Value;
end;
procedure TSimpleMsgPack.setAsInteger(pvValue: Int64);
begin
FDataType := mptInteger;
SetLength(FValue, SizeOf(Int64));
PInt64(@FValue[0])^ := pvValue;
end;
procedure TSimpleMsgPack.SetAsSingle(const Value: Single);
begin
FDataType := mptSingle;
SetLength(FValue, SizeOf(Single));
PSingle(FValue)^ := Value;
end;
{$IFDEF FPC}
procedure TSimpleMsgPack.setAsString(pvValue: string);
var l : SizeInt;
begin
FDataType := mptString;
if SizeOf(Char) = 2 then
l := Length(pvValue) shl 1
else
l := Length(pvValue);
SetLength(FValue, l);
if l > 0 then
Move(PChar(pvValue)^, FValue[0], l);
end;
{$ELSE}
procedure TSimpleMsgPack.setAsString(pvValue: string);
begin
FDataType := mptString;
if SizeOf(Char) = 2 then
begin
SetLength(FValue, length(pvValue) shl 1);
Move(PChar(pvValue)^, FValue[0], Length(FValue));
end else
begin
SetLength(FValue, length(pvValue));
Move(PChar(pvValue)^, FValue[0], Length(FValue));
end;
end;
{$ENDIF}
/// <summary>
/// copy from qdac3
/// </summary>
procedure TSimpleMsgPack.SetAsVariant(const Value: Variant);
var
I: Integer;
AType: TVarType;
procedure VarAsBytes;
var
L: Integer;
p: PByte;
begin
FDataType := mptBinary;
L := VarArrayHighBound(Value, 1) + 1;
SetLength(FValue, L);
p := VarArrayLock(Value);
Move(p^, FValue[0], L);
VarArrayUnlock(Value);
end;
begin
if VarIsArray(Value) then
begin
AType := VarType(Value);
if (AType and varTypeMask) = varByte then
VarAsBytes
else
begin
checkObjectDataType(mptArray);
ClearAndFreeAllChildren;
for I := VarArrayLowBound(Value, VarArrayDimCount(Value))
to VarArrayHighBound(Value, VarArrayDimCount(Value)) do
Add.AsVariant := Value[I];
end;
end
else
begin
case VarType(Value) of
varSmallInt, varInteger, varByte, varShortInt, varWord,
varLongWord, varInt64:
AsInteger := Value;
varSingle, varDouble, varCurrency:
AsFloat := Value;
varDate:
AsDateTime := Value;
varOleStr, varString{$IFDEF UNICODE}, varUString{$ENDIF}:
AsString := Value;
varBoolean:
AsBoolean := Value;
varNull,varEmpty,varUnknown:
begin
FDataType:=mptNull;
SetLength(FValue, 0);
end;
{$IF RtlVersion>=26}
varUInt64:
AsInteger := Value;
{$IFEND}
else
// null
;//raise Exception.Create(SVariantConvertNotSupport);
end;
end;
end;
procedure TSimpleMsgPack.SetB(pvPath: String; const Value: Boolean);
var
lvObj:TSimpleMsgPack;
begin
lvObj := ForcePathObject(pvPath);
lvObj.AsBoolean := Value;
end;
procedure TSimpleMsgPack.SetD(pvPath: String; const Value: Double);
var
lvObj:TSimpleMsgPack;
begin
lvObj := ForcePathObject(pvPath);
lvObj.AsFloat := Value;
end;
procedure TSimpleMsgPack.SetI(pvPath: String; const Value: Int64);
var
lvObj:TSimpleMsgPack;
begin
lvObj := ForcePathObject(pvPath);
lvObj.AsInteger := Value;
end;
procedure TSimpleMsgPack.setName(pvName: string);
begin
FName := pvName;
FLowerName := LowerCase(FName);
end;
procedure TSimpleMsgPack.SetO(pvPath: String; const Value: TSimpleMsgPack);
var
lvName:String;
s:String;
sPtr:PChar;
lvTempObj, lvParent:TSimpleMsgPack;
j:Integer;
begin
s := pvPath;
lvParent := Self;
sPtr := PChar(s);
while sPtr^ <> #0 do
begin
lvName := getFirst(sPtr, ['.', '/','\']);
if lvName = '' then
begin
Break;
end else
begin
if sPtr^ = #0 then
begin // end
j := lvParent.indexOf(lvName);
if j <> -1 then
begin
lvTempObj := TSimpleMsgPack(lvParent.FChildren[j]);
lvParent.FChildren[j] := Value;
lvTempObj.Free; // free old
end else
begin
Value.setName(lvName);
lvParent.InnerAddToChildren(mptMap, Value);
end;
end else
begin
// find childrean
lvTempObj := lvParent.findObj(lvName);
if lvTempObj = nil then
begin
lvParent := lvParent.Add(lvName);
end else
begin
lvParent := lvTempObj;
end;
end;
end;
if sPtr^ = #0 then Break;
Inc(sPtr);
end;
end;
procedure TSimpleMsgPack.SetS(pvPath: String; const Value: string);
var
lvObj:TSimpleMsgPack;
begin
lvObj := ForcePathObject(pvPath);
lvObj.AsString := Value;
end;
end.
|
//Ejercicio 11
//La solución de un sistema de ecuaciones lineales con dos incógnitas, se puede obtener mediante la regla de Cramer. Suponga que el
//sistema de ecuaciones es:
//a x + b y = c
//d x + e y = f
//La regla de Cramer dice que, si existe una solución, esta es:
//x = (ce - fb) / (ae - db)
//y = (af - dc) / (ae -db)
//Escriba un programa en PASCAL que lea de la entrada estándar los valores a, b, c, d, e , y f,
//que determine la solución del sistema de ecuaciones correspondiente y la
//imprima en caso de que exista, o que imprima un mensaje de error en caso contrario.
program ejercicio11;
var a, b, c, d, e, f, x, y, denox, denoy : real;
begin
writeln('Ingrese el valor de a.');
readln(a);
writeln('Ingrese el valor de b.');
readln(b);
writeln('Ingrese el valor de c.');
readln(c);
writeln('Ingrese el valor de d.');
readln(d);
writeln('Ingrese el valor de e.');
readln(e);
writeln('Ingrese el valor de f.');
readln(f);
denox := (a*e - d*b);
denoy := (a*e - d*b);
if (denox <> 0) and (denoy <> 0) then
begin
x := (c*e - f*b) / denox;
y := (a*f - d*c) / denoy;
writeln('La solucin es x = ',x:4:2,' y = ',y:4:2)
end
else
writeln('No tiene solucion.');
end. |
unit uCST;
interface
uses
Contnrs,
uRegistro;
type
TCST = class(TRegistro)
private
fID : Integer; // Toda chave primaria nossa no banco dentro do objeto vai chamar ID
fCodigo : String;
fDescricao : String;
procedure SetCodigo(const Value: String);
procedure SetDescricao(const Value: String);
procedure SetID(const Value: Integer);
public
property ID : Integer read fID write SetID;
property Descricao : String read fDescricao write SetDescricao;
property Codigo : String read fCodigo write SetCodigo;
function Todos : TObjectList;
function Procurar () : TRegistro;
constructor create();
end;
implementation
uses
UCSTBD;
{ TCST }
constructor TCST.create;
begin
end;
function TCST.Procurar: TRegistro;
var
lCSTBD : TCSTBD;
begin
lCSTBD := TCSTBD.Create;
result := lCSTBD.Procurar(self);
fDescricao := TCST(result).fDescricao;
fCodigo := TCST(result).fCodigo;
end;
procedure TCST.SetCodigo(const Value: String);
begin
fCodigo := Value;
end;
procedure TCST.SetDescricao(const Value: String);
begin
fDescricao := Value;
end;
procedure TCST.SetID(const Value: Integer);
begin
fID := Value;
end;
function TCST.Todos: TObjectList;
var
lCSTBD : TCSTBD;
begin
lCSTBD := TCSTBD.Create;
result := lCSTBD.Todos();
end;
end.
|
unit Unit1;
//
// From original Synopse test program (http://synopse.info/)
// (Indicate a valid search path for the LLCL files before compiling)
//
{$IFDEF FPC}
{$mode objfpc}{$H+}
// {$mode delphi}
// {$mode objfpc}{$modeswitch unicodestrings}{$H+} // Requires FPC 2.7.1+
// {$mode delphiunicode}{$codepage UTF8} // (See LLCL README.txt)
{$ENDIF}
{$IFDEF FPC_OBJFPC} {$DEFINE IS_FPC_OBJFPC_MODE} {$ENDIF}
interface
uses
SysUtils, {$IFDEF FPC}LazUTF8, LCLType,{$ELSE} Variants, XPMan,{$ENDIF}
Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
ComCtrls, Menus;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Button7: TButton;
Button8: TButton;
Button9: TButton;
Button10: TButton;
Button11: TButton;
Edit1: TEdit;
ComboBox1: TComboBox;
ListBox1: TListBox;
Memo1: TMemo;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
GroupBox1: TGroupBox;
OpenDialog1: TOpenDialog;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
ComboBox2: TComboBox;
Label1: TLabel;
SaveDialog1: TSaveDialog;
StaticText1: TStaticText;
ProgressBar1: TProgressBar;
StaticText2: TStaticText;
Timer1: TTimer;
MainMenu1: TMainMenu;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
MenuItem5: TMenuItem;
MenuItem6: TMenuItem;
MenuItem7: TMenuItem;
MenuItem8: TMenuItem;
MenuItem9: TMenuItem;
MenuItem10: TMenuItem;
MenuItem11: TMenuItem;
MenuItem12: TMenuItem;
MenuItem13: TMenuItem;
PopupMenu1: TPopupMenu;
{$IFDEF FPC}
{$ELSE}
XPManifest1: TXPManifest;
{$ENDIF}
procedure Button10Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure Button11Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure Edit1DblClick(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ListBox1DblClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure Timer1Timer(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure MenuItem6Click(Sender: TObject);
procedure MenuItem7Click(Sender: TObject);
procedure MenuItem8Click(Sender: TObject);
procedure MenuItem9Click(Sender: TObject);
procedure MenuItem10Click(Sender: TObject);
procedure MenuItem11Click(Sender: TObject);
procedure MenuItem12Click(Sender: TObject);
private
{ Private declarations }
TrackBar1: TTrackBar;
// Workaround for FPC (TCheckBox and TRadioButton don't have any alignment property)
{$IFDEF FPC}
{$IF Declared(LLCLVersion)}
protected
procedure CreateParams(var Params : TCreateParams); override;
{$IFEND}
{$ENDIF}
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
//
// Format an output string with various input values,
// And add it to Memo1
//
procedure MemoAddLineFmt(MemoCtrl: TMemo; const s: string; const Args: array of const);
begin
MemoCtrl.Lines.Add(Format(s, Args));
end;
// Workaround for FPC (TCheckBox and TRadioButton don't have any alignment property)
{$IFDEF FPC}
// Sample of how to use specific code for LLCL (Not recommended)
{$IF Declared(LLCLVersion)}
procedure TForm1.CreateParams(var Params : TCreateParams);
begin
inherited;
Form1.CheckBox1.Alignment := taLeftJustify; // Note: TCheckBox has an alignment
Form1.CheckBox3.Alignment := taLeftJustify; // property since Lazarus 1.4
Form1.RadioButton2.Alignment := taLeftJustify;
end;
{$IFEND}
{$ENDIF}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Called after form (and its controls) is created, but before it is shown
// Timer disabled when application started (see Cancel/Default pushbuttons)
Timer1.Enabled := false;
// Sample of a control created at runtime
TrackBar1 := TTrackBar.Create(self);
with TrackBar1 do
begin
Name := 'TrackBar1'; // (Optional)
Left := 184;
Height := {$IFDEF FPC}22{$ELSE}28{$ENDIF};
Top := 184;
Width := 215;
OnChange := {$IFDEF IS_FPC_OBJFPC_MODE}@{$ENDIF}TrackBar1Change;
Parent := self;
TabOrder := ListBox1.TabOrder+1;
end;
end;
procedure TForm1.Button10Click(Sender: TObject);
begin
// Should never happen
ShowMessage('Impossible: invisible control.');
end;
procedure TForm1.Button8Click(Sender: TObject);
begin
// Should never happen
ShowMessage('Impossible: disabled control.');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
// PushButton 1 has been clicked (mouse, keyboard ...)
// Adds Edit1 current text to ComboBox1 (choices list) and ListBox1
ComboBox1.Items.Add(Edit1.Text);
ListBox1.Items.Add(Edit1.Text);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
// Sets ComboBox1 (edit part) to Edit1 current text
Edit1.Text := ComboBox1.Text;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
// Clears both ComboBox1 (only choices list) and ListBox1
ComboBox1.Items.Clear;
ListBox1.Clear;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
// Sets Edit1 current text to ComboBox1 (edit part)
ComboBox1.Text := Edit1.Text;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
// PushButton 'Cancel Button' (defined with 'Cancel' property = Escape key)
// Clears ProgressBar1 and stops Timer1
Memo1.Lines.Add('Escape/Cancel');
if Timer1.Enabled then
begin
Timer1.Enabled := false;
ProgressBar1.Position := 0;
ShowMessage('Timer is now stopped.');
end;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
// All CheckBox values set to 'Grayed' (i.e. undefined state)
CheckBox1.State := cbGrayed;
CheckBox2.State := cbGrayed;
CheckBox3.State := cbGrayed;
end;
procedure TForm1.Button7Click(Sender: TObject);
begin
// Opens/Closes ComboBox1 choices list
ComboBox1.DroppedDown := not ComboBox1.DroppedDown;
end;
procedure TForm1.Button9Click(Sender: TObject);
begin
// Hides/Shows GroupBox1 and its controls (RadioButtons)
Memo1.Lines.Add('Button9Click');
GroupBox1.Visible := not GroupBox1.Visible;
end;
procedure TForm1.Button11Click(Sender: TObject);
begin
// PushButton 'Default Button' (defined with 'Default' property = Return key)
// Starts Timer1
Memo1.Lines.Add('Return/Default');
if not Timer1.Enabled then
begin
Timer1.Enabled := true;
ShowMessage('Timer is started. See progress bar...'+sLineBreak+sLineBreak+
'Escape (Cancel button) to stop it.');
end;
end;
procedure TForm1.Edit1Change(Sender: TObject);
begin
// Text has been changed for Edit1
Memo1.Lines.Add('Edit1: '+Edit1.Text);
end;
procedure TForm1.Edit1DblClick(Sender: TObject);
begin
// Double (left) click for Edit1
Memo1.Lines.Add('Edit1DblClick');
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
// New selection for ComboBox1 (form choices list, left click)
Memo1.Lines.Add('ComboBox1Change '+IntToStr(ComboBox1.ItemIndex));
end;
procedure TForm1.ListBox1DblClick(Sender: TObject);
begin
// Double (left) click (i.e. new selection) for one line of ListBox1
Memo1.Lines.Add('ListBox1DblClick '+IntToStr(ListBox1.ItemIndex));
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var s: String;
begin
// Mouse button down (any button) over Form1
if ssDouble in Shift then s := ' (Double click)' else s := '';
MemoAddLineFmt(Memo1,'FormMouseDown at %d %d'+s, [X, Y]);
end;
procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
// Mouse button up (any button) over Form1
MemoAddLineFmt(Memo1,'FormMouseUp at %d %d', [X, Y]);
// If right button (i.e. right click), shows a popup menu
if Button=mbRight then
PopupMenu1.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y);
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Keyboard key down (in most of controls)
// (Because Form1 has KeyPreview=True property)
MemoAddLineFmt(Memo1,'FormKeyDown %d', [Key]);
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Keyboard key up (in most of controls)
// (Because Form1 has KeyPreview=True property)
MemoAddLineFmt(Memo1,'FormKeyUp %d', [Key]);
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
// Keyboard key pressed (in most of controls)
// (Because Form1 has KeyPreview=True property)
// Only the character code is present here (see FormKeyDown, FormKeyUp)
MemoAddLineFmt(Memo1,'FormKeyPress #%d ''%s''', [Ord(Key),
{$if Defined(FPC) and not Defined(UNICODE)}SysToUTF8(Key){$else}Key{$ifend}]); // Char type is not UTF8
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// Timer fall
// Increments ProgressBar1 with one 'stepit' value (1/10 by default - SetStep to modify it)
// (ProgressBar1 automatically resets to 0 when maximum reached)
ProgressBar1.StepIt;
Memo1.Lines.Add('Timer Tick: ProgressBar='+IntToStr(ProgressBar1.Position));
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
// TrackBar position modified
Memo1.Lines.Add('TrackBar: New value='+IntToStr(TTrackBar(Sender).Position)+'/'+IntToStr(TTrackBar(Sender).Max));
end;
procedure TForm1.MenuItem6Click(Sender: TObject);
begin
// 'Quit' in main menu
// End of program
Application.Terminate;
end;
procedure TForm1.MenuItem7Click(Sender: TObject);
begin
// Simple main menu selection
Memo1.Lines.Add('Menu21');
end;
procedure TForm1.MenuItem8Click(Sender: TObject);
begin
// Simple main menu selection
Memo1.Lines.Add('Menu22');
end;
procedure TForm1.MenuItem11Click(Sender: TObject);
begin
// Main menu: Open a file...
OpenDialog1.Options := OpenDialog1.Options+[ofPathMustExist, ofFileMustExist];
OpenDialog1.Filter := 'Text files (*.txt)|*.txt|All files|*.*';
OpenDialog1.FilterIndex := 1;
OpenDialog1.Title := 'File to open';
if OpenDialog1.Execute then
ShowMessage('File to open: '+OpenDialog1.FileName);
end;
procedure TForm1.MenuItem12Click(Sender: TObject);
begin
// Main menu: Save a File...
SaveDialog1.Options := SaveDialog1.Options+[ofPathMustExist, ofOverwritePrompt];
SaveDialog1.Filter := 'Text files (*.txt)|*.txt|Temporary files (*.tmp)|*.tmp|All files|*.*';
SaveDialog1.FilterIndex := 2;
SaveDialog1.FileName := 'MyFile.tmp';
if SaveDialog1.Execute then
ShowMessage('File to save: '+SaveDialog1.FileName);
end;
procedure TForm1.MenuItem9Click(Sender: TObject);
begin
// Popup menu selection
Memo1.Lines.Add('Popup1');
end;
procedure TForm1.MenuItem10Click(Sender: TObject);
begin
// Popup menu selection
Memo1.Lines.Add('Popup2');
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit TableComp;
interface
uses
Classes, SelfCopied, Grids, Controls, Graphics, Tools, SelfSaved,
ClassInheritIDs, SysUtils, NumericGrid;
type
ETableCompList = class(Exception);
TTableCompList = class(TSelfCopiedCompList, IGridDataSource)
protected
FCaption: string;
SavedColWidths: TLongArray;
SavedRowHeights: TLongArray;
AreColWidthsReady: Boolean;
AreRowHeightsReady: Boolean;
FSavedCol, FSavedRow, FSavedLeftCol, FSavedTopRow: LongInt;
FSavedSelection: TGridRect;
SettingsSaved: Boolean;
HeightsSaved, WidthsSaved: Boolean;
Destroying: Boolean;
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
procedure CheckColIndex(const Index: LongInt);
procedure CheckRowIndex(const Index: LongInt);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure GridAssign(Grid: TStringGrid); virtual;
procedure GridRelease(Grid: TStringGrid); virtual;
procedure SetDataToGrid(Grid: TStringGrid); virtual; abstract;
function GetDataFromGrid(Grid: TStringGrid): Boolean; virtual; abstract;
procedure SetCaption(Grid: TStringGrid); virtual; abstract;
procedure SetColOptions(Grid: TStringGrid); virtual; abstract;
procedure SetColFunc(Grid: TStringGrid); virtual;
procedure SetColWidths(Grid: TStringGrid);
procedure GetColWidths(Grid: TStringGrid);
procedure SetRowHeights(Grid: TStringGrid);
procedure GetRowHeights(Grid: TStringGrid);
procedure SetRowContents(
Grid: TStringGrid; RowNum: LongInt); virtual; abstract;
function GetRowContents(
Grid: TStringGrid; RowNum: LongInt): Boolean; virtual; abstract;
procedure SetColContents(
Grid: TStringGrid; ColNum: LongInt); virtual; abstract;
function GetColContents(
Grid: TStringGrid; ColNum: LongInt): Boolean; virtual; abstract;
procedure InitColWidths;
procedure InitRowHeights;
function IsDataSourceEmpty: Boolean; virtual; abstract;
function ValueToString(const ACol, ARow: LongInt
): string; virtual; abstract;
procedure BeforeStringToValue(const ACol, ARow: LongInt;
const AString: string); virtual; abstract;
procedure StringToValue(const ACol, ARow: LongInt;
const AString: string
); virtual; abstract;
procedure SetValueByDefault(const ACol, ARow: LongInt); virtual; abstract;
function GetCellColor(
const ACol, ARow: LongInt;
var Color: TColor): Boolean; virtual;
function GetCellEditMask(
const ACol, ARow: LongInt): string; virtual; abstract;
function GetCellEnabledCharSet(
const ACol, ARow: LongInt): TCharSet; virtual; abstract;
function IsCellDisabled(
const ACol, ARow: LongInt): Boolean; virtual;
function IsDataValid(const ACol, ARow: LongInt;
const AString: string): Boolean; virtual; abstract;
function MayIDoInsertRows(StartRow, RowsCount: LongInt): Boolean; virtual;
function MayIDoDeleteRows(StartRow, RowsCount: LongInt): Boolean; virtual;
function MayIDoAddRow: Boolean; virtual;
function MayIDoInsertColumns(StartCol, ColsCount: LongInt): Boolean; virtual;
function MayIDoDeleteColumns(StartCol, ColsCount: LongInt): Boolean; virtual;
function MayIDoAddColumn: Boolean; virtual;
function MayIDoDeleteAllData: Boolean; virtual;
function MayIDoClearSelectedArea: Boolean; virtual;
function MayIDoClearAllCells: Boolean; virtual;
procedure DeleteAllColWidthItems;
procedure DeleteColWidthItem(const Index: LongInt);
procedure InsertColWidthItem(const Index: LongInt);
procedure AddColWidthItem;
procedure DeleteAllRowHeightItems;
procedure DeleteRowHeightItem(const Index: LongInt);
procedure InsertRowHeightItem(const Index: LongInt);
procedure AddRowHeightItem;
function GetColWidthByDefault(
const Index: LongInt): LongInt; virtual;
function GetRowHeightByDefault(
const Index: LongInt): LongInt; virtual;
procedure RowsDeleted(
const StartRow, RowsCount: LongInt); virtual;
procedure RowsInserted(
const StartRow, RowsCount: LongInt); virtual;
procedure RowAdded; virtual;
procedure ColumnsDeleted(
const StartCol, ColsCount: LongInt); virtual;
procedure ColumnsInserted(
const StartCol, ColsCount: LongInt); virtual;
procedure ColumnAdded; virtual;
procedure AllDataDeleted; virtual;
function GetColCount: LongInt; virtual;
function GetRowCount: LongInt; virtual;
function GetInfoCols: LongInt; virtual; abstract;
function GetInfoRows: LongInt; virtual; abstract;
function GetFixedCols: LongInt; virtual;
function GetFixedRows: LongInt; virtual;
function GetColNumFixed: Boolean; virtual;
function GetRowNumFixed: Boolean; virtual;
function GetColWidth(const Col: LongInt): LongInt;
procedure SaveColWidth(const Col, Width: LongInt);
function GetRowHeight(const Row: LongInt): LongInt;
procedure SaveRowHeight(const Row, Height: LongInt);
function AutoWidths: Boolean;
function AutoHeights: Boolean;
function GetSelection: TGridRect;
procedure SaveSelection(const Selection: TGridRect);
function GetCol: LongInt;
procedure SaveCol(const Col: LongInt);
function GetRow: LongInt;
procedure SaveRow(const Row: LongInt);
function GetLeftCol: LongInt;
procedure SaveLeftCol(const LeftCol: LongInt);
function GetTopRow: LongInt;
procedure SaveTopRow(const TopRow: LongInt);
property SavedCol: LongInt
read GetCol write SaveCol;
property SavedRow: LongInt
read GetRow write SaveRow;
property SavedLeftCol: LongInt
read GetLeftCol write SaveLeftCol;
property SavedTopRow: LongInt
read GetTopRow write SaveTopRow;
property SavedSelection: TGridRect
read GetSelection write SaveSelection;
property Caption: string
read FCaption write FCaption;
end;
ERowCompList = class(Exception);
EColCompList = class(Exception);
TRowCompList = class(TTableCompList)
protected
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
function CreateNewObject: TComponent; virtual; abstract;
public
function GetDataFromGrid(Grid: TStringGrid): Boolean; override;
procedure SetDataToGrid(Grid: TStringGrid); override;
function Add(Item: TComponent): Integer; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; Item: TComponent); override;
procedure BeforeStringToValue(const ACol, ARow: Integer;
const AString: string); override;
function MayIDoInsertRows(StartRow, RowsCount: LongInt): Boolean; override;
function MayIDoDeleteRows(StartRow, RowsCount: LongInt): Boolean; override;
function MayIDoAddRow: Boolean; override;
function MayIDoDeleteAllData: Boolean; override;
function MayIDoClearAllCells: Boolean; override;
function MayIDoClearSelectedArea: Boolean; override;
procedure RowsDeleted(
const StartRow, RowsCount: LongInt); override;
procedure RowsInserted(
const StartRow, RowsCount: LongInt); override;
procedure RowAdded; override;
procedure AllDataDeleted; override;
function IsDataSourceEmpty: Boolean; override;
function GetInfoRows: LongInt; override;
function GetColNumFixed: Boolean; override;
end;
TColCompList = class(TTableCompList)
protected
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
function CreateNewObject: TComponent; virtual; abstract;
public
function GetDataFromGrid(Grid: TStringGrid): Boolean; override;
procedure SetDataToGrid(Grid: TStringGrid); override;
function Add(Item: TComponent): Integer; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; Item: TComponent); override;
procedure BeforeStringToValue(const ACol, ARow: LongInt;
const AString: string); override;
function MayIDoInsertColumns(StartCol, ColsCount: LongInt): Boolean; override;
function MayIDoDeleteColumns(StartCol, ColsCount: LongInt): Boolean; override;
function MayIDoAddColumn: Boolean; override;
function MayIDoDeleteAllData: Boolean; override;
function MayIDoClearSelectedArea: Boolean; override;
function MayIDoClearAllCells: Boolean; override;
procedure ColumnsDeleted(
const StartCol, ColsCount: LongInt); override;
procedure ColumnsInserted(
const StartCol, ColsCount: LongInt); override;
procedure ColumnAdded; override;
procedure AllDataDeleted; override;
function IsDataSourceEmpty: Boolean; override;
function GetInfoCols: LongInt; override;
function GetRowNumFixed: Boolean; override;
end;
TIconicCompList = class(TTableCompList)
protected
FImageList: TImageList;
public
end;
implementation
constructor TTableCompList.Create;
begin
inherited Create(AOwner);
FSavedCol := GetFixedCols;
FSavedRow := GetFixedRows;
FSavedLeftCol := FSavedCol;
FSavedTopRow := FSavedRow;
with FSavedSelection do
begin
Left := FSavedCol;
Top := FSavedRow;
Right := FSavedCol;
Bottom := FSavedRow;
end;
end;
destructor TTableCompList.Destroy;
begin
Destroying := True;
Finalize(SavedColWidths);
Finalize(SavedrowHeights);
inherited Destroy;
end;
procedure TTableCompList.GridAssign(Grid: TStringGrid);
begin
with Grid do
begin
if Grid is TColorStringGrid then
with Grid as TColorStringGrid do
begin
RowCount := GetRowCount;
ColCount := GetColCount;
end
else
begin
RowCount := GetRowCount;
ColCount := GetColCount;
end;
FixedCols := GetFixedCols;
FixedRows := GetFixedRows;
LeftCol := GetLeftCol;
TopRow := GetTopRow;
Col := GetCol;
Row := GetRow;
Selection := GetSelection;
EditorMode := False;
Options := StaticOptions;
end;
SetCaption(Grid);
SetColOptions(Grid);
SetColFunc(Grid);
if Grid is TColorStringGrid then
with Grid as TColorStringGrid do EnumerateRows;
if Grid is TIDA_Grid then
with Grid as TIDA_Grid do Changeable := False;
if Grid is TServeredGrid then
with Grid as TServeredGrid do ShowTable;
SetDataToGrid(Grid);
SetColWidths(Grid);
SetRowHeights(Grid);
end;
procedure TTableCompList.SetColWidths(Grid: TStringGrid);
var i: LongInt;
begin
if (Grid is TIDA_Grid) and (not WidthsSaved) then
with Grid as TIDA_Grid do AutoColWidths
else
with Grid do
for i := 0 to ColCount - 1 do ColWidths[i] := GetColWidth(i);
end;
procedure TTableCompList.GetColWidths(Grid: TStringGrid);
var i: LongInt;
begin
with Grid do
for i := 0 to ColCount - 1 do SaveColWidth(i, ColWidths[i]);
end;
procedure TTableCompList.GridRelease(Grid: TStringGrid);
begin
GetRowHeights(Grid);
GetColWidths(Grid);
with Grid do
begin
SaveLeftCol(LeftCol);
SaveTopRow(TopRow);
SaveCol(Col);
SaveRow(Row);
SaveSelection(Selection);
end;
SettingsSaved := True;
end;
class function TTableCompList.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := TCLClassInheritID;
Result.PropVersionNum := TCLCurVerNum;
end;
class procedure TTableCompList.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
begin
with AnObject as Self, Reader do FCaption := ReadString;
end;
class procedure TTableCompList.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
begin
with AnObject as Self, Writer do WriteString(FCaption);
end;
{ TRowCompList }
procedure TRowCompList.AllDataDeleted;
begin
if not (Count = 0) then Clear;
end;
function TRowCompList.GetColNumFixed: Boolean;
begin
Result := True;
end;
function TRowCompList.GetDataFromGrid(Grid: TStringGrid): Boolean;
var i: LongInt;
begin
Result := True;
with Grid do
for i := FixedRows to RowCount - 1 do
if not GetRowContents(Grid, i) then Result := False;
end;
class function TRowCompList.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := RCLClassInheritID;
Result.PropVersionNum := RCLCurVerNum;
end;
function TRowCompList.GetInfoRows: LongInt;
begin
if Count <> 0 then Result := Count
else Result := 1;
end;
function TRowCompList.IsDataSourceEmpty: Boolean;
begin
Result := Count = 0;
end;
function TRowCompList.MayIDoAddRow: Boolean;
begin
Result := True;
end;
function TRowCompList.MayIDoClearAllCells: Boolean;
begin
Result := True;
end;
function TRowCompList.MayIDoClearSelectedArea: Boolean;
begin
Result := True;
end;
function TRowCompList.MayIDoDeleteAllData: Boolean;
begin
Result := True;
end;
function TRowCompList.MayIDoDeleteRows(StartRow,
RowsCount: Integer): Boolean;
begin
Result := True;
end;
function TRowCompList.MayIDoInsertRows(StartRow,
RowsCount: Integer): Boolean;
begin
Result := True;
end;
class procedure TRowCompList.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
begin
end;
procedure TRowCompList.RowAdded;
begin
if Count = 0 then Add(CreateNewObject);
Add(CreateNewObject);
end;
procedure TRowCompList.RowsDeleted(const StartRow, RowsCount: Integer);
var i: LongInt;
First, Last: LongInt;
begin
if not (Count = 0) then
begin
Last := StartRow - GetFixedRows + RowsCount - 1;
First := StartRow - GetFixedRows;
if (First < 0) or (Last > Count - 1) then
raise ERowCompList.Create('Invalid deleting parameters...');
i := 0;
while i < RowsCount do
begin
Delete(First);
Inc(i);
end;
end;
end;
procedure TRowCompList.RowsInserted(const StartRow, RowsCount: Integer);
var i: LongInt;
First: LongInt;
begin
First := StartRow - GetFixedRows;
if Count = 0 then Add(CreateNewObject);
if (First < 0) or (First > Count - 1) then
raise ERowCompList.Create('Invalid insertion parameters...');
for i := 1 to RowsCount do Insert(First, CreateNewObject);
end;
procedure TRowCompList.BeforeStringToValue(const ACol, ARow: Integer;
const AString: string);
begin
CheckColIndex(ACol);
CheckRowIndex(ARow);
if Count = 0 then Add(CreateNewObject);
end;
class procedure TRowCompList.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
begin
end;
function TRowCompList.Add(Item: TComponent): Integer;
var Flag: Boolean;
begin
Flag := Count = 0;
Result := inherited Add(Item);
if AreRowHeightsReady and not Flag then AddRowHeightItem;
end;
procedure TRowCompList.Delete(Index: Integer);
begin
if (not Destroying) and AreRowHeightsReady then
DeleteRowHeightItem(Index);
inherited;
if (not Destroying) and
(Count = 0) and AreRowHeightsReady then AddRowHeightItem;
end;
procedure TRowCompList.Insert(Index: Integer; Item: TComponent);
var Flag: Boolean;
begin
Flag := Count = 0;
inherited;
if AreRowHeightsReady and not Flag then InsertRowHeightItem(Index);
end;
procedure TRowCompList.SetDataToGrid(Grid: TStringGrid);
var i: LongInt;
begin
with Grid do
for i := FixedRows to RowCount - 1 do SetRowContents(Grid, i);
end;
{ TColCompList }
function TColCompList.Add(Item: TComponent): Integer;
var Flag: Boolean;
begin
Flag := Count = 0;
Result := inherited Add(Item);
if AreColWidthsReady and not Flag then AddColWidthItem;
end;
procedure TColCompList.AllDataDeleted;
begin
if not (Count = 0) then Clear;
end;
procedure TColCompList.ColumnAdded;
begin
if Count = 0 then Add(CreateNewObject);
Add(CreateNewObject);
end;
procedure TColCompList.ColumnsDeleted(const StartCol, ColsCount: Integer);
var i: LongInt;
First, Last: LongInt;
begin
if not (Count = 0) then
begin
Last := StartCol - GetFixedCols + ColsCount - 1;
First := StartCol - GetFixedCols;
if (First < 0) or (Last > Self.Count - 1) then
raise EColCompList.Create('Invalid deleting parameters...');
i := 0;
while i < ColsCount do
begin
Delete(First);
Inc(i);
end;
end;
end;
procedure TColCompList.ColumnsInserted(const StartCol, ColsCount: Integer);
var i: LongInt;
First: LongInt;
begin
First := StartCol - GetFixedCols;
if Count = 0 then Add(CreateNewObject);
if (First < 0) or (First > Self.Count - 1) then
raise EColCompList.Create('Invalid insertion parameters...');
for i := 1 to ColsCount do Insert(First, CreateNewObject);
end;
procedure TColCompList.Delete(Index: Integer);
begin
if (not Destroying) and AreColWidthsReady then
DeleteColWidthItem(Index);
inherited;
if (not Destroying) and
(Count = 0) and AreColWidthsReady then AddColWidthItem;
end;
function TColCompList.GetDataFromGrid(Grid: TStringGrid): Boolean;
var i: LongInt;
begin
Result := True;
with Grid do
for i := FixedCols to ColCount - 1 do
if not GetColContents(Grid, i) then Result := False;
end;
function TColCompList.GetInfoCols: LongInt;
begin
if Count <> 0 then Result := Count
else Result := 1;
end;
class function TColCompList.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := CCLClassInheritID;
Result.PropVersionNum := CCLCurVerNum;
end;
function TColCompList.GetRowNumFixed: Boolean;
begin
Result := True;
end;
procedure TColCompList.Insert(Index: Integer; Item: TComponent);
var Flag: Boolean;
begin
Flag := Count = 0;
inherited;
if AreColWidthsReady and not Flag then InsertColWidthItem(Index);
end;
function TColCompList.IsDataSourceEmpty: Boolean;
begin
Result := Count = 0;
end;
function TColCompList.MayIDoAddColumn: Boolean;
begin
Result := True;
end;
function TColCompList.MayIDoClearAllCells: Boolean;
begin
Result := True;
end;
function TColCompList.MayIDoClearSelectedArea: Boolean;
begin
Result := True;
end;
function TColCompList.MayIDoDeleteAllData: Boolean;
begin
Result := True;
end;
function TColCompList.MayIDoDeleteColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := True;
end;
function TColCompList.MayIDoInsertColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := True;
end;
class procedure TColCompList.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
begin
end;
procedure TColCompList.SetDataToGrid(Grid: TStringGrid);
var i: LongInt;
begin
with Grid do
for i := FixedCols to ColCount - 1 do SetColContents(Grid, i);
end;
procedure TColCompList.BeforeStringToValue(const ACol, ARow: Integer;
const AString: string);
begin
CheckColIndex(ACol);
CheckRowIndex(ARow);
if Count = 0 then Add(CreateNewObject);
end;
class procedure TColCompList.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
begin
end;
function TTableCompList.GetCellColor(const ACol, ARow: Integer;
var Color: TColor): Boolean;
begin
Result := False;
end;
function TTableCompList.IsCellDisabled(const ACol, ARow: Integer): Boolean;
begin
Result := False;
end;
procedure TTableCompList.AllDataDeleted;
begin
raise ETableCompList.Create('All data deleting is impossible...');
end;
procedure TTableCompList.ColumnAdded;
begin
raise ETableCompList.Create('Columns adding is impossible...');
end;
procedure TTableCompList.ColumnsDeleted(const StartCol,
ColsCount: Integer);
begin
raise ETableCompList.Create('Columns deleting is impossible...');
end;
procedure TTableCompList.ColumnsInserted(const StartCol,
ColsCount: Integer);
begin
raise ETableCompList.Create('Columns insertion is impossible...');
end;
procedure TTableCompList.RowAdded;
begin
raise ETableCompList.Create('Row adding is impossible...');
end;
procedure TTableCompList.RowsDeleted(const StartRow, RowsCount: Integer);
begin
raise ETableCompList.Create('Row deleting is impossible...');
end;
procedure TTableCompList.RowsInserted(const StartRow, RowsCount: Integer);
begin
raise ETableCompList.Create('Row insertion is impossible...');
end;
function TTableCompList.MayIDoAddColumn: Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoAddRow: Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoClearAllCells: Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoClearSelectedArea: Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoDeleteAllData: Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoDeleteColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoDeleteRows(StartRow,
RowsCount: Integer): Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoInsertColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := False;
end;
function TTableCompList.MayIDoInsertRows(StartRow,
RowsCount: Integer): Boolean;
begin
Result := False;
end;
function TTableCompList.GetColNumFixed: Boolean;
begin
Result := False;
end;
function TTableCompList.GetFixedCols: LongInt;
begin
Result := 1;
end;
function TTableCompList.GetFixedRows: LongInt;
begin
Result := 1;
end;
function TTableCompList.GetRowNumFixed: Boolean;
begin
Result := False;
end;
function TTableCompList.GetColCount: LongInt;
begin
Result := GetInfoCols + GetFixedCols;
end;
function TTableCompList.GetRowCount: LongInt;
begin
Result := GetInfoRows + GetFixedRows;
end;
function TTableCompList.GetCol: LongInt;
begin
Result := FSavedCol;
end;
function TTableCompList.GetColWidth(const Col: Integer): LongInt;
begin
CheckColIndex(Col);
InitColWidths;
Result := SavedColWidths[Col];
end;
function TTableCompList.GetLeftCol: LongInt;
begin
Result := FSavedLeftCol;
end;
function TTableCompList.GetRow: LongInt;
begin
Result := FSavedRow;
end;
function TTableCompList.GetRowHeight(const Row: Integer): LongInt;
begin
CheckRowIndex(Row);
InitRowHeights;
Result := SavedRowHeights[Row];
end;
function TTableCompList.GetSelection: TGridRect;
begin
Result := FSavedSelection;
end;
function TTableCompList.GetTopRow: LongInt;
begin
Result := FSavedTopRow;
end;
procedure TTableCompList.SaveCol(const Col: Integer);
begin
FSavedCol := Col;
end;
procedure TTableCompList.SaveColWidth(const Col, Width: Integer);
begin
CheckColIndex(Col);
InitColWidths;
SavedColWidths[Col] := Width;
WidthsSaved := True;
end;
procedure TTableCompList.SaveLeftCol(const LeftCol: Integer);
begin
FSavedLeftCol := LeftCol;
end;
procedure TTableCompList.SaveRow(const Row: Integer);
begin
FSavedRow := Row;
end;
procedure TTableCompList.SaveRowHeight(const Row, Height: Integer);
begin
CheckRowIndex(Row);
InitRowHeights;
SavedRowHeights[Row] := Height;
HeightsSaved := True;
end;
procedure TTableCompList.SaveSelection(const Selection: TGridRect);
begin
FSavedSelection := Selection;
end;
procedure TTableCompList.SaveTopRow(const TopRow: Integer);
begin
FSavedTopRow := TopRow;
end;
procedure TTableCompList.AddColWidthItem;
begin
CheckColIndex(Length(SavedColWidths)(* - 1 + 1*));
AddItemLongArr(SavedColWidths,
GetColWidthByDefault(Length(SavedColWidths)(* - 1 + 1*)));
end;
procedure TTableCompList.AddRowHeightItem;
begin
CheckRowIndex(Length(SavedRowHeights)(* - 1 + 1*));
AddItemLongArr(SavedRowHeights,
GetRowHeightByDefault(Length(SavedRowHeights)(* - 1 + 1*)));
end;
procedure TTableCompList.DeleteColWidthItem(const Index: Integer);
begin
CheckColIndex(Index);
DeleteItemLongArr(SavedColWidths, Index);
end;
procedure TTableCompList.DeleteRowHeightItem(const Index: Integer);
begin
CheckRowIndex(Index);
DeleteItemLongArr(SavedRowHeights, Index);
end;
procedure TTableCompList.InsertColWidthItem(const Index: Integer);
begin
CheckColIndex(Index);
InsertItemLongArr(SavedColWidths, Index, GetColWidthByDefault(Index));
end;
procedure TTableCompList.InsertRowHeightItem(const Index: Integer);
begin
CheckRowIndex(Index);
InsertItemLongArr(SavedRowHeights, Index, GetRowHeightByDefault(Index));
end;
procedure TTableCompList.CheckColIndex(const Index: Integer);
begin
if (Index < 0) or (Index >= GetColCount) then
raise ETableCompList.Create('Invalid column index...');
end;
procedure TTableCompList.CheckRowIndex(const Index: Integer);
begin
if (Index < 0) or (Index >= GetRowCount) then
raise ETableCompList.Create('Invalid row index...');
end;
procedure TTableCompList.DeleteAllColWidthItems;
begin
Finalize(SavedColWidths);
end;
procedure TTableCompList.DeleteAllRowHeightItems;
begin
Finalize(SavedRowHeights);
end;
function TTableCompList.GetColWidthByDefault(
const Index: Integer): LongInt;
begin
CheckColIndex(Index);
Result := 64;
end;
function TTableCompList.GetRowHeightByDefault(
const Index: Integer): LongInt;
begin
CheckRowIndex(Index);
Result := 20;
end;
procedure TTableCompList.GetRowHeights(Grid: TStringGrid);
var i: LongInt;
begin
with Grid do
for i := 0 to RowCount - 1 do SaveRowHeight(i, RowHeights[i]);
end;
procedure TTableCompList.SetRowHeights(Grid: TStringGrid);
var i: LongInt;
begin
if (Grid is TIDA_Grid) and (not HeightsSaved) then
with Grid as TIDA_Grid do AutoRowHeights
else
with Grid do
for i := 0 to RowCount - 1 do RowHeights[i] := GetRowHeight(i);
end;
procedure TTableCompList.InitColWidths;
var i: LongInt;
begin
if not AreColWidthsReady then
begin
DeleteAllColWidthItems;
for i := 1 to GetColCount do AddColWidthItem;
AreColWidthsReady := True;
end;
end;
procedure TTableCompList.InitRowHeights;
var i: LongInt;
begin
if not AreRowHeightsReady then
begin
DeleteAllRowHeightItems;
for i := 1 to GetRowCount do AddRowHeightItem;
AreRowHeightsReady := True;
end;
end;
function TTableCompList.AutoHeights: Boolean;
begin
Result := not HeightsSaved;
end;
function TTableCompList.AutoWidths: Boolean;
begin
Result := not WidthsSaved;
end;
procedure TTableCompList.SetColFunc(Grid: TStringGrid);
var i: LongInt;
begin
with Grid do
if FixedRows <> 0 then
for i := 0 to ColCount - 1 do Objects[i, 0] := nil;
end;
initialization
RegisterClass(TRowCompList);
RegisterClass(TColCompList);
RegisterClass(TTableCompList);
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.WebConst;
interface
resourcestring
sDuplicateActionName = 'Duplicate action name';
sOnlyOneDispatcher = 'Only one WebDispatcher per form/data module';
sHTTPItemName = 'Name';
sHTTPItemURI = 'PathInfo';
sHTTPItemEnabled = 'Enabled';
sHTTPItemDefault = 'Default';
sHTTPItemProducer = 'Producer';
sHTTPItemMethod = 'Method';
sResNotFound = 'Resource %s not found';
sTooManyColumns = 'Too many table columns';
sFieldNameColumn = 'Field Name';
sFieldTypeColumn = 'Field Type';
sInternalApplicationError = '<html><body><h1>Internal Application Error</h1>' + sLineBreak +
'<p>%0:s' + sLineBreak +
'<p><hr width="100%%"><i>%1:s</i></body></html>';
sWebFileExtensionItemExtensions = 'Extensions';
sWebFileExtensionItemMimeType = 'Mime Type';
sDuplicateMimeTypes = 'Duplicate mime types for extension: %s';
sWebFileDirectoryItemMask = 'Directory Mask';
sWebFileDirectoryItemAction = 'Action';
sWebFileExtensionsItemDisplayName = 'Mime type: ''%0:s'', Extensions: ''%1:s''';
sWebDirectoryInclude = 'Include';
sWebDirectoryExclude = 'Exclude';
sWebDirectoryItemDisplayName = 'Action: %0:s, Mask: ''%1:s''';
implementation
end.
|
unit URegraCRUDPaciente;
interface
uses
URegraCRUD
, URepositorioDB
, URepositorioPaciente
, UEntidade
, UPaciente
;
type
TRegraCRUDPaciente = class(TRegraCRUD)
protected
procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override;
public
constructor Create; override;
end;
implementation
{ TRegraCRUDCidade }
uses
SysUtils
, UUtilitarios
, UMensagens
, UConstantes
;
constructor TRegraCRUDPaciente.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioPaciente.Create);
end;
procedure TRegraCRUDPaciente.ValidaInsercao(const coENTIDADE: TENTIDADE);
begin
inherited;
if Trim(TPACIENTE(coENTIDADE).CODIGO_SUS) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_CODIGO_SUS_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).NOME) = EmptyStr Then
raise EValidacaoNegocio.Create (STR_NOME_PACIENTE_NAO_INFORMADO);
//if (TPACIENTE(coENTIDADE).NASCIMENTO) = EmptyDateTime Then
//raise EValidacaoNegocio.Create(STR_NASCIMENTO_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).SEXO) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_SEXO_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).PAI) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_PAI_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).MAE) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_MAE_NAO_INFORMADA);
if Trim(TPACIENTE(coENTIDADE).ENDERECO) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_ENDERECO_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).ESTADO_CIVIL) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_ESTADO_CIVIL_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).UF) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_UF_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).BAIRRO) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_BAIRRO_NAO_INFORMADO);
if Trim(TPACIENTE(coENTIDADE).CIDADE) = EmptyStr Then
raise EValidacaoNegocio.Create(STR_CIDADE_NAO_INFORMADA);
end;
end.
|
unit ClassMyListView;
interface
uses ComCtrls, Classes;
type TMyListView = class( TListView )
private
procedure FOnColumnClick( Sender: TObject; Column: TListColumn );
public
constructor Create( AOwner : TComponent ); override;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents( 'Standard' , [TMyListView] );
end;
procedure TMyListView.FOnColumnClick( Sender: TObject; Column: TListColumn );
begin
end;
constructor TMyListView.Create( AOwner : TComponent );
begin
OnColumnClick := FOnColumnClick;
end;
end.
|
(**************************************************)
(* *)
(* Advanced Encryption Standard (AES) *)
(* Interface Unit v1.3 *)
(* *)
(* *)
(* Copyright (c) 2002 Jorlen Young *)
(* *)
(* *)
(* *)
(*说明: *)
(* *)
(* 基于 ElASE.pas 单元封装 *)
(* *)
(* 这是一个 AES 加密算法的标准接口。 *)
(* *)
(* *)
(* 作者:杨泽晖 2004.12.04 *)
(* *)
(* 支持 128 / 192 / 256 位的密匙 *)
(* 默认情况下按照 128 位密匙操作 *)
(* *)
(**************************************************)
{$H+}
unit AES;
// 2012-03-20 add xe 开启标识 DELPHIXE 定义
//支持 delphi 6 - xe2
{.$DEFINE DELPHIXE}
interface
uses
SysUtils, Classes, Math, ElAES, EncdDecd;
type
TKeyBit = (kb128, kb192, kb256);
{
TStringStream = class(TStream)
private
FDataString: string;
FPosition: Integer;
protected
procedure SetSize(NewSize: Longint); override;
public
constructor Create(const AString: string);
function Read(var Buffer; Count: Longint): Longint; override;
function ReadString(Count: Longint): string;
function Seek(Offset: Longint; Origin: Word): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
procedure WriteString(const AString: string);
property DataString: string read FDataString;
end;
}
function StrToHex(Value: AnsiString): AnsiString;
function HexToStr(Value: AnsiString): AnsiString;
function EncryptString(Value: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128): AnsiString;
function DecryptString(Value: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128): AnsiString;
function EncryptStream(Stream: TStream; Key: AnsiString;
KeyBit: TKeyBit = kb128): TStream;
function DecryptStream(Stream: TStream; Key: AnsiString;
KeyBit: TKeyBit = kb128): TStream;
procedure EncryptFile(SourceFile, DestFile: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128);
procedure DecryptFile(SourceFile, DestFile: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128);
implementation
{
constructor TStringStream.Create(const AString: string);
begin
inherited Create;
FDataString := AString;
end;
function TStringStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := Length(FDataString) - FPosition;
if Result > Count then Result := Count;
Move(PChar(@FDataString[FPosition + SizeOf(Char)])^, Buffer, Result * SizeOf(Char));
Inc(FPosition, Result);
end;
function TStringStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := Count;
SetLength(FDataString, (FPosition + Result));
Move(Buffer, PChar(@FDataString[FPosition + SizeOf(Char)])^, Result * SizeOf(Char));
Inc(FPosition, Result);
end;
function TStringStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset;
soFromCurrent: FPosition := FPosition + Offset;
soFromEnd: FPosition := Length(FDataString) - Offset;
end;
if FPosition > Length(FDataString) then
FPosition := Length(FDataString)
else if FPosition < 0 then FPosition := 0;
Result := FPosition;
end;
function TStringStream.ReadString(Count: Longint): string;
var
Len: Integer;
begin
Len := Length(FDataString) - FPosition;
if Len > Count then Len := Count;
SetString(Result, PChar(@FDataString[FPosition + SizeOf(Char)]), Len);
Inc(FPosition, Len);
end;
procedure TStringStream.WriteString(const AString: string);
begin
Write(PChar(AString)^, Length(AString));
end;
procedure TStringStream.SetSize(NewSize: Longint);
begin
SetLength(FDataString, NewSize);
if FPosition > NewSize then FPosition := NewSize;
end;
}
function StrToHex(Value: AnsiString): AnsiString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(Value) do
Result := Result + IntToHex(ord(Value[I]), 2);
end;
function HexToStr(Value: AnsiString): AnsiString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(Value) do
begin
if ((I mod 2) = 1) then
begin
Result := Result + ansichar(StrToInt('0x' + Copy(Value, I, 2)));
end;
end;
end;
{ -- 字符串加密函数 默认按照 128 位密匙加密 -- }
function EncryptString(Value: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128): AnsiString;
var
SS, DS: TStringStream;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
//I: Integer;
s: AnsiString;
begin
Result := '';
SS := TStringStream.Create(Value); // ,TEncoding.ASCII);
DS := TStringStream.Create(''); // ,TEncoding.ASCII);
try
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
EncryptAESStreamECB(SS, 0, AESKey128, DS);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
EncryptAESStreamECB(SS, 0, AESKey192, DS);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
EncryptAESStreamECB(SS, 0, AESKey256, DS);
end;
s := '';
{$IFDEF DELPHIXE}
if High(DS.Bytes) > 0 then
begin
for I := 0 to High(DS.Bytes) do
begin
s := s + IntToHex(DS.Bytes[I], 2);
end;
end;
{$ELSE}
s := StrToHex(DS.DataString);
{$ENDIF}
Result := (s);
finally
SS.Free;
DS.Free;
end;
end;
{ -- 字符串解密函数 默认按照 128 位密匙解密 -- }
function DecryptString(Value: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128): AnsiString;
var
SS, DS: TStringStream;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
Result := '';
SS := TStringStream.Create(HexToStr(Value));
DS := TStringStream.Create('');
try
// SS.ReadBuffer(Size, SizeOf(Size));
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey128, DS);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey192, DS);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey256, DS);
end;
Result := DS.DataString;
finally
SS.Free;
DS.Free;
end;
end;
{ -- 流加密函数 默认按照 128 位密匙解密 -- }
function EncryptStream(Stream: TStream; Key: AnsiString;
KeyBit: TKeyBit = kb128): TStream;
var
Count: Int64;
OutStrm: TStream;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
OutStrm := TStream.Create;
Stream.Position := 0;
Count := Stream.Size;
OutStrm.Write(Count, SizeOf(Count));
try
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey128, OutStrm);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey192, OutStrm);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey256, OutStrm);
end;
Result := OutStrm;
finally
OutStrm.Free;
end;
end;
{ -- 流解密函数 默认按照 128 位密匙解密 -- }
function DecryptStream(Stream: TStream; Key: AnsiString;
KeyBit: TKeyBit = kb128): TStream;
var
Count, OutPos: Int64;
OutStrm: TStream;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
OutStrm := TStream.Create;
Stream.Position := 0;
OutPos := OutStrm.Position;
Stream.ReadBuffer(Count, SizeOf(Count));
try
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey128,
OutStrm);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey192,
OutStrm);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey256,
OutStrm);
end;
OutStrm.Size := OutPos + Count;
OutStrm.Position := OutPos;
Result := OutStrm;
finally
OutStrm.Free;
end;
end;
{ -- 文件加密函数 默认按照 128 位密匙解密 -- }
procedure EncryptFile(SourceFile, DestFile: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128);
var
SFS, DFS: TFileStream;
Size: Int64;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
SFS := TFileStream.Create(SourceFile, fmOpenRead);
try
DFS := TFileStream.Create(DestFile, fmCreate);
try
Size := SFS.Size;
DFS.WriteBuffer(Size, SizeOf(Size));
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
EncryptAESStreamECB(SFS, 0, AESKey128, DFS);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
EncryptAESStreamECB(SFS, 0, AESKey192, DFS);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
EncryptAESStreamECB(SFS, 0, AESKey256, DFS);
end;
finally
DFS.Free;
end;
finally
SFS.Free;
end;
end;
{ -- 文件解密函数 默认按照 128 位密匙解密 -- }
procedure DecryptFile(SourceFile, DestFile: AnsiString; Key: AnsiString;
KeyBit: TKeyBit = kb128);
var
SFS, DFS: TFileStream;
Size: Int64;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
SFS := TFileStream.Create(SourceFile, fmOpenRead);
try
SFS.ReadBuffer(Size, SizeOf(Size));
DFS := TFileStream.Create(DestFile, fmCreate);
try
{ -- 128 位密匙最大长度为 16 个字符 -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
DecryptAESStreamECB(SFS, SFS.Size - SFS.Position, AESKey128, DFS);
end;
{ -- 192 位密匙最大长度为 24 个字符 -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0);
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
DecryptAESStreamECB(SFS, SFS.Size - SFS.Position, AESKey192, DFS);
end;
{ -- 256 位密匙最大长度为 32 个字符 -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0);
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
DecryptAESStreamECB(SFS, SFS.Size - SFS.Position, AESKey256, DFS);
end;
DFS.Size := Size;
finally
DFS.Free;
end;
finally
SFS.Free;
end;
end;
end.
|
unit DataMod;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DB, DBTables;
type
TCacheData = class(TDataModule)
CacheDS: TDataSource;
CacheDB: TDatabase;
CacheQuery: TQuery;
UpdateSQL: TUpdateSQL;
CacheQueryUpdateStatus: TStringField;
CacheQueryPROJ_ID: TStringField;
CacheQueryPROJ_NAME: TStringField;
procedure UpdateErrorHandler(DataSet: TDataSet; E: EDatabaseError;
UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
procedure CacheQueryCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CacheData: TCacheData;
implementation
uses CachedUp, ErrForm;
{$R *.DFM}
{ This event is triggered when an error occurs during the update process
(such as a key violation). Here we use another form to show the user
the error and allow them to decide what to do about it. See ErrForm.pas
for more information }
procedure TCacheData.UpdateErrorHandler(DataSet: TDataSet;
E: EDatabaseError; UpdateKind: TUpdateKind;
var UpdateAction: TUpdateAction);
begin
UpdateAction := UpdateErrorForm.HandleError(DataSet, E, UpdateKind);
end;
{ This event displays the current update status in a calculated field }
procedure TCacheData.CacheQueryCalcFields(DataSet: TDataSet);
const
UpdateStatusStr: array[TUpdateStatus] of string = ('Unmodified', 'Modified',
'Inserted', 'Deleted');
begin
if CacheQuery.CachedUpdates then
CacheQueryUpdateStatus.Value := UpdateStatusStr[CacheQuery.UpdateStatus];
end;
end.
|
unit amqp.connection;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$INCLUDE config.inc}
interface
uses {$IFDEF FPC}SysUtils,{$Else} System.SysUtils, {$ENDIF}amqp.socket, AMQP.Types,
amqp.framing, amqp.time, amqp.table,
amqp.privt, amqp.mem, amqp.tcp_socket;
function amqp_new_connection:Pamqp_connection_state;
procedure amqp_set_sockfd( state : Pamqp_connection_state; sockfd : integer);
function amqp_tune_connection( state : Pamqp_connection_state; channel_max, frame_max, heartbeat : integer):integer;
function amqp_destroy_connection( state : Pamqp_connection_state):integer;
procedure return_to_idle( state : Pamqp_connection_state);
function consume_data(state : Pamqp_connection_state; out received_data : Tamqp_bytes):size_t;
function amqp_release_buffers_ok( state : Pamqp_connection_state):amqp_boolean_t;
procedure amqp_release_buffers( state : Pamqp_connection_state);
procedure amqp_maybe_release_buffers( state : Pamqp_connection_state);
procedure amqp_maybe_release_buffers_on_channel( state : Pamqp_connection_state; channel : amqp_channel_t);
function amqp_frame_to_bytes(const Aframe : Tamqp_frame; Abuffer : Tamqp_bytes; out Aencoded : Tamqp_bytes):integer;
function amqp_send_frame(Astate : Pamqp_connection_state;const Aframe : Pamqp_frame):integer;
function amqp_send_frame_inner(Astate : Pamqp_connection_state;const Aframe : Tamqp_frame; Aflags : integer; Adeadline : Tamqp_time):integer;
function amqp_handle_input(Astate : Pamqp_connection_state;
var Areceived_data : Tamqp_bytes;
out Adecoded_frame : Tamqp_frame):integer;
//function amqp_heartbeat_send(state: Pamqp_connection_state): int;
function amqp_heartbeat_recv(state: Pamqp_connection_state): int;
const
AMQP_INITIAL_FRAME_POOL_PAGE_SIZE = 65536;
AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE = 131072;
AMQP_DEFAULT_LOGIN_TIMEOUT_SEC = 12;
implementation
function amqp_send_frame_inner(Astate : Pamqp_connection_state;const Aframe : Tamqp_frame;
Aflags : integer; Adeadline : Tamqp_time):integer;
var
Lres, count, Level : integer;
Lsent : ssize_t;
Lencoded : Tamqp_bytes;
Lnext_timeout : Tamqp_time;
label start_send ;
begin
{ TODO: if the AMQP_SF_MORE socket optimization can be shown to work
* correctly, then this could be un-done so that body-frames are sent as 3
* send calls, getting rid of the copy of the body content, some testing
* would need to be done to see if this would actually a win for performance.
* }
Inc(gLevel);
Level := gLevel;
count := 0;
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.connection:: amqp_frame_to_bytes==>');
{$ENDIF}
Lres := amqp_frame_to_bytes(Aframe, Astate.outbound_buffer, Lencoded);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.connection::amqp_frame_to_bytes, res=' + IntToStr(Lres));
{$ENDIF}
if Int(AMQP_STATUS_OK) <> Lres then
Exit(Lres);
start_send:
Inc(count);
Lnext_timeout := amqp_time_first(Adeadline, Astate.next_recv_heartbeat);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.socket:: amqp_try_send==>, start_send:' + IntToStr(count));
{$ENDIF}
Lsent := amqp_try_send(Astate, Lencoded.bytes, Lencoded.len, Lnext_timeout, Aflags);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.socket:: amqp_try_send, res=' + IntToStr(Lsent));
{$ENDIF}
if 0 > Lsent then
Exit(int(Lsent));
{ A partial send has occurred, because of a heartbeat timeout (so try recv
* something) or common timeout (so return AMQP_STATUS_TIMEOUT) }
if ssize_t(Lencoded.len) <> Lsent then
begin
if Lnext_timeout = Adeadline then
{ timeout of method was received, so return from method}
Exit(Integer(AMQP_STATUS_TIMEOUT));
Lres := amqp_try_recv(Astate);
if Int(AMQP_STATUS_TIMEOUT) = Lres then
Exit(Integer(AMQP_STATUS_HEARTBEAT_TIMEOUT))
else
if (Int(AMQP_STATUS_OK) <> Lres) then
Exit(Lres);
Inc(Lencoded.bytes ,Lsent);
Lencoded.len := Lencoded.len - Lsent;
goto start_send;
end;
Lres := amqp_time_s_from_now(Astate.next_send_heartbeat,
Astate.heartbeat);
Result := Lres;
end;
function amqp_heartbeat_recv( state: Pamqp_connection_state): int;
begin
Result := 2 * state.heartbeat;
end;
function amqp_handle_input(Astate : Pamqp_connection_state;
var Areceived_data : Tamqp_bytes;
out Adecoded_frame : Tamqp_frame):integer;
var
bytes_consumed : size_t;
raw_frame : PAMQPChar;
channel : amqp_channel_t;
channel_pool : Pamqp_pool;
frame_size : uint32;
encoded : Tamqp_bytes;
res,Level : integer;
begin
{ Returning frame_type of zero indicates either insufficient input,
or a complete, ignored frame was read. }
Inc(gLevel);
Level := gLevel;
Adecoded_frame.frame_type := 0;
if Areceived_data.len = 0 then
Exit(Int(AMQP_STATUS_OK));
if Astate.state = CONNECTION_STATE_IDLE then
Astate.state := CONNECTION_STATE_HEADER;
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.connection:: consume_data==>');
{$ENDIF}
bytes_consumed := consume_data(Astate, Areceived_data);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.connection:: consume_data, bytes_consumed=' + IntToStr(bytes_consumed));
{$ENDIF}
{ do we have target_size data yet? if not, return with the
expectation that more will arrive }
if Astate.inbound_offset < Astate.target_size then
Exit(int(bytes_consumed));
raw_frame := (Astate.inbound_buffer.bytes);
//var p := PAnsiChar( state.inbound_buffer.bytes);
case Astate.state of
CONNECTION_STATE_INITIAL,
CONNECTION_STATE_HEADER,
CONNECTION_STATE_BODY:
begin
{ check for a protocol header from the server }
if CompareMem(raw_frame, PAnsiChar('AMQP'), 4) then
//if PAnsiChar(raw_frame) = 'AMQP' then
begin
Adecoded_frame.frame_type := Ord(AMQP_PSEUDOFRAME_PROTOCOL_HEADER);
Adecoded_frame.channel := 0;
Adecoded_frame.payload.protocol_header.transport_high := amqp_d8(amqp_offset(raw_frame, 4));
Adecoded_frame.payload.protocol_header.transport_low := amqp_d8(amqp_offset(raw_frame, 5));
Adecoded_frame.payload.protocol_header.protocol_version_major := amqp_d8(amqp_offset(raw_frame, 6));
Adecoded_frame.payload.protocol_header.protocol_version_minor := amqp_d8(amqp_offset(raw_frame, 7));
return_to_idle(Astate);
Exit(int(bytes_consumed));
end;
//CONNECTION_STATE_HEADER:
channel := amqp_d16(amqp_offset(raw_frame, 1));
{ frame length is 3 bytes in }
frame_size := amqp_d32(amqp_offset(raw_frame, 3));
{ To prevent the target_size calculation below from overflowing, check
* that the stated frame_size is smaller than a signed 32-bit. Given
* the library only allows configuring frame_max as an int32_t, and
* frame_size is uint32_t, the math below is safe from overflow. }
if frame_size >= INT32_MAX then
Exit(Int(AMQP_STATUS_BAD_AMQP_DATA));
Astate.target_size := frame_size + HEADER_SIZE + FOOTER_SIZE;
if size_t(Astate.frame_max) < Astate.target_size then
Exit(Int(AMQP_STATUS_BAD_AMQP_DATA));
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.mem:: amqp_get_or_create_channel_pool==>');
{$ENDIF}
channel_pool := Astate.get_or_create_channel_pool(channel);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.mem:: amqp_get_or_create_channel_pool.');
{$ENDIF}
if nil = channel_pool then
Exit(Int(AMQP_STATUS_NO_MEMORY));
channel_pool.alloc_bytes( Astate.target_size, Astate.inbound_buffer);
if nil = Astate.inbound_buffer.bytes then
Exit(Int(AMQP_STATUS_NO_MEMORY));
memcpy(Astate.inbound_buffer.bytes, @Astate.header_buffer, HEADER_SIZE);
raw_frame := Astate.inbound_buffer.bytes;
Astate.state := CONNECTION_STATE_BODY;
bytes_consumed := bytes_consumed + consume_data(Astate, Areceived_data);
{ do we have target_size data yet? if not, return with the
expectation that more will arrive }
if Astate.inbound_offset < Astate.target_size then
Exit(int(bytes_consumed));
{ fall through to process body }
//CONNECTION_STATE_BODY:
{ Check frame end marker (footer) }
if amqp_d8(amqp_offset(raw_frame, Astate.target_size - 1 )) <> AMQP_FRAME_END then
Exit(Int(AMQP_STATUS_BAD_AMQP_DATA));
Adecoded_frame.frame_type := amqp_d8(amqp_offset(raw_frame, 0));
Adecoded_frame.channel := amqp_d16(amqp_offset(raw_frame, 1));
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.mem:: amqp_get_or_create_channel_pool==>');
{$ENDIF}
channel_pool := Astate.get_or_create_channel_pool(Adecoded_frame.channel);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.mem:: amqp_get_or_create_channel_pool.');
{$ENDIF}
if nil = channel_pool then
Exit(Int(AMQP_STATUS_NO_MEMORY));
case Adecoded_frame.frame_type of
AMQP_FRAME_METHOD:
begin
Adecoded_frame.payload.method.id := amqp_d32(amqp_offset(raw_frame, HEADER_SIZE));
encoded.bytes := amqp_offset(raw_frame, HEADER_SIZE + 4);
encoded.len := Astate.target_size - HEADER_SIZE - 4 - FOOTER_SIZE;
{$IFDEF _DEBUG_}
DebugOut(Level, 'AMQP_FRAME_METHOD step into amqp.framming:: amqp_decode_method==>');
{$ENDIF}
res := amqp_decode_method(Adecoded_frame.payload.method.id,
channel_pool, encoded,
Adecoded_frame.payload.method.decoded);
{$IFDEF _DEBUG_}
DebugOut(Level, 'AMQP_FRAME_METHOD step over amqp.framming:: amqp_decode_method, res=' + IntToStr(res));
{$ENDIF}
if res < 0 then
Exit(res);
end;
AMQP_FRAME_HEADER:
begin
Adecoded_frame.payload.properties.class_id := amqp_d16(amqp_offset(raw_frame, HEADER_SIZE));
{ unused 2-byte weight field goes here }
Adecoded_frame.payload.properties.body_size := amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4));
encoded.bytes := amqp_offset(raw_frame, HEADER_SIZE + 12);
encoded.len := Astate.target_size - HEADER_SIZE - 12 - FOOTER_SIZE;
Adecoded_frame.payload.properties.raw := encoded;
{$IFDEF _DEBUG_}
DebugOut(Level, 'AMQP_FRAME_HEADER step into amqp.framming:: amqp_decode_properties==>');
{$ENDIF}
res := amqp_decode_properties(Adecoded_frame.payload.properties.class_id,
channel_pool, encoded,
@Adecoded_frame.payload.properties.decoded);
{$IFDEF _DEBUG_}
DebugOut(Level, 'AMQP_FRAME_HEADER step over amqp.framming:: amqp_decode_properties, res=' + IntToStr(res));
{$ENDIF}
if res < 0 then
Exit(res);
end;
AMQP_FRAME_BODY:
begin
Adecoded_frame.payload.body_fragment.len := Astate.target_size - HEADER_SIZE - FOOTER_SIZE;
Adecoded_frame.payload.body_fragment.bytes := amqp_offset(raw_frame, HEADER_SIZE);
end;
AMQP_FRAME_HEARTBEAT:
begin
//
end;
else
begin
{ Ignore the frame }
Adecoded_frame.frame_type := 0;
end;
end;
return_to_idle(Astate);
Exit(int(bytes_consumed)) ;
end;
else
raise Exception.Create('Internal error: invalid amqp_connection_state_t.state '
+ IntToStr(Int(Astate.state)));
end;
end;
function amqp_new_connection:Pamqp_connection_state;
var
res : integer;
state : Pamqp_connection_state;
label out_nomem;
begin
state := Pamqp_connection_state(AllocMem(1* sizeof(Tamqp_connection_state)));
if state = nil then
Exit(nil);
res := amqp_tune_connection(state, 0, AMQP_INITIAL_FRAME_POOL_PAGE_SIZE, 0);
if 0 <> res then
goto out_nomem;
state.inbound_buffer.bytes := @state.header_buffer;
state.inbound_buffer.len := sizeof(state.header_buffer);
state.state := CONNECTION_STATE_INITIAL;
{ the server protocol version response is 8 bytes, which conveniently
is also the minimum frame size }
state.target_size := 8;
state.sock_inbound_buffer.len := AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE;
state.sock_inbound_buffer.bytes := malloc(AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE);
if state.sock_inbound_buffer.bytes = nil then
goto out_nomem;
//init_amqp_pool(@state.properties_pool, 512);
state.properties_pool.Create(512);
{ Use address of the internal_handshake_timeout object by default. }
state.internal_handshake_timeout.tv_sec := AMQP_DEFAULT_LOGIN_TIMEOUT_SEC;
state.internal_handshake_timeout.tv_usec := 0;
state.handshake_timeout := @state.internal_handshake_timeout;
Exit(state);
out_nomem:
free(state.sock_inbound_buffer.bytes);
free(state);
Result := nil;
end;
procedure amqp_set_sockfd( state : Pamqp_connection_state; sockfd : integer);
var
socket : Pamqp_socket;
begin
socket := amqp_tcp_socket_new(state);
if not Assigned(socket) then
//amqp_abort('%s', strerror(errno));
raise Exception.Create('CRAETE new socket error!!!');
amqp_tcp_socket_set_sockfd(socket, sockfd);
end;
procedure ENFORCE_STATE( statevec : Pamqp_connection_state; statenum : Tamqp_connection_state_enum);
var
_check_state : Pamqp_connection_state;
_wanted_state : Tamqp_connection_state_enum;
s: string;
begin
_check_state := (statevec);
_wanted_state := (statenum);
if _check_state.state <> _wanted_state then
begin
s := Format('Programming error: invalid AMQP connection state: expected %d, '+
'got %d',
[Int(_wanted_state), Int(_check_state.state)]);
raise Exception.Create(s);
end;
end;
function amqp_tune_connection( state : Pamqp_connection_state; channel_max, frame_max, heartbeat : integer):integer;
var
newbuf : Pointer;
res : integer;
begin
ENFORCE_STATE(state, CONNECTION_STATE_IDLE);
state.channel_max := channel_max;
state.frame_max := frame_max;
state.heart_beat := heartbeat;
if 0 > state.heart_beat then
state.heart_beat := 0;
res := amqp_time_s_from_now(state.next_send_heartbeat, state.heartbeat);
if Int(AMQP_STATUS_OK) <> res then
Exit(res);
res := amqp_time_s_from_now(state.next_recv_heartbeat,
amqp_heartbeat_recv(state));
if Int(AMQP_STATUS_OK) <> res then
Exit(res);
state.outbound_buffer.len := frame_max;
//newbuf := realloc(state.outbound_buffer.bytes, frame_max);
reallocMem(state.outbound_buffer.bytes, frame_max);
newbuf := state.outbound_buffer.bytes;
if newbuf = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
//state.outbound_buffer.bytes := newbuf;
Result := Int(AMQP_STATUS_OK);
end;
function amqp_destroy_connection( state : Pamqp_connection_state):integer;
var
status,
i : integer;
entry,
todelete : Pamqp_pool_table_entry;
begin
status := Int(AMQP_STATUS_OK);
if Assigned(state) then
begin //++i
for i := 0 to POOL_TABLE_SIZE -1 do
begin
//Inc(i);
entry := state.pool_table[i];
while nil <> entry do
begin
todelete := entry;
entry.pool.empty;
entry := entry.next;
free(todelete);
end;
end;
free(state.outbound_buffer.bytes);
free(state.sock_inbound_buffer.bytes);
state.Fsocket.delete;
state.properties_pool.empty;
free(state);
end;
Result := status;
end;
procedure return_to_idle( state : Pamqp_connection_state);
begin
state.inbound_buffer.len := sizeof(state.header_buffer);
state.inbound_buffer.bytes := @state.header_buffer;
state.inbound_offset := 0;
state.target_size := HEADER_SIZE;
state.state := CONNECTION_STATE_IDLE;
end;
function consume_data(state : Pamqp_connection_state; out received_data : Tamqp_bytes):size_t;
var
bytes_consumed : size_t;
begin
{ how much data is available and will fit? }
bytes_consumed := state.target_size - state.inbound_offset;
if received_data.len < bytes_consumed then
bytes_consumed := received_data.len;
//此句执行后导致state.Fsock不可访问
memcpy(amqp_offset(state.inbound_buffer.bytes, state.inbound_offset), received_data.bytes, bytes_consumed);
state.inbound_offset := state.inbound_offset + bytes_consumed;
//received_data.bytes :=
Inc(received_data.bytes, bytes_consumed);
received_data.len := received_data.len - bytes_consumed;
Result := bytes_consumed;
end;
function amqp_release_buffers_ok( state : Pamqp_connection_state):amqp_boolean_t;
begin
if (state.state = CONNECTION_STATE_IDLE) then
Result := 1
else
Result := 0;
end;
procedure amqp_release_buffers( state : Pamqp_connection_state);
var
i : integer;
Lentry : Pamqp_pool_table_entry;
begin
ENFORCE_STATE(state, CONNECTION_STATE_IDLE);
for i := 0 to POOL_TABLE_SIZE-1 do
begin
Lentry := state.pool_table[i];
While nil <> Lentry do
begin
amqp_maybe_release_buffers_on_channel(state, Lentry.channel);
Lentry := Lentry.next;
end;
end;
end;
procedure amqp_maybe_release_buffers( state : Pamqp_connection_state);
begin
if amqp_release_buffers_ok(state) > 0 then
amqp_release_buffers(state);
end;
procedure amqp_maybe_release_buffers_on_channel( state : Pamqp_connection_state; channel : amqp_channel_t);
var
queued_link : Pamqp_link;
pool : Pamqp_pool;
frame : Pamqp_frame;
begin
if CONNECTION_STATE_IDLE <> state.state then
exit;
queued_link := state.first_queued_frame;
while nil <> queued_link do
begin
frame := queued_link.data;
if channel = frame.channel then
Exit;
queued_link := queued_link.next;
end;
pool := state.get_channel_pool(channel);
if pool <> nil then
pool.recycle;
end;
function amqp_frame_to_bytes(const Aframe : Tamqp_frame; Abuffer : Tamqp_bytes;
out Aencoded : Tamqp_bytes):integer;
var
Lout_frame : PAMQPChar;
Lout_frame_len : size_t;
Lres ,Level : integer;
Lproperties_encoded,
Lmethod_encoded : Tamqp_bytes;
Lbody : Tamqp_bytes;
begin
Inc(gLevel);
Level := gLevel;
Lout_frame := Abuffer.bytes;
amqp_e8(Aframe.frame_type, amqp_offset(Lout_frame, 0));
amqp_e16(Aframe.channel, amqp_offset(Lout_frame, 1));
case Aframe.frame_type of
AMQP_FRAME_BODY:
begin
{$IFDEF _DEBUG_}
DebugOut(Level, ' frame_type = AMQP_FRAME_BODY');
{$ENDIF}
Lbody := Aframe.payload.body_fragment;
memcpy(amqp_offset(Lout_frame, HEADER_SIZE), Lbody.bytes, Lbody.len);
Lout_frame_len := Lbody.len;
end;
AMQP_FRAME_METHOD:
begin
{$IFDEF _DEBUG_}
DebugOut(Level, ' frame_type = AMQP_FRAME_METHOD');
{$ENDIF}
amqp_e32(Aframe.payload.method.id, amqp_offset(Lout_frame, HEADER_SIZE));
Lmethod_encoded.bytes := amqp_offset(Lout_frame, HEADER_SIZE + 4);
Lmethod_encoded.len := Abuffer.len - HEADER_SIZE - 4 - FOOTER_SIZE;
Lres := amqp_encode_method(Aframe.payload.method.id,
Aframe.payload.method.decoded, Lmethod_encoded);
if Lres < 0 then
Exit(Lres);
Lout_frame_len := Lres + 4;
end;
AMQP_FRAME_HEADER:
begin
{$IFDEF _DEBUG_}
DebugOut(Level, ' frame_type = AMQP_FRAME_HEADER');
{$ENDIF}
amqp_e16(Aframe.payload.properties.class_id,
amqp_offset(Lout_frame, HEADER_SIZE));
amqp_e16(0, amqp_offset(Lout_frame, HEADER_SIZE + 2)); { 'weight' }
amqp_e64(Aframe.payload.properties.body_size,
amqp_offset(Lout_frame, HEADER_SIZE + 4));
Lproperties_encoded.bytes := amqp_offset(Lout_frame, HEADER_SIZE + 12);
Lproperties_encoded.len := Abuffer.len - HEADER_SIZE - 12 - FOOTER_SIZE;
Lres := amqp_encode_properties(Aframe.payload.properties.class_id,
Aframe.payload.properties.decoded,
Lproperties_encoded);
if Lres < 0 then
Exit(Lres);
Lout_frame_len := Lres + 12;
end;
AMQP_FRAME_HEARTBEAT:
begin
{$IFDEF _DEBUG_}
DebugOut(Level, ' frame_type = AMQP_FRAME_HEARTBEAT');
{$ENDIF}
Lout_frame_len := 0;
end;
else
Exit(Int(AMQP_STATUS_INVALID_PARAMETER));
end;
amqp_e32(uint32_t(Lout_frame_len), amqp_offset(Lout_frame, 3));
amqp_e8(AMQP_FRAME_END, amqp_offset(Lout_frame, HEADER_SIZE + Lout_frame_len));
Aencoded.bytes := Lout_frame;
Aencoded.len := Lout_frame_len + HEADER_SIZE + FOOTER_SIZE;
Result := Int(AMQP_STATUS_OK);
end;
function amqp_send_frame(Astate : Pamqp_connection_state;const Aframe : Pamqp_frame):integer;
begin
Result := amqp_send_frame_inner(Astate, Aframe^, Int(AMQP_SF_NONE), Tamqp_time.infinite);
end;
initialization
end.
|
unit mml_calc;
{-------------------------------------------------------------------------------
ソフト:テキスト音楽「サクラ」
作 者:クジラ飛行机 https://sakuramml.com
説 明:計算の下請けをするクラス。計算速度や、効率は悪いけれど、
分かりやすくするために、演算子ごとクラスに分けてみた
履 歴:
2002/06/03 15:13 雛型作成
-------------------------------------------------------------------------------}
interface
uses
SysUtils,
Classes,
mml_const,
mml_error,
mml_var;
type
//----------------------------------------------------------------------------
// 計算式に用いるクラス
TMCalc = class(TMVarCustom)
public
value: string;
function Calc(a, b: TMVarCustom): TMVarCustom; virtual;
function clone: TMVarCustom; override;
end;
TMPlus = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMMinus = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMMul = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMDiv = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMMod = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMEqual = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMNotEqual = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMGreat = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMSmall = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMGreatEqual = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMSmallEqual = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMAnd = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMOr = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
TMXor = class(TMCalc)
public
function Calc(a, b: TMVarCustom): TMVarCustom; override;
end;
//----------------------------------------------------------------------------
//適当なスタック
TMStack = class(TList)
public
procedure Clear; override;
function GetFirst: TMVarCustom;
function Pop: TMVarCustom;
procedure Push(v: TMVarCustom);
end;
//----------------------------------------------------------------------------
//計算式を行う
function CreateEnzansi(s: string): TMCalc;
function CalcTMStack(stack: TMStack): TMVarCustom;
implementation
{ TMStack }
procedure TMStack.Clear;
var
i: Integer;
m: TMVarCustom;
begin
for i:=0 to Count-1 do
begin
m := Items[i];
if m<>nil then m.Free ;
end;
inherited Clear;
end;
function TMStack.GetFirst: TMVarCustom;
begin
Result := nil;
if Count=0 then Exit;
Result := Items[0];
Self.Delete(0);
end;
function TMStack.Pop: TMVarCustom;
begin
Result := nil;
if Count=0 then Exit;
Result := Items[Count-1];
Self.Delete(Count-1);
end;
procedure TMStack.Push(v: TMVarCustom);
begin
Self.Add(v);
end;
{ TMPlus }
function TMPlus.Calc(a, b: TMVarCustom): TMVarCustom;
var
s1,s2: string;
begin
Result := nil;
if (a=nil)or(b=nil) then
begin
Exit;
end;
//どちらかが配列なら、配列を加算する
if (a.ClassType = TMArray) then
begin
Result := TMArray.Create ;
if b.ClassType = TMArray then
TMArray(Result).AddArray(b as TMArray)
else
TMArray(Result).Add(b);
Exit;
end;
if a.ClassType = TMInt then
begin
Result := TMInt.Create ;
TMInt(Result).value := a.IntValue + b.IntValue ;
end else if a.ClassType = TMStr then
begin
Result := a.clone ;
s1 := a.StrValue ;
s2 := b.StrValue ;
(Result as TMStr).value := s1 + s2;
end else
begin
Result := nil;
end;
end;
{ TMMinus }
function TMMinus.Calc(a, b: TMVarCustom): TMVarCustom;
begin
if (a=nil)or(b=nil) then
begin
if a=nil then
if b=nil then
Result := nil
else
begin
Result := b.clone;
if Result.ClassType = TMInt then
begin
TMInt(Result).value := - TMInt(Result).value;
end;
end
else
Result := a.clone ;
Exit;
end;
if a.ClassType = TMInt then
begin
Result := TMInt.Create ;
TMInt(Result).value := a.IntValue - b.IntValue ;
end else if a.ClassType = TMStr then
begin
raise EInvalidOperation.Create('文字列同士の引き算は出来ません。');
end else
begin
Result := nil;
end;
end;
{ TMMul }
function TMMul.Calc(a, b: TMVarCustom): TMVarCustom;
var
i: Integer;
begin
Result := nil;
if (a=nil)or(b=nil) then
begin
Exit;
end;
//どちらかが配列なら、配列を加算する
if (a.ClassType = TMArray) then
begin
Result := TMArray.Create ;
if b.ClassType = TMArray then
raise EInvalidOperation.Create('配列と配列を掛け合わせることは出来ません。');
for i:=0 to b.IntValue -1 do
begin
TMArray(Result).AddArray(a as TMArray);
end;
Exit;
end else
if (b.ClassType = TMArray) then
begin
if a.ClassType = TMArray then
raise EInvalidOperation.Create('配列と配列を掛け合わせることは出来ません。');
for i:=0 to a.IntValue -1 do
begin
TMArray(Result).AddArray(b as TMArray);
end;
Exit;
end;
if a.ClassType = TMInt then
begin
Result := TMInt.Create ;
TMInt(Result).value := Integer(a.IntValue * b.IntValue) ;
end else if a.ClassType = TMStr then
begin
Result := TMStr.Create ;
for i:=0 to b.IntValue -1 do
begin
TMStr(Result).value := TMStr(Result).value + a.StrValue;
end;
end else
begin
Result := nil;
end;
end;
{ TMDiv }
function TMDiv.Calc(a, b: TMVarCustom): TMVarCustom;
begin
if (a=nil)or(b=nil) then
begin
if a=nil then
if b=nil then
Result := nil
else
begin
Result := b.clone;
end
else
Result := a.clone ;
Exit;
end;
if a.ClassType = TMInt then
begin
Result := TMInt.Create ;
if b.IntValue<>0 then
TMInt(Result).value := a.IntValue div b.IntValue
else
TMInt(Result).value := 0;
end else if a.ClassType = TMStr then
begin
raise EInvalidOperation.Create('文字列同士の引き算は出来ません。');
end else
begin
Result := nil;
end;
end;
{ TMMod }
function TMMod.Calc(a, b: TMVarCustom): TMVarCustom;
begin
if (a=nil)or(b=nil) then
begin
Result := nil;
Exit;
end;
if a.ClassType = TMInt then
begin
Result := TMInt.Create ;
try
TMInt(Result).value := a.IntValue mod b.IntValue ;
except
TMInt(Result).value := 0;
end;
end else if a.ClassType = TMStr then
begin
raise EInvalidOperation.Create('文字列を使って余りを求めることはできません。');
end else
begin
Result := nil;
end;
end;
{ TMEqual }
function TMEqual.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_TRUE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
begin
if b.StrValue = '' then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end;
if b=nil then
begin
if a.StrValue = '' then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end;
Exit;
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue = b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue = b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
{ TMNotEqual }
function TMNotEqual.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_FALSE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
begin
if b.StrValue = '' then
TMInt(Result).value := BOOL_FALSE
else
TMInt(Result).value := BOOL_TRUE;
end;
if b=nil then
begin
if a.StrValue = '' then
TMInt(Result).value := BOOL_FALSE
else
TMInt(Result).value := BOOL_TRUE;
end;
Exit;
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue <> b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue <> b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
{ TMGreat }
function TMGreat.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_FALSE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue > b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue > b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
{ TMSmall }
function TMSmall.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_FALSE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
TMInt(Result).value := BOOL_FALSE
else
TMInt(Result).value := BOOL_TRUE
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue < b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue < b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
{ TMGreatEqual }
function TMGreatEqual.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_TRUE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue >= b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue >= b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
{ TMSmallEqual }
function TMSmallEqual.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_TRUE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
TMInt(Result).value := BOOL_FALSE
else
TMInt(Result).value := BOOL_TRUE
end;
if a.ClassType = TMArray then
begin
raise EInvalidOperation.Create('配列と配列を比較することはできません。');
end;
if a.ClassType = TMInt then
begin
if a.IntValue <= b.IntValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else if a.ClassType = TMStr then
begin
if a.StrValue <= b.StrValue then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_FALSE;
end else
begin
Result := nil;
end;
end;
function CreateEnzansi(s: string): TMCalc;
begin
if s='*' then Result := TMMul.Create
else if s='/' then Result := TMDiv.Create
else if s='+' then Result := TMPlus.Create
else if s='-' then Result := TMMinus.Create
else if s='=' then Result := TMEqual.Create
else if s='%' then Result := TMMod.Create
else if s='>' then Result := TMGreat.Create
else if s='<' then Result := TMSmall.Create
else if s='<>' then Result := TMNotEqual.Create
else if s='><' then Result := TMNotEqual.Create
else if s='!=' then Result := TMNotEqual.Create
else if s='>=' then Result := TMGreatEqual.Create
else if s='=>' then Result := TMGreatEqual.Create
else if s='<=' then Result := TMSmallEqual.Create
else if s='=<' then Result := TMSmallEqual.Create
else if s='==' then Result := TMEqual.Create
else if s='&' then Result := TMAnd.Create
else if s='&&' then Result := TMAnd.Create
else if s='|' then Result := TMOr.Create
else if s='||' then Result := TMOr.Create
else if s='^' then Result := TMXor.Create
else Result := nil;
end;
//スタック上に積まれた式を計算する
function CalcTMStack(stack: TMStack): TMVarCustom;
var
ch: TMVarCustom ;
i: Integer;
procedure Keisan(Idx: Integer);
var a, b: TMVarCustom;
begin
a := stack.Items[idx-1];
b := stack.Items[idx+1];
stack.Items[idx-1] := TMCalc(ch).Calc(a, b);
stack.Delete(idx);
stack.Delete(idx);
end;
procedure Kakezan;
begin
i := 0;
while i < stack.Count do
begin
ch := stack.Items[i];
if (ch.ClassType = TMMul)or(ch.ClassType = TMDiv)or(ch.ClassType = TMMod) then
Keisan(i) else Inc(i);
end;
end;
procedure Tasizan;
begin
i := 0;
while i < stack.Count do
begin
ch := stack.Items[i];
if (ch.ClassType = TMPlus)or(ch.ClassType = TMMinus) then
Keisan(i) else Inc(i);
end;
end;
procedure Hikaku;
begin
i := 0;
while i < stack.Count do
begin
ch := stack.Items[i];
if (ch.ClassType = TMEqual)or(ch.ClassType = TMNotEqual)or
(ch.ClassType = TMGreat)or(ch.ClassType = TMGreatEqual)or
(ch.ClassType = TMSmall)or(ch.ClassType = TMSmallEqual) then
Keisan(i) else Inc(i);
end;
end;
procedure AndOrXor;
begin
i := 0;
while i < stack.Count do
begin
ch := stack.Items[i];
if (ch.ClassType = TMAnd)or(ch.ClassType = TMOr)or(ch.ClassType = TMXor) then
Keisan(i) else Inc(i);
end;
end;
begin
Result := nil;
if stack=nil then Exit;
if stack.Count = 0 then Exit;
if stack.Count = 1 then begin
Result := TMVarCustom(stack.Items[0]).clone;
Exit;
end;
try
Kakezan;
Tasizan;
Hikaku;
AndOrXor;
Result := TMVarCustom(stack.Items[0]).clone;
except
raise EParserError.Create('計算式が不正です。');
end;
//_debug((Result as TMVarCustom).StrValue);
//raise EParserError.Create('式が不正です。演算子が足りません');
end;
{ TMCalc }
function TMCalc.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := nil;
end;
function TMCalc.clone: TMVarCustom;
begin
Result := TMCalc.Create ;
end;
{ TMAnd }
function TMAnd.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)and(b=nil) then
begin
TMInt(Result).value := BOOL_FALSE; Exit;
end else
if (a=nil)or(b=nil) then
begin
if a=nil then
TMInt(Result).value := BOOL_TRUE
else
TMInt(Result).value := BOOL_TRUE
end;
if a.ClassType <> TMInt then
begin
raise EInvalidOperation.Create('整数以外の論理演算はできません。');
end;
if a.ClassType = TMInt then
begin
TMInt(Result).value := a.IntValue and b.IntValue;
end;
end;
{ TMOr }
function TMOr.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)or(b=nil) then
begin
TMInt(Result).value := BOOL_False; Exit;
end;
if a.ClassType <> TMInt then
begin
raise EInvalidOperation.Create('整数以外の論理演算はできません。');
end;
if a.ClassType = TMInt then
begin
TMInt(Result).value := a.IntValue or b.IntValue;
end;
end;
{ TMXor }
function TMXor.Calc(a, b: TMVarCustom): TMVarCustom;
begin
Result := TMInt.Create ;
if (a=nil)or(b=nil) then
begin
TMInt(Result).value := BOOL_False; Exit;
end;
if a.ClassType <> TMInt then
begin
raise EInvalidOperation.Create('整数以外の論理演算はできません。');
end;
if a.ClassType = TMInt then
begin
TMInt(Result).value := a.IntValue xor b.IntValue;
end;
end;
end.
|
unit FrameLogin;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, ExtCtrls, Dialogs, DataBases;
type
{ TFrameLogin }
TFrameLogin = class(TFrame)
ButtonRegistration: TButton;
ButtonLogin: TButton;
EditEmail: TLabeledEdit;
EditPassword: TLabeledEdit;
LabelInfoText: TLabel;
LabelUps: TLabel;
Panel: TPanel;
procedure ButtonLoginClick(Sender: TObject);
procedure ButtonRegistrationClick(Sender: TObject);
procedure FrameResize(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
implementation
{$R *.lfm}
uses Main, FrameRegisterUser;
{ TFrameLogin }
procedure TFrameLogin.FrameResize(Sender: TObject);
begin
Panel.Left := TFrame(Sender).Width div 2 - Panel.Width div 2;
Panel.Top := TFrame(Sender).Height div 2 - Panel.Height div 4;
end;
procedure TFrameLogin.ButtonLoginClick(Sender: TObject);
// Вход в систему
begin
if DataBase.Login(EditEmail.Text, EditPassword.Text) then
MainForm.ShowFrameDialogs
else
MessageDlg('Ошибка', 'Ошибка входа в систему, вероятно не верно введены данные...',
mtWarning, [mbOK], 0);
end;
procedure TFrameLogin.ButtonRegistrationClick(Sender: TObject);
// Регистрация нового пользователя
begin
MainForm.ShowRegisterFrame;
MainForm.FrameRegister.NotFirstRegistration(FRAME_LOGIN);
end;
end.
|
PROGRAM stringcat;
VAR
string1, string2 : string
FUNCTION inquote(instring : string) : string;
BEGIN
inquote := '"' + instring + '"'
END;
BEGIN
WRITELN(string1);
string1 := 'Now ';
WRITELN(inquote(string1));
string2 := 'is the time ';
WRITELN(inquote(string2));
string1 := string1 + string2 + 'for all good men ';
WRITELN(inquote(string1));
string2 := 'to come ' + 'to ';
WRITELN(inquote(string2));
string1 := string1 + string2;
WRITELN(inquote(string1));
string2 := 'of their party';
WRITELN(inquote(string2));
string2 := 'the aid ' + string2;
WRITELN(inquote(string2));
string1 := string1 + string2 + '.';
WRITELN(inquote(string1));
END.
|
unit SQLiteTable3;
(*
Простой класс для использования базовых функций библиотеки SQLite (exec и get_table).
TSQLiteDatabase - это обёртка для открытия и закрытия БД SQLite.
Также она позволяет вызвать SQLite_exec для запросов, которые возвращают наборы данных.
TSQLiteTable - обёртка для выполнения SQL-запросов.
Она выполняет запрос и записывает возвращаемые им строки во внутренний буфер.
Она позволяет обращаться к полям таблицы по именами и обеспечивает навигацию по полям
(переход к первой и последней строкам, шаг на одну строку вперёд/назад).
Благодарности
* Оригинальный модуль - Pablo Pissanetzky (pablo@myhtpc.net)
* Адаптация к Delphi - Tim Anderson (tim@itwriting.com)
* Модификация и расширения - Lukas Gebauer, Tobias Gunkel
* Удаление лишних и дублирующих классов/методов; изменения для большей совместимости
со стандартным компонентом TQuery; перенос части функций в Private-зону - Nikolay Petrochenko (http://petrochenko.ru)
*)
interface
{$IFDEF FPC}
{$MODE Delphi}//{$H+}
{$ENDIF}
uses {$IFDEF WIN32} Windows, {$ENDIF} SQLite3, Classes, SysUtils;
const
dtInt = 1;
dtNumeric = 2;
dtStr = 3;
dtBlob = 4;
dtNull = 5;
const
SecPerDay = 86400;
Offset1970 = 25569;
type
ESQLiteException = class(Exception)
end;
THookQuery = procedure(Sender: TObject; SQL: String) of object;
TSQLiteTable = class;
{ TSQLiteDatabase }
TSQLiteDatabase = class
private
fDB: TSQLiteDB;
fInTrans: boolean;
fSync: boolean;
FOnQuery: THookQuery;
procedure RaiseError(s: string; SQL: string);
function GetRowsChanged: integer;
protected
procedure SetSynchronised(Value: boolean);
procedure DoQuery(value: string);
public
constructor Create(const FileName: string);
destructor Destroy; override;
function GetTable(const SQL: Ansistring): TSQLiteTable; overload;
procedure ExecSQL(const SQL: Ansistring);
procedure UpdateBlob(const SQL: Ansistring; BlobData: TStream);
procedure BeginTransaction;
procedure Commit;
procedure Rollback;
function TableExists(TableName: string): boolean;
function GetLastInsertRowID: int64;
function GetLastChangedRows: int64;
function Version: string;
procedure AddCustomCollate(name: string; xCompare: TCollateXCompare);
//adds collate named SYSTEM for correct data sorting by user's locale
Procedure AddSystemCollate;
property DB: TSQLiteDB read fDB;
function GetMaxValue(table_name: string; column_name: string): integer;
published
property IsTransactionOpen: boolean read fInTrans;
//database rows that were changed (or inserted or deleted) by the most recent SQL statement
property RowsChanged : integer read getRowsChanged;
property Synchronised: boolean read FSync write SetSynchronised;
property OnQuery: THookQuery read FOnQuery write FOnQuery;
end;
{ TSQLiteTable }
TSQLiteTable = class
private
fResults: TList;
fRowCount: cardinal;
fColCount: cardinal;
fCols: TStringList;
fColTypes: TList;
fRow: cardinal;
function GetFields(FieldName: string): string;
function GetEOF: boolean;
function GetBOF: boolean;
function GetFieldIndex(FieldName: string): integer;
function GetCount: integer;
property EOF: boolean read GetEOF;
property BOF: boolean read GetBOF;
public
constructor Create(DB: TSQLiteDatabase; const SQL: Ansistring); overload;
destructor Destroy; override;
function FieldAsInteger(FieldName: string): int64;
function FieldAsBlob(FieldName: string): TMemoryStream;
function FieldAsBlobText(FieldName: string): string;
function FieldIsNull(FieldName: string): boolean;
function FieldAsString(FieldName: string): string;
function FieldAsDouble(FieldName: string): double;
function FieldAsDateTime(FieldName: string): TDateTime;
function Next: boolean;
function Previous: boolean;
property Row: cardinal read fRow;
function First: boolean;
function Last: boolean;
function MoveTo(position: cardinal): boolean;
property Count: integer read GetCount;
end;
function UnixTimeToDateTime(UnixTime: LongInt): TDate;
function DateTimeToUnixTime(DelphiDate: TDate): LongInt;
//
procedure DisposePointer(ptr: pointer); cdecl;
{$IFDEF WIN32}
function SystemCollate(Userdta: pointer; Buf1Len: integer; Buf1: pointer;
Buf2Len: integer; Buf2: pointer): integer; cdecl;
{$ENDIF}
implementation
// Функции для преобразования даты между форматами TDate и Unix
function UnixTimeToDateTime(UnixTime : LongInt): TDate;
begin
Result:= UnixTime / SecPerDay + Offset1970;
end;
function DateTimeToUnixTime(DelphiDate: TDate): LongInt;
begin
Result:= Trunc((DelphiDate - Offset1970) * SecPerDay);
end;
procedure DisposePointer(ptr: pointer); cdecl;
begin
if assigned(ptr) then
freemem(ptr);
end;
{$IFDEF WIN32}
function SystemCollate(Userdta: pointer; Buf1Len: integer; Buf1: pointer;
Buf2Len: integer; Buf2: pointer): integer; cdecl;
begin
Result := CompareStringW(LOCALE_USER_DEFAULT, 0, PWideChar(Buf1), Buf1Len,
PWideChar(Buf2), Buf2Len) - 2;
end;
{$ENDIF}
//------------------------------------------------------------------------------
// TSQLiteDatabase
//------------------------------------------------------------------------------
constructor TSQLiteDatabase.Create(const FileName: string);
var
Msg: PAnsiChar;
iResult: integer;
// utf8FileName: UTF8string;
begin
inherited Create;
self.fInTrans := False;
Msg := nil;
try
// utf8FileName := UTF8String(FileName);
iResult := SQLite3_Open(PAnsiChar(FileName), Fdb);
if iResult <> SQLITE_OK then
if Assigned(Fdb) then
begin
Msg := Sqlite3_ErrMsg(Fdb);
raise ESqliteException.CreateFmt('Failed to open database "%s" : %s',
[FileName, Msg]);
end
else
raise ESqliteException.CreateFmt('Failed to open database "%s" : unknown error',
[FileName]);
finally
if Assigned(Msg) then
SQLite3_Free(Msg);
end;
end;
//..............................................................................
destructor TSQLiteDatabase.Destroy;
begin
if self.fInTrans then
self.Rollback; //assume rollback
if Assigned(fDB) then
SQLite3_Close(fDB);
inherited;
end;
function TSQLiteDatabase.GetLastInsertRowID: int64;
begin
Result := Sqlite3_LastInsertRowID(self.fDB);
end;
function TSQLiteDatabase.GetLastChangedRows: int64;
begin
Result := SQLite3_TotalChanges(self.fDB);
end;
//..............................................................................
procedure TSQLiteDatabase.RaiseError(s: string; SQL: string);
//look up last error and raise an exception with an appropriate message
var
Msg: PAnsiChar;
ret : integer;
begin
Msg := nil;
ret := sqlite3_errcode(self.fDB);
if ret <> SQLITE_OK then
Msg := sqlite3_errmsg(self.fDB);
if Msg <> nil then
raise ESqliteException.CreateFmt(s +'.'#13'Error [%d]: %s.'#13'"%s": %s', [ret, SQLiteErrorStr(ret),SQL, Msg])
else
raise ESqliteException.CreateFmt(s, [SQL, 'No message']);
end;
procedure TSQLiteDatabase.SetSynchronised(Value: boolean);
begin
if Value <> fSync then
begin
if Value then
ExecSQL('PRAGMA synchronous = ON;')
else
ExecSQL('PRAGMA synchronous = OFF;');
fSync := Value;
end;
end;
procedure TSQLiteDatabase.ExecSQL(const SQL: Ansistring);
var
Stmt: TSQLiteStmt = nil;
NextSQLStatement: PAnsiChar;
iStepResult: integer;
begin
try
if Sqlite3_Prepare_v2(self.fDB, PAnsiChar(SQL), -1, Stmt, NextSQLStatement{%H-}) <>
SQLITE_OK then
RaiseError('Error executing SQL', SQL);
if (Stmt = nil) then
RaiseError('Could not prepare SQL statement', SQL);
DoQuery(SQL);
iStepResult := Sqlite3_step(Stmt);
if (iStepResult <> SQLITE_DONE) then
begin
SQLite3_reset(stmt);
RaiseError('Error executing SQL statement', SQL);
end;
finally
if Assigned(Stmt) then
Sqlite3_Finalize(stmt);
end;
end;
procedure TSQLiteDatabase.UpdateBlob(const SQL: Ansistring; BlobData: TStream);
var
iSize: integer;
ptr: pointer;
Stmt: TSQLiteStmt = nil;
Msg: PAnsiChar;
NextSQLStatement: PAnsiChar = '';
iStepResult: integer;
iBindResult: integer;
begin
//expects SQL of the form 'UPDATE MYTABLE SET MYFIELD = ? WHERE MYKEY = 1'
if pos('?', SQL) = 0 then
RaiseError('SQL must include a ? parameter', SQL);
Msg := nil;
try
if Sqlite3_Prepare_v2(self.fDB, PAnsiChar(SQL), -1, Stmt, NextSQLStatement) <>
SQLITE_OK then
RaiseError('Could not prepare SQL statement', SQL);
if (Stmt = nil) then
RaiseError('Could not prepare SQL statement', SQL);
DoQuery(SQL);
//now bind the blob data
iSize := BlobData.size;
GetMem(ptr, iSize);
if (ptr = nil) then
raise ESqliteException.CreateFmt('Error getting memory to save blob',
[SQL, 'Error']);
BlobData.position := 0;
BlobData.Read(ptr^, iSize);
iBindResult := SQLite3_Bind_Blob(stmt, 1, ptr, iSize, @DisposePointer);
if iBindResult <> SQLITE_OK then
RaiseError('Error binding blob to database', SQL);
iStepResult := Sqlite3_step(Stmt);
if (iStepResult <> SQLITE_DONE) then
begin
SQLite3_reset(stmt);
RaiseError('Error executing SQL statement', SQL);
end;
finally
if Assigned(Stmt) then
Sqlite3_Finalize(stmt);
if Assigned(Msg) then
SQLite3_Free(Msg);
end;
end;
//..............................................................................
function TSQLiteDatabase.GetTable(const SQL: Ansistring): TSQLiteTable;
begin
Result := TSQLiteTable.Create(Self, SQL);
end;
procedure TSQLiteDatabase.BeginTransaction;
begin
if not self.fInTrans then
begin
self.ExecSQL('BEGIN TRANSACTION');
self.fInTrans := True;
end
else
raise ESqliteException.Create('Transaction already open');
end;
procedure TSQLiteDatabase.Commit;
begin
self.ExecSQL('COMMIT');
self.fInTrans := False;
end;
procedure TSQLiteDatabase.Rollback;
begin
self.ExecSQL('ROLLBACK');
self.fInTrans := False;
end;
function TSQLiteDatabase.TableExists(TableName: string): boolean;
var
sql: string;
ds: TSqliteTable;
begin
//returns true if table exists in the database
sql := 'select [sql] from sqlite_master where [type] = ''table'' and lower(name) = ''' +
lowercase(TableName) + ''' ';
ds := self.GetTable(sql);
try
Result := (ds.Count > 0);
finally
ds.Free;
end;
end;
function TSQLiteDatabase.Version: string;
begin
Result := SQLite3_Version;
end;
procedure TSQLiteDatabase.AddCustomCollate(name: string;
xCompare: TCollateXCompare);
begin
sqlite3_create_collation(fdb, PAnsiChar(name), SQLITE_UTF8, nil, xCompare);
end;
procedure TSQLiteDatabase.AddSystemCollate;
begin
{$IFDEF WIN32}
sqlite3_create_collation(fdb, 'SYSTEM', SQLITE_UTF16LE, nil, @SystemCollate);
{$ENDIF}
end;
//database rows that were changed (or inserted or deleted) by the most recent SQL statement
function TSQLiteDatabase.GetRowsChanged: integer;
begin
Result := SQLite3_Changes(self.fDB);
end;
procedure TSQLiteDatabase.DoQuery(value: string);
begin
if assigned(OnQuery) then
OnQuery(Self, Value);
end;
//------------------------------------------------------------------------------
// TSQLiteTable
//------------------------------------------------------------------------------
constructor TSQLiteTable.Create(DB: TSQLiteDatabase; const SQL: Ansistring);
var
Stmt: TSQLiteStmt = nil;
NextSQLStatement: PAnsiChar = '';
iStepResult: integer;
ptr: pointer;
iNumBytes: integer;
thisBlobValue: TMemoryStream;
thisStringValue: pstring;
thisDoubleValue: pDouble;
thisIntValue: pInt64;
thisColType: pInteger;
i: integer;
DeclaredColType: PAnsiChar;
ActualColType: integer;
ptrValue: PAnsiChar;
begin
inherited create;
try
self.fRowCount := 0;
self.fColCount := 0;
//if there are several SQL statements in SQL, NextSQLStatment points to the
//beginning of the next one. Prepare only prepares the first SQL statement.
if Sqlite3_Prepare_v2(DB.fDB, PAnsiChar(SQL), -1, Stmt, NextSQLStatement) <> SQLITE_OK then
DB.RaiseError('Error executing SQL', SQL);
if (Stmt = nil) then
DB.RaiseError('Could not prepare SQL statement', SQL);
DB.DoQuery(SQL);
iStepResult := Sqlite3_step(Stmt);
while (iStepResult <> SQLITE_DONE) do
begin
case iStepResult of
SQLITE_ROW:
begin
Inc(fRowCount);
if (fRowCount = 1) then
begin
//get data types
fCols := TStringList.Create;
fColTypes := TList.Create;
fColCount := SQLite3_ColumnCount(stmt);
for i := 0 to Pred(fColCount) do
fCols.Add(AnsiUpperCase(Sqlite3_ColumnName(stmt, i)));
for i := 0 to Pred(fColCount) do
begin
new(thisColType);
DeclaredColType := Sqlite3_ColumnDeclType(stmt, i);
if DeclaredColType = nil then
thisColType^ := Sqlite3_ColumnType(stmt, i) //use the actual column type instead
//seems to be needed for last_insert_rowid
else
if (DeclaredColType = 'INTEGER') or (DeclaredColType = 'BOOLEAN') then
thisColType^ := dtInt
else
if (DeclaredColType = 'NUMERIC') or
(DeclaredColType = 'FLOAT') or
(DeclaredColType = 'DOUBLE') or
(DeclaredColType = 'REAL') then
thisColType^ := dtNumeric
else
if DeclaredColType = 'BLOB' then
thisColType^ := dtBlob
else
thisColType^ := dtStr;
fColTypes.Add(thiscoltype);
end;
fResults := TList.Create;
end;
//get column values
for i := 0 to Pred(fColCount) do
begin
ActualColType := Sqlite3_ColumnType(stmt, i);
if (ActualColType = SQLITE_NULL) then
fResults.Add(nil)
else
if pInteger(fColTypes[i])^ = dtInt then
begin
new(thisintvalue);
thisintvalue^ := Sqlite3_ColumnInt64(stmt, i);
fResults.Add(thisintvalue);
end
else
if pInteger(fColTypes[i])^ = dtNumeric then
begin
new(thisdoublevalue);
thisdoublevalue^ := Sqlite3_ColumnDouble(stmt, i);
fResults.Add(thisdoublevalue);
end
else
if pInteger(fColTypes[i])^ = dtBlob then
begin
iNumBytes := Sqlite3_ColumnBytes(stmt, i);
if iNumBytes = 0 then
thisblobvalue := nil
else
begin
thisblobvalue := TMemoryStream.Create;
thisblobvalue.position := 0;
ptr := Sqlite3_ColumnBlob(stmt, i);
thisblobvalue.writebuffer(ptr^, iNumBytes);
end;
fResults.Add(thisblobvalue);
end
else
begin
new(thisstringvalue);
ptrValue := Sqlite3_ColumnText(stmt, i);
setstring(thisstringvalue^, ptrvalue, strlen(ptrvalue));
fResults.Add(thisstringvalue);
end;
end;
end;
SQLITE_BUSY:
raise ESqliteException.CreateFmt('Could not prepare SQL statement',
[SQL, 'SQLite is Busy']);
else
begin
SQLite3_reset(stmt);
DB.RaiseError('Could not retrieve data', SQL);
end;
end;
iStepResult := Sqlite3_step(Stmt);
end;
fRow := 0;
finally
if Assigned(Stmt) then
Sqlite3_Finalize(stmt);
end;
end;
//..............................................................................
destructor TSQLiteTable.Destroy;
var
i: cardinal;
iColNo: integer;
begin
if Assigned(fResults) then
begin
for i := 0 to fResults.Count - 1 do
begin
//check for blob type
iColNo := (i mod fColCount);
case pInteger(self.fColTypes[iColNo])^ of
dtBlob:
TMemoryStream(fResults[i]).Free;
dtStr:
if fResults[i] <> nil then
begin
setstring(string(fResults[i]^), nil, 0);
dispose(fResults[i]);
end;
else
dispose(fResults[i]);
end;
end;
fResults.Free;
end;
if Assigned(fCols) then
fCols.Free;
if Assigned(fColTypes) then
for i := 0 to fColTypes.Count - 1 do
dispose(fColTypes[i]);
fColTypes.Free;
inherited;
end;
//..............................................................................
function TSQLiteTable.GetCount: integer;
begin
Result := FRowCount;
end;
//..............................................................................
function TSQLiteTable.GetEOF: boolean;
begin
Result := fRow >= fRowCount;
end;
function TSQLiteTable.GetBOF: boolean;
begin
Result := fRow <= 0;
end;
//..............................................................................
function TSQLiteTable.GetFieldIndex(FieldName: string): integer;
begin
if (fCols = nil) then
begin
raise ESqliteException.Create('Field ' + fieldname + ' Not found. Empty dataset');
exit;
end;
if (fCols.count = 0) then
begin
raise ESqliteException.Create('Field ' + fieldname + ' Not found. Empty dataset');
exit;
end;
Result := fCols.IndexOf(AnsiUpperCase(FieldName));
if (result < 0) then
begin
raise ESqliteException.Create('Field not found in dataset: ' + fieldname)
end;
end;
//..............................................................................
function TSqliteTable.FieldAsBlob(FieldName: string): TMemoryStream;
var
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
if EOF then
raise ESqliteException.Create('Table is at End of File');
if (self.fResults[(self.frow * self.fColCount) + I] = nil) then
Result := nil
else
if pInteger(self.fColTypes[I])^ = dtBlob then
Result := TMemoryStream(self.fResults[(self.frow * self.fColCount) + I])
else
raise ESqliteException.Create('Not a Blob field');
end;
function TSqliteTable.FieldAsBlobText(FieldName: string): string;
var
MemStream: TMemoryStream;
Buffer: PAnsiChar;
begin
Result := '';
MemStream := self.FieldAsBlob(FieldName);
if MemStream <> nil then
if MemStream.Size > 0 then
begin
MemStream.position := 0;
{$IFDEF UNICODE}
Buffer := AnsiStralloc(MemStream.Size + 1);
{$ELSE}
Buffer := Stralloc(MemStream.Size + 1);
{$ENDIF}
MemStream.readbuffer(Buffer[0], MemStream.Size);
(Buffer + MemStream.Size)^ := chr(0);
SetString(Result, Buffer, MemStream.size);
strdispose(Buffer);
end;
//do not free the TMemoryStream here; it is freed when
//TSqliteTable is destroyed
end;
function TSQLiteTable.GetFields(FieldName: string): string;
var
thisvalue: pstring;
thistype: integer;
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
Result := '';
if EOF then
raise ESqliteException.Create('Table is at End of File');
//integer types are not stored in the resultset
//as strings, so they should be retrieved using the type-specific
//methods
thistype := pInteger(self.fColTypes[I])^;
case thistype of
dtStr:
begin
thisvalue := self.fResults[(self.frow * self.fColCount) + I];
if (thisvalue <> nil) then
Result := thisvalue^
else
Result := '';
end;
dtInt:
Result := IntToStr(self.FieldAsInteger(FieldName));
dtNumeric:
Result := FloatToStr(self.FieldAsDouble(FieldName));
dtBlob:
Result := self.FieldAsBlobText(FieldName);
else
Result := '';
end;
end;
function TSqliteTable.FieldAsInteger(FieldName: string): int64;
var
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
if EOF then
raise ESqliteException.Create('Table is at End of File');
if (self.fResults[(self.frow * self.fColCount) + I] = nil) then
Result := 0
else
if pInteger(self.fColTypes[I])^ = dtInt then
Result := pInt64(self.fResults[(self.frow * self.fColCount) + I])^
else
if pInteger(self.fColTypes[I])^ = dtNumeric then
Result := trunc(strtofloat(pString(self.fResults[(self.frow * self.fColCount) + I])^))
else
raise ESqliteException.Create('Not an integer or numeric field');
end;
function TSqliteTable.FieldAsDouble(FieldName: string): double;
var
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
if EOF then
raise ESqliteException.Create('Table is at End of File');
if (self.fResults[(self.frow * self.fColCount) + I] = nil) then
Result := 0
else
if pInteger(self.fColTypes[I])^ = dtInt then
Result := pInt64(self.fResults[(self.frow * self.fColCount) + I])^
else
if pInteger(self.fColTypes[I])^ = dtNumeric then
Result := pDouble(self.fResults[(self.frow * self.fColCount) + I])^
else
raise ESqliteException.Create('Not an integer or numeric field');
end;
function TSqliteTable.FieldAsString(FieldName: string): string;
var
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
if EOF then
raise ESqliteException.Create('Table is at End of File');
if (self.fResults[(self.frow * self.fColCount) + I] = nil) then
Result := ''
else
// Result := UTF8Encode(self.GetFields(FieldName));
Result := self.GetFields(FieldName);
end;
function TSqliteTable.FieldAsDateTime(FieldName: string): TDateTime;
begin
result:=UnixTimeToDateTime(StrToInt(FieldAsString(FieldName)));
end;
function TSqliteTable.FieldIsNull(FieldName: string): boolean;
var
thisvalue: pointer;
i: cardinal;
begin
i:=GetFieldIndex(FieldName);
if EOF then
raise ESqliteException.Create('Table is at End of File');
thisvalue := self.fResults[(self.frow * self.fColCount) + I];
Result := (thisvalue = nil);
end;
//..............................................................................
function TSQLiteTable.Next: boolean;
begin
Result := False;
if not EOF then
begin
Inc(fRow);
Result := True;
end;
end;
function TSQLiteTable.Previous: boolean;
begin
Result := False;
if not BOF then
begin
Dec(fRow);
Result := True;
end;
end;
function TSQLiteTable.First: boolean;
begin
Result := False;
if self.fRowCount > 0 then
begin
fRow := 0;
Result := True;
end;
end;
function TSQLiteTable.Last: boolean;
begin
Result := False;
if self.fRowCount > 0 then
begin
fRow := fRowCount - 1;
Result := True;
end;
end;
{$WARNINGS OFF}
function TSQLiteTable.MoveTo(position: cardinal): boolean;
begin
Result := False;
if (self.fRowCount > 0) and (self.fRowCount > position) then
begin
fRow := position;
Result := True;
end;
end;
{$WARNINGS ON}
// Максимальное значение поля в заданной таблице (например, поиск максимального ID)
function TSQLiteDatabase.GetMaxValue(table_name: string; column_name: string): integer;
var
temp_table: TSQLiteTable;
begin
temp_table:=self.GetTable('SELECT '+column_name+' FROM '+table_name+' ORDER by '+column_name+' DESC LIMIT 1;');
//
if temp_table.Count<=0
then result:=0
else result:=temp_table.FieldAsInteger(column_name);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC DataSnap driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IF DEFINED(IOS) OR DEFINED(ANDROID)}
{$HPPEMIT LINKUNIT}
{$ELSE}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.Phys.DS.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.Phys.DS.o"'}
{$ENDIF}
{$ENDIF}
unit FireDAC.Phys.DS;
interface
uses
System.Classes,
FireDAC.Phys.TDBXBase;
type
TFDPhysDSDriverLink = class;
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidiOS or pfidAndroid)]
TFDPhysDSDriverLink = class(TFDPhysTDBXBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils, System.IniFiles, System.Variants, System.JSON,
System.Generics.Collections,
Data.DBXCommon, Data.DbxDatasnap, Data.DbxJSON, Datasnap.DSProxy, Datasnap.DSCommon,
Data.DBXTransport, Data.DBXPlatform,
FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.SQLGenerator, FireDAC.Phys.Meta,
FireDAC.Phys.DSMeta, FireDAC.Phys.DSDef;
type
TFDPhysDSDriver = class;
TFDPhysDSConnection = class;
TFDPhysDSEventAlerter = class;
TFDPhysDSCommand = class;
TFDPhysDSDriver = class(TFDPhysTDBXDriverBase)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysDSConnection = class(TFDPhysTDBXConnectionBase)
private
FProductVersion: TFDVersion;
function CheckNetworkError(AExc: Exception; AObj: TObject): Boolean;
protected
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand):
TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure InternalConnect; override;
procedure InternalPing; override;
procedure CheckDBXDriver; override;
procedure BuildDBXConnParams(const AConnectionDef: IFDStanConnectionDef;
AConnProps: TDBXProperties); override;
end;
TFDPhysDSEventAlerter = class(TFDPhysEventAlerter)
private
FManagers: TFDObjList;
FCallbacks: TFDStringList;
function GetDSConn: TFDPhysDSConnection;
protected
procedure InternalAllocHandle; override;
procedure InternalReleaseHandle; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalRegister; override;
procedure InternalUnregister; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
public
constructor Create(AConnection: TFDPhysConnection; const AKind: String); override;
destructor Destroy; override;
property DSConn: TFDPhysDSConnection read GetDSConn;
end;
TFDPhysDSCommand = class(TFDPhysTDBXCommand)
private
function GetDSConn: TFDPhysDSConnection;
protected
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
function InternalNextRecordSet: Boolean; override;
procedure InternalPrepare; override;
public
property DSConn: TFDPhysDSConnection read GetDSConn;
end;
const
S_FD_TCPIP = 'TCP/IP';
S_FD_HTTP = 'HTTP';
{-------------------------------------------------------------------------------}
{ TFDPhysDSDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysDSDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_DSId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysDSDriver.GetBaseDriverID: String;
begin
Result := S_FD_DSId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDSDriver.GetBaseDriverDesc: String;
begin
Result := 'DataSnap Server';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDSDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.DataSnap;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysDSDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysDSConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysDSConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
aList: TDBXStringArray;
i: Integer;
s: String;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', -1);
oView.Rows[0].EndEdit;
end;
aList := TDBXCommunicationLayerFactory.RegisteredLayerList;
s := '';
for i := 0 to Length(aList) - 1 do
s := s + ';' + aList[i];
s := Copy(s, 2, Length(s));
Result.Rows.Add([Unassigned, S_FD_ConnParam_DS_Protocol, s, S_FD_TCPIP, S_FD_ConnParam_DS_Protocol, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.IPImplementationID, '@S', '', TDBXPropertyNames.IPImplementationID, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.CommunicationIPVersion, ';IP_IPv4;IP_IPv6', '', TDBXPropertyNames.CommunicationIPVersion, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, '@S', S_FD_Local, S_FD_ConnParam_Common_Server, 2]);
if (AKeys <> nil) and
(Pos(S_FD_HTTP, UpperCase(AKeys.Values[S_FD_ConnParam_DS_Protocol])) > 0) then
s := '8080'
else
s := '211';
Result.Rows.Add([Unassigned, TDBXPropertyNames.Port, '@I', s, TDBXPropertyNames.Port, 3]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.BufferKBSize, '@I', '32', TDBXPropertyNames.BufferKBSize, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.Filters, '@S', '', TDBXPropertyNames.Filters, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_LoginTimeout, '@I', '10000', S_FD_ConnParam_Common_LoginTimeout, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.CommunicationTimeout, '@I', '', TDBXPropertyNames.CommunicationTimeout, -1]);
if (AKeys <> nil) and
(Pos(S_FD_HTTP, UpperCase(AKeys.Values[S_FD_ConnParam_DS_Protocol])) > 0) then begin
Result.Rows.Add([Unassigned, TDBXPropertyNames.URLPath, '@S', '', TDBXPropertyNames.URLPath, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DatasnapContext, '@S', DS_CONTEXT, TDBXPropertyNames.DatasnapContext, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DSProxyHost, '@S', '', TDBXPropertyNames.DSProxyHost, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DSProxyPort, '@I', '8888', TDBXPropertyNames.DSProxyPort, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DSProxyUsername, '@S', '', TDBXPropertyNames.DSProxyUsername, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DSProxyPassword, '@S', '', TDBXPropertyNames.DSProxyPassword, -1]);
Result.Rows.Add([Unassigned, TDBXPropertyNames.DSAuthenticationScheme, ';basic', '', TDBXPropertyNames.DSAuthenticationScheme, -1]);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSConnection }
{-------------------------------------------------------------------------------}
function TFDPhysDSConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_DS_Events) = 0 then
Result := TFDPhysDSEventAlerter.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysDSCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
Result := TFDPhysCommandGenerator.Create(ACommand);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSConnection.InternalCreateMetadata: TObject;
begin
Result := TFDPhysDSMetadata.Create(Self, 0, FProductVersion, True);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSConnection.CheckDBXDriver;
begin
FDriverName := 'DataSnap';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSConnection.BuildDBXConnParams(
const AConnectionDef: IFDStanConnectionDef; AConnProps: TDBXProperties);
procedure SetParam(const ADbxPar, AFDPar, ADef: String);
var
s: String;
begin
s := AFDPar;
if s = '' then
s := ADbxPar;
s := AConnectionDef.AsString[s];
if s = '' then
s := ADef;
if s <> '' then
AConnProps.Values[ADbxPar] := s;
end;
begin
AConnProps.Values[TDBXPropertyNames.DriverName] := FDriverName;
AConnProps.Values[TDBXPropertyNames.DriverUnit] := 'Data.DbxDatasnap';
SetParam(TDBXPropertyNames.CommunicationProtocol, S_FD_ConnParam_DS_Protocol, S_FD_TCPIP);
SetParam(TDBXPropertyNames.IPImplementationID, '', '');
SetParam(TDBXPropertyNames.CommunicationIPVersion, '', '');
SetParam(TDBXPropertyNames.HostName, S_FD_ConnParam_Common_Server, '127.0.0.1');
if Pos(S_FD_HTTP, UpperCase(AConnectionDef.AsString[S_FD_ConnParam_DS_Protocol])) > 0 then
SetParam(TDBXPropertyNames.Port, '', '8080')
else
SetParam(TDBXPropertyNames.Port, '', '211');
SetParam(TDBXPropertyNames.BufferKBSize, '', '32');
SetParam(TDBXPropertyNames.Filters, '', '');
SetParam(TDBXPropertyNames.ConnectTimeout, S_FD_ConnParam_Common_LoginTimeout, '10000');
SetParam(TDBXPropertyNames.CommunicationTimeout, '', '');
SetParam(TDBXPropertyNames.URLPath, '', '');
SetParam(TDBXPropertyNames.DatasnapContext, '', DS_CONTEXT);
SetParam(TDBXPropertyNames.DSProxyHost, '', '');
SetParam(TDBXPropertyNames.DSProxyPort, '', '8888');
SetParam(TDBXPropertyNames.DSProxyUsername, '', '');
SetParam(TDBXPropertyNames.DSProxyPassword, '', '');
SetParam(TDBXPropertyNames.DSAuthenticationUser, S_FD_ConnParam_Common_UserName, '');
SetParam(TDBXPropertyNames.DSAuthenticationPassword, S_FD_ConnParam_Common_Password, '');
SetParam(TDBXPropertyNames.DSAuthenticationScheme, '', '');
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSConnection.CheckNetworkError(AExc: Exception; AObj: TObject): Boolean;
var
oExc: ETDBXNativeException;
oExcClass: TClass;
begin
if (AExc is TDBXError) and (AExc.InnerException <> nil) then
AExc := AExc.InnerException;
oExcClass := AExc.ClassType;
while (oExcClass <> nil) and (CompareText(oExcClass.ClassName, 'EIdException') <> 0) do
oExcClass := oExcClass.ClassParent;
if oExcClass <> nil then begin
oExc := ETDBXNativeException.Create(er_FD_DBXGeneral,
FDExceptionLayers([S_FD_LPhys, S_FD_TDBXId, S_FD_DSId]) + ' ' + AExc.Message);
oExc.AppendError(1, TDBXErrorCodes.ConnectionFailed, AExc.Message, '', ekServerGone, -1, -1);
FDException(AObj, oExc {$IFDEF FireDAC_Monitor}, False {$ENDIF});
Result := True;
end
else
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSConnection.InternalConnect;
begin
try
inherited InternalConnect;
FProductVersion := FDVerStr2Int(DbxConnection.ProductVersion);
except
on E: Exception do
if not CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSConnection.InternalPing;
begin
try
// simplest DataSnap command
DbxConnection.GetVendorProperty(TDBXPropertyNames.ProductVersion);
except
on E: Exception do
if not CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysDSEventMessage = class(TFDPhysEventMessage)
private
FCBName: String;
FArgs: Variant;
public
constructor Create(const ACBName: String; const AArgs: Variant);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysDSEventMessage.Create(const ACBName: String;
const AArgs: Variant);
begin
inherited Create;
FCBName := ACBName;
FArgs := AArgs;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSCallback }
{-------------------------------------------------------------------------------}
type
TFDPhysDSCallback = class(TDBXCallback)
private
[weak] FAlerter: TFDPhysDSEventAlerter;
FName: String;
public
constructor Create(AAlerter: TFDPhysDSEventAlerter; const AName: String);
function Execute(const AArg: TJSONValue): TJSONValue; overload; override;
function Execute(AArg: TObject): TObject; overload; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysDSCallback.Create(AAlerter: TFDPhysDSEventAlerter;
const AName: String);
begin
inherited Create;
FAlerter := AAlerter;
FName := AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSCallback.Execute(const AArg: TJSONValue): TJSONValue;
var
V: Variant;
i: Integer;
begin
if AArg is TJSONArray then begin
V := VarArrayCreate([0, TJSONArray(AArg).Count - 1], varUString);
for i := 0 to TJSONArray(AArg).Count - 1 do
V[i] := TJSONArray(AArg).Items[i].Value;
end
else
V := AArg.Value;
if FAlerter.IsRunning then
FAlerter.FMsgThread.EnqueueMsg(TFDPhysDSEventMessage.Create(FName, V));
Result := TJSONTrue.Create;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSCallback.Execute(AArg: TObject): TObject;
begin
Result := Execute(TDSClientCallbackChannelManager(FAlerter.FManagers[0]).
MarshalData(AArg));
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSEventAlerter }
{-------------------------------------------------------------------------------}
constructor TFDPhysDSEventAlerter.Create(AConnection: TFDPhysConnection;
const AKind: String);
begin
inherited Create(AConnection, AKind);
FManagers := TFDObjList.Create;
FCallbacks := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysDSEventAlerter.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FManagers);
FDFreeAndNil(FCallbacks);
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSEventAlerter.GetDSConn: TFDPhysDSConnection;
begin
Result := TFDPhysDSConnection(ConnectionObj);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalAllocHandle;
var
oDef: IFDStanConnectionDef;
oParams: TFDPhysDSConnectionDefParams;
oNames: TStrings;
i: Integer;
oMan: TDSClientCallbackChannelManager;
sCBName: String;
sChnlName: String;
function Def(const AValue, ADef: String): String;
begin
if AValue = '' then
Result := ADef
else
Result := AValue;
end;
function GenSessionId: String;
begin
Result := TDSSessionHelper.GenerateSessionId;
end;
begin
oDef := DSConn.ConnectionDef;
oParams := oDef.Params as TFDPhysDSConnectionDefParams;
oNames := GetNames;
for i := 0 to oNames.Count - 1 do begin
oMan := TDSClientCallbackChannelManager.Create(nil);
FManagers.Add(oMan);
oMan.CommunicationProtocol := Def(oDef.AsString[S_FD_ConnParam_DS_Protocol], S_FD_TCPIP);
oMan.IPImplementationID := oParams.IPImplementationID;
oMan.DSHostname := oParams.Server;
if CompareText(oMan.CommunicationProtocol, S_FD_TCPIP) = 0 then
oMan.DSPort := Def(oDef.AsString[S_FD_ConnParam_Common_Port], '211')
else
oMan.DSPort := Def(oDef.AsString[S_FD_ConnParam_Common_Port], '8080');
oMan.DSPath := oParams.URLPath;
oMan.UserName := oParams.UserName;
oMan.Password := oParams.Password;
oMan.ProxyHost := oParams.DSProxyHost;
oMan.ProxyPort := oParams.DSProxyPort;
oMan.ProxyUsername := oParams.DSProxyUsername;
oMan.ProxyPassword := oParams.DSProxyPassword;
oMan.ConnectionTimeout := IntToStr(oParams.LoginTimeout);
oMan.CommunicationTimeout := IntToStr(oParams.CommunicationTimeout);
oMan.ManagerId := GenSessionId;
sChnlName := oNames.KeyNames[i];
if sChnlName = '' then
sChnlName := GenSessionId;
oMan.ChannelName := sChnlName;
sCBName := oNames.ValueFromIndex[i];
if sCBName = '' then
sCBName := GenSessionId;
FCallbacks.Add(sCBName);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalHandle(AEventMessage: TFDPhysEventMessage);
begin
InternalHandleEvent(TFDPhysDSEventMessage(AEventMessage).FCBName,
TFDPhysDSEventMessage(AEventMessage).FArgs);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalRegister;
var
i: Integer;
oCB: TFDPhysDSCallback;
begin
for i := 0 to FManagers.Count - 1 do begin
oCB := TFDPhysDSCallback.Create(Self, FCallbacks[i]);
TDSClientCallbackChannelManager(FManagers[i]).RegisterCallback(oCB.FName, oCB);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalUnregister;
var
i: Integer;
begin
for i := 0 to FManagers.Count - 1 do
TDSClientCallbackChannelManager(FManagers[i]).UnregisterCallback(FCallbacks[i]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalReleaseHandle;
var
i: Integer;
begin
for i := 0 to FManagers.Count - 1 do
FDFree(TDSClientCallbackChannelManager(FManagers[i]));
FManagers.Clear;
FCallbacks.Clear;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSEventAlerter.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
iChnl, i: Integer;
oClnt: TDSAdminClient;
oArr: TJSONArray;
oMsg: TJSONValue;
oRsp: TJSONValue;
begin
iChnl := GetNames.IndexOfName(AEvent);
if iChnl = -1 then
iChnl := GetNames.IndexOf(AEvent);
if VarIsArray(AArgument) then begin
oArr := TJSONArray.Create;
for i := VarArrayLowBound(AArgument, 1) to VarArrayHighBound(AArgument, 1) do
oArr.Add(VarToStrDef(AArgument[i], ''));
oMsg := oArr;
end
else
oMsg := TJSONString.Create(VarToStrDef(AArgument, ''));
oClnt := TDSAdminClient.Create(DSConn.DbxConnection);
try
if iChnl <> -1 then
oClnt.BroadcastToChannel(AEvent, oMsg)
else
oClnt.NotifyCallback(AArgument[0], AEvent, oMsg, oRsp);
finally
FDFree(oClnt);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysDSCommand }
{-------------------------------------------------------------------------------}
function TFDPhysDSCommand.GetDSConn: TFDPhysDSConnection;
begin
Result := TFDPhysDSConnection(TDBXConn);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSCommand.InternalPrepare;
begin
try
inherited InternalPrepare;
except
on E: Exception do
if not DSConn.CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysDSCommand.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
try
inherited InternalExecute(ATimes, AOffset, ACount);
except
on E: Exception do
if not DSConn.CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSCommand.InternalOpen(var ACount: TFDCounter): Boolean;
begin
Result := False;
try
Result := inherited InternalOpen(ACount);
except
on E: Exception do
if not DSConn.CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysDSCommand.InternalNextRecordSet: Boolean;
begin
Result := False;
try
Result := inherited InternalNextRecordSet;
except
on E: Exception do
if not DSConn.CheckNetworkError(E, Self) then
raise;
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysDSDriver);
finalization
FDUnregisterDriverClass(TFDPhysDSDriver);
end.
|
// This unit is part of the GLScene Project, http://glscene.org
{: GLFileOCT<p>
Support-code to load OCT Files into TGLFreeForm-Components in GLScene.<br>
(OCT being the format output from FSRad, http://www.fluidstudios.com/fsrad.html).<p>
<b>History : </b><font size=-1><ul>
<li>19/06/11 - Yar - Fixed problem with image converting in Lazarus (thanks to Johannes Pretorius, Bugtracker ID = 3322324)
<li>22/01/10 - Yar - Added GLTextureFormat to uses
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>19/09/03 - EG - "Lighmap" -> "LightMap"
<li>06/05/03 - mrqzzz - added Gamma and Brightness correction variables (vGLFileOCTLightmapBrightness, vGLFileOCTLightmapGammaCorrection)
<li>02/02/03 - EG - Creation
</ul><p>
}
unit GLFileOCT;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
GLVectorFileObjects, GLVectorGeometry, GLApplicationFileIO,
FileOCT;
type
// TGLOCTVectorFile
{: The OCT vector file (FSRad output).<p> }
TGLOCTVectorFile = class(TVectorFile)
public
{ Public Declarations }
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
var
vGLFileOCTLightmapBrightness: single = 1;
// Mrqzzz : scaling factor, 1.0 = unchanged
vGLFileOCTLightmapGammaCorrection: single = 1;
// Mrqzzz : scaling factor, 1.0 = unchanged
vGLFileOCTAllocateMaterials: boolean = True;
// Mrqzzz : Flag to avoid loading materials (useful for IDE Extensions or scene editors)
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
GLTexture, GLMaterial, GLGraphics, GLCrossPlatform, GLState,
GLUtils, GLTextureFormat;
// ------------------
// ------------------ TGLOCTVectorFile ------------------
// ------------------
// Capabilities
class function TGLOCTVectorFile.Capabilities: TDataFileCapabilities;
begin
Result := [dfcRead];
end;
// LoadFromStream
procedure TGLOCTVectorFile.LoadFromStream(aStream: TStream);
var
i, y, n: integer;
oct: TOCTFile;
octFace: POCTFace;
octLightmap: POCTLightmap;
mo: TMeshObject;
fg: TFGVertexIndexList;
lightmapLib: TGLMaterialLibrary;
lightmapBmp: TGLBitmap;
libMat: TGLLibMaterial;
begin
oct := TOCTFile.Create(aStream);
try
mo := TMeshObject.CreateOwned(Owner.MeshObjects);
mo.Mode := momFaceGroups;
lightmapLib := Owner.LightmapLibrary;
if (Assigned(lightmapLib)) and (vGLFileOCTAllocateMaterials) then
begin
// import lightmaps
n := oct.Header.numLightmaps;
lightmapBmp := TGLBitmap.Create;
try
lightmapBmp.PixelFormat := glpf24bit;
lightmapBmp.Width := 128;
lightmapBmp.Height := 128;
for i := 0 to n - 1 do
begin
octLightmap := @oct.Lightmaps[i];
// Brightness correction
if vGLFileOCTLightmapBrightness <> 1.0 then
BrightenRGBArray(@octLightmap.map,
lightmapBmp.Width * lightmapBmp.Height,
vGLFileOCTLightmapBrightness);
// Gamma correction
if vGLFileOCTLightmapGammaCorrection <> 1.0 then
GammaCorrectRGBArray(@octLightmap.map,
lightmapBmp.Width * lightmapBmp.Height,
vGLFileOCTLightmapGammaCorrection);
// convert RAW RGB to BMP
for y := 0 to 127 do
Move(octLightmap.map[y * 128 * 3], lightmapBmp.ScanLine[127 - y]^, 128 * 3);
// spawn lightmap
libMat := lightmapLib.AddTextureMaterial(IntToStr(i), lightmapBmp);
with libMat.Material.Texture do
begin
MinFilter := miLinear;
TextureWrap := twNone;
TextureFormat := tfRGB;
end;
end;
finally
lightmapBmp.Free;
end;
end;
// import geometry
n := oct.Header.numVerts;
mo.Vertices.AdjustCapacityToAtLeast(n);
mo.TexCoords.AdjustCapacityToAtLeast(n);
mo.LightMapTexCoords.AdjustCapacityToAtLeast(n);
for i := 0 to n - 1 do
with oct.Vertices[i] do
begin
mo.Vertices.Add(pos.V[0], pos.V[1], pos.V[2]);
mo.TexCoords.Add(tv.s, tv.t);
mo.LightMapTexCoords.Add(lv.s, lv.t);
end;
// import faces
n := oct.Header.numFaces;
for i := 0 to n - 1 do
begin
octFace := @oct.Faces[i];
fg := TFGVertexIndexList.CreateOwned(mo.FaceGroups);
fg.Mode := fgmmTriangleFan;
fg.VertexIndices.AddSerie(octFace.start, 1, octFace.num);
if (Assigned(lightmapLib)) and (vGLFileOCTAllocateMaterials) then
fg.LightMapIndex := octFace.lid;
end;
finally
oct.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('oct', 'FSRad OCT files', TGLOCTVectorFile);
end.
|
unit moway_api;
{$IFDEF CompilerVersion > 14.5}
// Delphi 6默认未处理FPC,故使用版本后区分,简化编译条件。 shijc 2016-8-8
// 备注:原文无版本判断
{$IFDEF FPC}
{$WARNINGS OFF}
{$HINTS OFF}
{$ELSE FPC}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF FPC}
{$ENDIF}
interface
uses
{$IF CompilerVersion >= 23}
// XE2 及以上版本引用头文件
Winapi.Windows, System.SysUtils, System.Classes,
BTMemory_x86_64;
{$ELSE}
// XE以下版本(包括Delphi7)
windows, SysUtils, Classes,
BTMemory_x86;
{$IFEND}
{$I moway_api.inc}
var
{/*!
* @brief 枚举魔锐设备
* @param[in out] pDevInfoList 枚举输出的魔锐设备列表
* @param[in] uiDevListCount 枚举列表(pDevInfoList)能存放的设备的个数。注:最大个数参见宏定义MW_ENUM_DEVICE_MAX_COUNT
* @param[out] puiDevCount 实际枚举出的魔锐设备数量
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks 注意:用户必须按照uiDevListCount乘以sizeof(MW_DEVICE_INFO_CTX)分配内存给pDevInfoList,API内部不分配内存给pDevInfoList。
*/}
mw_enum: function (
{OUT} pDevInfoList: PMW_DEVICE_INFO_CTX;
{IN} uiDevListCount: LONGWORD;
{OUT} var puiDevCount: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 打开魔锐设备
* @param[in] pDevInfo 指向魔锐设备信息结构体的指针。
* @param[in] uiShareMode 独占或者共享模式打开。参见宏定义MW_OPEN_SHARE_MODE MW_OPEN_EXCLUSIVE_MODE
* @param[out] phHandle 打开魔锐设备后,输出一个句柄以便后续调用。
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks Open an moway device with DevInfo enumerated by mw_enum()
*/}
mw_open: function (
{IN} pDevInfo: PMW_DEVICE_INFO_CTX;
{IN} uiShareMode: LONGWORD;
{OUT} var phHandle: MWHANDLE
): LONGWORD; stdcall;
{/*!
* @brief 关闭设备
* @param[in] hHandle 魔锐设备句柄
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_close: function (
{IN} hHandle: MWHANDLE
): LONGWORD; stdcall;
{/*!
* @brief 校验PIN
* @param[in] hHandle 魔锐设备句柄
* @param[in] ucPinType Pin码类型 参见宏定义:MW_PIN_TYPE_XXX
* @param[in] pucPin Pin码数据,用户8字节,开发商24字节
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_verify_pin: function (
{IN} hHandle: MWHANDLE;
{IN} ucPinType: BYTE;
{IN} pucPin: PBYTE
): LONGWORD; stdcall;
{/*!
* @brief 修改PIN
* @param[in] hHandle 魔锐设备句柄
* @param[in] ucPinType Pin码类型 参见宏定义:MW_PIN_TYPE_XXX
* @param[in] usLimitCount 最大尝试次数,注:不限次数设置为0,限制次数范围是1-15, 如为其它数则返回参数错误
* @param[in] pucOldPin 旧Pin码数据,用户8字节,开发商24字节
* @param[in] pucNewPin 新Pin码数据,用户8字节,开发商24字节
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_change_Pin: function (
{IN} hHandle: MWHANDLE;
{IN} ucPinType: BYTE;
{IN} usLimitCount: WORD;
{IN} pucOldPin: PBYTE;
{IN} pucNewPin: PBYTE
): LONGWORD; stdcall;
{/*!
* @brief 设置PID
* @param[in] hHandle 魔锐设备句柄
* @param[in] pucPIDSeed 种子码
* @param[in] uiSeedLen 种子码长度,长度范围是4-32,参见宏定义MW_SEED_LENGTH_MIN、MW_SEED_LENGTH_MAX
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_set_pid: function (
{IN} hHandle: MWHANDLE;
{IN} pucPIDSeed: PBYTE;
{IN} uiSeedLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 控制命令
* @param[in] hHandle 魔锐设备句柄
* @param[in] uiCtrlCodeItem 控制码,参见宏定义 MW_CTRL_CODE_ITEM_XXX
* @param[in] pvInBuffer 输入数据
* @param[in] uiInBufferLen 输入数据的长度
* @param[out] pvOutBuffer 输出数据
* @param[in] uiOutBufferLen 输出数据的长度
* @param[out] puiReturnedLen 实际输出数据的长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_control: function (
{IN} hHandle: MWHANDLE;
{IN} uiCtrlCodeItem: BYTE;
{IN} pvInBuffer: Pointer;
{IN} uiInBufferLen: LONGWORD;
{OUT} pvOutBuffer: Pointer;
{IN} uiOutBufferLen: LONGWORD;
{OUT} var puiReturnedLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 获取设备信息
* @param[in] hHandle 魔锐设备句柄
* @param[in] ucInfoItem 指定获取的设备信息的具体项,参见宏定义:MW_GET_INFO_ITEM_XXX
* @param[out] pvBuffer 输出获取的设备信息项
* @param[in out] puiBufferLength 输出设备信息项的数据长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_get_device_info: function (
{IN} hHandle: MWHANDLE;
{IN} ucInfoItem: BYTE;
{OUT} pvBuffer: Pointer;
{INOUT} var puiBufferLength: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 获取设备状态
* @param[in] hHandle 魔锐设备句柄
* @param[out] pstDeviceStatusCtx 当前设备状态。
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_get_device_status: function (
{IN} hHandle: MWHANDLE;
{OUT} pstDeviceStatusCtx: PMW_DEVICE_STATUS
): LONGWORD; stdcall;
{/*!
* @brief 列举文件
* @param[in] hHandle 魔锐设备句柄
* @param[out] pstFilePropertyList 结构体MW_FILE_PROPERTY数组,它的大小由uiFileListCount指定
* @param[in] uiFileListCount 指定pstFilePropertyList数组的大小
* @param[out] puiReturnedFileCount 实际返回列举到文件的个数
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks 注意:pstFilePropertyList由函数外部调用者分配,大小为uiFileListCount * sizeof(MW_FILE_PROPERTY)
*/}
mw_enum_file: function (
{IN} hHandle: MWHANDLE;
{OUT} pstFilePropertyList: PMW_FILE_PROPERTY;
{IN} uiFileListCount: LONGWORD;
{OUT} var puiReturnedFileCount: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 创建文件
* @param[in] hHandle 魔锐设备句柄
* @param[in] pstFileProperty 指定需要创建文件的属性,其中文件类型、文件权限、文件大小为必填项
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_create_file: function (
{IN} hHandle: MWHANDLE;
{IN} pstFileProperty: PMW_FILE_PROPERTY
): LONGWORD; stdcall;
{/*!
* @brief 读文件
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcFileName 文件名称,以'\0'结尾的字符串
* @param[in] uiReadOffset 读文件的偏移量
* @param[in] uiReadSize 预计读取文件的大小。
* @param[out] pucReadBuffer 读取文件数据到缓冲区。注:必须分配足够uiReadSize大小,否则会访问越界。
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_read_file: function (
{IN} hHandle: MWHANDLE;
{IN} pcFileName: PANSIChar;
{IN} uiReadOffset: LONGWORD;
{IN} uiReadSize: LONGWORD;
{OUT} pucReadBuffer: PBYTE
): LONGWORD; stdcall;
{/*!
* @brief 写文件
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcFileName 文件名称,以'\0'结尾的字符串
* @param[in] uiWriteOffset 写文件的偏移量
* @param[in] uiWriteSize 写文件的大小。
* @param[in] pucWriteBuffer 需要写入文件的缓冲区
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_write_file: function (
{IN} hHandle: MWHANDLE;
{IN} pcFileName: PANSIChar;
{IN} uiWriteOffset: LONGWORD;
{IN} uiWriteSize: LONGWORD;
{IN} pucWriteBuffer: PBYTE
): LONGWORD; stdcall;
{/*!
* @brief 删除文件
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcFileName 文件名称,以'\0'结尾的字符串
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_delete_file: function (
{IN} hHandle: MWHANDLE;
{IN} pcFileName: PANSIChar
): LONGWORD; stdcall;
{/*!
* @brief 获取文件属性
* @param[in] hHandle 魔锐设备句柄
* @param[in] lpszFileName 文件名称,以'\0'结尾的字符串
* @param[out] pstFileProperty 文件属性信息
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_get_file_property: function (
{IN} hHandle: MWHANDLE;
{IN} pcFileName: PANSIChar;
{OUT} pstFileProperty: PMW_FILE_PROPERTY
): LONGWORD; stdcall;
{/*!
* @brief 对称加密
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucAlgoMode 对称加密的算法,参见宏定义:MW_ALG_TYPE_XXX
* @param[in] pucIV 对称加密算法中需要使用到的向量,固定16字节,CBC模式需要填入,ECB可不填
* @param[in] pucInData 加密输入的明文,必须是16的倍数,
* @param[in] uiInDataLen 加密明文的数据长度,
* @param[out] pucOutData 加密后输出的密文
* @param[in out] puiOutDataLen 加密后密文的长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_sym_encrypt: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucAlgoMode: BYTE;
{IN} pucIV: PBYTE;
{IN} pucInData: PBYTE;
{IN} uiInDataLen: LONGWORD;
{OUT} pucOutData: PBYTE;
{INOUT} var puiOutDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 对称解密
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucAlgoMode 对称加密的算法,参见宏定义:MW_ALG_TYPE_XXX
* @param[in] pucIV 对称加密算法中需要使用到的向量,固定16字节,CBC模式需要填入,ECB可不填
* @param[in] pucInData 输入的密文,必须是16的倍数,
* @param[in] uiInDataLen 输入密文长度,
* @param[out] pucOutData 解密后输出明文
* @param[in out] puiOutDataLen 解密后输出明文长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_sym_decrypt: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucAlgoMode: BYTE;
{IN} pucIV: PBYTE;
{IN} pucInData: PBYTE;
{IN} uiInDataLen: LONGWORD;
{OUT} pucOutData: PBYTE;
{INOUT} var puiOutDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief rsa非对称加密
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucPadMode 加密的算法,参见宏定义:MW_RSA_MODE_XXX
* @param[in] pucInData 输入明文数据
* @param[in] uiInDataLen 输入明文数据的长度
* @param[out] pucOutData 输出密文数据
* @param[in out] puiOutDataLen 输出密文数据的长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks 注:当ucPadMode为MW_RSA_MODE_NORMAL时,RSA_1024位加密最大加密明文长度为128,RSA_2048位加密最大长度为256;
* 当ucPadMode为MW_RSA_MODE_PKCS1_V1_5时, RSA_1024位加密最大加密明文长度为117,RSA_2048位加密最大长度为245;
*/}
mw_rsa_encrypt: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucPadMode: BYTE;
{IN} pucInData: PBYTE;
{IN} uiInDataLen: LONGWORD;
{OUT} pucOutData: PBYTE;
{INOUT} var puiOutDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief rsa非对称解密
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucPadMode 加密的算法,参见宏定义:MW_RSA_MODE_XXX
* @param[in] pucInData 输入密文
* @param[in] uiInDataLen 输入密文长度 注:它的长度必须为128或者256
* @param[out] pucOutData 输出明文
* @param[in out] puiOutDataLen 输出明文长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_rsa_decrypt: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucPadMode: BYTE;
{IN} pucInData: PBYTE;
{IN} uiInDataLen: LONGWORD;
{OUT} pucOutData: PBYTE;
{INOUT} var puiOutDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 签名
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucHashAlg 哈希算法类型,参见宏定义:MW_HASH_ALGO_SHA1, MW_HASH_ALGO_SHA256, MW_HASH_ALGO_NONE
* @param[in] pucMessageData 输入消息数据
* @param[in] uiMessageDataLen 输入消息数据长度 注:最大数据长度参见宏定义 MW_INPUT_DATA_LENGTH_MAX
* @param[out] pucSignData 输出签名数据
* @param[in out] puiSignDataLen 输出签名数据长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_signature: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucHashAlg: BYTE;
{IN} pucMessageData: PBYTE;
{IN} uiMessageDataLen: LONGWORD;
{OUT} pucSignData: PBYTE;
{INOUT} var puiSignDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 验签
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] ucHashAlg 哈希算法类型,参见宏定义:MW_HASH_ALGO_XXX
* @param[in] pucSignData 输入签名数据
* @param[in] uiSignDataLen 输入签名数据长度
* @param[in] pucMessageData 输入消息数据
* @param[in] uiMessageDataLen 输入消息数据长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_verify_sign: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} ucHashAlg: BYTE;
{IN} pucSignData: PBYTE;
{IN} uiSignDataLen: LONGWORD;
{IN} pucMessageData: PBYTE;
{IN} uiMessageDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief HMAC计算
* @param[in] hHandle 魔锐设备句柄
* @param[in] pcKeyFileName 密钥文件名称
* @param[in] pucInData 输入数据
* @param[in] uiInDataLen 输入数据长度
* @param[out] pucOutData 输出数据
* @param[in out] puiOutDataLen 输出数据长度,参见宏定义:MW_HMAC_MD5_DIGEST_LENGTH、MW_HMAC_SHA1_DIGEST_LENGTH、MW_HMAC_SHA256_DIGEST_LENGTH
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_hmac_calc: function (
{IN} hHandle: MWHANDLE;
{IN} pcKeyFileName: PANSIChar;
{IN} pucInData: PBYTE;
{IN} uiInDataLen: LONGWORD;
{OUT} pucOutData: PBYTE;
{INOUT} var puiOutDataLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 制作升级包
* @param[in] hHandle 魔锐设备句柄
* @param[in] uiDevPID 设备产品号
* @param[in] pucSerialNum 硬件唯一序列号 固定长度为:MW_SN_LENGTH,不指定SN绑定时,可以为NULL
* @param[in] pstUpdateFileList 文件路径列表,最大文件个数参见宏定义MW_UPDATE_FILE_COUNT_MAX,升级文件的个数为uiFileCount
* @param[in] uiFileCount 升级文件的个数,它指定了pstUpdateFileList中的大小
* @param[out] pucOutPkg 升级包数据
* @param[in out] puiOutPkgLen 升级包数据长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_make_update_pkg: function (
{IN} hHandle: MWHANDLE;
{IN} uiDevPID: LONGWORD;
{IN} pucSN: PBYTE;
{IN} pstFilePathList: PMW_UPDADE_FILE_CTX;
{IN} uiFileCount: LONGWORD;
{OUT} pucOutPkg: PBYTE;
{INOUT} var puiOutPkgLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 远程升级
* @param[in] hHandle 魔锐设备句柄
* @param[in] pucInPkg 升级包数据
* @param[in] uiInPkgLen 升级包数据长度
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_update: function (
{IN} hHandle: MWHANDLE;
{IN} pucInPkg: PBYTE;
{IN} uiInPkgLen: LONGWORD
): LONGWORD; stdcall;
{/*!
* @brief 恢复出厂设置
* @param[in] hHandle 魔锐设备句柄
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks 将设备恢复出厂状态,即默认PID、默认PIN,文件系统清空。需开发商权限
*/}
mw_restore_factory: function (
{IN} hHandle: MWHANDLE
): LONGWORD; stdcall;
{/*!
* @brief 错误码帮助
* @param[in] hHandle 魔锐设备句柄
* @param[in] uiErrorCode 错误码
* @param[in] uiLanguageID 语言种类ID
* @return 执行成功返回 MW_SUCCESS ,执行失败时返回错误码。
* @remarks
*/}
mw_get_error_desc: function(
{IN} uiErrorCode: LONGWORD;
{IN} uiLanguageID: LONGWORD
): PAnsiChar; stdcall;
implementation
resourcestring
rsErrLoadMemLibary = '加载库失败';
// 引用将 dll 转换为二进制数组的inc文件
// 安全升级方案:避免静态分析替换dll内容
// 可对 dll 转换后的二进制数据进行加密处理,然后在使用期间解密。
// 软件开发者可根据实际情况酌情考虑此方案。
const
{$I moway_api.dll.inc}
var
{$IF CompilerVersion >= 23}
LibModule: TMemoryModule;
{$ELSE}
LibModule: TBTMemoryModule;
{$IFEND}
LibInited: Boolean;
procedure Init;
function GetFuncAddress(const AProcName: PChar): Pointer;
begin
{$IF CompilerVersion >= 23}
Result := MemoryGetProcAddress(LibModule, PAnsiChar(AProcName));
{$ELSE}
Result := BTMemoryGetProcAddress(LibModule, PChar(AProcName));
{$IFEND}
end;
begin
if LibInited then
Exit;
{$IF CompilerVersion >= 23}
LibModule := MemoryLoadLibary(@data);
{$ELSE}
LibModule := BTMemoryLoadLibary(@data, Length(data));
{$IFEND}
if LibModule = nil then
Exit;
@mw_enum := GetFuncAddress(PChar('mw_enum'));
@mw_open := GetFuncAddress(PChar('mw_open'));
@mw_close := GetFuncAddress(PChar('mw_close'));
@mw_verify_pin := GetFuncAddress(PChar('mw_verify_pin'));
@mw_change_pin := GetFuncAddress(PChar('mw_change_pin'));
@mw_set_pid := GetFuncAddress(PChar('mw_set_pid'));
@mw_control := GetFuncAddress(PChar('mw_control'));
@mw_get_device_info := GetFuncAddress(PChar('mw_get_device_info'));
@mw_get_device_status := GetFuncAddress(PChar('mw_get_device_status'));
@mw_enum_file := GetFuncAddress(PChar('mw_enum_file'));
@mw_create_file := GetFuncAddress(PChar('mw_create_file'));
@mw_read_file := GetFuncAddress(PChar('mw_read_file'));
@mw_write_file := GetFuncAddress(PChar('mw_write_file'));
@mw_delete_file := GetFuncAddress(PChar('mw_delete_file'));
@mw_get_file_property := GetFuncAddress(PChar('mw_get_file_property'));
@mw_sym_encrypt := GetFuncAddress(PChar('mw_sym_encrypt'));
@mw_sym_decrypt := GetFuncAddress(PChar('mw_sym_decrypt'));
@mw_rsa_encrypt := GetFuncAddress(PChar('mw_rsa_encrypt'));
@mw_rsa_decrypt := GetFuncAddress(PChar('mw_rsa_decrypt'));
@mw_signature := GetFuncAddress(PChar('mw_signature'));
@mw_verify_sign := GetFuncAddress(PChar('mw_verify_sign'));
@mw_hmac_calc := GetFuncAddress(PChar('mw_hmac_calc'));
@mw_make_update_pkg := GetFuncAddress(PChar('mw_make_update_pkg'));
@mw_update := GetFuncAddress(PChar('mw_update'));
@mw_restore_factory := GetFuncAddress(PChar('mw_restore_factory'));
@mw_get_error_desc := GetFuncAddress(PChar('mw_get_error_desc'));
LibInited := True;
end;
procedure Done;
begin
if not LibInited then
Exit;
//TODO Pointer for Function
if LibModule <> nil then
{$IF CompilerVersion >= 23}
MemoryFreeLibrary(LibModule);
{$ELSE}
BTMemoryFreeLibrary(LibModule);
{$IFEND}
LibModule := nil;
LibInited := False;
end;
////////////////////////////////////////////////////////////////////////////////
//功能:初始化、析构
//参数:
////////////////////////////////////////////////////////////////////////////////
initialization
Init;
finalization
Done;
end.
|
unit uGMV_SaveRestore;
interface
uses SysUtils, Forms, Dialogs;
procedure SaveWindowSettings(Form: TForm);
procedure RestoreWindowSettings(var Form: TForm);
implementation
uses uGMV_Common, uGMV_Const
, uGMV_Engine, system.UITypes;
procedure SaveWindowSettings(Form: TForm);
var
WindowSetting: string;
State: TWindowState;
s: String;
begin
State := Form.WindowState;
Form.WindowState := wsNormal;
Form.Visible := False;
WindowSetting :=
IntToStr(Screen.Width) + ';' +
IntToStr(Screen.Height) + ';' +
IntToStr(Form.Left) + ';' +
IntToStr(Form.Top) + ';' +
IntToStr(Form.Width) + ';' +
IntToStr(Form.Height) + ';' +
IntToStr(integer(State));
{
CallRemoteProc(RPCBroker, RPC_USER, ['SETPAR', Form.ClassName + '^' + WindowSetting]);
if Piece(RPCBroker.RemoteProcedure[0], '^', 1) = '-1' then
MessageDlg(
'Unable to set parameter ' + Form.ClassName + '.' + #13 +
'Error Message: ' + Piece(RPCBroker.RemoteProcedure[0], '^', 2), mtError, [mbOK], 0);
}
s := setUserSettings(Form.ClassName,WindowSetting);
if Piece(s,'^', 1) = '-1' then
MessageDlg('Unable to set parameter ' + Form.ClassName + '.' + #13 +
'Error Message: ' + Piece(s, '^', 2), mtError, [mbOK], 0);
end;
procedure RestoreWindowSettings(var Form: TForm);
var
WindowSetting: string;
begin
// CallRemoteProc(RPCBroker, RPC_USER, ['GETPAR', Form.ClassName]);
// WindowSetting := RPCBroker.Results[0];
WindowSetting := getUserSettings(Form.ClassName);
{Verify valid settings and same screen resolution}
if (WindowSetting = '') or
(StrToIntDef(Piece(WindowSetting, ';', 1), 0) <> Screen.Width) or
(StrToIntDef(Piece(WindowSetting, ';', 2), 0) <> Screen.Height) then
Form.Position := poScreenCenter
else
begin
Form.Position := poDesigned;
Form.Left := StrToIntDef(Piece(WindowSetting, ';', 3), Form.Left);
Form.Top := StrToIntDef(Piece(WindowSetting, ';', 4), Form.Top);
Form.Width := StrToIntDef(Piece(WindowSetting, ';', 5), Form.Width);
Form.Height := StrToIntDef(Piece(WindowSetting, ';', 6), Form.Height);
{Sanity checks to ensure form is completely visible}
if ((Form.Left + Form.Width) > Screen.Width) and (Form.Width <= Screen.Width) then
Form.Left := Screen.Width - Form.Width;
if ((Form.Top + Form.Height) > Screen.Height) and (Form.Height < Screen.Height) then
Form.Top := Screen.Height - Form.Height;
try
Form.WindowState := TWindowState(StrToIntDef(Piece(WindowSetting, ';', 7), 0));
except
end;
end;
end;
end.
|
unit uCI1580Device;
interface
uses
CPort, AssThreadTimer, Contnrs;
type
TCI1580CommandType = (cicmdNone,
cicmdWeight,
cicmdGetLowerLimitSP1,
cicmdGetUpperLimitSP2,
cicmdSetLowerLimitSP1,
cicmdSetUpperLimitSP2,
cicmdSetZero);
TCI1580Command = class
private
FCommand : TCI1580CommandType;
FValue : double;
public
property Command : TCI1580CommandType read FCommand write FCommand;
property Value : double read FValue write FValue;
end;
TCI1580Device = class
private
FCommandQueue : TObjectQueue;
FTimer : TAssThreadTimer;
FPort : TComPort;
FSendCommand : TCI1580CommandType;
FReadCompleted : boolean;
FLastSendTime : Int64;
FLastReadTime : Int64;
FCommunicationError : boolean;
FCommunicationTimeout : integer;
FReadData : string;
FStatus : string;
FWeightType : string;
FWeight : double;
FLowerLimitPV : double;
FUpperLimitPV : double;
FLowerLimitSV : double;
FUpperLimitSV : double;
procedure TimerTick(Sender: TObject);
procedure ComPortRxChar(Sender: TObject; Count: Integer);
procedure ParsingData(data : string);
function GetCommand(data : string) : TCI1580CommandType;
procedure ParsingWeight(data : string);
procedure ParsingGetLowerLimitSP1(data : string);
procedure ParsingGetUpperLimitSP2(data : string);
procedure ParsingSetLowerLimitSP1(data : string);
procedure ParsingSetUpperLimitSP2(data : string);
procedure SendCommand;
procedure PushCommand(command : TCI1580CommandType); overload;
procedure PushCommand(command : TCI1580CommandType; value : double); overload;
function PopCommand : TCI1580Command;
function GetPortNo: string;
procedure SetPortNo(const Value: string);
public
constructor Create;
destructor Destroy; override;
procedure Open;
procedure Close;
procedure SetLowerLimit(value : double);
procedure SetUpperLimit(value : double);
procedure SetZero;
property PortNo : string read GetPortNo write SetPortNo;
property Status : string read FStatus;
property WeightType : string read FWeightType;
property Weight : double read FWeight;
property LowerLimitPV : double read FLowerLimitPV;
property UpperLimitPV : double read FUpperLimitPV;
property LowerLimitSV : double read FLowerLimitSV;
property UpperLimitSV : double read FUpperLimitSV;
property CommunicationError : boolean read FCommunicationError;
property CommunicationTimeout : integer read FCommunicationTimeout write FCommunicationTimeout;
end;
implementation
uses
SysUtils, TypInfo, uPerformanceCounter;
{ TCI1580Device }
procedure TCI1580Device.PushCommand(command: TCI1580CommandType);
var
obj : TCI1580Command;
begin
obj := TCI1580Command.Create;
obj.Command := command;
FCommandQueue.Push(obj);
end;
procedure TCI1580Device.Close;
begin
FTimer.Enabled := False;
FPort.Close;
end;
procedure TCI1580Device.ComPortRxChar(Sender: TObject; Count: Integer);
const
DATA_LENGTH_LIMIT = 1000;
var
buffer : string;
stxPos, etxPos : integer;
validData : string;
begin
FLastReadTime := GetMillisecondsTick;
FCommunicationError := false;
TComPort(Sender).ReadStr(buffer, Count);
FReadData := FReadData + buffer;
if Length(FReadData) > DATA_LENGTH_LIMIT then
begin
FReadData := '';
exit;
end;
stxPos := Pos(#02, FReadData);
if stxPos = 0 then exit;
etxPos := Pos(#03, FReadData);
if etxPos = 0 then exit;
validData := Copy(FReadData, stxPos, etxPos - stxPos + 1);
ParsingData(validData);
FReadData := '';
end;
constructor TCI1580Device.Create;
begin
FCommunicationError := true;
CommunicationTimeout := 3000;
FCommandQueue := TObjectQueue.Create;
FSendCommand := cicmdWeight;
FTimer := TAssThreadTimer.Create(nil);
FTimer.Interval := 20;
FTimer.OnTimer := TimerTick;
FPort := TComPort.Create(nil);
FPort.BaudRate := br9600;
FPort.OnRxChar := ComPortRxChar;
FReadCompleted := false;
FLastSendTime := GetMillisecondsTick;
end;
destructor TCI1580Device.Destroy;
begin
FTimer.Free;
FPort.Free;
inherited;
end;
function TCI1580Device.GetCommand(data: string): TCI1580CommandType;
var
command : string;
len : integer;
begin
len := Length(data);
if len < 8 then
begin
result := cicmdNone;
exit;
end;
command := Copy(data, 4, 4);
if command = 'RCWT' then
result := cicmdWeight
else if command = 'RSP1' then
result := cicmdGetLowerLimitSP1
else if command = 'RSP2' then
result := cicmdGetUpperLimitSP2
else if command = 'WSP1' then
result := cicmdSetLowerLimitSP1
else if command = 'WSP2' then
result := cicmdSetUpperLimitSP2;
FReadCompleted := true;
end;
procedure TCI1580Device.Open;
begin
FPort.Open;
FTimer.Enabled := True;
end;
procedure TCI1580Device.ParsingData(data: string);
begin
case GetCommand(data) of
cicmdWeight :
ParsingWeight(data);
cicmdGetLowerLimitSP1 :
ParsingGetLowerLimitSP1(data);
cicmdGetUpperLimitSP2 :
ParsingGetUpperLimitSP2(data);
cicmdSetLowerLimitSP1 :
ParsingSetLowerLimitSP1(data);
cicmdSetUpperLimitSP2 :
ParsingSetUpperLimitSP2(data);
end;
end;
procedure TCI1580Device.ParsingWeight(data: string);
var
stringWeight : string;
begin
try
FStatus := Copy(data, 8, 2);
FWeightType := Copy(data, 10, 2);
stringWeight := Copy(data, 12, 8);
FWeight := StrToFloat(stringWeight);
except
end;
end;
procedure TCI1580Device.TimerTick(Sender: TObject);
var
currentCommandNo : integer;
begin
if (GetMillisecondsTick - FLastReadTime) > CommunicationTimeout then
begin
FCommunicationError := true;
end;
SendCommand;
if FCommandQueue.Count > 1 then exit;
currentCommandNo := Ord(FSendCommand);
currentCommandNo := currentCommandNo + 1;
if currentCommandNo > Ord(cicmdGetUpperLimitSP2) then
currentCommandNo := 1;
FSendCommand := TCI1580CommandType(currentCommandNo);
PushCommand(FSendCommand);
end;
function TCI1580Device.PopCommand : TCI1580Command;
var
obj : TCI1580Command;
begin
obj := TCI1580Command(FCommandQueue.Pop);
result := obj;
end;
procedure TCI1580Device.SendCommand;
const
RECEIVE_DATA_TIMEOUT = 2000;
var
commandObj : TCI1580Command;
command : string;
value : string;
begin
if FCommandQueue.Count < 1 then exit;
if FReadCompleted = false then
begin
if (GetMillisecondsTick - FLastSendTime) < RECEIVE_DATA_TIMEOUT then
exit;
end;
value := '';
commandObj := PopCommand;
case commandObj.Command of
cicmdWeight :
command := 'RCWT';
cicmdGetLowerLimitSP1 :
command := 'RSP1';
cicmdGetUpperLimitSP2 :
command := 'RSP2';
cicmdSetLowerLimitSP1 :
begin
command := 'WSP1';
value := Format('%.6d', [Trunc(commandObj.Value)]);
end;
cicmdSetUpperLimitSP2 :
begin
command := 'WSP2';
value := Format('%.6d', [Trunc(commandObj.Value)]);
end;
cicmdSetZero :
command := 'WZER';
end;
commandObj.Free;
FPort.WriteStr(#02 + '01' + command + value + #03);
FReadCompleted := false;
FLastSendTime := GetMillisecondsTick;
end;
function TCI1580Device.GetPortNo: string;
begin
result := FPort.Port;
end;
procedure TCI1580Device.SetPortNo(const Value: string);
begin
FPort.Port := Value;
end;
procedure TCI1580Device.ParsingGetLowerLimitSP1(data: string);
var
strValue : string;
begin
try
strValue := Copy(data, 8, 6);
FLowerLimitPV := StrToInt(strValue) * 0.01;
except
end;
end;
procedure TCI1580Device.ParsingGetUpperLimitSP2(data: string);
var
strValue : string;
begin
try
strValue := Copy(data, 8, 6);
FUpperLimitPV := StrToInt(strValue) * 0.01;
except
end;
end;
procedure TCI1580Device.ParsingSetLowerLimitSP1(data: string);
begin
// 커맨드만 되돌아 온다.
// 따라서 파싱할 필요가 없다.
end;
procedure TCI1580Device.ParsingSetUpperLimitSP2(data: string);
begin
// 커맨드만 되돌아 온다.
// 따라서 파싱할 필요가 없다.
end;
procedure TCI1580Device.SetLowerLimit(value: double);
var
temp : integer;
begin
temp := Trunc(value * 100);
FLowerLimitSV := value;
PushCommand(cicmdSetLowerLimitSP1, temp);
end;
procedure TCI1580Device.SetUpperLimit(value: double);
var
temp : integer;
begin
temp := Trunc(value * 100);
FUpperLimitSV := value;
PushCommand(cicmdSetUpperLimitSP2, temp);
end;
procedure TCI1580Device.PushCommand(command: TCI1580CommandType;
value: double);
var
obj : TCI1580Command;
begin
obj := TCI1580Command.Create;
obj.Command := command;
obj.Value := value;
FCommandQueue.Push(obj);
end;
procedure TCI1580Device.SetZero;
begin
PushCommand(cicmdSetZero, 0);
end;
end.
|
unit UnitAntivirus;
interface
uses
Windows, SysUtils, ActiveX, ComObj, Variants;
type
TSecurityCenterInfo = Class
displayName: string;
end;
TSecurityCenterProduct = (AntiVirusProduct, AntiSpywareProduct, FirewallProduct);
procedure GetSecInfo(SecurityCenterProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
implementation
const
WmiRoot='root';
WmiClassSCProduct : array [TSecurityCenterProduct] of string = ('AntiVirusProduct','AntiSpywareProduct','FirewallProduct');
WmiNamespaceSCProduct : array [Boolean] of string = ('SecurityCenter','SecurityCenter2');
procedure GetSCProductInfo(SCProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
osVerInfo : TOSVersionInfo;
begin
osVerInfo.dwOSVersionInfoSize:=SizeOf(TOSVersionInfo);
GetVersionEx(osVerInfo);
if (SCProduct=AntiSpywareProduct) and (osVerInfo.dwMajorVersion<6) then exit;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost',Format('%s\%s',[WmiRoot,WmiNamespaceSCProduct[osVerInfo.dwMajorVersion>=6]]), '', '');
FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM %s',[WmiClassSCProduct[SCProduct]]),'WQL',0);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
if osVerInfo.dwMajorVersion >= 6 then //windows vista or newer
SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '|' // String
else
begin
case SCProduct of
AntiVirusProduct: SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '| ';// String
FirewallProduct: SecurityCenterInfo.displayName := SecurityCenterInfo.displayName + Format('%s',[FWbemObject.displayName]) + '| ';//String
end;
end;
FWbemObject:=Unassigned;
end;
end;
procedure GetSecInfo(SecurityCenterProduct: TSecurityCenterProduct; var SecurityCenterInfo: TSecurityCenterInfo);
begin
try
CoInitialize(nil);
try GetSCProductInfo(SecurityCenterProduct, SecurityCenterInfo);
finally CoUninitialize;
end;
except
end;
end;
end.
|
unit App.Log;
interface
uses
System.TypInfo,
System.DateUtils,
System.Classes,
System.IOUtils,
System.SyncObjs,
System.SysUtils;
type
TLogStates = (lsStart, lsEnd, lsError, lsAllert, lsNormal);
TLogs = class
private
PathName: string;
Name: String;
LogFile: TextFile;
CriticalSection: TCriticalSection;
procedure DoLog(NameProc: string; State: TLogStates; Msg: string);
procedure Init(AName: string);
procedure CreateLogFile;
procedure CreateFolber;
public
constructor Create(AName: string);
procedure DoStartProcedure(NameProcedure: String = '');
procedure DoEndProcedure(NameProcedure: String = '');
procedure DoError(NameProc: string; Msg: string);
procedure DoAlert(NameProc: string; Msg: string);
destructor Destroy; override;
end;
var
LogFolberPath: string;
implementation
{ TWebServerLogs }
constructor TLogs.Create(AName: String);
begin
Init(AName);
Name := AName;
CriticalSection := TCriticalSection.Create;
CriticalSection.Leave;
end;
destructor TLogs.Destroy;
begin
CriticalSection.Release;
CriticalSection.Destroy;
end;
procedure TLogs.CreateFolber;
var
Apath: string;
begin
Apath := TPath.Combine(GetCurrentDir, 'Logs');
LogFolberPath := Apath;
TDirectory.CreateDirectory(LogFolberPath);
end;
procedure TLogs.CreateLogFile;
begin
Assign(LogFile, PathName);
Rewrite(LogFile);
Close(LogFile);
end;
procedure TLogs.DoAlert(NameProc, Msg: string);
begin
DoLog(NameProc,lsAllert,'Allert Message: ' + Msg);
end;
procedure TLogs.DoEndProcedure(NameProcedure: String);
begin
DoLog(NameProcedure,lsEnd,'End procedure');
end;
procedure TLogs.DoError(NameProc, Msg: string);
begin
DoLog(NameProc,lsError,'Error: ' + UpperCase(Msg));
end;
procedure TLogs.DoLog(NameProc: string; State: TLogStates; Msg: string);
var
Value: string;
begin
Value := '[' + IntToStr(TThread.CurrentThread.ThreadID) +']' +
'[' + DateTimeToStr(Now) + ']' +
'[' + NameProc + ']' +
'[' + GetEnumName(TypeInfo(TLogStates),Ord(State)) + ']' +
'[' + Msg + ']';
try
CriticalSection.Enter;
Assign(LogFile,PathName);
Append(LogFile);
Writeln(LogFIle,Value);
Close(LogFile);
finally
CriticalSection.Leave;
end;
end;
procedure TLogs.DoStartProcedure(NameProcedure: String);
begin
DoLog(NameProcedure,lsStart,'Start Procedure');
end;
procedure TLogs.Init(AName: string);
begin
if not TDirectory.Exists(LogFolberPath) then
CreateFolber;
PathName := TPath.Combine(LogFolberPath, AName);
if not TFile.Exists(PathName) then
CreateLogFile;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_RecastMeshDetail;
interface
uses
Math, SysUtils, RN_Helper, RN_Recast, RN_RecastMesh;
/// Builds a detail mesh from the provided polygon mesh.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] mesh A fully built polygon mesh.
/// @param[in] chf The compact heightfield used to build the polygon mesh.
/// @param[in] sampleDist Sets the distance to use when samping the heightfield. [Limit: >=0] [Units: wu]
/// @param[in] sampleMaxError The maximum distance the detail mesh surface should deviate from
/// heightfield data. [Limit: >=0] [Units: wu]
/// @param[out] dmesh The resulting detail mesh. (Must be pre-allocated.)
/// @returns True if the operation completed successfully.
function rcBuildPolyMeshDetail(ctx: TrcContext; const mesh: PrcPolyMesh; const chf: PrcCompactHeightfield;
const sampleDist, sampleMaxError: Single;
dmesh: PrcPolyMeshDetail): Boolean;
const RC_UNSET_HEIGHT = $ffff;
type
PrcHeightPatch = ^TrcHeightPatch;
TrcHeightPatch = record
data: PWord;
xmin, ymin, width, height: Integer;
end;
implementation
uses RN_RecastAlloc, RN_RecastHelper;
function vdot2(const a, b: PSingle): Single;
begin
Result := a[0]*b[0] + a[2]*b[2];
end;
function vdistSq2(const p,q: PSingle): Single;
var dx,dy: Single;
begin
dx := q[0] - p[0];
dy := q[2] - p[2];
Result := dx*dx + dy*dy;
end;
function vdist2(const p,q: PSingle): Single;
begin
Result := sqrt(vdistSq2(p,q));
end;
function vcross2(const p1,p2,p3: PSingle): Single;
var u1,v1,u2,v2: Single;
begin
u1 := p2[0] - p1[0];
v1 := p2[2] - p1[2];
u2 := p3[0] - p1[0];
v2 := p3[2] - p1[2];
Result := u1 * v2 - v1 * u2;
end;
function circumCircle(const p1,p2,p3: PSingle;
c: PSingle; r: PSingle): Boolean;
const EPS = 0.000001;
var v1,v2,v3: array [0..2] of Single; cp,v1Sq,v2Sq,v3Sq: Single;
begin
v1[0] := 0; v1[1] := 0; v1[2] := 0;
// Calculate the circle relative to p1, to avoid some precision issues.
rcVsub(@v2[0], p2, p1);
rcVsub(@v3[0], p3, p1);
cp := vcross2(@v1[0], @v2[0], @v3[0]);
if (abs(cp) > EPS) then
begin
v1Sq := vdot2(@v1[0],@v1[0]);
v2Sq := vdot2(@v2[0],@v2[0]);
v3Sq := vdot2(@v3[0],@v3[0]);
c[0] := (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp);
c[1] := 0;
c[2] := (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp);
r^ := vdist2(c, @v1[0]);
rcVadd(c, c, p1);
Exit(true);
end;
rcVcopy(c, p1);
r^ := 0;
Result := False;
end;
function distPtTri(const p,a,b,c: PSingle): Single;
const EPS = 0.0001;
var v0,v1,v2: array [0..2] of Single; dot00,dot01,dot02,dot11,dot12: Single; invDenom,u,v,y: Single;
begin
rcVsub(@v0[0], c,a);
rcVsub(@v1[0], b,a);
rcVsub(@v2[0], p,a);
dot00 := vdot2(@v0[0], @v0[0]);
dot01 := vdot2(@v0[0], @v1[0]);
dot02 := vdot2(@v0[0], @v2[0]);
dot11 := vdot2(@v1[0], @v1[0]);
dot12 := vdot2(@v1[0], @v2[0]);
// Compute barycentric coordinates
invDenom := 1.0 / (dot00 * dot11 - dot01 * dot01);
u := (dot11 * dot02 - dot01 * dot12) * invDenom;
v := (dot00 * dot12 - dot01 * dot02) * invDenom;
// If point lies inside the triangle, return interpolated y-coord.
if (u >= -EPS) and (v >= -EPS) and ((u+v) <= 1+EPS) then
begin
y := a[1] + v0[1]*u + v1[1]*v;
Exit(abs(y-p[1]));
end;
Result := MaxSingle;
end;
function distancePtSeg(const pt,p,q: PSingle): Single;
var pqx, pqy, pqz, dx, dy, dz, d, t: Single;
begin
pqx := q[0] - p[0];
pqy := q[1] - p[1];
pqz := q[2] - p[2];
dx := pt[0] - p[0];
dy := pt[1] - p[1];
dz := pt[2] - p[2];
d := pqx*pqx + pqy*pqy + pqz*pqz;
t := pqx*dx + pqy*dy + pqz*dz;
if (d > 0) then
t := t/d;
if (t < 0) then
t := 0
else if (t > 1) then
t := 1;
dx := p[0] + t*pqx - pt[0];
dy := p[1] + t*pqy - pt[1];
dz := p[2] + t*pqz - pt[2];
Result := dx*dx + dy*dy + dz*dz;
end;
function distancePtSeg2d(const pt,p,q: PSingle): Single;
var pqx, pqz, dx, dz, d, t: Single;
begin
pqx := q[0] - p[0];
pqz := q[2] - p[2];
dx := pt[0] - p[0];
dz := pt[2] - p[2];
d := pqx*pqx + pqz*pqz;
t := pqx*dx + pqz*dz;
if (d > 0) then
t := t/d;
if (t < 0) then
t := 0
else if (t > 1) then
t := 1;
dx := p[0] + t*pqx - pt[0];
dz := p[2] + t*pqz - pt[2];
Result := dx*dx + dz*dz;
end;
function distToTriMesh(const p: PSingle; const verts: PSingle; const nverts: Integer; const tris: PInteger; const ntris: Integer): Single;
var dmin,d: Single; i: Integer; va,vb,vc: PSingle;
begin
dmin := MaxSingle;
for i := 0 to ntris - 1 do
begin
va := @verts[tris[i*4+0]*3];
vb := @verts[tris[i*4+1]*3];
vc := @verts[tris[i*4+2]*3];
d := distPtTri(p, va,vb,vc);
if (d < dmin) then
dmin := d;
end;
if (dmin = MaxSingle) then Exit(-1);
Result := dmin;
end;
function distToPoly(nvert: Integer; verts: PSingle; p: PSingle): Single;
var dmin: Single; i,j,c: Integer; vi,vj: PSingle;
begin
dmin := MaxSingle;
c := 0;
i := 0;
j := nvert-1;
while (i < nvert) do
begin
vi := @verts[i*3];
vj := @verts[j*3];
if (((vi[2] > p[2]) <> (vj[2] > p[2])) and
(p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) then
c := not c;
dmin := rcMin(dmin, distancePtSeg2d(p, vj, vi));
j := i;
Inc(i);
end;
Result := IfThen(c <> 0, -dmin, dmin);
end;
function getHeight(const fx, fy, fz: Single;
const cs, ics, ch: Single;
const hp: PrcHeightPatch): Word;
const off: array [0..15] of Integer = (-1,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1);
var ix,iz,nx,nz: Integer; h,nh: Word; i: Integer; dmin,d: Single;
begin
ix := floor(fx*ics + 0.01);
iz := floor(fz*ics + 0.01);
ix := rcClamp(ix-hp.xmin, 0, hp.width - 1);
iz := rcClamp(iz-hp.ymin, 0, hp.height - 1);
h := hp.data[ix+iz*hp.width];
if (h = RC_UNSET_HEIGHT) then
begin
// Special case when data might be bad.
// Find nearest neighbour pixel which has valid height.
dmin := MaxSingle;
for i := 0 to 7 do
begin
nx := ix+off[i*2+0];
nz := iz+off[i*2+1];
if (nx < 0) or (nz < 0) or (nx >= hp.width) or (nz >= hp.height) then continue;
nh := hp.data[nx+nz*hp.width];
if (nh = RC_UNSET_HEIGHT) then continue;
d := abs(nh*ch - fy);
if (d < dmin) then
begin
h := nh;
dmin := d;
end;
end;
end;
Result := h;
end;
//enum EdgeValues
const
EV_UNDEF = -1;
EV_HULL = -2;
function findEdge(edges: PInteger; nedges, s, t: Integer): Integer;
var i: Integer; e: PInteger;
begin
for i := 0 to nedges - 1 do
begin
e := @edges[i*4];
if ((e[0] = s) and (e[1] = t)) or ((e[0] = t) and (e[1] = s)) then
Exit(i);
end;
Result := EV_UNDEF;
end;
function addEdge(ctx: TrcContext; edges: PInteger; nedges: PInteger; const maxEdges, s, t, l, r: Integer): Integer;
var e: Integer; edge: PInteger;
begin
if (nedges^ >= maxEdges) then
begin
ctx.log(RC_LOG_ERROR, Format('addEdge: Too many edges (%d/%d).', [nedges^, maxEdges]));
Exit(EV_UNDEF);
end;
// Add edge if not already in the triangulation.
e := findEdge(edges, nedges^, s, t);
if (e = EV_UNDEF) then
begin
edge := @edges[nedges^*4];
edge[0] := s;
edge[1] := t;
edge[2] := l;
edge[3] := r;
Result := nedges^;
Inc(nedges^);
end
else
begin
Result := EV_UNDEF;
end;
end;
procedure updateLeftFace(e: PInteger; s, t, f: Integer);
begin
if (e[0] = s) and (e[1] = t) and (e[2] = EV_UNDEF) then
e[2] := f
else if (e[1] = s) and (e[0] = t) and (e[3] = EV_UNDEF) then
e[3] := f;
end;
function overlapSegSeg2d(a,b,c,d: PSingle): Integer;
var a1,a2,a3,a4: Single;
begin
a1 := vcross2(a, b, d);
a2 := vcross2(a, b, c);
if (a1*a2 < 0.0) then
begin
a3 := vcross2(c, d, a);
a4 := a3 + a2 - a1;
if (a3 * a4 < 0.0) then
Exit(1);
end;
Result := 0;
end;
function overlapEdges(const pts: PSingle; const edges: PInteger; nedges, s1, t1: Integer): Boolean;
var i,s0,t0: Integer;
begin
for i := 0 to nedges - 1 do
begin
s0 := edges[i*4+0];
t0 := edges[i*4+1];
// Same or connected edges do not overlap.
if (s0 = s1) or (s0 = t1) or (t0 = s1) or (t0 = t1) then
continue;
if (overlapSegSeg2d(@pts[s0*3], @pts[t0*3], @pts[s1*3], @pts[t1*3]) <> 0) then
Exit(true);
end;
Result := false;
end;
procedure completeFacet(ctx: TrcContext; const pts: PSingle; npts: Integer; edges: PInteger; nedges: PInteger; const maxEdges: Integer; nfaces: PInteger; e: Integer);
const EPS = 0.00001;
var edge: PInteger; s,t,pt,u: Integer; c: array [0..2] of Single; r,d,tol: Single;
begin
edge := @edges[e*4];
// Cache s and t.
//int s,t;
if (edge[2] = EV_UNDEF) then
begin
s := edge[0];
t := edge[1];
end
else if (edge[3] = EV_UNDEF) then
begin
s := edge[1];
t := edge[0];
end
else
begin
// Edge already completed.
Exit;
end;
// Find best point on left of edge.
pt := npts;
c[0] := 0; c[1] := 0; c[2] := 0;
r := -1;
for u := 0 to npts - 1 do
begin
if (u = s) or (u = t) then continue;
if (vcross2(@pts[s*3], @pts[t*3], @pts[u*3]) > EPS) then
begin
if (r < 0) then
begin
// The circle is not updated yet, do it now.
pt := u;
circumCircle(@pts[s*3], @pts[t*3], @pts[u*3], @c[0], @r);
continue;
end;
d := vdist2(@c[0], @pts[u*3]);
tol := 0.001;
if (d > r*(1+tol)) then
begin
// Outside current circumcircle, skip.
continue;
end
else if (d < r*(1-tol)) then
begin
// Inside safe circumcircle, update circle.
pt := u;
circumCircle(@pts[s*3], @pts[t*3], @pts[u*3], @c[0], @r);
end
else
begin
// Inside epsilon circum circle, do extra tests to make sure the edge is valid.
// s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
if (overlapEdges(pts, edges, nedges^, s,u)) then
continue;
if (overlapEdges(pts, edges, nedges^, t,u)) then
continue;
// Edge is valid.
pt := u;
circumCircle(@pts[s*3], @pts[t*3], @pts[u*3], @c[0], @r);
end;
end;
end;
// Add new triangle or update edge info if s-t is on hull.
if (pt < npts) then
begin
// Update face information of edge being completed.
updateLeftFace(@edges[e*4], s, t, nfaces^);
// Add new edge or update face info of old edge.
e := findEdge(edges, nedges^, pt, s);
if (e = EV_UNDEF) then
addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces^, EV_UNDEF)
else
updateLeftFace(@edges[e*4], pt, s, nfaces^);
// Add new edge or update face info of old edge.
e := findEdge(edges, nedges^, t, pt);
if (e = EV_UNDEF) then
addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces^, EV_UNDEF)
else
updateLeftFace(@edges[e*4], t, pt, nfaces^);
Inc(nfaces^);
end
else
begin
updateLeftFace(@edges[e*4], s, t, EV_HULL);
end;
end;
procedure delaunayHull(ctx: TrcContext; const npts: Integer; const pts: PSingle;
const nhull: Integer; const hull: PInteger;
tris, edges: PrcIntArray);
var i,j,nfaces,nedges,maxEdges,currentEdge: Integer; e,t: PInteger;
begin
nfaces := 0;
nedges := 0;
maxEdges := npts*10;
edges.resize(maxEdges*4);
i := 0;
j := nhull-1;
while (i < nhull) do
begin
addEdge(ctx, @edges.m_data[0], @nedges, maxEdges, hull[j], hull[i], EV_HULL, EV_UNDEF);
j := i;
Inc(i);
end;
currentEdge := 0;
while (currentEdge < nedges) do
begin
if (edges^[currentEdge*4+2] = EV_UNDEF) then
completeFacet(ctx, pts, npts, @edges.m_data[0], @nedges, maxEdges, @nfaces, currentEdge);
if (edges^[currentEdge*4+3] = EV_UNDEF) then
completeFacet(ctx, pts, npts, @edges.m_data[0], @nedges, maxEdges, @nfaces, currentEdge);
Inc(currentEdge);
end;
// Create tris
tris.resize(nfaces*4);
for i := 0 to nfaces*4 - 1 do
tris^[i] := -1;
for i := 0 to nedges - 1 do
begin
e := @edges.m_data[i*4];
if (e[3] >= 0) then
begin
// Left face
t := @tris.m_data[e[3]*4];
if (t[0] = -1) then
begin
t[0] := e[0];
t[1] := e[1];
end
else if (t[0] = e[1]) then
t[2] := e[0]
else if (t[1] = e[0]) then
t[2] := e[1];
end;
if (e[2] >= 0) then
begin
// Right
t := @tris.m_data[e[2]*4];
if (t[0] = -1) then
begin
t[0] := e[1];
t[1] := e[0];
end
else if (t[0] = e[0]) then
t[2] := e[1]
else if (t[1] = e[1]) then
t[2] := e[0];
end;
end;
i := 0;
while(i < tris.size div 4) do
begin
t := @tris.m_data[i*4];
if (t[0] = -1) or (t[1] = -1) or (t[2] = -1) then
begin
ctx.log(RC_LOG_WARNING, Format('delaunayHull: Removing dangling face %d [%d,%d,%d].', [i, t[0], t[1], t[2]]));
t[0] := tris^[tris.size-4];
t[1] := tris^[tris.size-3];
t[2] := tris^[tris.size-2];
t[3] := tris^[tris.size-1];
tris.resize(tris.size-4);
Dec(i);
end;
Inc(i);
end;
end;
// Calculate minimum extend of the polygon.
function polyMinExtent(verts: PSingle; nverts: Integer): Single;
var minDist,maxEdgeDist,d: Single; i,j,ni: Integer; p1,p2: PSingle;
begin
minDist := MaxSingle;
for i := 0 to nverts - 1 do
begin
ni := (i+1) mod nverts;
p1 := @verts[i*3];
p2 := @verts[ni*3];
maxEdgeDist := 0;
for j := 0 to nverts - 1 do
begin
if (j = i) or (j = ni) then continue;
d := distancePtSeg2d(@verts[j*3], p1, p2);
maxEdgeDist := rcMax(maxEdgeDist, d);
end;
minDist := rcMin(minDist, maxEdgeDist);
end;
Result := Sqrt(minDist);
end;
// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
function next(i, n: Integer): Integer; begin Result := (i+1) mod n; end;
function prev(i, n: Integer): Integer; begin Result := (i+n-1) mod n; end;
procedure triangulateHull(const nverts: Integer; const verts: PSingle; const nhull: Integer; const hull: PInteger; tris: PrcIntArray);
var start,left,right: Integer; dmin,d: Single; i,pi,ni,nleft,nright: Integer; pv,cv,nv: PSingle; cvleft,nvleft,cvright,nvright: PSingle;
dleft,dright: Single;
begin
start := 0; left := 1; right := nhull-1;
// Start from an ear with shortest perimeter.
// This tends to favor well formed triangles as starting point.
dmin := 0;
for i := 0 to nhull - 1 do
begin
pi := prev(i, nhull);
ni := next(i, nhull);
pv := @verts[hull[pi]*3];
cv := @verts[hull[i]*3];
nv := @verts[hull[ni]*3];
d := vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);
if (d < dmin) then
begin
start := i;
left := ni;
right := pi;
dmin := d;
end;
end;
// Add first triangle
tris.push(hull[start]);
tris.push(hull[left]);
tris.push(hull[right]);
tris.push(0);
// Triangulate the polygon by moving left or right,
// depending on which triangle has shorter perimeter.
// This heuristic was chose emprically, since it seems
// handle tesselated straight edges well.
while (next(left, nhull) <> right) do
begin
// Check to see if se should advance left or right.
nleft := next(left, nhull);
nright := prev(right, nhull);
cvleft := @verts[hull[left]*3];
nvleft := @verts[hull[nleft]*3];
cvright := @verts[hull[right]*3];
nvright := @verts[hull[nright]*3];
dleft := vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);
dright := vdist2(cvright, nvright) + vdist2(cvleft, nvright);
if (dleft < dright) then
begin
tris.push(hull[left]);
tris.push(hull[nleft]);
tris.push(hull[right]);
tris.push(0);
left := nleft;
end
else
begin
tris.push(hull[left]);
tris.push(hull[nright]);
tris.push(hull[right]);
tris.push(0);
right := nright;
end;
end;
end;
function getJitterX(const i: Integer): Single;
begin
Result := (((i * $8da6b343) and $ffff) / 65535.0 * 2.0) - 1.0;
end;
function getJitterY(const i: Integer): Single;
begin
Result := (((i * $d8163841) and $ffff) / 65535.0 * 2.0) - 1.0;
end;
function buildPolyDetail(ctx: TrcContext; &in: PSingle; nin: Integer;
const sampleDist, sampleMaxError: Single;
const chf: PrcCompactHeightfield; const hp: PrcHeightPatch;
verts: PSingle; nverts: PInteger; tris: PrcIntArray;
edges, samples: PrcIntArray): Boolean;
const MAX_VERTS = 127;
MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).
MAX_VERTS_PER_EDGE = 32;
var edge: array [0..(MAX_VERTS_PER_EDGE+1)*3-1] of Single; hull: array [0..MAX_VERTS] of Integer; nhull: Integer;
i,j,k,m: Integer; cs,ics,minExtent: Single; vi,vj: PSingle; swapped: Boolean; dx,dy,dz,d: Single; nn: Integer; u: Single;
pos: PSingle; idx: array [0..MAX_VERTS_PER_EDGE-1] of Integer; nidx,a,b: Integer; va,vb: PSingle; maxd: Single; maxi: Integer;
dev: Single; bmin, bmax,pt,bestpt: array [0..2] of Single; x0,x1,z0,z1,x,z: Integer; nsamples,iter: Integer; bestd: Single;
besti,ntris: Integer; s: PInteger;
begin
nhull := 0;
nverts^ := 0;
for i := 0 to nin - 1 do
rcVcopy(@verts[i*3], @&in[i*3]);
nverts^ := nin;
edges.resize(0);
tris.resize(0);
cs := chf.cs;
ics := 1.0/cs;
// Calculate minimum extents of the polygon based on input data.
minExtent := polyMinExtent(verts, nverts^);
// Tessellate outlines.
// This is done in separate pass in order to ensure
// seamless height values across the ply boundaries.
if (sampleDist > 0) then
begin
i := 0; j := nin-1;
while (i < nin) do
begin
vj := @&in[j*3];
vi := @&in[i*3];
swapped := false;
// Make sure the segments are always handled in same order
// using lexological sort or else there will be seams.
if (abs(vj[0]-vi[0]) < 0.000001) then
begin
if (vj[2] > vi[2]) then
begin
rcSwap(vj,vi);
swapped := true;
end;
end
else
begin
if (vj[0] > vi[0]) then
begin
rcSwap(vj,vi);
swapped := true;
end;
end;
// Create samples along the edge.
dx := vi[0] - vj[0];
dy := vi[1] - vj[1];
dz := vi[2] - vj[2];
d := sqrt(dx*dx + dz*dz);
nn := 1 + floor(d/sampleDist);
if (nn >= MAX_VERTS_PER_EDGE) then nn := MAX_VERTS_PER_EDGE-1;
if (nverts^+nn >= MAX_VERTS) then
nn := MAX_VERTS-1-nverts^;
for k := 0 to nn do
begin
u := k/nn;
pos := @edge[k*3];
pos[0] := vj[0] + dx*u;
pos[1] := vj[1] + dy*u;
pos[2] := vj[2] + dz*u;
pos[1] := getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, hp)*chf.ch;
end;
// Simplify samples.
FillChar(idx[0], SizeOf(Integer) * MAX_VERTS_PER_EDGE, #0);
idx[0] := 0; idx[1] := nn;
nidx := 2;
k := 0;
while (k < nidx-1) do
begin
a := idx[k];
b := idx[k+1];
va := @edge[a*3];
vb := @edge[b*3];
// Find maximum deviation along the segment.
maxd := 0;
maxi := -1;
for m := a+1 to b - 1 do
begin
dev := distancePtSeg(@edge[m*3],va,vb);
if (dev > maxd) then
begin
maxd := dev;
maxi := m;
end;
end;
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (maxi <> -1) and (maxd > Sqr(sampleMaxError)) then
begin
for m := nidx downto k + 1 do
idx[m] := idx[m-1];
idx[k+1] := maxi;
Inc(nidx);
end
else
begin
Inc(k);
end;
end;
hull[nhull] := j;
Inc(nhull);
// Add new vertices.
if (swapped) then
begin
for k := nidx-2 downto 1 do
begin
rcVcopy(@verts[nverts^*3], @edge[idx[k]*3]);
hull[nhull] := nverts^;
Inc(nhull);
Inc(nverts^);
end;
end
else
begin
for k := 1 to nidx-1 - 1 do
begin
rcVcopy(@verts[nverts^*3], @edge[idx[k]*3]);
hull[nhull] := nverts^;
Inc(nhull);
Inc(nverts^);
end;
end;
j := i;
Inc(i);
end;
end;
// If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.
if (minExtent < sampleDist*2) then
begin
triangulateHull(nverts^, verts, nhull, @hull[0], tris);
Exit(true);
end;
// Tessellate the base mesh.
// We're using the triangulateHull instead of delaunayHull as it tends to
// create a bit better triangulation for long thing triangles when there
// are no internal points.
triangulateHull(nverts^, verts, nhull, @hull[0], tris);
if (tris.size = 0) then
begin
// Could not triangulate the poly, make sure there is some valid data there.
ctx.log(RC_LOG_WARNING, Format('buildPolyDetail: Could not triangulate polygon (%d verts).', [nverts^]));
Exit(true);
end;
if (sampleDist > 0) then
begin
// Create sample locations in a grid.
rcVcopy(@bmin[0], @&in[0]);
rcVcopy(@bmax[0], @&in[0]);
for i := 1 to nin - 1 do
begin
rcVmin(@bmin[0], @&in[i*3]);
rcVmax(@bmax[0], @&in[i*3]);
end;
x0 := floor(bmin[0]/sampleDist);
x1 := ceil(bmax[0]/sampleDist);
z0 := floor(bmin[2]/sampleDist);
z1 := ceil(bmax[2]/sampleDist);
samples.resize(0);
for z := z0 to z1 - 1 do
begin
for x := x0 to x1 - 1 do
begin
pt[0] := x*sampleDist;
pt[1] := (bmax[1]+bmin[1])*0.5;
pt[2] := z*sampleDist;
// Make sure the samples are not too close to the edges.
if (distToPoly(nin,&in,@pt[0]) > -sampleDist/2) then continue;
samples.push(x);
samples.push(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, hp));
samples.push(z);
samples.push(0); // Not added
end;
end;
// Add the samples starting from the one that has the most
// error. The procedure stops when all samples are added
// or when the max error is within treshold.
nsamples := samples.size div 4;
for iter := 0 to nsamples - 1 do
begin
if (nverts^ >= MAX_VERTS) then
break;
// Find sample with most error.
bestpt[0] := 0; bestpt[1] := 0; bestpt[2] := 0;
bestd := 0;
besti := -1;
for i := 0 to nsamples - 1 do
begin
s := @samples.m_data[i*4];
if (s[3] <> 0) then continue; // skip added.
// The sample location is jittered to get rid of some bad triangulations
// which are cause by symmetrical data from the grid structure.
pt[0] := s[0]*sampleDist + getJitterX(i)*cs*0.1;
pt[1] := s[1]*chf.ch;
pt[2] := s[2]*sampleDist + getJitterY(i)*cs*0.1;
d := distToTriMesh(@pt[0], verts, nverts^, @tris.m_data[0], tris.size div 4);
if (d < 0) then continue; // did not hit the mesh.
if (d > bestd) then
begin
bestd := d;
besti := i;
rcVcopy(@bestpt[0],@pt[0]);
end;
end;
// If the max error is within accepted threshold, stop tesselating.
if (bestd <= sampleMaxError) or (besti = -1) then
break;
// Mark sample as added.
samples^[besti*4+3] := 1;
// Add the new sample point.
rcVcopy(@verts[nverts^*3], @bestpt[0]);
Inc(nverts^);
// Create new triangulation.
// TODO: Incremental add instead of full rebuild.
edges.resize(0);
tris.resize(0);
delaunayHull(ctx, nverts^, verts, nhull, @hull[0], tris, edges);
end;
end;
ntris := tris.size div 4;
if (ntris > MAX_TRIS) then
begin
tris.resize(MAX_TRIS*4);
ctx.log(RC_LOG_ERROR, Format('rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.', [ntris, MAX_TRIS]));
end;
Result := true;
end;
procedure getHeightDataSeedsFromVertices(const chf: PrcCompactHeightfield;
const poly: PWord; const npoly: Integer;
const verts: PWord; const bs: Integer;
hp: PrcHeightPatch; stack: PrcIntArray);
const offset: array [0..9*2-1] of Integer = (0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0);
var i,j,k,cx,cy,cz,ci,dmin,ax,ay,az,d,idx: Integer; c: PrcCompactCell; s,cs: PrcCompactSpan; pcx,pcz,dir,ai: Integer;
begin
// Floodfill the heightfield to get 2D height data,
// starting at vertex locations as seeds.
// Note: Reads to the compact heightfield are offset by border size (bs)
// since border size offset is already removed from the polymesh vertices.
FillChar(hp.data[0], sizeof(Word)*hp.width*hp.height, 0);
stack.resize(0);
// Use poly vertices as seed points for the flood fill.
for j := 0 to npoly - 1 do
begin
cx := 0; cz := 0; ci := -1;
dmin := RC_UNSET_HEIGHT;
for k := 0 to 8 do
begin
ax := verts[poly[j]*3+0] + offset[k*2+0];
ay := verts[poly[j]*3+1];
az := verts[poly[j]*3+2] + offset[k*2+1];
if (ax < hp.xmin) or (ax >= hp.xmin+hp.width) or
(az < hp.ymin) or (az >= hp.ymin+hp.height) then
continue;
c := @chf.cells[(ax+bs)+(az+bs)*chf.width];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
d := Abs(ay - s.y);
if (d < dmin) then
begin
cx := ax;
cz := az;
ci := i;
dmin := d;
end;
end;
end;
if (ci <> -1) then
begin
stack.push(cx);
stack.push(cz);
stack.push(ci);
end;
end;
// Find center of the polygon using flood fill.
pcx := 0; pcz := 0;
for j := 0 to npoly - 1 do
begin
Inc(pcx, verts[poly[j]*3+0]);
Inc(pcz, verts[poly[j]*3+2]);
end;
pcx := pcx div npoly;
pcz := pcz div npoly;
for i := 0 to stack.size div 3 - 1 do
begin
cx := stack^[i*3+0];
cy := stack^[i*3+1];
idx := cx-hp.xmin+(cy-hp.ymin)*hp.width;
hp.data[idx] := 1;
end;
while (stack.size > 0) do
begin
ci := stack.pop();
cy := stack.pop();
cx := stack.pop();
// Check if close to center of the polygon.
if (Abs(cx-pcx) <= 1) and (Abs(cy-pcz) <= 1) then
begin
stack.resize(0);
stack.push(cx);
stack.push(cy);
stack.push(ci);
break;
end;
cs := @chf.spans[ci];
for dir := 0 to 3 do
begin
if (rcGetCon(cs, dir) = RC_NOT_CONNECTED) then continue;
ax := cx + rcGetDirOffsetX(dir);
ay := cy + rcGetDirOffsetY(dir);
if (ax < hp.xmin) or (ax >= (hp.xmin+hp.width)) or
(ay < hp.ymin) or (ay >= (hp.ymin+hp.height)) then
continue;
if (hp.data[ax-hp.xmin+(ay-hp.ymin)*hp.width] <> 0) then
continue;
ai := chf.cells[(ax+bs)+(ay+bs)*chf.width].index + rcGetCon(cs, dir);
idx := ax-hp.xmin+(ay-hp.ymin)*hp.width;
hp.data[idx] := 1;
stack.push(ax);
stack.push(ay);
stack.push(ai);
end;
end;
FillChar(hp.data[0], sizeof(Word)*hp.width*hp.height, $ff);
// Mark start locations.
for i := 0 to stack.size div 3 - 1 do
begin
cx := stack^[i*3+0];
cy := stack^[i*3+1];
ci := stack^[i*3+2];
idx := cx-hp.xmin+(cy-hp.ymin)*hp.width;
cs := @chf.spans[ci];
hp.data[idx] := cs.y;
// getHeightData seeds are given in coordinates with borders
stack^[i+0] := stack^[i+0] + bs;
stack^[i+1] := stack^[i+1] + bs;
end;
end;
procedure getHeightData(chf: PrcCompactHeightfield;
const poly: PWord; const npoly: Integer;
const verts: PWord; const bs: Integer;
hp: PrcHeightPatch; stack: PrcIntArray;
region: Integer);
const RETRACT_SIZE = 256;
var empty: Boolean; hy,hx,y,x,i,dir: Integer; c: PrcCompactCell; s: PrcCompactSpan; border: Boolean; ax,ay,ai: Integer;
&as,cs: PrcCompactSpan; head: Integer; cx,cy,ci: Integer;
begin
// Note: Reads to the compact heightfield are offset by border size (bs)
// since border size offset is already removed from the polymesh vertices.
stack.resize(0);
FillChar(hp.data[0], sizeof(Word)*hp.width*hp.height, $ff);
empty := true;
// Copy the height from the same region, and mark region borders
// as seed points to fill the rest.
for hy := 0 to hp.height - 1 do
begin
y := hp.ymin + hy + bs;
for hx := 0 to hp.width - 1 do
begin
x := hp.xmin + hx + bs;
c := @chf.cells[x+y*chf.width];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
if (s.reg = region) then
begin
// Store height
hp.data[hx + hy*hp.width] := s.y;
empty := false;
// If any of the neighbours is not in same region,
// add the current location as flood fill start
border := false;
for dir := 0 to 3 do
begin
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
&as := @chf.spans[ai];
if (&as.reg <> region) then
begin
border := true;
break;
end;
end;
end;
if (border) then
begin
stack.push(x);
stack.push(y);
stack.push(i);
end;
break;
end;
end;
end;
end;
// if the polygon does not contian any points from the current region (rare, but happens)
// then use the cells closest to the polygon vertices as seeds to fill the height field
if (empty) then
getHeightDataSeedsFromVertices(chf, poly, npoly, verts, bs, hp, stack);
//static const int RETRACT_SIZE := 256;
head := 0;
while (head*3 < stack.size) do
begin
cx := stack^[head*3+0];
cy := stack^[head*3+1];
ci := stack^[head*3+2];
Inc(head);
if (head >= RETRACT_SIZE) then
begin
head := 0;
if (stack.size > RETRACT_SIZE*3) then
Move(stack^.m_data[RETRACT_SIZE*3], stack^.m_data[0], sizeof(integer)*(stack.size-RETRACT_SIZE*3));
stack.resize(stack.size-RETRACT_SIZE*3);
end;
cs := @chf.spans[ci];
for dir := 0 to 3 do
begin
if (rcGetCon(cs, dir) = RC_NOT_CONNECTED) then continue;
ax := cx + rcGetDirOffsetX(dir);
ay := cy + rcGetDirOffsetY(dir);
hx := ax - hp.xmin - bs;
hy := ay - hp.ymin - bs;
if (hx < 0) or (hx >= hp.width) or (hy < 0) or (hy >= hp.height) then
continue;
if (hp.data[hx + hy*hp.width] <> RC_UNSET_HEIGHT) then
continue;
ai := chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);
&as := @chf.spans[ai];
hp.data[hx + hy*hp.width] := &as.y;
stack.push(ax);
stack.push(ay);
stack.push(ai);
end;
end;
end;
function getEdgeFlags(const va, vb: PSingle;
const vpoly: PSingle; const npoly: Integer): Byte;
const thrSqr = 0.000001;
var i,j: Integer;
begin
// Return true if edge (va,vb) is part of the polygon.
i := 0;
j := npoly-1;
while(i < npoly) do
begin
if (distancePtSeg2d(va, @vpoly[j*3], @vpoly[i*3]) < thrSqr) and
(distancePtSeg2d(vb, @vpoly[j*3], @vpoly[i*3]) < thrSqr) then
Exit(1);
j := i;
Inc(i);
end;
Result := 0;
end;
function getTriFlags(const va, vb, vc: PSingle;
const vpoly: PSingle; const npoly: Integer): Byte;
var flags: Byte;
begin
flags := 0;
flags := flags or getEdgeFlags(va,vb,vpoly,npoly) shl 0;
flags := flags or getEdgeFlags(vb,vc,vpoly,npoly) shl 2;
flags := flags or getEdgeFlags(vc,va,vpoly,npoly) shl 4;
Result := flags;
end;
/// @par
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig
function rcBuildPolyMeshDetail(ctx: TrcContext; const mesh: PrcPolyMesh; const chf: PrcCompactHeightfield;
const sampleDist, sampleMaxError: Single;
dmesh: PrcPolyMeshDetail): Boolean;
var nvp,borderSize: Integer; cs,ch: Single; orig: PSingle; edges,tris,stack,samples: TrcIntArray; verts: array [0..256*3-1] of Single;
hp: TrcHeightPatch; nPolyVerts,maxhw,maxhh: Integer; bounds: PInteger; poly: PSingle; i,j: Integer; xmin,xmax,ymin,ymax: PInteger;
p,v: PWord; vcap,tcap,npoly,nverts,ntris: Integer; newv: PSingle; newt: PByte; t: PInteger;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_POLYMESHDETAIL);
if (mesh.nverts = 0) or (mesh.npolys = 0) then
begin
Result :=true;
Exit;
end;
nvp := mesh.nvp;
cs := mesh.cs;
ch := mesh.ch;
orig := @mesh.bmin[0];
borderSize := mesh.borderSize;
edges.Create(64);
tris.Create(512);
stack.Create(512);
samples.Create(512);
//float verts[256*3];
//rcHeightPatch hp;
nPolyVerts := 0;
maxhw := 0; maxhh := 0;
GetMem(bounds, sizeof(integer)*mesh.npolys*4);
GetMem(poly, sizeof(Single)*nvp*3);
// Find max size for a polygon area.
for i := 0 to mesh.npolys - 1 do
begin
p := @mesh.polys[i*nvp*2];
xmin := @bounds[i*4+0];
xmax := @bounds[i*4+1];
ymin := @bounds[i*4+2];
ymax := @bounds[i*4+3];
xmin^ := chf.width;
xmax^ := 0;
ymin^ := chf.height;
ymax^ := 0;
for j := 0 to nvp - 1 do
begin
if(p[j] = RC_MESH_NULL_IDX) then break;
v := @mesh.verts[p[j]*3];
xmin^ := rcMin(xmin^, v[0]);
xmax^ := rcMax(xmax^, v[0]);
ymin^ := rcMin(ymin^, v[2]);
ymax^ := rcMax(ymax^, v[2]);
Inc(nPolyVerts);
end;
xmin^ := rcMax(0,xmin^-1);
xmax^ := rcMin(chf.width,xmax^+1);
ymin^ := rcMax(0,ymin^-1);
ymax^ := rcMin(chf.height,ymax^+1);
if (xmin^ >= xmax^) or (ymin^ >= ymax^) then continue;
maxhw := rcMax(maxhw, xmax^-xmin^);
maxhh := rcMax(maxhh, ymax^-ymin^);
end;
GetMem(hp.data, sizeof(Word)*maxhw*maxhh);
dmesh.nmeshes := mesh.npolys;
dmesh.nverts := 0;
dmesh.ntris := 0;
GetMem(dmesh.meshes, sizeof(Cardinal)*dmesh.nmeshes*4);
vcap := nPolyVerts+nPolyVerts div 2;
tcap := vcap*2;
dmesh.nverts := 0;
GetMem(dmesh.verts, sizeof(Single)*vcap*3);
dmesh.ntris := 0;
GetMem(dmesh.tris, sizeof(Byte)*tcap*4);
for i := 0 to mesh.npolys - 1 do
begin
p := @mesh.polys[i*nvp*2];
// Store polygon vertices for processing.
npoly := 0;
for j := 0 to nvp - 1 do
begin
if(p[j] = RC_MESH_NULL_IDX) then break;
v := @mesh.verts[p[j]*3];
poly[j*3+0] := v[0]*cs;
poly[j*3+1] := v[1]*ch;
poly[j*3+2] := v[2]*cs;
Inc(npoly);
end;
// Get the height data from the area of the polygon.
hp.xmin := bounds[i*4+0];
hp.ymin := bounds[i*4+2];
hp.width := bounds[i*4+1]-bounds[i*4+0];
hp.height := bounds[i*4+3]-bounds[i*4+2];
getHeightData(chf, p, npoly, mesh.verts, borderSize, @hp, @stack, mesh.regs[i]);
// Build detail mesh.
nverts := 0;
if (not buildPolyDetail(ctx, poly, npoly,
sampleDist, sampleMaxError,
chf, @hp, @verts[0], @nverts, @tris,
@edges, @samples)) then
begin
Exit(false);
end;
// Move detail verts to world space.
for j := 0 to nverts - 1 do
begin
verts[j*3+0] := verts[j*3+0] + orig[0];
verts[j*3+1] := verts[j*3+1] + orig[1] + chf.ch; // Is this offset necessary?
verts[j*3+2] := verts[j*3+2] + orig[2];
end;
// Offset poly too, will be used to flag checking.
for j := 0 to npoly - 1 do
begin
poly[j*3+0] := poly[j*3+0] + orig[0];
poly[j*3+1] := poly[j*3+1] + orig[1];
poly[j*3+2] := poly[j*3+2] + orig[2];
end;
// Store detail submesh.
ntris := tris.size div 4;
dmesh.meshes[i*4+0] := dmesh.nverts;
dmesh.meshes[i*4+1] := nverts;
dmesh.meshes[i*4+2] := dmesh.ntris;
dmesh.meshes[i*4+3] := ntris;
// Store vertices, allocate more memory if necessary.
if (dmesh.nverts+nverts > vcap) then
begin
while (dmesh.nverts+nverts > vcap) do
Inc(vcap, 256);
GetMem(newv, sizeof(Single)*vcap*3);
if (dmesh.nverts <> 0) then
Move(dmesh.verts^, newv^, sizeof(Single)*3*dmesh.nverts);
FreeMem(dmesh.verts);
dmesh.verts := newv;
end;
for j := 0 to nverts - 1 do
begin
dmesh.verts[dmesh.nverts*3+0] := verts[j*3+0];
dmesh.verts[dmesh.nverts*3+1] := verts[j*3+1];
dmesh.verts[dmesh.nverts*3+2] := verts[j*3+2];
Inc(dmesh.nverts);
end;
// Store triangles, allocate more memory if necessary.
if (dmesh.ntris+ntris > tcap) then
begin
while (dmesh.ntris+ntris > tcap) do
Inc(tcap, 256);
GetMem(newt, sizeof(Byte)*tcap*4);
if (dmesh.ntris <> 0) then
Move(dmesh.tris^, newt^, sizeof(Byte)*4*dmesh.ntris);
FreeMem(dmesh.tris);
dmesh.tris := newt;
end;
for j := 0 to ntris - 1 do
begin
t := @tris.m_data[j*4];
dmesh.tris[dmesh.ntris*4+0] := Byte(t[0]);
dmesh.tris[dmesh.ntris*4+1] := Byte(t[1]);
dmesh.tris[dmesh.ntris*4+2] := Byte(t[2]);
dmesh.tris[dmesh.ntris*4+3] := getTriFlags(@verts[t[0]*3], @verts[t[1]*3], @verts[t[2]*3], poly, npoly);
Inc(dmesh.ntris);
end;
end;
FreeMem(bounds);
FreeMem(poly);
// Delphi: Manually release record and buffer it holds within
edges.Free;
tris.Free;
stack.Free;
samples.Free;
ctx.stopTimer(RC_TIMER_BUILD_POLYMESHDETAIL);
Result := true;
end;
{/// @see rcAllocPolyMeshDetail, rcPolyMeshDetail
bool rcMergePolyMeshDetails(ctx: TrcContext; rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)
begin
rcAssert(ctx);
ctx.startTimer(RC_TIMER_MERGE_POLYMESHDETAIL);
int maxVerts := 0;
int maxTris := 0;
int maxMeshes := 0;
for (int i := 0; i < nmeshes; ++i)
begin
if (!meshes[i]) continue;
maxVerts += meshes[i].nverts;
maxTris += meshes[i].ntris;
maxMeshes += meshes[i].nmeshes;
end;
mesh.nmeshes := 0;
mesh.meshes := (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);
if (!mesh.meshes)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).', maxMeshes*4);
return false;
end;
mesh.ntris := 0;
mesh.tris := (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);
if (!mesh.tris)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).', maxTris*4);
return false;
end;
mesh.nverts := 0;
mesh.verts := (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);
if (!mesh.verts)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).', maxVerts*3);
return false;
end;
// Merge datas.
for (int i := 0; i < nmeshes; ++i)
begin
rcPolyMeshDetail* dm := meshes[i];
if (!dm) continue;
for (int j := 0; j < dm.nmeshes; ++j)
begin
unsigned int* dst := &mesh.meshes[mesh.nmeshes*4];
unsigned int* src := &dm.meshes[j*4];
dst[0] := (unsigned int)mesh.nverts+src[0];
dst[1] := src[1];
dst[2] := (unsigned int)mesh.ntris+src[2];
dst[3] := src[3];
mesh.nmeshes++;
end;
for (int k := 0; k < dm.nverts; ++k)
begin
rcVcopy(&mesh.verts[mesh.nverts*3], &dm.verts[k*3]);
mesh.nverts++;
end;
for (int k := 0; k < dm.ntris; ++k)
begin
mesh.tris[mesh.ntris*4+0] := dm.tris[k*4+0];
mesh.tris[mesh.ntris*4+1] := dm.tris[k*4+1];
mesh.tris[mesh.ntris*4+2] := dm.tris[k*4+2];
mesh.tris[mesh.ntris*4+3] := dm.tris[k*4+3];
mesh.ntris++;
end;
end;
ctx.stopTimer(RC_TIMER_MERGE_POLYMESHDETAIL);
return true;
end;}
end. |
unit Model.Pizza;
interface
uses
Model.Interfaces, FMX.Graphics, iORM.Attributes;
type
[ioEntity, diImplements(IPizza)]
TPizza = class(TInterfacedObject, IPizza)
private
FID: Integer;
FName: String;
FPrice: Currency;
FPhoto: TBitMap;
function GetID: Integer;
function GetName: String;
function GetPrice: Currency;
function GetPhoto: TBitMap;
procedure SetID(const Value: Integer);
procedure SetName(const Value: String);
procedure SetPrice(const Value: Currency);
procedure SetPhoto(const Value: TBitMap);
public
constructor Create;
destructor Destroy; override;
property ID:Integer read GetID write SetID;
property Name:String read GetName write SetName;
property Photo:TBitMap read GetPhoto write SetPhoto;
property Price:Currency read GetPrice write SetPrice;
end;
implementation
{ TPizza }
constructor TPizza.Create;
begin
FPhoto := TBitMap.Create;
end;
destructor TPizza.Destroy;
begin
FPhoto.Free;
inherited;
end;
function TPizza.GetID: Integer;
begin
Result := FID;
end;
function TPizza.GetName: String;
begin
Result := FName;
end;
function TPizza.GetPhoto: TBitMap;
begin
Result := FPhoto;
end;
function TPizza.GetPrice: Currency;
begin
Result := FPrice;
end;
procedure TPizza.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TPizza.SetName(const Value: String);
begin
FName := Value;
end;
procedure TPizza.SetPhoto(const Value: TBitMap);
begin
FPhoto := Value;
end;
procedure TPizza.SetPrice(const Value: Currency);
begin
FPrice := Value;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLFileGRD<p>
GRD (Grid Text Format) vector file format implementation.<p>
<b>History :</b><font size=-1><ul>
<li>01/05/15 - PW - Fixed LoadFromStream procedure
<li>10/04/09 - PW - Separated from GLVectorFileObjects.pas
<li>10/04/09 - Aaron Hochwimmer - Added support for Surfer ASCII grd format
<li>26/10/00 - Phil Scadden - created import of Arcinfo ASCII grd format
</ul></font>
}
unit GLFileGRD;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
// GLS
GLVectorGeometry, GLVectorTypes, GLVectorFileObjects,
GLApplicationFileIO, GLGraph;
type
// TGLGRDVectorFile
//
{ : The GRD file represents ascii grid formats in 2D/3D.<p>
This is a format for storing regular grid values as a
matrices of cell centers. The format supports variations and
subformats. This importer works for Sutfer, ArcInfo and GMS formats }
TGLGRDVectorFile = class(TVectorFile)
public
{ Public Declarations }
HeightField: TGLHeightField;
Nodes: array of TSingleArray;
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
private
StrVal: String;
StrLine: String;
MaxZ: Single;
function ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
function WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ TGLGRDVectorFile ------------------
// ------------------
const
dSURFBLANKVAL = 1.70141E38; // default value in Surfer for blanking
NODATA_value = -9999; // default value in GIS ArcInfo for blanking
// Capabilities
//
class function TGLGRDVectorFile.Capabilities: TDataFileCapabilities;
begin
Result := [dfcRead];
end;
function TGLGRDVectorFile.WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while ((I <= Length(S)) and (Count <> N)) do
begin
// skip over delimiters
while (I <= Length(S)) and CharInSet(S[I], WordDelims) do
Inc(I);
// if we're not beyond end of S, we're at the start of a word
if I <= Length(S) then
Inc(Count);
// if not finished, find the end of the current word
if Count <> N then
while (I <= Length(S)) and not CharInSet(S[I], WordDelims) do
Inc(I)
else
Result := I;
end;
end;
// ExtractWord
//
function TGLGRDVectorFile.ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
var
I, Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if (I <> 0) then
// find the end of the current word
while (I <= Length(S)) and not CharInSet(S[I], WordDelims) do
begin
// add the I'th character to result
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
SetLength(Result, Len);
end;
// LoadFromStream
//
procedure TGLGRDVectorFile.LoadFromStream(aStream: TStream);
var
I, J, K: Integer;
N: Integer; // N => counter to increment through file
Sl, Tl: TStringList;
Nx, Ny: Integer;
Dx, Dy: Single;
Xo, Xe, Yo, Ye, Zo, Ze: Single;
NBlanks: Integer; // Number of blank nodes
BlankVal, NoData: Double;
{ sub } function ReadLine: string;
begin
Result := Sl[N];
Inc(N);
end;
begin
Sl := TStringList.Create;
Tl := TStringList.Create;
try
Sl.LoadFromStream(aStream);
if (Copy(Sl[0], 1, 4) <> 'DSAA') and (Copy(Sl[0], 1, 5) <> 'ncols') then
begin
raise Exception.Create('Not a valid grd file !');
Exit;
end;
HeightField := TGLHeightField.Create(Owner);
Zo := 3 * 10E38; // Low
Ze := -3 * 10E38; // High
Tl.DelimitedText := Copy(ReadLine, 1, 4);
if (Tl[0] = 'DSAA') then // Surfer ASCII grid
begin
Tl.DelimitedText := ReadLine;
Nx := StrToInt(Tl[0]);
Ny := StrToInt(Tl[1]);
Tl.DelimitedText := ReadLine;
Xo := StrToFloat(Tl[0]);
Xe := StrToFloat(Tl[1]);
Tl.DelimitedText := ReadLine;
Yo := StrToFloat(Tl[0]);
Ye := StrToFloat(Tl[1]);
Tl.DelimitedText := ReadLine;
Zo := StrToFloat(Tl[0]);
Ze := StrToFloat(Tl[1]);
Dx := (Xe - Xo) / Nx;
Dy := (Ye - Yo) / Ny;
SetLength(Nodes, Ny, Nx);
NBlanks := 0;
BlankVal := dSURFBLANKVAL;
NoData := BlankVal; // NoData value
// loop over the Ny-1 Rows
for I := 0 to Ny - 1 do
begin
J := 0;
// reading lines until Nx-1 Cols entries have been obtained
while J <= Nx - 1 do
begin
StrLine := ReadLine;
K := 1;
StrVal := ExtractWord(K, StrLine, [' ']);
while (StrVal <> '') do
begin
if (J <= Nx - 1) then
Nodes[I, J] := StrToFloat(StrVal);
if Nodes[I, J] > MaxZ then
MaxZ := Nodes[I, J];
if (Nodes[I, J] >= BlankVal) then
NBlanks := NBlanks + 1;
Inc(J);
Inc(K);
StrVal := ExtractWord(K, StrLine, [' ']);
end;
if (J > Nx - 1) then
Break;
end;
end
end
else // ArcInfo ASCII grid
begin
Tl.DelimitedText := Sl[0];
Ny := StrToInt(Tl[1]); // ncols
Tl.DelimitedText := Sl[1];
Nx := StrToInt(Tl[1]); // nrows
Tl.DelimitedText := Sl[2];
Xo := StrToFloat(Tl[1]); // xllcorner
Tl.DelimitedText := Sl[3];
Yo := StrToFloat(Tl[1]); // yllcorner
Tl.DelimitedText := Sl[4];
Dx := StrToFloat(Tl[1]);
Dy := Dx; // cellsize
Tl.DelimitedText := Sl[5];
NoData := StrToFloat(Tl[1]); // NoData value
MaxZ := -3 * 10E38;
SetLength(Nodes, Nx, Ny);
for I := 0 to Nx - 1 do
begin
Tl.DelimitedText := Sl[I + 6];
for J := 0 to Ny - 1 do
begin
StrVal := Tl[J];
Nodes[I, J] := StrToFloat(StrVal);
if Nodes[I, J] > MaxZ then
MaxZ := Nodes[I, J];
end;
end;
end;
HeightField.XSamplingScale.Min := -(Nx div 2);
HeightField.XSamplingScale.Max := (Nx div 2);
HeightField.YSamplingScale.Min := -(Ny div 2);
HeightField.YSamplingScale.Max := (Ny div 2);
finally
Tl.Free;
Sl.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('grd', 'ArcInfo/Surfer grids', TGLGRDVectorFile);
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit BindHelp;
interface
var
{
Indicates the quality of the BindHelp unit's interface.
More is better.
}
BindHelp_Deluxe_Interface: Integer = 42;
procedure CopyUnicodeToPWideString(Unicode: PWideChar; var S: WideString;
Len: Integer); cdecl; export;
implementation
uses
{$IFDEF LINUX}
Libc,
{$ENDIF}
SysUtils, Qt, Types;
// AnsiString Helpers
procedure CopyCharsToPAnsiString(Chars: PAnsiChar; var S: AnsiString); cdecl; export;
begin
S := Chars;
end;
function CharsOfPAnsiString(var S: AnsiString): PAnsiChar; cdecl; export;
begin
Result := PAnsiChar(Pointer(S));
end;
procedure InitPAnsiString(var S: PAnsiString); cdecl; export;
begin
New(S);
end;
procedure FinalPAnsiString(var S: PAnsiString); cdecl; export;
begin
Dispose(S);
end;
// WideString Helpers
procedure CopyUnicodeToPWideString(Unicode: PWideChar; var S: WideString;
Len: Integer); cdecl; export;
{$IFDEF LINUX}
var
I: Integer;
begin
SetLength(S, Len);
for I := 0 to Len - 1 do
Word(S[I + 1]) := Swap(Word(Unicode[I]));
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
begin
SetString(S, Unicode, Len);
end;
{$ENDIF}
function UnicodeOfPWideString(var S: WideString): PWideChar; cdecl; export;
const
cEmptyStr = '';
begin
if @S = nil then
Result := cEmptyStr
else
Result := PWideChar(Pointer(S));
end;
function LengthOfPWideString(var S: WideString): Integer; cdecl; export;
begin
if @S <> nil then
Result := Length(S)
else
Result := 0;
end;
procedure InitPWideString(var S: PWideString); cdecl; export;
begin
New(S);
end;
procedure FinalPWideString(var S: PWideString); cdecl; export;
begin
Dispose(S);
end;
// TPointArray helpers
function GetPointsPtr(const PA: TPointArray): Pointer; cdecl; export;
begin
Result := @PA[0];
end;
function GetPointsLength(const PA: TPointArray): Integer; cdecl; export;
begin
Result := Length(PA);
end;
procedure SetPointsLength(var PA: TPointArray; Len: Integer); cdecl; export;
begin
SetLength(PA, Len);
end;
// Int array helpers
function GetIntsPtr(const PA: TIntArray): Pointer; cdecl; export;
begin
Result := @PA[0];
end;
function GetIntsLength(const PA: TIntArray): Integer; cdecl; export;
begin
Result := Length(PA);
end;
procedure SetIntsLength(var PA: TIntArray; Len: Integer); cdecl; export;
begin
SetLength(PA, Len);
end;
{$IFDEF LINUX}
// fun with the Linux loader!
procedure InitLibQt;
const
QtLibNames: array[Boolean] of string = (
'libqt.so.2', 'libborqt-6.9-qt2.3.so' );
QtShareNames: array[Boolean] of string = (
'libqtintf-6.9-qt2.3.so', 'libborqt-6.9-qt2.3.so');
var
StaticallyBound: Boolean;
UseBorQt: Boolean;
begin
UseBorQt := GetModuleHandle(PChar(QtShareNames[True])) <> 0;
StaticallyBound := UseBorQt or (GetModuleHandle(PChar(QtShareNames[False])) <> 0);
if not StaticallyBound then
begin
UseBorQt := GetEnvironmentVariable('CLX_USE_LIBQT') = '';
dlopen(PChar(QtShareNames[UseBorQt]), RTLD_LAZY or RTLD_GLOBAL);
end;
Qt.QtIntf := QtShareNames[UseBorQt];
Qt.QtLib := QtLibNames[UseBorQt];
end;
{$ENDIF}
initialization
{$IFDEF LINUX}
InitLibQt;
{$ENDIF}
Qt.InitializePAnsiString(@CopyCharsToPAnsiString, @CharsOfPAnsiString,
@InitPAnsiString, @FinalPAnsiString);
Qt.InitializePWideString(@CopyUnicodeToPWideString, @UnicodeOfPWideString,
@LengthOfPWideString, @InitPWideString, @FinalPWideString);
Qt.InitializePPointArray(@GetPointsPtr, @GetPointsLength, @SetPointsLength);
Qt.InitializePIntArray(@GetIntsPtr, @GetIntsLength, @SetIntsLength);
end.
|
{============================= Program Header ========================================
PROGRAM-NAME : PZZ1070A(정보검색Ⅱ 관리자)
SYSTEM-NAME : 종합인사정보
SUBSYSTEM-NAME : 기타
Programmer : 이상문
Version : 1.00
Date : 2017.11.10
Update contents
1.00 2017.11.10 이상문 기존프로그램 재개발 정보검색Ⅱ 관리자
1.01 2018.04.23 이상문 사용자 그룹 권한 관리 개발
======================================================================================}
unit PZZ10701;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Grids, DBGrids, OnGrDBGrid, OnFocusButton, Db, MemDS,
DBAccess, Ora , Func, OnEditBaseCtrl, OnEditStdCtrl, OnEditCombo,
OnEditMemo;
type
TForm1 = class(TForm)
Panel1: TPanel;
fb_UserQuery: TOnFocusButton;
pn_Title: TPanel;
OnGrDbGrid1: TOnGrDbGrid;
lb_Title: TLabel;
fb_User: TOnFocusButton;
OraQuery1: TOraQuery;
OraDataSource1: TOraDataSource;
lb_Sub: TLabel;
Ora_DML: TOraQuery;
fb_Userm: TOnFocusButton;
Ora_Group: TOraQuery;
pn_Bottom: TPanel;
fb_Search: TOnFocusButton;
fb_Add: TOnFocusButton;
fb_Save: TOnFocusButton;
fb_Del: TOnFocusButton;
pn_Detail: TPanel;
pn_Search: TPanel;
fb_Group: TOnFocusButton;
procedure fb_Click(Sender : TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure fb_SearchClick(Sender: TObject);
procedure OnGrDbGrid1DblClick(Sender: TObject);
procedure fb_AddClick(Sender: TObject);
procedure fb_SaveClick(Sender: TObject);
procedure fb_DelClick(Sender: TObject);
// arr_OnCombo[1] Change Event
procedure ComboChange(Sender : TObject);
// arr_OnEdit[0] KeyPress Event
procedure KeyEnter(Sender : TObject; var Key: Char);
procedure fb_GroupClick(Sender: TObject);
private
{ Private declarations }
// 검색
procedure Retrieve(current : Integer);
// 입력 동적 생성
procedure GenerateEdit(current : Integer);
// 입력 비활성화
procedure InvisibleEdit;
// 그리드에서 해당 필드의 인덱스 얻음
function GetIndexByFieldName(Target : TOnGrDbGrid; FN : String) : Integer;
// 유저명으로 ID찾기
function GetUserIdByUserName(P_UserName : String) : String;
// 입력창 텍스트 초기화
procedure ClearEdit;
public
{ Public declarations }
arr_OnEdit : array of TOnEdit;
arr_OnCombo : array of TOnComboEdit;
OnMemo1 : TOnMemo;
current : Integer;
end;
var
Form1: TForm1;
implementation
Uses PZZ10702;
{$R *.DFM}
var
Form2 : TForm2;
{ TForm1 }
procedure TForm1.fb_Click(Sender: TObject);
var
i : Integer;
Title : String;
begin
// invisible
if (length(arr_OnEdit) <> 0) and
(current <> (Sender as TOnFocusButton).Tag) then
begin
InvisibleEdit;
end;
current := (Sender as TOnFocusButton).Tag;
Title := (Sender as TOnFocusButton).Caption;
pn_Title.Caption := '-- ' + Title + ' --';
lb_Title.Caption := '◆ ' + Title + ' 열람';
case current of
0 : // 사용자 권한 관리
begin
lb_Sub.Caption := '◆ 사용자 권한 입력';
fb_Add.Caption := '추가';
fb_Del.Visible := True;
end;
1 : // 그룹별 사용자 관리
begin
lb_Sub.Caption := '◆ 그룹별 사용자 입력';
fb_Add.Caption := '수정';
fb_Del.Visible := False;
end;
2 : // 사용자 질의 정보 관리
begin
lb_Sub.Caption := '◆ 사용자 질의 정보 입력';
fb_Add.Caption := '추가';
fb_Del.Visible := True;
end;
end; // case end
SetLength(arr_OnEdit, 5);
SetLength(arr_OnCombo, 3);
// 검색
Retrieve(current);
// 입력 동적 생성
GenerateEdit(current);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
OraConnect;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Form1 := nil;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := CaFree;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
fb_Click(fb_UserQuery);
end;
procedure TForm1.fb_SearchClick(Sender: TObject);
begin
Retrieve(current);
end;
// 검색
procedure TForm1.Retrieve(current: Integer);
var
i : Integer;
begin
with OraQuery1 do
begin
Close;
Sql.Clear;
case current of
0 : begin // 사용자 권한 관리
Close;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' USERID "사용자 ID" ');
Sql.Add(' ,USERNAME "사용자명" ');
Sql.Add(' ,CONTENT "사용자 설명" ');
Sql.Add(' FROM ');
Sql.Add(' AQUSER ');
if arr_OnEdit[0] <> nil then
begin
Sql.Add(' WHERE USERNAME LIKE ''%' + arr_OnEdit[0].Text + '%'' ');
end;
Sql.Add(' ORDER BY USERID ');
Open;
OnGrDbGrid1.Columns[0].Width := 100;
OnGrDbGrid1.Columns[1].Width := 100;
OnGrDbGrid1.Columns[2].Width := 800;
OnGrDbGrid1.Columns[0].Alignment := taCenter;
OnGrDbGrid1.Columns[1].Alignment := taCenter;
end; // case 0 end
1 : begin // 그룹별 사용자 관리
Close;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' GROUPNAME "그룹명" ');
Sql.Add(' ,USERID "사용자" ');
{Sql.Add(' ,USER01 "사용자01" ');
Sql.Add(' ,USER02 "사용자02" ');
Sql.Add(' ,USER03 "사용자03" ');
Sql.Add(' ,USER04 "사용자04" ');
Sql.Add(' ,USER05 "사용자05" ');
Sql.Add(' ,USER06 "사용자06" ');
Sql.Add(' ,USER07 "사용자07" ');
Sql.Add(' ,USER08 "사용자08" ');
Sql.Add(' ,USER09 "사용자09" ');
Sql.Add(' ,USER10 "사용자10" ');
Sql.Add(' ,USER11 "사용자11" ');
Sql.Add(' ,USER12 "사용자12" ');
Sql.Add(' ,USER13 "사용자13" ');
Sql.Add(' ,USER14 "사용자14" ');
Sql.Add(' ,USER15 "사용자15" ');}
Sql.Add(' FROM ');
Sql.Add(' AQGRUSER ');
Sql.Add(' ORDER BY GROUPNAME ');
Open;
OnGrDbGrid1.Columns[0].Width := 150;
for i := 1 to Fields.Count - 1 do
begin
OnGrDbGrid1.Columns[i].Width := 65;
end;
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
Close;
Sql.Clear;
Sql.Add('SELECT a.GROUPNAME "그룹명" ');
Sql.Add(' ,a.QUERYNAME "사용자 질의명" ');
Sql.Add(' ,a.CONTENT "설명" ');
Sql.Add(' ,a.SEQNO "일련번호" ');
Sql.Add(' ,a.USERSQL "SQL 문장" ');
Sql.Add(' ,a.USEYN "사용여부" ');
Sql.Add(' FROM AQUSERQUERY a ');
//Sql.Add(' ,AQUSER b ');
Sql.Add(' WHERE a.USERID = ''0000'' ');
//Sql.Add(' AND b.USERID = a.USERID ');
if arr_OnEdit[0] <> nil then
begin
Sql.Add(' AND a.QUERYNAME LIKE ''%' + arr_OnEdit[0].Text + '%'' ');
end;
if arr_OnCombo[0] <> nil then
begin
if arr_OnCombo[0].Text <> '전체' then
begin
Sql.Add(' AND a.GROUPNAME LIKE ''%' + arr_OnCombo[0].Text + ''' ')
end
end;
Sql.Add(' ORDER BY a.SEQNO ');
{if arr_OnCombo[0] = nil then
//begin
ParamByName('UserName').AsString := '모든 사용자'
//end
else
ParamByName('UserName').AsString := arr_OnCombo[0].Text;}
Open;
{
OnGrDbGrid1.Columns[0].Width := 100;
OnGrDbGrid1.Columns[1].Width := 150;
OnGrDbGrid1.Columns[2].Width := 300;
OnGrDbGrid1.Columns[3].Width := 450;
OnGrDbGrid1.Columns[4].Width := 0;
OnGrDbGrid1.Columns[5].Width := 0;
OnGrDbGrid1.Columns[6].Width := 0;
}
OnGrDbGrid1.Columns[0].Width := 200;
OnGrDbGrid1.Columns[1].Width := 350;
OnGrDbGrid1.Columns[2].Width := 450;
OnGrDbGrid1.Columns[3].Width := 0;
OnGrDbGrid1.Columns[4].Width := 0;
OnGrDbGrid1.Columns[5].Width := 0;
end; // case 2 end
end; // case end
ClearEdit;
end; // with end
end;
// 입력 동적 생성
procedure TForm1.GenerateEdit(current: Integer);
var
i : Integer;
De_Top, De_Left : Integer;
begin
De_Top := 10;
De_Left := 40;
case current of
0 : begin // 사용자 권한 관리
// 검색
arr_OnEdit[0] := TOnEdit.Create(Self);
arr_OnEdit[0].Parent := pn_Search;
arr_OnEdit[0].Top := De_Top - 5;
arr_OnEdit[0].Left := De_Left;
arr_OnEdit[0].Width := 1000;
arr_OnEdit[0].Height := 24;
arr_OnEdit[0].EditLabel.Width := 100;
arr_OnEdit[0].EditLabel.Caption := '사용자명';
arr_OnEdit[0].OnKeyPress := KeyEnter;
arr_OnEdit[0].Visible := True;
// 입력
for i := 1 to OraQuery1.Fields.Count do
begin
arr_OnEdit[i] := TOnEdit.Create(Self);
arr_OnEdit[i].Parent := pn_Detail;
arr_OnEdit[i].Top := De_Top + (25 * (i-1));
arr_OnEdit[i].Left := De_Left;
arr_OnEdit[i].Width := 1000;
arr_OnEdit[i].Height := 24;
arr_OnEdit[i].EditLabel.Width := 100;
arr_OnEdit[i].EditLabel.Caption := OraQuery1.Fields[i-1].FieldName;
arr_OnEdit[i].EditLabel.Font.Style := [fsBold];
if i = 1 then arr_OnEdit[i].EditLabel.Color := $FFCF9D;
arr_OnEdit[i].Visible := True;
end; // for end
end; // case 0 end
1 : begin // 그룹별 사용자 관리
// 검색
arr_OnEdit[0] := TOnEdit.Create(Self);
arr_OnEdit[0].Parent := pn_Search;
arr_OnEdit[0].Top := De_Top - 5;
arr_OnEdit[0].Left := De_Left;
arr_OnEdit[0].Width := 1000;
arr_OnEdit[0].Height := 24;
arr_OnEdit[0].EditLabel.Width := 100;
arr_OnEdit[0].EditLabel.Caption := '사용자ID';
arr_OnEdit[0].OnKeyPress := KeyEnter;
arr_OnEdit[0].Visible := True;
// 입력
arr_OnCombo[0] := TOnComboEdit.Create(Self);
arr_OnCombo[0].Parent := pn_Detail;
arr_OnCombo[0].Top := De_Top;
arr_OnCombo[0].Left := De_Left;
arr_OnCombo[0].Width := 300;
arr_OnCombo[0].Height := 24;
arr_OnCombo[0].EditLabel.Width := 100;
arr_OnCombo[0].EditLabel.Caption := OraQuery1.Fields[0].FieldName;
arr_OnCombo[0].EditLabel.Font.Style := [fsBold];
arr_OnCombo[0].EditLabel.Color := $FFCF9D;
while(true) do
begin
arr_OnCombo[0].Items.Add(OraQuery1.Fields[0].Text);
OraQuery1.Next;
if OraQuery1.Eof then break;
end;
OraQuery1.First;
arr_OnCombo[0].Visible := True;
arr_OnCombo[1] := TOnComboEdit.Create(Self);
arr_OnCombo[1].Parent := pn_Detail;
arr_OnCombo[1].Top := De_Top;
arr_OnCombo[1].Left := 350;
arr_OnCombo[1].Width := 200;
arr_OnCombo[1].Height := 24;
arr_OnCombo[1].EditLabel.Width := 100;
arr_OnCombo[1].EditLabel.Caption := '순번';
arr_OnCombo[1].EditLabel.Font.Style := [fsBold];
for i := 1 to OraQuery1.Fields.Count - 1 do
begin
arr_OnCombo[1].Items.Add(OraQuery1.Fields[i].FieldName);
end;
arr_OnCombo[1].OnChange := ComboChange;
arr_OnCombo[1].Visible := True;
arr_OnEdit[1] := TOnEdit.Create(Self);
arr_OnEdit[1].Parent := pn_Detail;
arr_OnEdit[1].Top := De_Top;
arr_OnEdit[1].Left := 560;
arr_OnEdit[1].Width := 200;
arr_OnEdit[1].Height := 24;
arr_OnEdit[1].EditLabel.Width := 100;
arr_OnEdit[1].EditLabel.Caption := '사용자ID';
arr_OnEdit[1].EditLabel.Font.Style := [fsBold];
arr_OnEdit[1].EditLabel.Color := $FFCF9D;
arr_OnEdit[1].Visible := True;
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
// 검색
arr_OnCombo[0] := TOnComboEdit.Create(Self);
arr_OnCombo[0].Parent := pn_Search;
arr_OnCombo[0].Top := De_Top - 5;
arr_OnCombo[0].Left := De_Left;
arr_OnCombo[0].Width := 300;
arr_OnCombo[0].Height := 24;
arr_OnCombo[0].EditLabel.Width := 100;
arr_OnCombo[0].EditLabel.Caption := '사용자 그룹';
arr_OnCombo[0].OnChange := ComboChange;
arr_OnCombo[0].Visible := True;
arr_OnEdit[0] := TOnEdit.Create(Self);
arr_OnEdit[0].Parent := pn_Search;
arr_OnEdit[0].Top := De_Top - 5;
arr_OnEdit[0].Left := De_Left + 310;
arr_OnEdit[0].Width := 700;
arr_OnEdit[0].Height := 24;
arr_OnEdit[0].EditLabel.Width := 100;
arr_OnEdit[0].EditLabel.Caption := '사용자 질의명';
arr_OnEdit[0].OnKeyPress := KeyEnter;
arr_OnEdit[0].Visible := True;
// 입력
arr_OnCombo[1] := TOnComboEdit.Create(Self);
arr_OnCombo[1].Parent := pn_Detail;
arr_OnCombo[1].Top := De_Top;
arr_OnCombo[1].Left := De_Left;
arr_OnCombo[1].Width := 300;
arr_OnCombo[1].Height := 24;
arr_OnCombo[1].EditLabel.Width := 100;
arr_OnCombo[1].EditLabel.Caption := '사용자명';
arr_OnCombo[1].EditLabel.Font.Style := [fsBold];
arr_OnCombo[1].EditLabel.Color := $FFCF9D;
Ora_Group.Close;
Ora_Group.Open;
arr_OnCombo[0].Items.Add('전체');
while(True) do
begin
arr_OnCombo[0].Items.Add(Ora_Group.FieldByName('GROUPNAME').Text);
Ora_Group.Next;
if Ora_Group.Eof then break;
end;
arr_OnCombo[0].ItemIndex := 0;
arr_OnCombo[1].Visible := False;
arr_OnEdit[1] := TOnEdit.Create(Self);
arr_OnEdit[1].Parent := pn_Detail;
arr_OnEdit[1].Top := De_Top;
arr_OnEdit[1].Left := De_Left; //De_Left + 310;
arr_OnEdit[1].Width := 200;
arr_OnEdit[1].Height := 24;
arr_OnEdit[1].EditLabel.Width := 100;
arr_OnEdit[1].EditLabel.Caption := '일련번호';
arr_OnEdit[1].EditLabel.Font.Style := [fsBold];
arr_OnEdit[1].EditLabel.Color := $FFCF9D;
arr_OnEdit[1].Visible := True;
arr_OnEdit[2] := TOnEdit.Create(Self);
arr_OnEdit[2].Parent := pn_Detail;
arr_OnEdit[2].Top := De_Top;
arr_OnEdit[2].Left := De_Left + 210; //De_Left + 520;
arr_OnEdit[2].Width := 240;
arr_OnEdit[2].Height := 24;
arr_OnEdit[2].EditLabel.Width := 100;
arr_OnEdit[2].EditLabel.Caption := '그룹명';
arr_OnEdit[2].EditLabel.Font.Style := [fsBold];
arr_OnEdit[2].Visible := True;
arr_OnEdit[3] := TOnEdit.Create(Self);
arr_OnEdit[3].Parent := pn_Detail;
arr_OnEdit[3].Top := De_Top + 25;
arr_OnEdit[3].Left := De_Left;
arr_OnEdit[3].Width := 970;
arr_OnEdit[3].Height := 24;
arr_OnEdit[3].EditLabel.Width := 100;
arr_OnEdit[3].EditLabel.Caption := '사용자 질의명';
arr_OnEdit[3].Visible := True;
OnMemo1 := TOnMemo.Create(Self);
OnMemo1.Parent := pn_Detail;
OnMemo1.Top := arr_OnEdit[3].Top + 25;
OnMemo1.Left := De_Left;
OnMemo1.Width := 970;
OnMemo1.Height := 70;
OnMemo1.ScrollBars := ssVertical;
OnMemo1.EditLabel.Width := 100;
OnMemo1.EditLabel.Caption := 'SQL 문장';
OnMemo1.Visible := True;
arr_OnEdit[4] := TOnEdit.Create(Self);
arr_OnEdit[4].Parent := pn_Detail;
arr_OnEdit[4].Top := OnMemo1.Top + 71;
arr_OnEdit[4].Left := De_Left;
arr_OnEdit[4].Width := 970;
arr_OnEdit[4].Height := 24;
arr_OnEdit[4].EditLabel.Width := 100;
arr_OnEdit[4].EditLabel.Caption := '설명';
arr_OnEdit[4].Visible := True;
arr_OnCombo[2] := TOnComboEdit.Create(Self);
arr_OnCombo[2].Parent := pn_Detail;
arr_OnCombo[2].Top := De_Top;
arr_OnCombo[2].Left := De_Left + 460; //De_Left + 770;
arr_OnCombo[2].Width := 200;
arr_OnCombo[2].Height := 24;
arr_OnCombo[2].EditLabel.Width := 100;
arr_OnCombo[2].EditLabel.Caption := '사용여부';
arr_OnCombo[2].EditLabel.Font.Style := [fsBold];
arr_OnCombo[2].Items.Add('Y');
arr_OnCombo[2].Items.Add('N');
//arr_OnCombo[2].ReadOnly := True;
arr_OnCombo[2].Visible := True;
end; // case 2 end
end; // case end
pn_Detail.Visible := True;
end;
procedure TForm1.OnGrDbGrid1DblClick(Sender: TObject);
var
i : Integer;
sl : TStrings;
ms : TMemoryStream;
begin
case current of
0 : begin // 사용자 권한 관리
for i := 1 to OraQuery1.Fields.Count do
begin
arr_OnEdit[i].Text := OnGrDbGrid1.Fields[i-1].Text;
end; // for end
arr_OnEdit[1].Enabled := False;
end; // case 0 end
1 : begin // 그룹별 사용자 관리
arr_OnCombo[0].Text := OnGrDbGrid1.Fields[0].Text;
arr_OnCombo[1].Text := OnGrDbGrid1.Fields[1].FieldName;
arr_OnEdit[1].Text := OnGrDbGrid1.Fields[GetIndexByFieldName(OnGrDbGrid1,arr_OnCombo[1].Text)].Text;
arr_OnCombo[0].Enabled := False;
arr_OnEdit[1].Enabled := False;
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
//arr_OnCombo[1].Text := OnGrDbGrid1.Fields[0].Text;
arr_OnEdit[1].Text := OnGrDbGrid1.Fields[3].Text;//4
arr_OnEdit[2].Text := OnGrDbGrid1.Fields[0].Text;//1
arr_OnEdit[3].Text := OnGrDbGrid1.Fields[1].Text;//2
OnMemo1.Lines.Text := TBlobField(OnGrDbGrid1.Fields[4]).AsString;//5
arr_OnEdit[4].Text := OnGrDbGrid1.Fields[2].Text;//3
arr_OnCombo[2].Text := OnGrDbGrid1.Fields[5].Text;//6
arr_OnCombo[1].Enabled := False;
arr_OnEdit[1].Enabled := False;
end; // case 2 end
end; // case end
end;
procedure TForm1.fb_AddClick(Sender: TObject);
var
i : Integer;
begin
case current of
0 : begin // 사용자 권한 관리
for i := 1 to OraQuery1.Fields.Count do
begin
arr_OnEdit[i].Text := '';
end; // for end
arr_OnEdit[1].Enabled := True;
arr_OnEdit[1].SetFocus;
end; // case 0 end
1 : begin // 그룹별 사용자 관리
arr_OnEdit[1].Enabled := True;
arr_OnCombo[0].Text := '';
arr_OnCombo[1].Text := '';
arr_OnEdit[1].Enabled := True;
arr_OnCombo[0].Enabled := True;
arr_OnCombo[0].SetFocus;
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
arr_OnCombo[1].Text := '';
arr_OnEdit[1].Text := '';
arr_OnEdit[2].Text := '';
arr_OnEdit[3].Text := '';
OnMemo1.Lines.Text := '';
arr_OnEdit[4].Text := '';
arr_OnCombo[1].Enabled := True;
arr_OnEdit[1].Enabled := True;
end; // case 2 end
end; // case end
end;
procedure TForm1.fb_SaveClick(Sender: TObject);
begin
case current of
0 : begin // 사용자 권한 관리
if (arr_OnEdit[1].Text = '') or (arr_OnEdit[2].Text = '') then
begin
Showmessage('사용자ID와 사용자명은 필수 입력 사항입니다.');
Exit;
end;
if IDNO = Application.MessageBox('사용자 권한을 저장하시겠습니까?','작업안내', MB_YesNo) then Exit;
with Ora_DML do
begin
Close;
Sql.Clear;
Sql.Add('SELECT COUNT(USERID) CNT ');
Sql.Add(' FROM AQUSER ');
Sql.Add(' WHERE USERID = :UserId ');
ParamByName('UserId').AsString := arr_OnEdit[1].Text;
Open;
if FieldByName('CNT').AsInteger = 0 then
begin
Sql.Clear;
Sql.Add('INSERT INTO AQUSER ');
Sql.Add('VALUES ( ');
Sql.Add(' :UserId ');
Sql.Add(' ,:UserName ');
Sql.Add(' ,:Content ');
Sql.Add(' ) ');
ParamByName('UserId').AsString := arr_OnEdit[1].Text;
ParamByName('UserName').AsString := arr_OnEdit[2].Text;
ParamByName('Content').AsString := arr_OnEdit[3].Text;
ExecSQL;
Showmessage('권한이 부여되었습니다.');
end
else
begin
Sql.Clear;
Sql.Add('UPDATE AQUSER ');
Sql.Add(' SET USERNAME = :UserName ');
Sql.Add(' ,CONTENT = :Content ');
Sql.Add(' WHERE USERID = :UserId ');
ParamByName('UserId').AsString := arr_OnEdit[1].Text;
ParamByName('UserName').AsString := arr_OnEdit[2].Text;
ParamByName('Content').AsString := arr_OnEdit[3].Text;
ExecSQL;
Showmessage('권한정보가 수정되었습니다.');
end;
end; // with end
end; // case 0 end
1 : begin // 그룹별 사용자 관리
if (arr_OnCombo[0].Text = '') or
(arr_OnCombo[1].Text = '') then
begin
Showmessage('그룹명과 순번은 필수 입력 사항입니다.');
Exit;
end;
if IDNO = Application.MessageBox('그룹별 사용자를 저장하시겠습니까?','작업안내', MB_YesNo) then Exit;
with Ora_DML do
begin
Close;
Sql.Clear;
Sql.Add('UPDATE AQUSERM ');
Sql.Add(' SET '+'USER' + Copy(arr_OnCombo[1].Text,7,2)+' = :UserId ');
Sql.Add(' WHERE GROUPNAME = :GroupName ');
ParamByName('UserId').AsString := arr_OnEdit[1].Text;
ParamByName('GroupName').AsString := arr_OnCombo[0].Text;
ExecSQL;
Showmessage('그룹별 사용자가 저장되었습니다.');
end;
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
if arr_OnEdit[1].Text = ''then
begin
Showmessage('일련번호는 필수 입력 사항입니다.');
Exit;
end;
if IDNO = Application.MessageBox('사용자 질의를 저장하시겠습니까?','작업안내', MB_YesNo) then Exit;
with Ora_DML do
begin
Close;
Sql.Clear;
Sql.Add('SELECT COUNT(SEQNO) CNT ');
Sql.Add(' FROM AQUSERQUERY a ');
//Sql.Add(' ,AQUSER b ');
Sql.Add(' WHERE a.USERID = ''0000'' ');
//Sql.Add(' AND b.USERNAME = :UserName ');
Sql.Add(' AND a.SEQNO = :SeqNo ');
//ParamByName('UserName').AsString := arr_OnCombo[1].Text;
ParamByName('SeqNo').AsString := arr_OnEdit[1].Text;
Open;
if FieldByName('CNT').AsInteger = 0 then
begin
Sql.Clear;
Sql.Add('INSERT INTO AQUSERQUERY ');
Sql.Add('VALUES ( ');
Sql.Add(' :UserId ');
Sql.Add(' ,:SeqNo ');
Sql.Add(' ,:QueryName ');
Sql.Add(' ,:Content ');
Sql.Add(' ,:UserSql ');
Sql.Add(' ,:GroupName ');
Sql.Add(' ,:UseYn ');
Sql.Add(' ) ');
//ParamByName('UserId').AsString := GetUserIdByUserName(arr_OnCombo[1].Text);
ParamByName('UserId').AsString := '0000';
ParamByName('SeqNo').AsInteger := StrToInt(arr_OnEdit[1].Text);
ParamByName('QueryName').AsString := arr_OnEdit[3].Text;
ParamByName('Content').AsString := arr_OnEdit[4].Text;
ParamByName('UserSql').AsBlob := OnMemo1.Lines.Text;
ParamByName('GroupName').AsString := arr_OnEdit[2].Text;
ParamByName('UseYn').AsString := arr_OnCombo[2].Text;
ExecSQL;
Showmessage('사용자 질의가 추가되었습니다.');
end
else
begin
Sql.Clear;
Sql.Add('UPDATE AQUSERQUERY ');
Sql.Add(' SET GROUPNAME = :GroupName ');
Sql.Add(' ,QUERYNAME = :QueryName ');
Sql.Add(' ,CONTENT = :Content ');
Sql.Add(' ,USERSQL = :UserSql ');
Sql.Add(' ,USEYN = :UseYn ');
Sql.Add(' WHERE USERID = :UserId ');
Sql.Add(' AND SEQNO = :SeqNo ');
//ParamByName('UserId').AsString := GetUserIdByUserName(arr_OnCombo[1].Text);
ParamByName('UserId').AsString := '0000';
ParamByName('SeqNo').AsInteger := StrToInt(arr_OnEdit[1].Text);
ParamByName('QueryName').AsString := arr_OnEdit[3].Text;
ParamByName('Content').AsString := arr_OnEdit[4].Text;
ParamByName('UserSql').AsBlob := OnMemo1.Lines.Text;
ParamByName('GroupName').AsString := arr_OnEdit[2].Text;
ParamByName('UseYn').AsString := arr_OnCombo[2].Text;
ExecSQL;
Showmessage('사용자 질의가 수정되었습니다.');
end;
end;
end; // case 2 end
end; // case end
Retrieve(current);
end;
procedure TForm1.fb_DelClick(Sender: TObject);
var
UserId, UserName, SeqNo : String;
begin
case current of
0 : begin // 사용자 권한 관리
UserId := OnGrDbGrid1.Fields[0].Text;
UserName := OnGrDbGrid1.Fields[1].Text;
if IDNO = Application.MessageBox(PChar(UserName+'('+UserId+')의 사용자 권한을 삭제하시겠습니까?'),'작업안내', MB_YesNo) then Exit;
with Ora_DML do
begin
Close;
Sql.Clear;
Sql.Add('DELETE AQUSER ');
Sql.Add(' WHERE USERID = :UserId ');
ParamByName('UserId').AsString := UserId;
ExecSQL ;
Showmessage('권한이 삭제되었습니다.');
end; // with end
end; // case 0 end
1 : begin // 그룹별 사용자 관리
//
end; // case 1 end
2 : begin // 사용자 질의 정보 관리
UserId := GetUserIdByUserName(OnGrDbGrid1.Fields[0].Text);
SeqNo := OnGrDbGrid1.Fields[3].Text;
if IDNO = Application.MessageBox(PChar(OnGrDbGrid1.Fields[0].Text+'의 사용자 질의 '''+
OnGrDbGrid1.Fields[1].Text+''' 을(를) 삭제하시겠습니까?'),'작업안내', MB_YesNo) then Exit;
with Ora_DML do
begin
Close;
Sql.Clear;
Sql.Add('DELETE AQUSERQUERY ');
Sql.Add(' WHERE 1=1 ');
Sql.Add(' AND SEQNO = :SeqNo ');
ParamByName('SeqNo').AsString := SeqNo;
ExecSQL;
Showmessage('사용자 질의가 삭제되었습니다.');
end; // with end
end;
end; // case end
Retrieve(current);
end;
// 입력 비활성화
procedure TForm1.InvisibleEdit;
var
i : Integer;
begin
if pn_Search.ControlCount > 0 then
begin
for i := (pn_Search.ControlCount - 1) downto 0 do
begin
pn_Search.Controls[i].Free;
if i = 0 then break;
end;
end;
if pn_Detail.ControlCount > 0 then
begin
for i := (pn_Detail.ControlCount - 1) downto 0 do
begin
pn_Detail.Controls[i].Free;
if i = 0 then break;
end;
end;
arr_onEdit := nil;
arr_OnCombo := nil;
SetLength(arr_OnEdit, 0);
SetLength(arr_OnCombo, 0);
end;
// 그리드에서 해당 필드의 인덱스 얻음
function TForm1.GetIndexByFieldName(Target: TOnGrDbGrid; FN : String): Integer;
var
i : Integer;
begin
for i := 0 to Target.FieldCount - 1 do
begin
if Target.Fields[i].FieldName = FN then Result := i;
end;
end;
// arr_OnCombo[1] Change Event
procedure TForm1.ComboChange(Sender: TObject);
begin
if current = 1 then // 그룹별 사용자 관리
begin
if arr_OnCombo[0].Enabled = False then
begin
if arr_OnCombo[1].Text <> '' then
arr_OnEdit[1].Text := OnGrDbGrid1.Fields[GetIndexByFieldName(OnGrDbGrid1,arr_OnCombo[1].Text)].Text
else
arr_OnEdit[1].Text := '';
end;
end
else if current = 2 then
begin
Retrieve(current);
end;
end;
procedure TForm1.KeyEnter(Sender: TObject; var Key: Char);
begin
if Key = #13 then
fb_Search.Click;
end;
// 유저명으로 ID찾기
function TForm1.GetUserIdByUserName(P_UserName: String): String;
begin
{with Ora_User do
begin
First;
while(true) do
begin
if FieldByName('USERNAME').Text <> P_UserName then
begin
Next;
end
else
begin
break;
end; // end if
end; // end while
result := FieldByName('USERID').Text;
end;}
end;
// 입력창 텍스트 초기화
procedure TForm1.ClearEdit;
var
i : Integer;
begin
if pn_Detail.ControlCount > 0 then
begin
for i := (pn_Detail.ControlCount - 1) downto 0 do
begin
// 각 컴포넌트의 텍스트 초기화
if pn_Detail.Controls[i].ClassName = 'TOnEdit' then
(pn_Detail.Controls[i] as TOnEdit).Text := ''
else if pn_Detail.Controls[i].ClassName = 'TOnComboEdit' then
(pn_Detail.Controls[i] as TOnComboEdit).Text := ''
else if pn_Detail.Controls[i].ClassName = 'TOnMemo' then
(pn_Detail.Controls[i] as TOnMemo).Lines.Text := '';
// Enabled False -> True
if pn_Detail.Controls[i].Enabled = False then pn_Detail.Controls[i].Enabled := True;
if i = 0 then break;
end;
end;
end;
procedure TForm1.fb_GroupClick(Sender: TObject);
begin
// 사용자 그룹 권한 오픈
Form2 := TForm2.Create(Form1);
try
Form2.ShowModal;
finally
Form2.Free;
end;
end;
end.
|
unit IdEMailAddress;
{
ToDo: look into alterations required for TIdEMailAddressItem.GetText.
}
{
2001-Aug-30 - Jim Gunkel
- Fixed bugs that would occur with group names containing spaces (box test 19)
and content being located after the email address (box test 33)
2001-Jul-11 - Allen O'Neill
- Added hack to not allow recipient entries being added that are blank
2001-Jul-11 - Allen O'Neill
- Added hack to accomodate a PERIOD (#46) in an email address - this whole area needs to be looked at.
2001-Feb-03 - Peter Mee
- Overhauled TIdEMailAddressItem.GetText to support non-standard textual
elements.
2001-Jan-29 - Peter Mee
- Overhauled TIdEMailAddressList.SetEMailAddresses to support comments
and escaped characters and to ignore groups.
2001-Jan-28 - Peter Mee
- Overhauled TIdEMailAddressItem.SetText to support comments and escaped
characters.
2000-Jun-10 - J. Peter Mugaas
- started this unit to facilitate some Indy work including the
TIdEMailAddressItem and TIdEMailAddressList classes
- The GetText and SetText were originally the ToArpa and FromArpa functions in
the TIdMessage component}
interface
uses
Classes,
IdException;
type
EIdEmailParseError = class(EIdException);
TIdEMailAddressItem = class (TCollectionItem)
protected
FAddress : String;
FName : String;
Function GetText : String;
Procedure SetText(AText : String);
function ConvertAddress : String;
public
procedure Assign(Source: TPersistent); override;
published
{This is the E-Mail address itself }
property Address: string read FAddress write FAddress;
{This is the person's name} {Do not Localize}
property Name: string read FName write FName;
{This is the combined person's name and E-Mail address} {Do not Localize}
property Text: String read GetText write SetText;
end;
TIdEMailAddressList = class (TOwnedCollection)
protected
function GetItem ( Index: Integer ) : TIdEMailAddressItem;
procedure SetItem ( Index: Integer; const Value: TIdEMailAddressItem );
function GetEMailAddresses : String;
procedure SetEMailAddresses( AList : String);
public
constructor Create ( AOwner : TPersistent ); reintroduce;
{This returns formatted list of formated
addresses including the names from the collection }
procedure FillTStrings(AStrings : TStrings);
function Add: TIdEMailAddressItem;
property Items [ Index: Integer ] : TIdEMailAddressItem read GetItem write SetItem; default;
{This is a comma separated list of formated
addresses including the names from the collection }
property EMailAddresses : String read GetEMailAddresses
write SetEMailAddresses;
end;
implementation
uses
IdGlobal,
IdResourceStrings,
SysUtils;
const
// This is actually the ATEXT without the '"' and space characters... {Do not Localize}
IETF_ATEXT: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' {Do not Localize}
+ '1234567890!#$%&''*+-/=?_`{}|~'; {Do not Localize}
// ATEXT without the '"' {Do not Localize}
IETF_ATEXT_SPACE: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' {Do not Localize}
+ '1234567890!#$%&''*+-/=?_`{}|~ '; {Do not Localize}
IETF_QUOTABLE: string = '\"'; {Do not Localize}
// Three functions for easier manipulating of strings.
// Don't know of any system functions to perform these actions. {Do not Localize}
// If there aren't & someone can find an optimised way of performing {Do not Localize}
// then please implement...
function FindFirstOf(AFind, AText: string): Integer;
var
nCount, nPos: Integer;
begin
Result := 0;
for nCount := 1 to Length(AFind) do begin
nPos := IndyPos(AFind[nCount], AText);
if nPos > 0 then begin
if Result = 0 then begin
Result := nPos;
end else if Result > nPos then begin
Result := nPos;
end;
end;
end;
end;
function FindFirstNotOf(AFind, AText : String) : Integer;
var
i : Integer;
begin
result := 0;
if length(AFind) = 0 then
begin
result := 1;
exit;
end;
if length(AText) = 0 then
begin
exit;
end;
for i := 1 to length(AText) do
begin
if IndyPos(AText[i], AFind) = 0 then
begin
result := i;
exit;
end;
end;
end;
function TrimAllOf(ATrim, AText : String) : String;
begin
while Length(AText) > 0 do
begin
if Pos(AText[1], ATrim) > 0 then
begin
System.Delete(AText, 1, 1);
end else break;
end;
while Length(AText) > 0 do begin
if Pos(AText[length(AText)], ATrim) > 0 then
begin
System.Delete(AText, Length(AText), 1);
end else break;
end;
result := AText;
end;
{ TIdEMailAddressItem }
procedure TIdEMailAddressItem.Assign(Source: TPersistent);
var Addr : TIdEMailAddressItem;
begin
if ClassType <> Source.ClassType then
begin
inherited
end
else
begin
Addr := TIdEMailAddressItem(Source);
Address := Addr.Address;
Name := Addr.Name;
end;
end;
function TIdEMailAddressItem.ConvertAddress : String;
var
i : Integer;
domainPart, tempAddress, localPart : String;
begin
if length(FAddress) = 0 then
begin
if Length(FName) > 0 then
begin
result := '<>'; {Do not Localize}
end else
begin
result := ''; {Do not Localize}
end;
exit;
end;
// First work backwards to the @ sign.
for i := length(FAddress) downto 1 do
begin
if FAddress[i] = '@' then {Do not Localize}
begin
domainPart := Copy(FAddress, i, length(FAddress));
tempAddress := Copy(FAddress, 1, i - 1);
break;
end;
end;
i := FindFirstNotOf(IETF_ATEXT, tempAddress);
if (i = 0) or (tempAddress[i] = #46) then //hack to accomodate periods in emailaddress
// if i = 0 then
begin
if length(FName) > 0 then
begin
result := '<' + tempAddress + domainPart + '>'; {Do not Localize}
end else
begin
result := tempAddress + domainPart;
end;
end else
begin
localPart := '"'; {Do not Localize}
while i > 0 do
begin
localPart := localPart + Copy(tempAddress, 1, i - 1);
if IndyPos(tempAddress[i], IETF_QUOTABLE) > 0 then
begin
localPart := localPart + '\'; {Do not Localize}
end;
localPart := localPart + tempAddress[i];
tempAddress := Copy(tempAddress, i + 1, length(tempAddress));
i := FindFirstNotOf(IETF_ATEXT, tempAddress);
end;
result := '<' + localPart + tempAddress + '"' + domainPart + '>'; {Do not Localize}
end;
end;
function TIdEMailAddressItem.GetText: String;
var
i : Integer;
tempName, resName : String;
begin
if ( Length ( FName ) > 0 ) and ( UpperCase ( FAddress ) <> FName ) then
begin
i := FindFirstNotOf(IETF_ATEXT_SPACE, FName);
if i > 0 then
begin
// Need to quote the FName.
resName := '"' + Copy(FName, 1, i - 1); {Do not Localize}
if IndyPos(FName[i], IETF_QUOTABLE) > 0 then
begin
resName := resName + '\'; {Do not Localize}
end;
resName := resName + FName[i];
tempName := Copy(FName, i + 1, length(FName));
while length(tempName) <> 0 do
begin
i := FindFirstNotOf(IETF_ATEXT_SPACE, tempName);
if i = 0 then
begin
Result := resName + tempName + '" ' + ConvertAddress; {Do not Localize}
exit;
end;
resName := resName + Copy(tempName, 1, i-1);
if IndyPos(tempName[i], IETF_QUOTABLE) > 0 then
begin
resName := resName + '\'; {Do not Localize}
end;
resName := resName + tempName[i];
tempName := Copy(tempName, i + 1, length(tempName));
end;
Result := resName + '" ' + ConvertAddress; {Do not Localize}
end else
begin
Result := FName + ' ' + ConvertAddress; {Do not Localize}
end;
end // if
else
begin
Result := ConvertAddress;
end; // else .. if
end;
procedure TIdEMailAddressItem.SetText(AText: String);
var
nFirst,
nBracketCount : Integer;
bInAddress,
bAddressInLT,
bAfterAt,
bInQuote : Boolean;
begin
FAddress := ''; {Do not Localize}
FName := ''; {Do not Localize}
AText := Trim(AText);
if Length(AText) = 0 then exit;
// Find the first known character type.
nFirst := FindFirstOf('("< @' + TAB, AText); {Do not Localize}
if nFirst <> 0 then
begin
nBracketCount := 0;
bInAddress := False;
bAddressInLT := False;
bInQuote := False;
bAfterAt := False;
repeat
case AText[nFirst] of
' ', TAB : {Do not Localize}
begin
if nFirst = 1 then
begin
System.Delete(AText, 1, 1);
end else
begin
// Only valid if in a name not contained in quotes - keep the space.
if bAfterAt then begin
FAddress := FAddress + Trim(Copy(AText, 1, nFirst - 1));
end else begin
FName := FName + Copy(AText, 1, nFirst);
end;
AText := Copy(AText, nFirst + 1, Length(AText));
end;
end;
'(' : {Do not Localize}
begin
Inc(nBracketCount);
if (nFirst > 1) then
begin
// There's at least one character to the name {Do not Localize}
if bInAddress then
begin
FAddress := FAddress + Trim(Copy(AText, 1, nFirst - 1));
end else
begin
if nBracketCount = 1 then
begin
FName := FName + Copy(AText, 1, nFirst - 1);
end;
end;
AText := Copy(AText, nFirst + 1, length(AText));
end else
begin
System.Delete(AText, 1, 1);
end;
end;
')' : {Do not Localize}
begin
Dec(nBracketCount);
AText := Copy(AText, nFirst + 1, Length(AText));
end;
'"' : {Do not Localize}
begin
if bInQuote then
begin
if bAddressInLT then
begin
FAddress := FAddress + Trim(Copy(AText, 1, nFirst - 1));
end else
begin
FName := FName + Trim(Copy(AText, 1, nFirst - 1));
end;
AText := Copy(AText, nFirst + 1, length(AText));
bInQuote := False;
end else
begin
bInQuote := True;
System.Delete(AText, 1, 1);
end;
end;
'<' : {Do not Localize}
begin
if nFirst > 1 then
begin
FName := FName + Copy(AText,1,nFirst - 1);
end;
FName := TrimAllOf(' ' + TAB, Trim(FName)); {Do not Localize}
bAddressInLT := True;
bInAddress := True;
System.Delete(AText, 1, nFirst);
end;
'>' : {Do not Localize}
begin
// Only searched for if the address starts with '<' {Do not Localize}
bInAddress := False;
bAfterAt := False;
FAddress := FAddress +
TrimAllOf(' ' + TAB, Trim(Copy(AText, 1, nFirst -1))); {Do not Localize}
AText := Copy(AText, nFirst + 1, length(AText));
end;
'@' : {Do not Localize}
begin
bAfterAt := True;
if bInAddress then
begin
FAddress := FAddress + Copy(AText, 1, nFirst);
AText := Copy(AText, nFirst + 1, Length(AText));
end else
begin
if bAddressInLT then
begin
// Strange use. For now raise an exception until a real-world
// example can be found.
// Basically, it's formatted as follows: {Do not Localize}
// <someguy@domain.example> some-text @ some-text
// or:
// some-text <someguy@domain.example> some-text @ some-text
// where some text may be blank.
raise EIdEmailParseError.Create(RSEMailSymbolOutsideAddress);
end else
begin
// If at this point, we're either supporting an e-mail address {Do not Localize}
// on it's own, or the old-style valid format: {Do not Localize}
// "Name" name@domain.example
bInAddress := true;
FAddress := FAddress + Copy(AText, 1, nFirst);
AText := Copy(AText, nFirst + 1, length(AText));
end;
end;
end;
'.' : {Do not Localize}
begin
// Must now be a part of the domain part of the address.
if bAddressInLT then
begin
// Whitespace is possible around the parts of the domain.
FAddress := FAddress +
TrimAllOf(' ' + TAB, Trim(Copy(AText, 1, nFirst - 1))) + '.'; {Do not Localize}
AText := TrimLeft(Copy(AText, nFirst + 1, length(AText)));
end else
begin
// No whitespace is allowed if no wrapping <> characters.
FAddress := FAddress + Copy(AText, 1, nFirst);
AText := Copy(AText, nFirst + 1, length(AText));
end;
end;
'\' : {Do not Localize}
begin
// This will only be discovered in a bracketted or quoted section.
// It's an escape character indicating the next cahracter is {Do not Localize}
// a literal.
if bInQuote then
begin
// Need to retain the second character
if bInAddress then
begin
FAddress := FAddress + Copy(AText, 1, nFirst - 1);
FAddress := FAddress + AText[nFirst + 1];
end else
begin
FName := FName + Copy(AText, 1, nFirst - 1);
FName := FName + AText[nFirst + 1];
end;
end;
AText := Copy(AText, nFirst + 2, length(AText));
end;
end;
// Check for bracketted sections first: ("<>" <> "" <"">) - all is ignored
if nBracketCount > 0 then
begin
// Inside a bracket, only three charatcers are special.
// '(' Opens a nested bracket: (One (Two (Three ))) {Do not Localize}
// ')' Closes a bracket {Do not Localize}
// '/' Escape character: (One /) /( // (Two /) )) {Do not Localize}
nFirst := FindFirstOf('()\', AText); {Do not Localize}
// Check if in quote before address: <"My Name"@domain.example> is valid
end else if bInQuote then
begin
// Inside quotes, only the end quote and escape character are special.
nFirst := FindFirstOf('"\', AText); {Do not Localize}
// Check if after the @ of the address: domain.example>
end else if bAfterAt then
begin
if bAddressInLT then
begin
// If the address is enclosed, then only the '(', '.' & '>' need be {Do not Localize}
// looked for, trimming all content when found: domain . example >
nFirst := FindFirstOf('.>(', AText); {Do not Localize}
end else
begin
nFirst := FindFirstOf('.( ', AText); {Do not Localize}
end;
// Check if in address: <name@domain.example>
end else if bInAddress then
begin
nFirst := FindFirstOf('"(@>', AText); {Do not Localize}
// Not in anything - check for opening charactere
end else
begin
// Outside brackets
nFirst := FindFirstOf('("< @' + TAB, AText); {Do not Localize}
end;
until nFirst = 0;
if bInAddress and not bAddressInLT then
begin
FAddress := FAddress + TrimAllOf(' ' + TAB, Trim(AText)); {Do not Localize}
end;
end else
begin
// No special characters, so assume a simple address
FAddress := AText;
end;
end;
{ TIdEMailAddressList }
function TIdEMailAddressList.Add: TIdEMailAddressItem;
begin
Result := TIdEMailAddressItem ( inherited Add );
end;
constructor TIdEMailAddressList.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TIdEMailAddressItem);
end;
procedure TIdEMailAddressList.FillTStrings(AStrings: TStrings);
var idx : Integer;
begin
idx := 0;
while ( idx < Count ) do
begin
AStrings.Add ( GetItem ( idx ).Text );
Inc ( idx );
end; // while ( idx < Count ) do
end;
function TIdEMailAddressList.GetItem(Index: Integer): TIdEMailAddressItem;
begin
Result := TIdEMailAddressItem ( inherited Items [ Index ] );
end;
function TIdEMailAddressList.GetEMailAddresses: String;
var idx : Integer;
begin
Result := ''; {Do not Localize}
idx := 0;
while ( idx < Count ) do
begin
Result := Result + ', ' + GetItem ( idx ).Text; {Do not Localize}
Inc ( idx );
end; // while ( idx < Count ) do
{Remove the first comma and the following space ', ' } {Do not Localize}
System.Delete ( Result, 1, 2 );
end;
procedure TIdEMailAddressList.SetItem(Index: Integer;
const Value: TIdEMailAddressItem);
begin
inherited SetItem(Index, Value );
end;
procedure TIdEMailAddressList.SetEMailAddresses(AList: String);
var
EMail : TIdEMailAddressItem;
iStart : integer ;
sTemp : string ;
nInBracket : Integer;
bInQuote : Boolean;
begin
Clear;
if (trim(Alist) = '') then exit; {Do not Localize}
iStart := FindFirstOf(':;(", ' + TAB, AList); {Do not Localize}
if iStart = 0 then begin
EMail := Add;
EMail.Text := TrimLeft(AList);
end else begin
sTemp := ''; {Do not Localize}
nInBracket := 0;
bInQuote := False;
repeat
case AList[iStart] of
' ', TAB: begin {Do not Localize}
if iStart = 1 then begin
sTemp := sTemp + AList[iStart];
System.Delete(AList, 1, 1);
end else begin
sTemp := sTemp + Copy(AList, 1, iStart);
AList := Copy(AList, iStart + 1, Length(AList));
end;
end;
':' : {Do not Localize}
begin
// The start of a group - ignore the lot.
AList := Copy(AList, iStart + 1, Length(AList));
sTemp := ''; {Do not Localize}
end;
';' : {Do not Localize}
begin
// End of a group. If we have something (groups can be empty),
// then process it.
sTemp := sTemp + Copy(AList, 1, iStart - 1);
if Length(Trim(sTemp)) > 0 then begin
EMail := Add;
EMail.Text := TrimLeft(sTemp);
sTemp := ''; {Do not Localize}
end;
// Now simply remove the end of the group.
AList := Copy(AList, iStart + 1, length(AList));
end;
'(': begin {Do not Localize}
Inc(nInBracket);
sTemp := sTemp + Copy(AList, 1, iStart);
AList := Copy(AList, iStart + 1, length(AList));
end;
')': begin {Do not Localize}
Dec(nInBracket);
sTemp := sTemp + Copy(AList, 1, iStart);
AList := Copy(AList, iStart + 1, length(AList));
end;
'"': begin {Do not Localize}
sTemp := sTemp + Copy(AList, 1, iStart);
AList := Copy(AList, iStart + 1, Length(AList));
bInQuote := not bInQuote;
end;
',': begin {Do not Localize}
sTemp := sTemp + Copy(AList, 1, iStart - 1);
EMail := Add;
EMail.Text := sTemp;
// added - Allen .. saves blank entries being added
if (trim(Email.Text) = '') or (trim(Email.Text) = '<>') then {Do not Localize}
begin
FreeAndNil(Email);
end;
sTemp := ''; {Do not Localize}
AList := Copy(AList, iStart + 1, length(AList));
end;
'\': begin {Do not Localize}
// Escape character - simply copy this char and the next to the buffer.
sTemp := sTemp + Copy(AList, 1, iStart + 1);
AList := Copy(AList, iStart + 2, length(AList));
end;
end;
if nInBracket > 0 then begin
iStart := FindFirstOf('(\)', AList); {Do not Localize}
end else if bInQuote then begin
iStart := FindFirstOf('"\', AList); {Do not Localize}
end else begin
iStart := FindFirstOf(':;(", ' + TAB, AList); {Do not Localize}
end;
until iStart = 0;
// Clean up the content in sTemp
if (Length(Trim(sTemp)) > 0) or (Length(Trim(AList)) > 0) then begin
sTemp := sTemp + AList;
EMail := Add;
EMail.Text := TrimLeft(sTemp);
// added - Allen .. saves blank entries being added
if (trim(Email.Text) = '') or (trim(Email.Text) = '<>') then {Do not Localize}
begin
FreeAndNil(Email);
end;
end;
end;
end;
end.
|
unit darray_procs_1;
interface
implementation
var G: Int32;
procedure IncG;
begin
Inc(G);
end;
procedure Test;
var
Arr: array of procedure;
begin
SetLength(Arr, 10);
for var i := 0 to Length(Arr) - 1 do
Arr[i] := IncG;
for var i := 0 to Length(Arr) - 1 do
Arr[i]();
end;
initialization
Test();
finalization
Assert(G = 10);
end. |
unit SystemPatch;
interface
type
PPMonitor = ^PMonitor;
PMonitor = ^TMonitor;
TMonitor = record
strict private
type
PWaitingThread = ^TWaitingThread;
TWaitingThread = record
Next: PWaitingThread;
Thread: TThreadID;
WaitEvent: Pointer;
end;
{ TSpinWait implements an exponential backoff algorithm for TSpinLock. The algorithm is as follows:
If the CPUCount > 1, then the first 10 (YieldThreshold) spin cycles (calls to SpinCycle) will use a base 2
exponentially increasing spin count starting at 4. After 10 cycles, then the behavior reverts to the same
behavior as when CPUCount = 1.
If the CPUCount = 1, then it will sleep 1ms every modulus 20 cycles and sleep 0ms every modulus 5 cycles.
All other cycles simply yield (SwitchToThread - Windows, sched_yield - POSIX). }
TSpinWait = record
private const
YieldThreshold = 10;
Sleep1Threshold = 20;
Sleep0Threshold = 5;
private
FCount: Integer;
public
procedure Reset; inline;
procedure SpinCycle;
end;
{ TSpinLock implements a very simple non-reentrant lock. This lock does not block the calling thread using a
synchronization object. Instead it opts to burn a few extra CPU cycles using the above TSpinWait type. This
is typically far faster than fully blocking since the length of time the lock is held is relatively few
cycles and the thread switching overhead will usually far outpace the few cycles burned by simply spin
waiting. }
TSpinLock = record
private
FLock: Integer;
public
procedure Enter;
procedure Exit;
end;
var
FLockCount: Integer;
FRecursionCount: Integer;
FOwningThread: TThreadID;
FLockEvent: Pointer;
FSpinCount: Integer;
FWaitQueue: PWaitingThread;
FQueueLock: TSpinLock;
class var CacheLineSize: Integer;
class procedure Spin(Iterations: Integer); static;
class function GetCacheLineSize: Integer; static;
procedure QueueWaiter(var WaitingThread: TWaitingThread);
procedure RemoveWaiter(var WaitingThread: TWaitingThread);
function DequeueWaiter: PWaitingThread;
function GetEvent: Pointer;
function CheckOwningThread: TThreadID;
class procedure CheckMonitorSupport; static; inline;
class function Create: PMonitor; static;
// Make sure the following Destroy overload is always
// listed first since it is called from an asm block
// and there is no overload-resolution done from an
// basm symbol reference
private
class procedure Destroy(AObject: TObject); overload; static;
strict private
class function GetFieldAddress(AObject: TObject): PPMonitor; inline; static;
class function GetMonitor(AObject: TObject): PMonitor; static;
procedure Destroy; overload;
function Enter(Timeout: Cardinal): Boolean; overload;
procedure Exit; overload;
function TryEnter: Boolean; overload;
function Wait(ALock: PMonitor; Timeout: Cardinal): Boolean; overload;
procedure Pulse; overload;
procedure PulseAll; overload;
public
{ In multi-core/multi-processor systems, it is sometimes desirable to spin for a few cycles instead of blocking
the current thread when attempting to Enter the monitor. Use SetSpinCount to set a reasonable number of times to
spin before fully blocking the thread. This value usually obtained through empirical study of the particular
situation. }
class procedure SetSpinCount(AObject: TObject; ASpinCount: Integer); static;
{ Enter locks the monitor object with an optional timeout (in ms) value. Enter without a timeout will wait until
the lock is obtained. If the procedure returns it can be assumed that the lock was acquired. Enter with a
timeout will return a boolean status indicating whether or not the lock was obtained (True) or the attempt timed
out prior to acquire the lock (False). Calling Enter with an INFINITE timeout is the same as calling Enter
without a timeout.
TryEnter will simply attempt to obtain the lock and return immediately whether or not the lock was acuired.
Enter with a 0ms timeout is functionally equivalent to TryEnter.
Exit will potentially release the lock acquired by a call to Enter or TryEnter. Since Enter/TryEnter are
rentrant, you must balance each of those calls with a corresponding call to Exit. Only the last call to Exit will
release the lock and allow other threads to obtain it. Runtime error, reMonitorNoLocked, is generated if Exit is
called and the calling thread does not own the lock. }
class procedure Enter(AObject: TObject); overload; static; inline;
class function Enter(AObject: TObject; Timeout: Cardinal): Boolean; overload; static;
class procedure Exit(AObject: TObject); overload; static;
class function TryEnter(AObject: TObject): Boolean; overload; static;
{ Wait will atomically fully release the lock (regardless of the recursion count) and block the calling thread
until another thread calls Pulse or PulseAll. The first overloaded Wait function will assume the locked object
and wait object are the same and thus the calling thread must own the lock. The second Wait allows the given
monitor to atomically unlock the separate monitor lock object and block with the calling thread on the first
given wait object. Wait will not return (even if it times out) until the monitor lock can be acquired again. It
is possible for wait to return False (the timeout expired) after a much longer period of time has elapsed if
the locking object was being held by another thread for an extended period. When Wait returns the recursion
level of the lock has been restored.
Pulse must be called on the exact same instance passed to Wait in order to properly release one waiting thread.
PulseAll works the same as Pulse except that it will release all currently waiting threads.
Wait/Pulse/PulseAll are the same as a traditional condition variable.
}
class function Wait(AObject: TObject; Timeout: Cardinal): Boolean; overload; static;
class function Wait(AObject, ALock: TObject; Timeout: Cardinal): Boolean; overload; static;
class procedure Pulse(AObject: TObject); overload; static;
class procedure PulseAll(AObject: TObject); overload; static;
end;
const
INFINITE = Cardinal($FFFFFFFF); {$EXTERNALSYM INFINITE}
implementation
{ TMonitor }
{$IFDEF POSIX}
procedure Sleep(Timeout: Integer); inline;
begin
usleep(Timeout * 1000);
end;
function GetTickCount: Cardinal; inline;
{$IFDEF LINUX}
var
t: tms;
begin
Result := Cardinal(Int64(Cardinal(times(t)) * 1000) div sysconf(_SC_CLK_TCK));
end;
{$ENDIF}
{$IFDEF MACOS}
begin
Result := AbsoluteToNanoseconds(UpTime) div 1000000;
end;
{$ENDIF MACOS}
{$ENDIF POSIX}
{ TMonitor.TSpinWait }
procedure TMonitor.TSpinWait.Reset;
begin
FCount := 0;
end;
procedure TMonitor.TSpinWait.SpinCycle;
var
SpinCount: Integer;
begin
if (FCount > YieldThreshold) or (CPUCount <= 1) then
begin
if FCount >= YieldThreshold then
SpinCount := FCount - 10
else
SpinCount := FCount;
if SpinCount mod Sleep1Threshold = Sleep1Threshold - 1 then
Sleep(1)
else if SpinCount mod Sleep0Threshold = Sleep0Threshold - 1 then
Sleep(0)
else
{$IFDEF MSWINDOWS}
Yield;
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
sched_yield;
{$ENDIF POSIX}
end else
Spin(4 shl FCount);
Inc(FCount);
if FCount < 0 then
FCount := 10;
end;
{ TMonitor.TSpinLock }
procedure TMonitor.TSpinLock.Enter;
var
LLock: Integer;
Wait: TSpinWait;
begin
Wait.Reset;
while True do
begin
LLock := FLock;
if LLock = 0 then
begin
if InterlockedCompareExchange(FLock, 1, LLock) = LLock then
System.Exit;
end;
Wait.SpinCycle;
end;
end;
procedure TMonitor.TSpinLock.Exit;
begin
InterlockedExchange(FLock, 0);
end;
class procedure TMonitor.Spin(Iterations: Integer);
{$IF defined(CPUX86) or defined(CPUX64)}
asm
CMP Iterations, 0
JNG @Done
@Loop:
PAUSE
DEC Iterations
CMP Iterations, 0
JG @LOOP
@Done:
end;
{$ELSE}
begin
while Iterations > 0 do
begin
YieldProcessor;
Dec(Iterations);
end;
end;
{$IFEND}
class function TMonitor.GetCacheLineSize: Integer;
{$IFDEF MSWINDOWS}
{$POINTERMATH ON}
var
ProcInfo, CurInfo: PSystemLogicalProcessorInformation;
Len: DWORD;
begin
Len := 0;
if (GetProcAddress(GetModuleHandle(kernel), 'GetLogicalProcessorInformation') <> nil) and
not GetLogicalProcessorInformation(nil, Len) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
GetMem(ProcInfo, Len);
try
GetLogicalProcessorInformation(ProcInfo, Len);
CurInfo := ProcInfo;
while Len > 0 do
begin
if (CurInfo.Relationship = RelationCache) and (CurInfo.Cache.Level = 1) then
System.Exit(CurInfo.Cache.LineSize);
Inc(CurInfo);
Dec(Len, SizeOf(CurInfo^));
end;
finally
FreeMem(ProcInfo);
end;
end;
Result := 64; // Use a reasonable default cache line size.
end;
{$POINTERMATH OFF}
{$ENDIF}
{$IFDEF POSIX}
var
LineSize: UInt64;
Size: Integer;
begin
Size := SizeOf(LineSize);
if sysctlbyname('hw.cachelinesize', @LineSize, @Size, nil, 0) = 0 then
Result := LineSize
else
Result := 64;
end;
{$ENDIF}
class procedure TMonitor.CheckMonitorSupport;
begin
if MonitorSupport = nil then
Error(reNoMonitorSupport);
end;
function TMonitor.CheckOwningThread: TThreadID;
begin
Result := FOwningThread;
if Result <> GetCurrentThreadId then
Error(reMonitorNotLocked)
end;
class function TMonitor.Create: PMonitor;
begin
if CacheLineSize = 0 then
InterlockedExchange(CacheLineSize, GetCacheLineSize);
if CacheLineSize > SizeOf(Result^) then
Result := AllocMem(CacheLineSize)
else
Result := AllocMem(SizeOf(Result^));
end;
class procedure TMonitor.Destroy(AObject: TObject);
var
MonitorFld: PPMonitor;
Monitor: PMonitor;
begin
MonitorFld := GetFieldAddress(AObject);
if MonitorFld^ <> nil then
begin
Monitor := MonitorFld^;
MonitorFld^ := nil;
Monitor.Destroy;
end;
end;
procedure TMonitor.Destroy;
begin
if (MonitorSupport <> nil) and (FLockEvent <> nil) then
MonitorSupport.FreeSyncObject(FLockEvent);
FreeMem(@Self);
end;
class procedure TMonitor.Enter(AObject: TObject);
begin
CheckMonitorSupport;
GetMonitor(AObject).Enter(INFINITE);
end;
class function TMonitor.Enter(AObject: TObject; Timeout: Cardinal): Boolean;
begin
CheckMonitorSupport;
Result := GetMonitor(AObject).Enter(Timeout);
end;
function TMonitor.DequeueWaiter: PWaitingThread;
begin
FQueueLock.Enter;
try
Result := FWaitQueue;
if (Result = nil) or (Result.Next = Result) then
begin
FWaitQueue := nil;
System.Exit;
end else
begin
Result := FWaitQueue.Next;
FWaitQueue.Next := FWaitQueue.Next.Next;
end;
finally
FQueueLock.Exit;
end;
end;
function TMonitor.Enter(Timeout: Cardinal): Boolean;
label
TryAgain;
var
Done: Boolean;
LockCount: Integer;
StartCount, EndCount: Cardinal;
SpinCount: Integer;
begin
SpinCount := FSpinCount;
// Return here if signaled and lock wasn't acquired
TryAgain:
Result := TryEnter;
if not Result and (Timeout <> 0) then
begin
Done := False;
// Get the spin count
if SpinCount > 0 then
begin
StartCount := GetTickCount;
while SpinCount > 0 do
begin
if (Timeout <> INFINITE) and ((GetTickCount - StartCount) >= Timeout) then
begin
Result := False;
System.Exit;
end;
// if there are already waiters, don't bother spinning
if FLockCount > 1 then
Break;
// Try to get the lock
if FLockCount = 0 then
if InterlockedCompareExchange(FLockCount, 1, 0) = 0 then
begin
FOwningThread := GetCurrentThreadId;
FRecursionCount := 1;
Result := True;
System.Exit;
end;
YieldProcessor;
Dec(SpinCount);
// Keep trying until the spin count expires
end;
// Adjust the timeout in case the spin-lock expired above.
if Timeout <> INFINITE then
begin
EndCount := GetTickCount;
if EndCount - StartCount >= Timeout then
begin
Result := False;
System.Exit;
end;
Dec(Timeout, EndCount - StartCount);
end;
end;
// Before we can block, we add our count to the lock
while True do
begin
LockCount := FLockCount;
if LockCount = 0 then
goto TryAgain;
if InterlockedCompareExchange(FLockCount, LockCount + 2, LockCount) = LockCount then
Break;
end;
while True do
begin
StartCount := GetTickCount;
// We're not the owner, so blocking is needed
// GetEvent does a "safe" allocation of the Event
Result := MonitorSupport.WaitOrSignalObject(nil, GetEvent, Timeout) = WAIT_OBJECT_0;
if Timeout <> INFINITE then
begin
EndCount := GetTickCount;
if EndCount - StartCount < Timeout then
Dec(Timeout, EndCount - StartCount)
else
Timeout := 0;
end;
if Result then
begin
// Event was signaled, so try to acquire the lock since this could be a spurious condition
while True do
begin
LockCount := FLockCount;
if LockCount and 1 <> 0 then
Break;
if InterlockedCompareExchange(FLockCount, (LockCount - 2) or 1, LockCount) = LockCount then
begin
Done := True;
Break;
end;
end;
end else
begin
// We timed out, remove our presence from the lock count
repeat
LockCount := FLockCount;
until InterlockedCompareExchange(FLockCount, LockCount - 2, LockCount) = LockCount;
Done := True;
end;
if Done then
Break;
end;
if Result then
begin
FOwningThread := GetCurrentThreadId;
FRecursionCount := 1;
end;
end;
end;
procedure TMonitor.Exit;
var
LockCount: Integer;
begin
CheckOwningThread;
Dec(FRecursionCount);
if FRecursionCount = 0 then
begin
FOwningThread := 0;
while True do
begin
LockCount := FLockCount;
if InterlockedCompareExchange(FLockCount, LockCount - 1, LockCount) = LockCount then
begin
// if LockCount is <> 0 after we dropped our lock, there were waiters, so signal them
if LockCount and not 1 <> 0 then
MonitorSupport.WaitOrSignalObject(GetEvent, nil, 0);
Break;
end;
end;
end;
end;
class procedure TMonitor.Exit(AObject: TObject);
begin
CheckMonitorSupport;
GetMonitor(AObject).Exit;
end;
function TMonitor.GetEvent: Pointer;
var
SleepTime: Integer;
Event: Pointer;
begin
SleepTime := 1;
Result := FLockEvent;
if Result = nil then
while True do
begin
Event := MonitorSupport.NewSyncObject;
Result := InterlockedCompareExchangePointer(FLockEvent, Event, nil);
if Result = nil then
// We won! Nobody else was trying to allocate the Event.
Result := Event
else if Event <> nil then
// Oh Well. We tried. Close the handle if someone got to it first.
MonitorSupport.FreeSyncObject(Event);
// Check if we actually were able to allocate the event without fail
if Result <> nil then
System.Exit;
// We failed to allocate the event, so wait a bit to see if one becomes available
Sleep(SleepTime);
// Don't let it run-away, so return to a reasonable value and keep trying
if SleepTime > 512 then
SleepTime := 1
else
// Next time wait a little longer
SleepTime := SleepTime shl 1;
end;
end;
class function TMonitor.GetFieldAddress(AObject: TObject): PPMonitor;
begin
Result := PPMonitor(PByte(AObject) + AObject.InstanceSize - hfFieldSize + hfMonitorOffset);
end;
class function TMonitor.GetMonitor(AObject: TObject): PMonitor;
var
MonitorFld: PPMonitor;
Monitor: PMonitor;
begin
MonitorFld := GetFieldAddress(AObject);
Result := MonitorFld^;
if Result = nil then
begin
Monitor := TMonitor.Create;
Result := InterlockedCompareExchangePointer(Pointer(MonitorFld^), Monitor, nil);
if Result = nil then
Result := Monitor
else
FreeMem(Monitor);
end;
end;
procedure TMonitor.Pulse;
var
WaitingThread: PWaitingThread;
begin
WaitingThread := DequeueWaiter;
if WaitingThread <> nil then
MonitorSupport.WaitOrSignalObject(WaitingThread.WaitEvent, nil, 0);
end;
class procedure TMonitor.Pulse(AObject: TObject);
begin
CheckMonitorSupport;
GetMonitor(AObject).Pulse;
end;
procedure TMonitor.PulseAll;
var
WaitingThread: PWaitingThread;
begin
WaitingThread := DequeueWaiter;
while WaitingThread <> nil do
begin
MonitorSupport.WaitOrSignalObject(WaitingThread.WaitEvent, nil, 0);
WaitingThread := DequeueWaiter;
end;
end;
class procedure TMonitor.PulseAll(AObject: TObject);
begin
CheckMonitorSupport;
GetMonitor(AObject).PulseAll;
end;
procedure TMonitor.QueueWaiter(var WaitingThread: TWaitingThread);
begin
FQueueLock.Enter;
try
if FWaitQueue = nil then
begin
FWaitQueue := @WaitingThread;
WaitingThread.Next := @WaitingThread;
end else
begin
WaitingThread.Next := FWaitQueue.Next;
FWaitQueue.Next := @WaitingThread;
FWaitQueue := @WaitingThread;
end;
finally
FQueueLock.Exit;
end;
end;
procedure TMonitor.RemoveWaiter(var WaitingThread: TWaitingThread);
var
Last, Walker: PWaitingThread;
begin
// Perform a check, lock, check
if FWaitQueue <> nil then
begin
FQueueLock.Enter;
try
if FWaitQueue <> nil then
begin
Last := FWaitQueue;
Walker := Last.Next;
while Walker <> FWaitQueue do
begin
if Walker = @WaitingThread then
begin
Last.Next := Walker.Next;
Break;
end;
Last := Walker;
Walker := Walker.Next;
end;
if (Walker = FWaitQueue) and (Walker = @WaitingThread) then
if Walker.Next = Walker then
FWaitQueue := nil
else
begin
FWaitQueue := Walker.Next;
Last.Next := FWaitQueue;
end;
end;
finally
FQueueLock.Exit;
end;
end;
end;
class procedure TMonitor.SetSpinCount(AObject: TObject; ASpinCount: Integer);
var
Monitor: PMonitor;
begin
if CPUCount > 1 then
begin
Monitor := GetMonitor(AObject);
InterlockedExchange(Monitor.FSpinCount, ASpinCount);
end;
end;
class function TMonitor.TryEnter(AObject: TObject): Boolean;
begin
CheckMonitorSupport;
Result := GetMonitor(AObject).TryEnter;
end;
function TMonitor.TryEnter: Boolean;
begin
if FOwningThread = GetCurrentThreadId then // check for recursion
begin
// Only the owning thread can increment this value so no need to guard it
Inc(FRecursionCount);
Result := True;
// check to see if we can gain ownership
end else if (FLockCount = 0) and (InterlockedCompareExchange(FLockCount, 1, 0) = 0) then
begin
// Yep, got it. Now claim ownership
FOwningThread := GetCurrentThreadId;
FRecursionCount := 1;
Result := True;
end else
Result := False;
end;
function TMonitor.Wait(ALock: PMonitor; Timeout: Cardinal): Boolean;
var
RecursionCount: Integer;
WaitingThread: TWaitingThread;
begin
WaitingThread.Next := nil;
WaitingThread.Thread := ALock.CheckOwningThread;
// This event should probably be cached someplace.
// Probably not on the instance since this is a per-thread-per-instance resource
WaitingThread.WaitEvent := MonitorSupport.NewWaitObject;
try
// Save the current recursion count for later
RecursionCount := ALock.FRecursionCount;
// Add the current thread to the waiting queue
QueueWaiter(WaitingThread);
// Set it back to almost released so the next Exit call actually drops the lock
ALock.FRecursionCount := 1;
// Now complete the exit and signal any waiters
ALock.Exit;
// Get in line for someone to do a Pulse or PulseAll
Result := MonitorSupport.WaitOrSignalObject(nil, WaitingThread.WaitEvent, Timeout) = WAIT_OBJECT_0;
// Got to get the lock back and block waiting for it.
ALock.Enter(INFINITE);
// Remove any dangling waiters from the list
RemoveWaiter(WaitingThread);
// Lets restore the recursion to return to the proper nesting level
ALock.FRecursionCount := RecursionCount;
finally
MonitorSupport.FreeWaitObject(WaitingThread.WaitEvent);
end;
end;
class function TMonitor.Wait(AObject: TObject; Timeout: Cardinal): Boolean;
var
Monitor: PMonitor;
begin
CheckMonitorSupport;
Monitor := GetMonitor(AObject);
Result := Monitor.Wait(Monitor, Timeout);
end;
class function TMonitor.Wait(AObject, ALock: TObject; Timeout: Cardinal): Boolean;
begin
CheckMonitorSupport;
Result := GetMonitor(AObject).Wait(GetMonitor(ALock), Timeout);
end;
function MonitorEnter(AObject: TObject; Timeout: Cardinal = INFINITE): Boolean;
begin
Result := TMonitor.Enter(AObject, Timeout);
end;
function MonitorTryEnter(AObject: TObject): Boolean;
begin
Result := TMonitor.TryEnter(AObject);
end;
procedure MonitorExit(AObject: TObject);
begin
TMonitor.Exit(AObject);
end;
function MonitorWait(AObject: TObject; Timeout: Cardinal): Boolean;
begin
Result := TMonitor.Wait(AObject, AObject, Timeout);
end;
function MonitorWait(AObject: TObject; ALock: TObject; Timeout: Cardinal): Boolean;
begin
Result := TMonitor.Wait(AObject, ALock, Timeout);
end;
procedure MonitorPulse(AObject: TObject);
begin
TMonitor.Pulse(AObject);
end;
procedure MonitorPulseAll(AObject: TObject);
begin
TMonitor.PulseAll(AObject);
end;
procedure MemoryBarrier;
{$IF defined(CPUX64)}
asm
MFENCE
end;
{$ELSEIF defined(CPUX86)}
asm
PUSH EAX
XCHG [ESP],EAX
POP EAX
end;
{$ELSE}
begin
Error(rePlatformNotImplemented);
end;
{$IFEND}
procedure YieldProcessor;
{$IF defined(CPUX86) or defined(CPUX64)}
asm
PAUSE
end;
{$ELSE}
begin
Error(rePlatformNotImplemented);
end;
{$IFEND}
end.
|
unit Teste.ChangeSet.JSONData;
interface
uses
System.JSON;
type
TChangeSetJSONData = class
class function Pegar: TJSONArray;
class function PegarChangeSetItem: TJSONObject;
class function PegarChangeSetItemDoisArquivos: TJSONObject;
end;
implementation
class function TChangeSetJSONData.Pegar: TJSONArray;
begin
Result := TJSONObject.ParseJSONValue(
'[ '+
' { '+
' "_class": "com.ibm.team.build.internal.hjplugin.RTCChangeLogChangeSetEntry", '+
' "commitId": null, '+
' "affectedPaths": [ '+
' "/src/Classes/nomeDoArquivo.pas" '+
' ], '+
' "author": { '+
' "absoluteUrl": "http://jenkins/user/jian.kowalski", '+
' "fullName": "Jose da Silva Sauro" '+
' }, '+
' "msg": "Descrição do commit", '+
' "timestamp": 1548268243953 '+
' }, '+
' { '+
' "_class": "com.ibm.team.build.internal.hjplugin.RTCChangeLogChangeSetEntry", '+
' "commitId": null, '+
' "affectedPaths": [ '+
' "/src/Classes/nomeDoArquivo.pas" '+
' ], '+
' "author": { '+
' "absoluteUrl": "http://jenkins/user/jian.kowalski", '+
' "fullName": "Jose da Silva Sauro" '+
' }, '+
' "msg": "Descrição do commit", '+
' "timestamp": 1548436904300 ' +
' } ' +
'] ') as TJSONArray;
end;
class function TChangeSetJSONData.PegarChangeSetItem: TJSONObject;
begin
Result := TJSONObject.ParseJSONValue(
'{ ' +
' "_class": "com.ibm.team.build.internal.hjplugin.RTCChangeLogChangeSetEntry", ' +
' "commitId": null, ' +
' "affectedPaths": [ ' +
' "/src/Classes/nomeDoArquivo.pas" ' +
' ], ' +
' "author": { ' +
' "absoluteUrl": "http://jenkins/user/jian.kowalski", ' +
' "fullName": "Jose da Silva Sauro" ' +
' }, ' +
' "msg": "Descrição do commit", ' +
' "timestamp": 1548268243953 ' +
'} ') as TJSONObject;
end;
class function TChangeSetJSONData.PegarChangeSetItemDoisArquivos: TJSONObject;
begin
Result := TJSONObject.ParseJSONValue(
'{ ' +
' "_class": "com.ibm.team.build.internal.hjplugin.RTCChangeLogChangeSetEntry", ' +
' "commitId": null, ' +
' "affectedPaths": [ ' +
' "/src/Classes/nomeDoArquivo.pas", ' +
' "/src/Classes/nomeDoArquivo2.pas" ' +
' ], ' +
' "author": { ' +
' "absoluteUrl": "http://jenkins/user/jian.kowalski", ' +
' "fullName": "Jose da Silva Sauro" ' +
' }, ' +
' "msg": "Descrição do commit", ' +
' "timestamp": 1548268243953 ' +
'} ') as TJSONObject;
end;
end.
|
unit meetingsEditScreen;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, uMeetingsClass, uMeetingsArray,
programmesScreen;
type
TfrmMeetingsEditScreen = class(TForm)
btnSubmit: TButton;
lblHeading: TLabel;
Label1: TLabel;
edtTime: TEdit;
Label2: TLabel;
edtLocation: TEdit;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
edtMeetingNo: TEdit;
edtNoAttending: TEdit;
cmbProgramme: TComboBox;
rchTheme: TRichEdit;
btnViewProgramme: TButton;
dateBox: TDateTimePicker;
procedure FormShow(Sender: TObject);
procedure btnSubmitClick(Sender: TObject);
procedure btnViewProgrammeClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
function IsNumericString(const inStr: string): Boolean;
private
{ Private declarations }
meetingsErrorFlag : integer;
public
{ Public declarations }
date : string;
time : string;
location : string;
meetingNo : integer;
programme : integer;
attending : integer;
theme : string;
add : integer;
end;
var
frmMeetingsEditScreen: TfrmMeetingsEditScreen;
implementation
uses
mainScreen;
{$R *.dfm}
procedure TfrmMeetingsEditScreen.FormShow(Sender: TObject);
begin
{If a new meeting is being added, then the default values are fed into the
form to give the user an example of the expected data types and formats to
be entered. The other elements are all cleared or reset to remove any
residual data from previous instances of it.}
if add = 1 then
begin
dateBox.Date := StrToDate('2000-01-01');
edtTime.Text := '06:00:00 PM';
edtLocation.Text := 'Centenary Centre';
edtMeetingNo.Clear;
cmbProgramme.Text := '';
edtNoAttending.Clear;
rchTheme.Clear;
end
{If a meeting is being updated then the values assigned to the meeting are
read in from the variables in the form and the elements of the form are
populated with the corresponding data.}
else if add = 0 then
begin
dateBox.Date := StrToDate(date);
edtTime.Text := time;
edtLocation.Text := location;
edtMeetingNo.Text := IntToStr(meetingNo);
cmbProgramme.Text := IntToStr(programme);
edtNoAttending.Text := IntToStr(attending);
rchTheme.Text := theme;
end;
end;
{When the submit button is clicked, error checking is performed. If any element
on the form does not have data of the correct type or format then the user is
notified with a message and colour indicator. If all data entered is suitable
then the meetingsErrorFlag variable is set to 1 to indicate that the data can
be saved to the database. The database then has a meeting added or updated.}
procedure TfrmMeetingsEditScreen.btnSubmitClick(Sender: TObject);
var
newMeeting : TMeetings;
meetingsDB : TMeetingsArray;
currentMeeting : TMeetings;
begin
{Error checking ensures that the data entered into the form is valid and
correctly formatted. If not, it displays colour indicators and messages
indicating where the erroneous data is. If all data is suitable then the
meetingsErrorFlag variable is set to 1 to indicate that the data is correct
and may be computed.}
if (DateToStr(dateBox.DateTime) <> '')
and (DateToStr(dateBox.DateTime) <> '2000-01-01') then
begin
if (edtTime.Text <> '') and (edtTime.Text[3] = ':')
and (edtTime.Text[6] = ':') then
begin
if edtLocation.Text <> '' then
begin
if (edtMeetingNo.Text <> '')
and (IsNumericString(edtMeetingNo.Text)) then
begin
if (cmbProgramme.Text <> '')
and (IsNumericString(cmbProgramme.Text)) then
begin
if (edtNoAttending.Text <> '')
and (IsNumericString(edtNoAttending.Text)) then
begin
if rchTheme.Text <> '' then
begin
meetingsErrorFlag := 1;
end
else
begin
rchTheme.Color := clRed;
ShowMessage('A theme must be entered for the evening.');
rchTheme.Color := clWhite;
end;
end
else
begin
edtNoAttending.Color := clRed;
ShowMessage('Number attending must be '+
'entered as an integer value.');
edtNoAttending.Color := clWhite;
end;
end
else
begin
cmbProgramme.Color := clRed;
ShowMessage('The programme number must be a valid integer '+
'value and must not conflict with any other programmes.');
cmbProgramme.Color := clWhite;
end;
end
else
begin
edtMeetingNo.Color := clRed;
ShowMessage('A meeting number must be entered and must ' +
'be an integer value.');
edtMeetingNo.Color := clWhite;
end;
end
else
begin
edtLocation.Color := clRed;
ShowMessage('A location must be entered in the form of a text string. '+
'This can be changed later.');
edtLocation.Color := clWhite;
end;
end
else
begin
edtTime.Color := clRed;
ShowMessage('Time must conform to the format hh:mm:ss PM ' +
' and be a valid value.');
edtTime.Color := clWhite;
end;
end
else
begin
dateBox.Color := clRed;
ShowMessage('Date must conform to format yyyy-mm-dd and ' +
'must be a valid value.');
dateBox.Color := clWhite;
end;
{If all the error checking is performed successfully.}
if meetingsErrorFlag = 1 then
begin
{If a new meeting is being added then a meeting class is instantiated
and populated with the data from the form. A meetings array class is
instantiated and the database is added to.}
if add = 1 then
begin
newMeeting := TMeetings.Create(StrToInt(edtMeetingNo.Text),
DateToStr(dateBox.Date),
edtTime.Text,
edtLocation.Text,
StrToInt(edtNoAttending.Text),
rchTheme.Text,
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
StrToInt(cmbProgramme.Text));
meetingsDB := TMeetingsArray.Create('toastmasters.mdb');
meetingsDB.addMeeting(newMeeting);
end
else
begin
{If a meeting is being updated then a meeting class is instantiated
and populated with the data from the form. A meetings array class is
instantiated and the database is updated.}
newMeeting := TMeetings.Create(StrToInt(edtMeetingNo.Text),
DateToStr(dateBox.Date),
edtTime.Text,
edtLocation.Text,
StrToInt(edtNoAttending.Text),
rchTheme.Text,
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
StrToInt(cmbProgramme.Text));
meetingsDB := TMeetingsArray.Create('toastmasters.mdb');
meetingsDB.updateMeeting(newMeeting);
end;
{The meetings in the database populate the listbox on the main screen
to reflect changes.}
mainScreen.frmMainScreen.lstbMeetings.Items := meetingsDB.getAllMeetings;
Hide;
end;
end;
{The view programme button is clicked and the programmes edit screen is
shown. If a programme with the same programme number exists, then the data from
the text file stored in the project folder is read into the corresponding
sections of the programmes screen form. If not, then a new text file is created
and any changes are saved to it.}
procedure TfrmMeetingsEditScreen.btnViewProgrammeClick(Sender: TObject);
begin
programmesScreen.frmProgrammes.progNo := StrToInt(cmbProgramme.Text);
programmesScreen.frmProgrammes.Show;
hide;
end;
{When the form is activated the meetingsErrorFlag varriable is set to 0 to
indicate that the form has not been error checked. If the add variable is set
to 1 then he view programme button is dissabled as it requires the meeting to
be added to the database before it will function
- i.e. only when updating a meeting. If it is set to 0 then the view programme
button is enabled to allow the programme to be created / accessed.}
procedure TfrmMeetingsEditScreen.FormActivate(Sender: TObject);
begin
meetingsErrorFlag := 0;
if add = 1 then
begin
btnViewProgramme.Enabled := False;
end
else
begin
btnViewProgramme.Enabled := True;
end;
end;
{A function to test whether a string contains only numerals and thus can be
converted to an integer. This is used in error checking.}
function TfrmMeetingsEditScreen.IsNumericString(const inStr: string): Boolean;
var
i: extended;
begin
Result := TryStrToFloat(inStr,i);
end;
end.
|
unit uFuncoes;
interface
uses
SysUtils, Dialogs, Controls, Forms, Windows, TypInfo, Registry;
type
schar = set of char;
function SomenteNum(const s: string; conj: schar): boolean;
function ValidaCPF(const Value: String): boolean;
function ValidaCNPJ(const Value: String): boolean;
Function VersaoExeStr: String;
function DiretorioExe: String;
function VersaoExeInt: Integer;
function fnc_GetComputerName : string;
implementation
Function VersaoExeStr: String;
type
PFFI = ^vs_FixedFileInfo;
var
F : PFFI;
Handle : Dword;
Len : Longint;
Data : Pchar;
Buffer : Pointer;
Tamanho : Dword;
Parquivo: Pchar;
Arquivo : String;
begin
Arquivo := Application.ExeName;
Parquivo := StrAlloc(Length(Arquivo) + 1);
StrPcopy(Parquivo, Arquivo);
Len := GetFileVersionInfoSize(Parquivo, Handle);
Result := '';
if Len > 0 then
begin
Data:=StrAlloc(Len+1);
if GetFileVersionInfo(Parquivo,Handle,Len,Data) then
begin
VerQueryValue(Data, '',Buffer,Tamanho);
F := PFFI(Buffer);
Result := Format('%d.%d.%d.%d',
[HiWord(F^.dwFileVersionMs),
LoWord(F^.dwFileVersionMs),
HiWord(F^.dwFileVersionLs),
Loword(F^.dwFileVersionLs)]
);
end;
StrDispose(Data);
end;
StrDispose(Parquivo);
end;
function SomenteNum(const s: string; conj: schar): boolean;
var
i: integer;
begin
for i := 1 to Length(s) do
if not (s[i] in ['0'..'9']) then
begin
result := false;
exit;
end;
result := true;
end;
function ValidaCPF(const Value: String): boolean;
var
digito1, digito2: integer;
i, soma: integer;
begin
{analisa CPF no formato 00000000000}
if Length(Value) <> 11 then
begin
result := false;
exit;
end;
if Value = StringOfChar(Value[1], Length(Value)) then
begin
result := false;
exit;
end;
{verifica se todos os caracteres são nº}
if not SomenteNum(Value, ['0'..'9']) then
begin
result := false;
exit;
end;
{comeca a verificacao do digito}
{1° digito}
soma := 0;
for i := 1 to 9 do
Inc(soma, StrToInt(Value[10 - i]) * (i + 1));
digito1 := 11 - (soma mod 11);
if digito1 > 9 then
digito1 := 0;
{2° digito}
soma := 0;
for i := 1 to 10 do
Inc(soma, StrToInt(Value[11 - i]) * (i + 1));
digito2 := 11 - (soma mod 11);
if digito2 > 9 then
digito2 := 0;
{Checa os dois dígitos}
result := (Digito1 = StrToInt(Value[10])) and
(Digito2 = StrToInt(Value[11]));
end;
function ValidaCNPJ(const Value: String): boolean;
var
digito1, digito2: integer;
i, soma: integer;
begin
{analisa CGC no formato 00000000000000}
if Length(Value) <> 14 then
begin
result := false;
exit;
end;
{verifica se todos os caracteres são nº}
if not SomenteNum(Value, ['0'..'9']) then
begin
result := false;
exit;
end;
{comeca a verificacao do digito}
{1° digito}
soma := 0;
for i := 1 to 12 do
begin
if i < 5 then
Inc(soma, StrToInt(Value[i]) * (6 - i))
else
Inc(soma, StrToInt(Value[i]) * (14 - i))
end;
digito1 := 11 - (soma mod 11);
if digito1 > 9 then
digito1 := 0;
{2° digito}
soma := 0;
for i := 1 to 13 do
begin
if i < 6 then
Inc(soma, StrToInt(Value[i]) * (7 - i))
else
Inc(soma, StrToInt(Value[i]) * (15 - i))
end;
digito2 := 11 - (soma mod 11);
if digito2 > 9 then
digito2 := 0;
{Checa os dois dígitos}
result := (Digito1 = StrToInt(Value[13])) and
(Digito2 = StrToInt(Value[14]));
end;
function DiretorioExe: String;
begin
Result := ExtractFilePath(Application.ExeName);
end;
function VersaoExeInt: Integer;
begin
Result := StrToIntDef(StringReplace(VersaoExeStr, '.', '', [rfReplaceAll]), 0);
end;
function Min(a, b: integer): integer;
begin
if a < b then
Result := a
else
Result := b;
end;
function fnc_GetComputerName : string;
var ipbuffer : string;
nsize : dword;
begin
nsize := 255;
SetLength(ipbuffer,nsize);
if GetComputerName(pchar(ipbuffer),nsize) then
result := ipbuffer;
end;
end.
|
{******************************************}
{ TGanttSeries Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{******************************************}
unit TeeGanttEdi;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
Chart, GanttCh, TeCanvas, TeePenDlg, TeeProcs;
type
TGanttSeriesEditor = class(TForm)
Label2: TLabel;
SEPointVertSize: TEdit;
BConnLines: TButtonPen;
UDPointVertSize: TUpDown;
GPLine: TGroupBox;
BColor: TButtonColor;
CBColorEach: TCheckBox;
Label1: TLabel;
Edit1: TEdit;
UpDown1: TUpDown;
procedure FormShow(Sender: TObject);
procedure SEPointVertSizeChange(Sender: TObject);
procedure CBColorEachClick(Sender: TObject);
procedure BColorClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Edit1Change(Sender: TObject);
private
{ Private declarations }
PointerForm : TCustomForm;
TheSeries : TGanttSeries;
procedure RefreshShape;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses TeEngine, Series, TeePoEdi, TeeConst;
procedure TGanttSeriesEditor.RefreshShape;
begin
BColor.Enabled:=not TheSeries.ColorEachPoint;
end;
procedure TGanttSeriesEditor.FormShow(Sender: TObject);
begin
TheSeries:=TGanttSeries(Tag);
if Assigned(TheSeries) then
begin
With TheSeries do
begin
UDPointVertSize.Position:=Pointer.VertSize;
CBColorEach.Checked:=ColorEachPoint;
UpDown1.Position:=Transparency;
BConnLines.LinkPen(ConnectingPen);
end;
BColor.LinkProperty(TheSeries,'SeriesColor');
RefreshShape;
if not Assigned(PointerForm) then
begin
PointerForm:=TeeInsertPointerForm(Parent,TheSeries.Pointer,TeeMsg_GalleryGantt);
with PointerForm as TSeriesPointerEditor do HideSizeOptions;
end;
end;
end;
procedure TGanttSeriesEditor.SEPointVertSizeChange(Sender: TObject);
begin
if Showing then TheSeries.Pointer.VertSize:=UDPointVertSize.Position;
end;
procedure TGanttSeriesEditor.CBColorEachClick(Sender: TObject);
begin
TheSeries.ColorEachPoint:=CBColorEach.Checked;
RefreshShape;
end;
procedure TGanttSeriesEditor.BColorClick(Sender: TObject);
begin
TheSeries.ColorEachPoint:=False;
end;
procedure TGanttSeriesEditor.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
procedure TGanttSeriesEditor.Edit1Change(Sender: TObject);
begin
if Showing then TheSeries.Transparency:=UpDown1.Position;
end;
initialization
RegisterClass(TGanttSeriesEditor);
end.
|
function IsLeapYear(year: integer): boolean;
begin
if ((year mod 4 = 0) and (year mod 100 <> 0)) or (year mod 400 = 0) then
result := True;
else
result := False;
end; |
{
Algorithme Croix TantQue
But : Dessiner une croix d'une taille saisi par l'utilisateur et avec un caractere saisi par l'utilisateur.
Entrée : Taille, Symbole
Variables : Taille, Largeur, Hauteur : Entier
Symbole : Caractere
DEBUT
ECRIRE("Veuillez entrer le caractere que vous souhaitez utiliser :"");
LIRE(symbol);
ECRIRE("Veuillez entrez la taille de votre croix :"");
LIRE(taille);
TANTQUE hauteur<>taille FAIRE //On vérifie que la hauteur de la croix n'a pas encore été atteinte
SI (largeur=hauteur) OU (largeur=((taille-1)-hauteur))
ALORS //On test si on se trouve en une position où il faut mettre un caractere
write(symbol);
SINON //Si ce n'est pas le cas on écris un espace
ECRIRE(' ');
FINSI;
SI largeur=(taille-1)
ALORS //On test si la largeur de la croix a été atteinte
ECRIRE(); //Si c'est la cas on reviens à la ligne
largeur<-0; //On remet le compteur de largeur à 0
hauteur<-hauteur+1; //On incrémente la coordonnée verticale
SINON
largeur<-largeur+1; //On incrémente la coordonnée horizontale
FINSI;
FINTANTQUE;
FIN
}
PROGRAM croix_only_while;
USES crt;
VAR
taille,largeur,hauteur : integer;
symbol : char;
BEGIN
writeln('Veuillez entrer le caractere que vous souhaitez utiliser :');
readln(symbol);
writeln('Veuillez entrez la taille de votre croix :');
readln(taille);
clrscr;
while hauteur<>taille do //On vérifie que la hauteur de la croix n'a pas encore été atteinte
BEGIN
if (largeur=hauteur) or (largeur=((taille-1)-hauteur)) then //On test si on se trouve en une position où il faut mettre un caractere
BEGIN
write(symbol);
END
else //Si ce n'est pas le cas on écris un espace
BEGIN
write(' ');
END;
if largeur=(taille-1) then //On test si la largeur de la croix a été atteinte
BEGIN
writeln(); //Si c'est la cas on reviens à la ligne
largeur:=0; //On remet le compteur de largeur à 0
hauteur:=hauteur+1; //On incrémente la coordonnée vertical
END
else
BEGIN
largeur:=largeur+1; //Sinon on incremente la coordonnée horizontale
END;
END;
readln();
END.
|
unit uEditorForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ExtCtrls, StdCtrls, ComCtrls, EnhCtrls, Buttons,
uAssembler, uProcessor, uTimer, uResourceStrings, uMisc, Registry,
SynEdit, SynEditPrint, SynEditHighlighter, SynHighlighterAsm, ImgList,
SynEditOptionsDialog, uSynHighlighteri8008ASM;
type
{ *********** Projectfile Structure *********** }
{ 1. Processor Data }
{ 1.1 - Fileheader }
{ 1.2 - 'Halt' }
{ 1.3 - Stack Data }
{ 1.4 - RAM Data }
{ 1.5 - Register Data }
{ 1.6 - Flag Data }
{ 1.7 - IN Port Data }
{ 1.8 - OUT Port Data }
{ 2. Editor - 'CodeModified' }
{ [3. i8008 Program, if CodeModefied is false] }
{ 4. Sourcecode }
{ *********** Projectfile Structure *********** }
TSingleStepEnabledEvent = procedure(Sender: TObject; Enabled: Boolean) of object;
TRunningEnabledEvent = procedure(Sender: TObject; Enabled: Boolean) of object;
TPCRefreshRequestEvent = procedure(Listener: IProgramCounter) of object;
TLoadEvent = procedure(Stream: TStream; var Check: Boolean) of object;
TSaveEvent = procedure(Stream: TStream; var Check: Boolean) of object;
TSupportPlugin = class;
TEditorForm = class(TForm, IProgramCounter, ILanguage, IRegistry)
pBottom: TPanel;
lbError: TListBox;
pLeft: TPanel;
sbHide: TSpeedButton;
pStatus: TPanel;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
SaveProjectDialog: TSaveDialog;
OpenProjectDialog: TOpenDialog;
iProject: TImage;
iSourcecode: TImage;
LblFilename: TFilenameLabel;
synEditor: TSynEdit;
synEditorPrint: TSynEditPrint;
imglGutter: TImageList;
PrinterSetupDialog: TPrinterSetupDialog;
pMainBottom: TPanel;
procedure sbHideClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lbErrorClick(Sender: TObject);
procedure OnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure synEditorChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure OnKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure synEditorGutterClick(Sender: TObject; Button: TMouseButton;
X, Y, Line: Integer; Mark: TSynEditMark);
procedure synEditorSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
private
_HideErrors: Boolean;
_SizeHeight: Integer;
_StepLine: Integer;
_ErrorLine: Integer;
_isSingleStep: Boolean;
_isRunning: Boolean;
_EnableKeys: Boolean;
_CodeModified: Boolean;
_BreakpointList: TBreakpointList;
_i8008Assembler: Ti8008Assembler;
_Program: TProgram;
_AssembleRequest: TNotifyEvent;
_AfterAssemble: TNotifyEvent;
_OnSingleStepEnabled: TSingleStepEnabledEvent;
_OnRunningEnabled: TRunningEnabledEvent;
_OnTimerEnabledRequest: TTimerEnabledRequestEvent;
_OnTick: TTickEvent;
_OnPCRefreshRequest: TPCRefreshRequestEvent;
_OnLoadProject: TLoadEvent;
_OnLoadProgram: TLoadEvent;
_OnSaveProject: TSaveEvent;
_OnSaveProgram: TSaveEvent;
_SupportPlugin: TSupportPlugin;
_i8008ASMSyn: Ti8008ASMSyn;
procedure RefreshObject(Sender: TObject);
procedure Reset(Sender: TObject);
procedure PCUpdate(Sender: TObject; Value: Word);
procedure LoadData(RegistryList: TRegistryList);
procedure SaveData(RegistryList: TRegistryList);
procedure ErrorInsert(Sender: TObject; Index: Integer);
procedure ErrorDelete(Sender: TObject; Index: Integer);
procedure setErrorList(Hide: Boolean);
function getFilename: TFilename;
procedure Stop(ClearArrow: Boolean); overload;
procedure goToLine(Line: Integer);
procedure OnAfterPaint(ACanvas: TCanvas; const AClip: TRect; FirstLine, LastLine: Integer);
public
procedure Start;
procedure Stop; overload;
procedure SingleStep;
function Assemble: Boolean;
function New: Boolean;
procedure Open(Filename: TFilename);
function OpenFile: Boolean; overload;
function OpenFile(Filename: TFilename): Boolean; overload;
function OpenProject: Boolean; overload;
function OpenProject(Filename: TFilename): Boolean; overload;
function SaveRequest: Integer;
procedure Save;
function SaveFile: Boolean;
function SaveFileAs: Boolean;
function SaveProject: Boolean;
function SaveProjectAs: Boolean;
procedure Print;
procedure ShowProgress(Value: Boolean);
procedure LoadLanguage;
procedure Show(ATop, ALeft, AWidth, AHeight: Integer); overload;
property AProgram: TProgram read _Program write _Program;
property Filename: TFilename read getFilename;
property EnableKeys: Boolean read _EnableKeys write _EnableKeys;
property OnAssembleRequest: TNotifyEvent read _AssembleRequest write _AssembleRequest;
property OnSingleStepEnabled: TSingleStepEnabledEvent read _OnSingleStepEnabled write _OnSingleStepEnabled;
property OnRunningEnabled: TRunningEnabledEvent read _OnRunningEnabled write _OnRunningEnabled;
property OnAfterAssemble: TNotifyEvent read _AfterAssemble write _AfterAssemble;
property OnTimerEnabledRequest: TTimerEnabledRequestEvent read _OnTimerEnabledRequest write _OnTimerEnabledRequest;
property OnTick: TTickEvent read _OnTick write _OnTick;
property OnPCRefreshRequest: TPCRefreshRequestEvent read _OnPCRefreshRequest write _OnPCRefreshRequest;
property OnLoadProject: TLoadEvent read _OnLoadProject write _OnLoadProject;
property OnLoadProgram: TLoadEvent read _OnLoadProgram write _OnLoadProgram;
property OnSaveProject: TSaveEvent read _OnSaveProject write _OnSaveProject;
property OnSaveProgram: TSaveEvent read _OnSaveProgram write _OnSaveProgram;
end;
TSynPaintEvent = procedure(ACanvas: TCanvas; const AClip: TRect; FirstLine, LastLine: Integer) of object;
TSupportPlugin = class(TSynEditPlugin)
private
_OnAfterPaint: TSynPaintEvent;
protected
procedure AfterPaint(ACanvas: TCanvas; const AClip: TRect; FirstLine, LastLine: Integer); override;
procedure LinesInserted(FirstLine, Count: Integer); override;
procedure LinesDeleted(FirstLine, Count: Integer); override;
public
constructor Create(AOwner: TSynEdit);
property OnAfterPaint: TSynPaintEvent read _OnAfterPaint write _OnAfterPaint;
end;
var
EditorForm: TEditorForm;
implementation
{$R *.dfm}
constructor TSupportPlugin.Create(AOwner: TSynEdit);
begin
inherited Create(AOwner);
end;
procedure TSupportPlugin.AfterPaint(ACanvas: TCanvas; const AClip: TRect; FirstLine, LastLine: integer);
begin
if Assigned(OnAfterPaint) then OnAfterPaint(ACanvas, AClip, FirstLine, LastLine);
end;
procedure TSupportPlugin.LinesInserted(FirstLine, Count: integer);
begin
end;
procedure TSupportPlugin.LinesDeleted(FirstLine, Count: integer);
begin
end;
procedure TEditorForm.FormCreate(Sender: TObject);
begin
_i8008Assembler:= Ti8008Assembler.Create;
_i8008Assembler.ErrorList.OnItemInsert:= ErrorInsert;
_i8008Assembler.ErrorList.OnItemDelete:= ErrorDelete;
_HideErrors:= false;
_SizeHeight:= lbError.Height;
iSourcecode.Left:= 3;
iSourcecode.Top:= 3;
iSourcecode.Visible:= false;
iProject.Left:= 3;
iProject.Top:= 3;
iProject.Visible:= false;
LblFilename.Caption:= '';
synEditor.Modified:= false;
_i8008ASMSyn:= Ti8008ASMSyn.Create(self);
synEditor.Highlighter:= _i8008ASMSyn;
_SupportPlugin:= TSupportPlugin.Create(synEditor);
_SupportPlugin.OnAfterPaint:= OnAfterPaint;
_BreakpointList:= TBreakpointList.Create;
_BreakpointList.ClearAllBreakpoints;
_CodeModified:= true; //false;
_isSingleStep:= false;
_isRunning:= false;
_ErrorLine:= -1;
_StepLine:= -1;
EnableKeys:= false;
LoadLanguage;
end;
procedure TEditorForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
// CanClose:= SaveRequest <> mrCancel;
end;
procedure TEditorForm.FormDestroy(Sender: TObject);
begin
_BreakpointList.Free;
synEditor.Highlighter:= nil;
_i8008ASMSyn.Free;
_SupportPlugin.Free;
_i8008Assembler.Free;
end;
procedure TEditorForm.Start;
begin
if _CodeModified or not Assigned(AProgram) then begin
if Assigned(OnAssembleRequest) then OnAssembleRequest(Self);
end else
if Assigned(AProgram) then begin
Caption:= 'Editor ( '+getString(rsRunning)+' )';
synEditor.ReadOnly:= true;
if Visible then goToLine(-1);
_isRunning:= true;
_isSingleStep:= false;
if Assigned(OnRunningEnabled) then OnRunningEnabled(Self,_isRunning);
if Assigned(OnTimerEnabledRequest) then OnTimerEnabledRequest(true);
end;
end;
procedure TEditorForm.sbHideClick(Sender: TObject);
begin
setErrorList(not _HideErrors);
end;
procedure TEditorForm.lbErrorClick(Sender: TObject);
begin
if (lbError.ItemIndex >= 0) and Visible then begin
_ErrorLine:= _i8008Assembler.ErrorList.Items[lbError.ItemIndex].Line;
goToLine(_ErrorLine);
synEditor.Invalidate;
end;
lbError.SetFocus;
end;
procedure TEditorForm.synEditorChange(Sender: TObject);
begin
if synEditor.Modified then begin
_CodeModified:= true;
LblFilename.Font.Style:= [fsBold];
end;
end;
procedure TEditorForm.OnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if EnableKeys then
case Key of
VK_F2 : if (Shift = [ssCtrl]) then // stop
begin
Stop;
if Visible then goToLine(-1);
end;
VK_F9 : if Assigned(OnAssembleRequest) and (Shift = [ssCtrl]) then
OnAssembleRequest(Self) // assemble
else // start
Start;
ord('O'): if Shift = [ssCtrl] then // open file
OpenFile;
ord('P'): if Shift = [ssCtrl] then // open project
OpenProject;
ord('S'): if Shift = [ssCtrl] then // save file/project
Save;
end;
end;
procedure TEditorForm.OnKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_F7) then // single step
SingleStep;
end;
procedure TEditorForm.RefreshObject(Sender: TObject);
var
PItem: TProgramItem;
begin
if (Sender is Ti8008Stack) and (_isSingleStep or _isRunning) then
begin
if Assigned(AProgram) then
begin
PItem:= AProgram.FindItem((Sender as Ti8008Stack).ProgramCounter);
if Assigned(PItem) and _isSingleStep then begin
if Visible then goToLine(PItem.Link);
end else begin
if Visible then goToLine(-1);
end;
end;
end;
end;
procedure TEditorForm.Reset(Sender: TObject);
var
PItem: TProgramItem;
begin
if (Sender is Ti8008Stack) and (_isSingleStep or _isRunning) then
begin
if Assigned(AProgram) then
begin
PItem:= AProgram.FindItem((Sender as Ti8008Stack).ProgramCounter);
if Assigned(PItem) and _isSingleStep then begin
if Visible then goToLine(PItem.Link);
end else begin
if Visible then goToLine(-1);
end;
end;
end;
end;
procedure TEditorForm.PCUpdate(Sender: TObject; Value: Word);
var
PItem: TProgramItem;
begin
if Assigned(AProgram) then begin
PItem:= AProgram.FindItem(Value);
if _isRunning and Assigned(PItem) then begin
// stop the timer if a breakpoint is reached
if _BreakpointList.Breakpoint(PItem.Link+1) and _isRunning then begin
Stop(false);
// go to the specified sourcecodeline
_StepLine:= PItem.Link;
if Visible then goToLine(PItem.Link);
Caption:= 'Editor ( Breakpoint )';
end;
end else begin
// go to the specified sourcecodeline
if _isSingleStep and Assigned(PItem) then begin
_StepLine:= PItem.Link;
if Visible then begin
goToLine(PItem.Link);
synEditor.Invalidate;
end;
end else begin
if Visible then goToLine(-1);
end;
end;
end;
end;
procedure TEditorForm.LoadData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY, false) then begin
RegistryList.LoadFormSettings(Self, true);
if RegistryList.Registry.ValueExists('ErrorVisible') then
setErrorList(RegistryList.Registry.ReadInteger('ErrorVisible') = 1);
end;
end;
procedure TEditorForm.SaveData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then
begin
RegistryList.SaveFormSettings(Self,true);
if lbError.Visible then
RegistryList.Registry.WriteInteger('ErrorVisible',1)
else
RegistryList.Registry.WriteInteger('ErrorVisible',0);
end;
end;
procedure TEditorForm.ErrorInsert(Sender: TObject; Index: Integer);
var
Text: String;
Error: TErrorList;
begin
Error:= _i8008Assembler.ErrorList;
case Error.Items[Index].State of
isError : Text:= '['+getString(rsError)+'] : ('+IntToStr(Error.Items[Index].Line)+')';
isFatalError: Text:= '['+getString(rsFatalError)+'] : ('+IntToStr(Error.Items[Index].Line)+')';
isWarning : Text:= '['+getString(rsWarning)+'] : ('+IntToStr(Error.Items[Index].Line)+')';
isHint : Text:= '['+getString(rsHint)+'] : ('+IntToStr(Error.Items[Index].Line)+')';
isUndefined : Text:= '['+getString(rsError)+'] : ('+IntToStr(Error.Items[Index].Line)+')';
end;
Text:= Text + ' ' + Error.Items[Index].Text;
lbError.Items.Insert(Index,Text);
end;
procedure TEditorForm.ErrorDelete(Sender: TObject; Index: Integer);
begin
lbError.Items.Delete(Index);
end;
procedure TEditorForm.setErrorList(Hide: Boolean);
begin
_HideErrors:= Hide;
if Hide then pMainBottom.Height:= pMainBottom.Height - _SizeHeight
else pMainBottom.Height:= pMainBottom.Height + _SizeHeight;
if _HideErrors then sbHide.Down:= true
else sbHide.Down:= false;
end;
function TEditorForm.getFilename: TFilename;
begin
result:= LblFilename.Caption;
end;
procedure TEditorForm.Stop(ClearArrow: Boolean);
begin
if Assigned(AProgram) then
begin
Caption:= 'Editor';
synEditor.ReadOnly:= false;
if _isSingleStep then
begin
_isSingleStep:= false;
if Assigned(OnSingleStepEnabled) then
OnSingleStepEnabled(Self,_isSingleStep);
end;
if _isRunning then
begin
if Assigned(OnTimerEnabledRequest) then
OnTimerEnabledRequest(false);
_isRunning:= false;
if Assigned(OnRunningEnabled) then
OnRunningEnabled(Self,_isRunning);
end;
if ClearArrow and Visible then goToLine(-1);
end;
end;
procedure TEditorForm.Stop;
begin
Stop(true);
end;
procedure TEditorForm.SingleStep;
begin
if not _isRunning then
if _CodeModified or not Assigned(AProgram) then begin
if Assigned(OnAssembleRequest) then OnAssembleRequest(Self);
end else if Assigned(AProgram) then begin
if not _isSingleStep then begin
Caption:= 'Editor ( '+getString(rsSingleStep)+' )';
synEditor.ReadOnly:= true;
_isSingleStep:= true;
_isRunning:= false;
if Assigned(OnPCRefreshRequest) then
OnPCRefreshRequest(Self);
if Assigned(OnSingleStepEnabled) then
OnSingleStepEnabled(Self, _isSingleStep);
end else if Assigned(OnTick) then OnTick;
end;
end;
function TEditorForm.Assemble: Boolean;
var
Str: String;
Text: String;
i: Integer;
begin
Str:= '';
Text:= '';
for i:= 0 to synEditor.Lines.Count-1 do Text:= Text + synEditor.Lines.Strings[i]+#10#13;
result:= _i8008Assembler.Assemble(Text, _Program, LblFilename.Caption);
// Update Breakpoints
for i:= 0 to _BreakpointList.Count-1 do _BreakpointList.Items[i].State:= false;
for i:= 0 to _Program.Count-1 do _BreakpointList.BreakpointState[_Program.Items[i].Link+1]:= true;
if Visible then goToLine(-1);
// Show Errors
if not result and _HideErrors then setErrorList(false);
if result and Assigned(OnAfterAssemble) then OnAfterAssemble(Self);
_CodeModified:= not result;
end;
function TEditorForm.New: Boolean;
begin
if not (_isRunning or _isSingleStep) and
(SaveRequest <> mrCancel) then
begin
synEditor.Clear;
LblFilename.Caption:= '';
_BreakpointList.ClearAllBreakpoints;
synEditor.Modified:= false;
_CodeModified:= true;
AProgram:= nil;
result:= true;
iProject.Visible:= false;
iSourcecode.Visible:= false;
end
else
result:= false;
end;
function TEditorForm.OpenFile: Boolean;
begin
if not (_isRunning or _isSingleStep) then
begin
if OpenDialog.Execute then
try
if SaveRequest <> mrCancel then
begin
synEditor.Lines.LoadFromFile(OpenDialog.Filename);
LblFilename.Caption:= OpenDialog.Filename;
_BreakpointList.ClearAllBreakpoints;
if not Visible then
Show;
if Visible then goToLine(-1);
result:= true;
synEditor.Modified:= false;
_CodeModified:= true;
iProject.Visible:= false;
iSourcecode.Visible:= true;
end
else
result:= false;
except
result:= false;
end
else
result:= false;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
AProgram:= nil;
end
else
result:= false;
end;
procedure TEditorForm.Open(Filename: TFilename);
begin
if LowerCase(ExtractFileExt(Filename)) = '.pj' then
OpenProject(Filename)
else
OpenFile(Filename);
end;
function TEditorForm.OpenFile(Filename: TFilename): Boolean;
begin
if not (_isRunning or _isSingleStep) then
begin
try
if SaveRequest <> mrCancel then
begin
synEditor.Lines.LoadFromFile(Filename);
LblFilename.Caption:= Filename;
_BreakpointList.ClearAllBreakpoints;
result:= true;
synEditor.Modified:= false;
_CodeModified:= true;
iProject.Visible:= false;
iSourcecode.Visible:= true;
end
else
result:= false;
except
result:= false;
end;
if synEditor.Modified then LblFilename.Font.Style:= [fsBold]
else LblFilename.Font.Style:= [];
AProgram:= nil;
end
else
result:= false;
end;
function TEditorForm.OpenProject: Boolean;
var
FStringStream: TStringStream;
FStream: TFileStream;
CodeModified: Boolean;
begin
if not (_isRunning or _isSingleStep) then
begin
AProgram:= nil;
if OpenProjectDialog.Execute then
try
FStream:= TFileStream.Create(OpenProjectDialog.FileName,fmOpenRead,fmShareDenyWrite);
if SaveRequest <> mrCancel then begin
result:= true;
// Load i8008
if Assigned(OnLoadProject) then OnLoadProject(FStream,result);
// Load Editor State
result:= result and
(FStream.Read(CodeModified,SizeOf(CodeModified)) = SizeOf(CodeModified));
// Load i8008 Program
if result and (not CodeModified) and Assigned(OnLoadProgram) then
OnLoadProgram(FStream,result);
// Load Sourcecode
if result then begin
FStringStream:= TStringStream.Create('');
try
FStringStream.CopyFrom(FStream, FStream.Size-FStream.Position);
synEditor.Lines.LoadFromStream(FStringStream);
finally
FreeAndNil(FStringStream);
end;
LblFilename.Caption:= OpenProjectDialog.Filename;
_BreakpointList.ClearAllBreakpoints;
if not Visible then Show;
if Visible then goToLine(-1);
synEditor.Modified:= false;
_CodeModified:= CodeModified;
iProject.Visible:= true;
iSourcecode.Visible:= false;
end else MessageDlg(getString(rs_msg_OpenError),mtError,[mbOk],0);
end else result:= false;
FStream.Free;
except
result:= false;
MessageDlg(getString(rs_msg_OpenError),mtError,[mbOk],0);
end
else
result:= false;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
end
else
result:= false;
end;
function TEditorForm.OpenProject(Filename: TFilename): Boolean;
var
FStringStream: TStringStream;
FStream: TFileStream;
CodeModified: Boolean;
begin
if not (_isRunning or _isSingleStep) then
begin
AProgram:= nil;
try
FStream:= TFileStream.Create(FileName,fmOpenRead,fmShareDenyWrite);
if SaveRequest <> mrCancel then begin
result:= true;
// Load i8008
if Assigned(OnLoadProject) then
OnLoadProject(FStream,result);
// Load Editor State
result:= result and
(FStream.Read(CodeModified,SizeOf(CodeModified)) = SizeOf(CodeModified));
// Load i8008 Program
if result and (not CodeModified) and Assigned(OnLoadProgram) then
OnLoadProgram(FStream,result);
// Load Sourcecode
if result then begin
FStringStream:= TStringStream.Create('');
try
FStringStream.CopyFrom(FStream, FStream.Size-FStream.Position);
synEditor.Lines.LoadFromStream(FStringStream);
finally
FreeAndNil(FStringStream);
end;
LblFilename.Caption:= Filename;
_BreakpointList.ClearAllBreakpoints;
synEditor.Modified:= false;
_CodeModified:= CodeModified;
iProject.Visible:= true;
iSourcecode.Visible:= false;
end else MessageDlg(getString(rs_msg_OpenError),mtError,[mbOk],0);
end else result:= false;
FStream.Free;
except
result:= false;
MessageDlg(getString(rs_msg_OpenError),mtError,[mbOk],0);
end;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
end
else
result:= false;
end;
function TEditorForm.SaveRequest: Integer;
begin
result:= mrNone;
if synEditor.Modified then
result:= MessageDlg(getString(rsSaveChanges),mtConfirmation,[mbYes,mbNo,mbCancel],0);
if result = mrYes then begin
if SaveFile then result:= mrYes
else result:= mrCancel;
end else if result = mrNo then synEditor.Modified:= false;
end;
procedure TEditorForm.Save;
begin
if LowerCase(ExtractFileExt(LblFilename.Caption)) = '.pj' then SaveProject
else SaveFile;
end;
function TEditorForm.SaveFile: Boolean;
var
BackupName: TFilename;
begin
if not (_isRunning or _isSingleStep) then
begin
if synEditor.Modified then
AProgram:= nil;
if LblFilename.Caption <> '' then
try
if FileExists(LblFilename.Caption) then
begin
BackupName:= ChangeFileExt(LblFilename.Caption,'.~asm');
if FileExists(BackupName) then
DeleteFile(BackupName);
RenameFile(LblFilename.Caption,BackupName);
end;
synEditor.Lines.SaveToFile(LblFilename.Caption);
result:= true;
synEditor.Modified:= false;
except
result:= false;
end
else
result:= false;
if not result then
result:= SaveFileAs;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
end
else
result:= false;
end;
function TEditorForm.SaveFileAs: Boolean;
begin
if not (_isRunning or _isSingleStep) then
begin
if SaveDialog.Execute then
begin
if synEditor.Modified then
AProgram:= nil;
try
LblFilename.Caption:= SaveDialog.Filename;
synEditor.Lines.SaveToFile(LblFilename.Caption);
result:= true;
synEditor.Modified:= false;
except
result:= false;
end
end
else
result:= false;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
end
else
result:= false;
end;
function TEditorForm.SaveProject: Boolean;
var
BackupName: TFilename;
FStream: TFileStream;
begin
if not (_isRunning or _isSingleStep) then
begin
if synEditor.Modified then
AProgram:= nil;
if LblFilename.Caption <> '' then
try
if FileExists(LblFilename.Caption) then
begin
BackupName:= ChangeFileExt(LblFilename.Caption,'.~pj');
if FileExists(BackupName) then
DeleteFile(BackupName);
RenameFile(LblFilename.Caption,BackupName);
end;
FStream:= TFileStream.Create(LblFilename.Caption,fmCreate,fmShareExclusive);
result:= true;
// Save i8008
if Assigned(OnSaveProject) then
OnSaveProject(FStream,result);
// Save Editor State
result:= result and
(FStream.Write(_CodeModified,SizeOf(_CodeModified)) = SizeOf(_CodeModified));
// Save i8008 Program
if result and (not _CodeModified) and Assigned(OnSaveProgram) then
OnSaveProgram(FStream,result);
// Save Sourcecode
synEditor.Lines.SaveToStream(FStream);
synEditor.Modified:= false;
if not result then
MessageDlg(getString(rs_msg_SaveError),mtError,[mbOk],0);
FStream.Free;
except
result:= false;
MessageDlg(getString(rs_msg_SaveError),mtError,[mbOk],0);
end
else
result:= false;
if not result then
result:= SaveProjectAs;
if synEditor.Modified then
LblFilename.Font.Style:= [fsBold]
else
LblFilename.Font.Style:= [];
end
else
result:= false;
end;
function TEditorForm.SaveProjectAs: Boolean;
var
FStream: TFileStream;
begin
if not (_isRunning or _isSingleStep) then
begin
if SaveProjectDialog.Execute then
begin
if synEditor.Modified then
AProgram:= nil;
try
LblFilename.Caption:= SaveProjectDialog.Filename;
FStream:= TFileStream.Create(LblFilename.Caption,fmCreate,fmShareExclusive);
result:= true;
// Save i8008
if Assigned(OnSaveProject) then
OnSaveProject(FStream,result);
// Save Editor State
result:= result and
(FStream.Write(_CodeModified,SizeOf(_CodeModified)) = SizeOf(_CodeModified));
// Save i8008 Program
if result and (not _CodeModified) and Assigned(OnSaveProgram) then
OnSaveProgram(FStream,result);
// Save Sourcecode
synEditor.Lines.SaveToStream(FStream);
synEditor.Modified:= false;
if not result then
MessageDlg(getString(rs_msg_SaveError),mtError,[mbOk],0);
FStream.Free;
except
result:= false;
MessageDlg(getString(rs_msg_SaveError),mtError,[mbOk],0);
end
end
else result:= false;
if synEditor.Modified then LblFilename.Font.Style:= [fsBold]
else LblFilename.Font.Style:= [];
end
else result:= false;
end;
procedure TEditorForm.Print;
var
old: Boolean;
begin
old:= synEditor.Modified;
if PrinterSetupDialog.Execute then begin
synEditorPrint.SynEdit:= synEditor;
synEditorPrint.DocTitle:= ExtractFilename(LblFilename.Caption);
synEditorPrint.Title:= ExtractFilename(LblFilename.Caption);
synEditorPrint.Print;
end;
synEditor.Modified:= old;
end;
procedure TEditorForm.ShowProgress(Value: Boolean);
begin
_i8008Assembler.ShowProgress:= Value;
end;
procedure TEditorForm.LoadLanguage;
begin
{ Dialog }
OpenDialog.Filter:= getString(rs_filter_File);
OpenDialog.Title:= getString(rs_m_Open)+' ...';
SaveDialog.Filter:= getString(rs_filter_File);
SaveDialog.Title:= getString(rs_m_SaveAs)+' ...';
OpenProjectDialog.Filter:= getString(rs_filter_Project);
OpenProjectDialog.Title:= getString(rs_m_ProjectOpen)+' ...';
SaveProjectDialog.Filter:= getString(rs_filter_Project);
SaveProjectDialog.Title:= getString(rs_m_ProjectSaveAs)+' ...';
end;
procedure TEditorForm.Show(ATop, ALeft, AWidth, AHeight: Integer);
begin
Top:= ATop;
Left:= ALeft;
Height:= AHeight;
Width:= AWidth;
Show;
end;
procedure TEditorForm.goToLine(Line: Integer);
var
FirstLine, LastLine: Integer;
begin
if Line < 0 then begin
_StepLine:= -1;
_ErrorLine:= -1;
synEditor.Invalidate;
end else begin
Line:= Line + 1;
FirstLine:= synEditor.TopLine;
LastLine:= FirstLine + synEditor.LinesInWindow - 1;
if (Line < FirstLine) or (Line > LastLine) then synEditor.TopLine:= Line;
synEditor.Invalidate;
end;
end;
procedure TEditorForm.synEditorGutterClick(Sender: TObject;
Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark);
var
i: Integer;
begin
_BreakpointList.ToggleBreakpoint(Line);
// Update Breakpoints
for i:= 0 to _BreakpointList.Count-1 do _BreakpointList.Items[i].State:= false;
if Assigned(_Program) then
for i:= 0 to _Program.Count-1 do _BreakpointList.BreakpointState[_Program.Items[i].Link+1]:= true;
synEditor.InvalidateLine(Line);
end;
procedure TEditorForm.synEditorSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
begin
// Error
Special:= Line = (_ErrorLine+1);
if Special then begin
FG:= clWhite;
BG:= clRed;
end;
// Programcounter
if not Special then begin
Special:= Line = (_StepLine+1);
if Special then begin
FG:= clWhite;
BG:= clAqua;
end;
// Breakpoint
if not Special then begin
Special:= _BreakpointList.Breakpoint(Line);
if Special then begin
FG:= clWhite;
BG:= clRed;
end;
end;
end;
end;
procedure TEditorForm.OnAfterPaint(ACanvas: TCanvas; const AClip: TRect;
FirstLine, LastLine: Integer);
var
X, Y, ImageIndex: Integer;
begin
if true then begin
X:= 14;
Y:= (synEditor.LineHeight - imglGutter.Height) div 2
+ synEditor.LineHeight * (FirstLine - synEditor.TopLine);
while FirstLine <= LastLine do begin
if (_StepLine+1) = FirstLine then begin
if _BreakpointList.Breakpoint(FirstLine) then ImageIndex:= 3
else ImageIndex:= 2
end else begin
if _BreakpointList.Breakpoint(FirstLine) then begin
if _BreakpointList.BreakpointState[FirstLine] then ImageIndex:= 1
else ImageIndex:= 0;
end else ImageIndex:= -1;
end;
if ImageIndex >= 0 then imglGutter.Draw(ACanvas, X, Y, ImageIndex);
Inc(FirstLine);
Inc(Y, synEditor.LineHeight);
end;
end;
end;
end.
|
unit clsTDBUtils;
interface
{$M+}
uses
System.SysUtils,
System.Classes,
Data.DB,
Data.DBCommonTypes,
Uni,
DBAccess;
type
TColDevQuery = class(TUniQuery);
TColDevConnection = class(TUniConnection);
TDBUtils = class(TObject)
private
FConexao: TColDevConnection;
FOwner: TComponent;
procedure SetConexao(const Value: TColDevConnection);
procedure SetOwner(const Value: TComponent);
public
constructor Create(AOwner: TComponent; StringDeConexao: String);
property Owner: TComponent read FOwner write SetOwner;
property Conexao: TColDevConnection read FConexao write SetConexao;
published
function QueryFactory(Statement: String): TColDevQuery;
end;
implementation
{ TDBUtils }
constructor TDBUtils.Create(AOwner: TComponent; StringDeConexao: String);
begin
Self.FOwner := AOwner;
// 'Provider Name=PostgreSQL;Login Prompt=False;Data Source=192.168.0.116;User ID=postgres;Password=bitnami;Database=WeBuy;Port=5432';
Self.FConexao.ConnectString := StringDeConexao;
Self.FConexao.Connect;
end;
function TDBUtils.QueryFactory(Statement: String): TColDevQuery;
begin
Result := TColDevQuery(TUniQuery).Create(Self.Owner);
Result.Connection := Self.Conexao;
Result.SQL.Add(Statement);
end;
procedure TDBUtils.SetConexao(const Value: TColDevConnection);
begin
FConexao := Value;
end;
procedure TDBUtils.SetOwner(const Value: TComponent);
begin
FOwner := Value;
end;
end.
|
unit MyMath;
interface
uses
SysUtils,
Nodes, TreeVisitor;
{ This unit defines subclasses of TNode for representing the following
signature:
Data = Real | BinOpKind | Funckind
Sorts = Math
Math = Hole | Meta | Const | Var | UMinus | BinOp | BinExp | Func | FuncApp
Hole = []
Meta = D[name: String]
Const = D[val: Real]
Var = D[name: Char]
UMinus = S[arg: Math]
BinOp = D[kind: BinOpKind]
BinExp = S[left: Math, op: BinOp, right: Math]
Func = D[kind: FuncKind]
FuncApp = S[func: Func, arg: Math]
}
const
// math kinds
mkHole = 29;
mkMeta = 30;
mkConst = 31;
mkVar = 32;
mkUMinus = 33; // Unary minus
mkBinop = 34; // Binary operator
mkBinExp = 35; // Binary expression
mkFunc = 36; // Function symbol
mkFuncApp = 37; // Function application
type
TMathKind = mkConst..mkFuncApp;
TBinOpKind = (boPlus, boMinus, boTimes, boDivide);
TFuncKind = (fkSin, fkCos, fkExp, fkLn);
TMath =
class(TNode)
end;
TMath_Hole =
class(TMath)
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function IsHole: Boolean; override;
end;
TMath_Meta =
class(TMath)
private
FName: String;
public
constructor Create(AName: String);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function HasData: Boolean; override;
function GetData: String; override;
procedure SetData(AString: String); override;
class function IsMeta: Boolean; override;
end;
TMath_Const =
class(TMath)
private
FVal: Integer;
public
constructor Create(AVal: Integer);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function HasData: Boolean; override;
function GetData: String; override;
procedure SetData(AString: String); override;
property Val: Integer read FVal;
end;
TMath_Var =
class(TMath)
private
FName: String;
public
constructor Create(AName: String);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function HasData: Boolean; override;
function GetData: String; override;
procedure Setdata(AString: String); override;
end;
TMath_Uminus =
class(TMath)
private
FArg: TMath;
public
constructor Create(AArg: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
property Arg: TMath read FArg;
end;
TMath_BinOp =
class(TMath)
private
FOpKind: TBinOpKind;
public
constructor Create(AOpKind: TBinOpKind);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function HasData: Boolean; override;
function GetData: String; override;
procedure SetData(AString: String); override;
property OpKind: TBinOpKind read FOpKind;
end;
TMath_BinExp =
class(TMath)
private
FLeft : TMath;
FOp : TMath_BinOp;
FRight: TMath;
public
constructor Create(ALeft: TMath; AOp: TMath_BinOp; ARight: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
property Left: TMath read FLeft;
property Op: TMath_BinOp read FOp;
property Right: TMath read FRight;
end;
TMath_Func =
class(TMath)
private
FFuncKind: TFuncKind;
public
constructor Create(AFuncKind: TFuncKind);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
class function HasData: Boolean; override;
function GetData: String; override;
procedure Setdata(AString: String); override;
property FuncKind: TFuncKind read FFuncKind;
end;
TMath_FuncApp =
class(TMath)
private
FFunc : TMath_Func;
FArg: TMath;
public
constructor Create(AFunc: TMath_Func; AArg: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
property Func: TMath_Func read FFunc;
property Arg: TMath read FArg;
end;
TMathVisitor =
class(TTreeVisitor)
procedure Visit(ANode: TNode); override;
procedure VisitConst (ANode: TMath_Const); virtual;
procedure VisitVar (ANode: TMath_Var); virtual;
procedure VisitUMinus (ANode: TMath_UMinus); virtual;
procedure VisitBinOp (ANode: TMath_BinOp); virtual;
procedure VisitBinExp (ANode: TMath_BinExp); virtual;
procedure VisitFunc (ANode: TMath_Func); virtual;
procedure VisitFuncApp(ANode: TMath_FuncApp); virtual;
end;
TMathFactory =
class(TSimpleNodeFactory)
public
function MakeHole: TMath_Hole; reintroduce;
function MakeMeta(AName: String): TMath_Meta; virtual;
function MakeConst(AVal: Integer): TMath_Const; virtual;
function MakeVar(AName: String): TMath_Var; virtual;
function MakeUMinus(AArg: TMath): TMath_UMinus; virtual;
function MakeBinExp(ALeft: TMath; AOp: TMath_BinOp; ARight: TMath)
: TMath_BinExp; virtual;
function MakeBinOp(AOpKind: TBinOpKind): TMath_BinOp; virtual;
function MakeFuncApp(AFunc: TMath_Func; AArg: TMath): TMath_FuncApp;
virtual;
function MakeFunc(AFuncKind: TFuncKind): TMath_Func;
end;
var
VMathFactory: TMathFactory;
implementation //===============================================================
{ TMath_Hole }
class function TMath_Hole.GetKind: TNodeKind;
begin
Result := mkHole;
end;
class function TMath_Hole.GetNrofSons: Integer;
begin
Result := 0;
end;
function TMath_Hole.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex.Create('Node error: Hole.GetSon with index ' + IntToStr(I));
end;
class function TMath_Hole.IsHole: Boolean;
begin
Result := true;
end;
class function TMath_Hole.OpName: String;
begin
Result := '??';
end;
procedure TMath_Hole.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Hole.SetSon with index ' + IntToStr(I));
end;
{ TMath_Meta }
constructor TMath_Meta.Create(AName: String);
begin
inherited Create;
FName := AName;
end;
function TMath_Meta.GetData: String;
begin
Result := FName;
end;
class function TMath_Meta.GetKind: TNodeKind;
begin
Result := mkMeta;
end;
class function TMath_Meta.GetNrofSons: Integer;
begin
Result := 0;
end;
function TMath_Meta.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex.Create('Node error: Meta.GetSon with index ' + IntToStr(I));
end;
class function TMath_Meta.HasData: Boolean;
begin
Result := true;
end;
class function TMath_Meta.IsMeta: Boolean;
begin
Result := true;
end;
class function TMath_Meta.OpName: String;
begin
Result := 'Meta';
end;
procedure TMath_Meta.SetData(AString: String);
begin
FName := AString;
end;
procedure TMath_Meta.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Meta.SetSon with index ' + IntToStr(I));
end;
{ TMath_Const }
constructor TMath_Const.Create(AVal: Integer);
begin
inherited Create;
FVal := AVal;
end;
class function TMath_Const.GetKind: TNodeKind;
begin
Result := mkConst;
end;
function TMath_Const.GetData: String;
begin
Result := IntToStr(FVal);
end;
class function TMath_Const.OpName: String;
begin
Result := 'Const';
end;
function TMath_Const.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Const.GetSon with index ' + IntToStr(I));
end;
class function TMath_Const.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Const.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Const.SetSon with index ' + IntToStr(I));
end;
class function TMath_Const.HasData: Boolean;
begin
Result := true;
end;
procedure TMath_Const.SetData(AString: String);
begin
FVal := StrToInt(AString);
end;
{ TMath_Var }
constructor TMath_Var.Create(AName: String);
begin
inherited Create;
FName := Aname;
end;
class function TMath_Var.GetKind: TNodeKind;
begin
Result := mkVar;
end;
function TMath_Var.GetData: String;
begin
Result := FName;
end;
class function TMath_Var.OpName: String;
begin
Result := 'Var';
end;
function TMath_Var.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Var.GetSon with index ' + IntToStr(I));
end;
class function TMath_Var.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Var.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Var.SetSon with index ' + IntToStr(I));
end;
class function TMath_Var.HasData: Boolean;
begin
Result := true;
end;
procedure TMath_Var.Setdata(AString: String);
begin
FName := AString;
end;
{ TMath_UMinus }
constructor TMath_UMinus.Create(AArg: TMath);
begin
inherited Create;
FArg := AArg;
end;
destructor TMath_UMinus.Destroy;
begin
FArg.Free;
inherited Destroy;
end;
class function TMath_UMinus.GetKind: TNodeKind;
begin
Result := mkUMinus;
end;
class function TMath_UMinus.GetNrofSons: Integer;
begin
Result := 1;
end;
function TMath_UMinus.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FArg
else
raise EGetSonIndex('Node error: UMinus.GetSon with index ' + IntToStr(I))
end;
end;
procedure TMath_UMinus.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FArg := ANode as TMath
else
raise ESetSonIndex('Node error: UMinus.SetSon with index ' + IntToStr(I))
end;
end;
class function TMath_UMinus.OpName: String;
begin
Result := 'UMinus';
end;
{ TMath_BinOp }
constructor TMath_BinOp.Create(AOpKind: TBinOpKind);
begin
inherited Create;
FOpKind := AOpKind;
end;
class function TMath_BinOp.GetKind: TNodeKind;
begin
Result := mkBinOp;
end;
function TMath_BinOp.GetData: String;
begin
case FOpKind of
boPlus:
Result := '+';
boMinus:
Result := '-';
boTimes:
Result := '*';
boDivide:
Result := '/';
end;
end;
class function TMath_BinOp.OpName: String;
begin
Result := 'BinOp';
end;
function TMath_BinOp.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: BinOp.GetSon with index ' + IntToStr(I));
end;
class function TMath_BinOp.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_BinOp.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Const.SetSon with index ' + IntToStr(I));
end;
class function TMath_BinOp.HasData: Boolean;
begin
Result := true;
end;
procedure TMath_BinOp.SetData(AString: String);
begin
if AString = '+' then FOpKind := boPlus
else if AString = '-' then FOpKind := boMinus
else if AString = '*' then FOpKind := boTimes
else if AString = '/' then FOpKind := boDivide
else raise Exception.Create('TMath_BinOp.SetData: wrong operator: ' + AString);
end;
{ TMath_BinExp }
constructor TMath_BinExp.Create(ALeft: TMath; AOp: TMath_BinOp;
ARight: TMath);
begin
inherited Create;
FLeft := ALeft;
FOp := AOp;
FRight := ARight;
end;
destructor TMath_BinExp.Destroy;
begin
FLeft.Free;
FOp.Free;
FRight.Free;
inherited Destroy;
end;
class function TMath_BinExp.GetKind: TNodeKind;
begin
Result := mkBinExp;
end;
class function TMath_BinExp.GetNrofSons: Integer;
begin
Result := 3;
end;
function TMath_BinExp.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FLeft;
1: Result := FOp;
2: Result := FRight
else
raise EGetSonIndex('Node error: BinExp.GetSon with index ' + IntToStr(I))
end;
end;
procedure TMath_BinExp.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FLeft := ANode as TMath;
1: FOp := ANode as TMath_BinOp;
2: FRight := ANode as TMath
else
raise ESetSonIndex('Node error: BinExp.SetSon with index ' + IntToStr(I))
end;
end;
class function TMath_BinExp.OpName: String;
begin
Result := 'BinExp';
end;
{ TMath_Func }
constructor TMath_Func.Create(AFuncKind: TFuncKind);
begin
inherited Create;
FFuncKind := AFuncKind;
end;
class function TMath_Func.GetKind: TNodeKind;
begin
Result := mkFunc;
end;
function TMath_Func.GetData: String;
begin
case FFuncKind of
fkSin:
Result := 'Sin';
fkCos:
Result := 'Cos';
fkExp:
Result := 'Exp';
fkLn:
Result := 'Ln';
end;
end;
procedure TMath_Func.Setdata(AString: String);
var
VString: String;
begin
VString := UpperCase(AString);
if VString = 'SIN' then FFuncKind := fkSin
else if VString = 'COS' then FFuncKind := fkCos
else if VString = 'EXP' then FFuncKind := fkExp
else if VString = 'LN' then FFuncKind := fkLn
else raise Exception.Create('TMath_Func.SetData: wrong function: ' + AString);
end;
class function TMath_Func.OpName: String;
begin
Result := 'Func';
end;
function TMath_Func.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Func.GetSon with index ' + IntToStr(I));
end;
class function TMath_Func.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Func.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Func.SetSon with index ' + IntToStr(I));
end;
class function TMath_Func.HasData: Boolean;
begin
Result := true;
end;
{ TMath_FuncApp }
constructor TMath_FuncApp.Create(AFunc: TMath_Func; AArg: TMath);
begin
inherited Create;
FFunc := AFunc;
FArg := AArg;
end;
destructor TMath_FuncApp.Destroy;
begin
FFunc.Free;
FArg.Free;
inherited Destroy;
end;
class function TMath_FuncApp.GetKind: TNodeKind;
begin
Result := mkFuncApp;
end;
class function TMath_FuncApp.GetNrofSons: Integer;
begin
Result := 2;
end;
function TMath_FuncApp.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FFunc;
1: Result := FArg;
else
raise EGetSonIndex('Node error: FuncApp.GetSon with index ' + IntToStr(I))
end;
end;
class function TMath_FuncApp.OpName: String;
begin
Result := 'FuncApp';
end;
procedure TMath_FuncApp.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FFunc := ANode as TMath_Func;
1: FArg := ANode as TMath;
else
raise ESetSonIndex('Node error: FuncApp.SetSon with index ' + IntToStr(I))
end;
end;
{ TMathVisitor }
procedure TMathVisitor.Visit(ANode: TNode);
begin
// Dispatch by means of ANode.GetKind
case ANode.GetKind of
mkConst : VisitConst (ANode as TMath_Const);
mkVar : VisitVar (ANode as TMath_Var );
mkUMinus : VisitUMinus (ANode as TMath_UMinus);
mkBinOp : VisitBinOp (ANode as TMath_BinOp );
mkBinExp : VisitBinExp (ANode as TMath_BinExp );
mkFunc : VisitFunc (ANode as TMath_Func );
mkFuncApp: VisitFuncApp(ANode as TMath_FuncApp);
else
raise ENodeKind.Create('Unexpected NodeKind in TPropVisitor');
end;
end;
procedure TMathVisitor.VisitBinExp(ANode: TMath_BinExp);
begin
end;
procedure TMathVisitor.VisitBinOp(ANode: TMath_BinOp);
begin
end;
procedure TMathVisitor.VisitConst(ANode: TMath_Const);
begin
end;
procedure TMathVisitor.VisitFunc(ANode: TMath_Func);
begin
end;
procedure TMathVisitor.VisitFuncApp(ANode: TMath_FuncApp);
begin
end;
procedure TMathVisitor.VisitUMinus(ANode: TMath_UMinus);
begin
end;
procedure TMathVisitor.VisitVar(ANode: TMath_Var);
begin
end;
{ TMathFactory }
function TMathFactory.MakeBinExp(ALeft: TMath; AOp: TMath_BinOp;
ARight: TMath): TMath_BinExp;
begin
Result := TMath_BinExp.Create(ALeft, AOP, ARight);
end;
function TMathFactory.MakeBinOp(AOpKind: TBinOpKind): TMath_BinOp;
begin
Result := TMath_BinOp.Create(AOpKind);
end;
function TMathFactory.MakeConst(AVal: Integer): TMath_Const;
begin
Result := TMath_Const.Create(AVal);
end;
function TMathFactory.MakeFunc(AFuncKind: TFuncKind): TMath_Func;
begin
Result := TMath_Func.Create(AFuncKind);
end;
function TMathFactory.MakeFuncApp(AFunc: TMath_Func;
AArg: TMath): TMath_FuncApp;
begin
Result := TMath_FuncApp.Create(AFunc, AArg);
end;
function TMathFactory.MakeHole: TMath_Hole;
begin
Result := TMath_Hole.Create;
end;
function TMathFactory.MakeMeta(AName: String): TMath_Meta;
begin
Result := TMath_Meta.Create(AName);
end;
function TMathFactory.MakeUMinus(AArg: TMath): TMath_UMinus;
begin
Result := TMath_UMinus.Create(AArg);
end;
function TMathFactory.MakeVar(AName: String): TMath_Var;
begin
Result := TMath_Var.Create(AName);
end;
initialization
VMathFactory := TMathFactory.Create;
with VMathFactory do
begin
AddNodeClass(TMath_Hole);
AddNodeClass(TMath_Meta);
AddNodeClass(TMath_Const);
AddNodeClass(TMath_Var);
AddNodeClass(TMath_UMinus);
AddNodeClass(TMath_BinExp);
AddNodeClass(TMath_FuncApp);
AddNodeClass(TMath_BinOp);
AddNodeClass(TMath_Func);
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit DownhillSimplexAlgorithm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComponentList, Decisions, Algorithm, Tools;
type
TDownhillSimplexDecision = class(TFloatDecision)
public
function GetCopy: TDownhillSimplexDecision;
end;
TDownhillSimplexSADecision = class(TDownhillSimplexDecision)
protected
FFluctEvaluation: Double;
public
function GetCopy: TDownhillSimplexSADecision;
published
property FluctEvaluation: Double
read FFluctEvaluation write FFluctEvaluation;
end;
IDownhillSimplexServer = interface
['{2E685960-1C7C-11D4-893E-FA8655FAEA48}']
function GetInitParamLength(Sender: TComponent;
ParameterNumber, ParametersCount: LongInt
): Double;
procedure FillStartDecision(Sender: TComponent;
StartDecision: TFloatDecision);
procedure EvaluateDecision(Sender: TComponent;
Decision: TFloatDecision);
procedure UpdateResults(Sender: TComponent;
Decision: TFloatDecision);
function EndOfCalculation(Sender: TComponent): Boolean;
end;
EDownhillSimplexAlgorithm = class(Exception);
TDownhillSimplexAlgorithm = class(TAlgorithm)
protected
FDownhillSimplexServer: IDownhillSimplexServer;
FFinalTolerance: Double;
FRestartDisabled: Boolean;
FinalTolDefined: Boolean;
FExitDerivative: Double;
Simplex: TComponentList;
ParametersSum: array of Double;
BestDecision: TDownhillSimplexDecision;
function TryNewDecision(const Highest: LongInt; Factor: Double): Double; virtual;
function MoveWorstDecision(const Highest: LongInt; Factor: Double): TDownhillSimplexDecision;
function CreateAppropriateDecision: TDownhillSimplexDecision; virtual;
function GetActuallyLowestDecision: TDownhillSimplexDecision;
procedure CreateSimplexVertices(StartDecision: TDownhillSimplexDecision);
procedure ReplaceDecision(OldDecision, NewDecision: TDownhillSimplexDecision);
procedure GetIndicativeDecisions(var Highest, NextHighest, Lowest: LongInt); virtual;
procedure GetParametersSum;
procedure Start;
procedure Restart;
procedure BasicCalcCycle(const Highest, NextHighest, Lowest: LongInt);
procedure SetFinalTolerance(AFinalTolerance: Double);
procedure SetParametersNumber(AParametersNumber: LongInt);
function GetParametersNumber: LongInt;
public
procedure AlgorithmRealization; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DownhillSimplexServer: IDownhillSimplexServer
read FDownhillSimplexServer write FDownhillSimplexServer;
property FinalTolerance: Double
read FFinalTolerance write SetFinalTolerance;
property RestartDisabled: Boolean
read FRestartDisabled write FRestartDisabled;
property ParametersNumber: LongInt
read GetParametersNumber write SetParametersNumber;
property ExitDerivative: Double
read FExitDerivative write FExitDerivative;
end;
TDownhillSimplexSAAlgorithm = class(TDownhillSimplexAlgorithm)
protected
FTemperature: Double;
procedure GetIndicativeDecisions(var Highest, NextHighest, Lowest: LongInt); override;
function TryNewDecision(const Highest: LongInt; Factor: Double): Double; override;
function CreateAppropriateDecision: TDownhillSimplexDecision; override;
function GetRandomFluct: Double;
public
procedure AlgorithmRealization; override;
published
property Temperature: Double read FTemperature write FTemperature;
end;
const TINY = 1e-10;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Algorithms', [TDownhillSimplexAlgorithm]);
RegisterComponents('Algorithms', [TDownhillSimplexSAAlgorithm]);
end;
procedure TDownhillSimplexAlgorithm.Restart;
var TempDecision: TDownhillSimplexDecision;
begin
TempDecision := GetActuallyLowestDecision.GetCopy;
with DownhillSimplexServer do EvaluateDecision(Self, TempDecision);
CreateSimplexVertices(TempDecision);
UtilizeObject(BestDecision);
BestDecision := GetActuallyLowestDecision.GetCopy;
DownhillSimplexServer.UpdateResults(Self, BestDecision);
end;
procedure TDownhillSimplexAlgorithm.Start;
var TempDecision: TDownhillSimplexDecision;
begin
TempDecision := CreateAppropriateDecision;
with DownhillSimplexServer do
begin
FillStartDecision(Self, TempDecision);
EvaluateDecision(Self, TempDecision);
end;
CreateSimplexVertices(TempDecision);
UtilizeObject(BestDecision);
BestDecision := GetActuallyLowestDecision.GetCopy;
DownhillSimplexServer.UpdateResults(Self, BestDecision);
end;
function TDownhillSimplexAlgorithm.GetActuallyLowestDecision:
TDownhillSimplexDecision;
var MinDecision, TempDecision: TDownhillSimplexDecision;
i: LongInt;
begin
MinDecision := TDownhillSimplexDecision(Simplex.Items[0]);
for i := 1 to Simplex.Count - 1 do
begin
TempDecision := TDownhillSimplexDecision(Simplex.Items[i]);
if TempDecision.Evaluation < MinDecision.Evaluation then
MinDecision := TempDecision;
end;
Result := MinDecision;
end;
procedure TDownhillSimplexAlgorithm.CreateSimplexVertices(
StartDecision: TDownhillSimplexDecision);
var i, j: LongInt;
TempDecision: TDownhillSimplexDecision;
begin
with DownhillSimplexServer do
begin
ParametersNumber := StartDecision.ParametersNumber;
Simplex.Clear;
Simplex.Add(StartDecision);
for i := 0 to ParametersNumber - 1 do
begin
TempDecision := CreateAppropriateDecision;
TempDecision.ParametersNumber := ParametersNumber;
for j := 0 to ParametersNumber - 1 do
TempDecision.Parameters[j] := StartDecision.Parameters[j];
TempDecision.Parameters[i] := TempDecision.Parameters[i] +
GetInitParamLength(Self, i, TempDecision.ParametersNumber);
EvaluateDecision(Self, TempDecision);
Simplex.Add(TempDecision);
end;
end;
GetParametersSum;
end;
procedure TDownhillSimplexAlgorithm.GetIndicativeDecisions(
var Highest, NextHighest, Lowest: LongInt);
var i: LongInt;
begin
if TDownhillSimplexDecision(Simplex.Items[0]).Evaluation >
TDownhillSimplexDecision(Simplex.Items[1]).Evaluation then
begin Highest := 0; NextHighest := 1; Lowest := 1 end
else
begin Highest := 1; NextHighest := 0; Lowest := 0 end;
for i := 2 to Simplex.Count - 1 do
begin
if TDownhillSimplexDecision(Simplex.Items[i]).Evaluation <
TDownhillSimplexDecision(Simplex.Items[Lowest]).Evaluation
then Lowest := i;
if TDownhillSimplexDecision(Simplex.Items[i]).Evaluation >
TDownhillSimplexDecision(Simplex.Items[Highest]).Evaluation then
begin NextHighest := Highest; Highest := i; end
else
begin
if TDownhillSimplexDecision(Simplex.Items[i]).Evaluation >
TDownhillSimplexDecision(Simplex.Items[NextHighest]).Evaluation then
NextHighest := i;
end;
end;
end;
procedure TDownhillSimplexSAAlgorithm.GetIndicativeDecisions(
var Highest, NextHighest, Lowest: LongInt);
var i: LongInt;
begin
with Simplex.Items[0] as TDownhillSimplexSADecision do
FluctEvaluation := Evaluation + GetRandomFluct;
with Simplex.Items[1] as TDownhillSimplexSADecision do
FluctEvaluation := Evaluation + GetRandomFluct;
if TDownhillSimplexSADecision(Simplex.Items[0]).FluctEvaluation >
TDownhillSimplexSADecision(Simplex.Items[1]).FluctEvaluation then
begin Highest := 0; NextHighest := 1; Lowest := 1 end
else
begin Highest := 1; NextHighest := 0; Lowest := 0 end;
for i := 2 to Simplex.Count - 1 do
begin
with Simplex.Items[i] as TDownhillSimplexSADecision do
FluctEvaluation := Evaluation + GetRandomFluct;
if TDownhillSimplexSADecision(Simplex.Items[i]).FluctEvaluation <
TDownhillSimplexSADecision(Simplex.Items[Lowest]).FluctEvaluation
then Lowest := i;
if TDownhillSimplexSADecision(Simplex.Items[i]).FluctEvaluation >
TDownhillSimplexSADecision(Simplex.Items[Highest]).FluctEvaluation
then begin NextHighest := Highest; Highest := i; end
else
begin
if TDownhillSimplexSADecision(Simplex.Items[i]).FluctEvaluation >
TDownhillSimplexSADecision(Simplex.Items[NextHighest]
).FluctEvaluation then NextHighest := i;
end;
end;
end;
function TDownhillSimplexAlgorithm.CreateAppropriateDecision:
TDownhillSimplexDecision;
begin
Result := TDownhillSimplexDecision.Create(nil);
end;
function TDownhillSimplexSAAlgorithm.CreateAppropriateDecision:
TDownhillSimplexDecision;
begin
Result := TDownhillSimplexSADecision.Create(nil);
end;
function TDownhillSimplexAlgorithm.MoveWorstDecision(
const Highest: LongInt;
Factor: Double): TDownhillSimplexDecision;
var HighestDecision, TempDecision: TDownhillSimplexDecision;
Factor1, Factor2: Double;
j: LongInt;
begin
HighestDecision := TDownhillSimplexDecision(Simplex.Items[Highest]);
TempDecision := CreateAppropriateDecision;
TempDecision.ParametersNumber := ParametersNumber;
Factor1 := (1 - Factor) / ParametersNumber;
Factor2 := Factor1 - Factor;
for j := 0 to ParametersNumber - 1 do
TempDecision.Parameters[j] := ParametersSum[j] * Factor1 -
HighestDecision.Parameters[j] * Factor2;
DownhillSimplexServer.EvaluateDecision(Self, TempDecision);
Result := TempDecision;
if TempDecision.Evaluation < BestDecision.Evaluation then
begin
UtilizeObject(BestDecision);
BestDecision := TempDecision.GetCopy;
DownhillSimplexServer.UpdateResults(Self, BestDecision);
end;
end;
procedure TDownhillSimplexAlgorithm.ReplaceDecision(
OldDecision, NewDecision: TDownhillSimplexDecision);
var Index: LongInt;
begin
Index := Simplex.IndexOf(OldDecision);
UtilizeObject(OldDecision);
Simplex.Items[Index] := NewDecision;
GetParametersSum;
end;
function TDownhillSimplexAlgorithm.TryNewDecision(
const Highest: LongInt; Factor: Double): Double;
var HighestDecision, TempDecision: TDownhillSimplexDecision;
begin
TempDecision := MoveWorstDecision(Highest, Factor);
HighestDecision := TDownhillSimplexDecision(Simplex.Items[Highest]);
Result := TempDecision.Evaluation;
if TempDecision.Evaluation < HighestDecision.Evaluation then
ReplaceDecision(HighestDecision, TempDecision)
else UtilizeObject(TempDecision);
end;
function TDownhillSimplexSAAlgorithm.TryNewDecision(
const Highest: LongInt; Factor: Double): Double;
var HighestDecision, TempDecision: TDownhillSimplexSADecision;
begin
TempDecision := TDownhillSimplexSADecision(MoveWorstDecision(Highest, Factor));
HighestDecision := TDownhillSimplexSADecision(Simplex.Items[Highest]);
TempDecision.FluctEvaluation := TempDecision.Evaluation - GetRandomFluct;
Result := TempDecision.FluctEvaluation;
if TempDecision.FluctEvaluation < HighestDecision.FluctEvaluation then
ReplaceDecision(HighestDecision, TempDecision)
else UtilizeObject(TempDecision);
end;
procedure TDownhillSimplexAlgorithm.GetParametersSum;
var i, j: LongInt;
Sum: Double;
begin
for j := 0 to ParametersNumber - 1 do
begin
Sum := 0;
for i := 0 to Simplex.Count - 1 do
Sum := Sum + TDownhillSimplexDecision(Simplex.Items[i]).Parameters[j];
ParametersSum[j] := Sum;
end;
end;
procedure TDownhillSimplexAlgorithm.BasicCalcCycle(
const Highest, NextHighest, Lowest: LongInt);
var TryResult, SavedResult: Double;
i, j: LongInt;
begin
with DownhillSimplexServer do
begin
TryResult := TryNewDecision(Highest, -1);
if TryResult < TDownhillSimplexDecision(
Simplex.Items[Lowest]).Evaluation then TryNewDecision(Highest, 2)
else
begin
if TryResult >= TDownhillSimplexDecision(
Simplex.Items[NextHighest]).Evaluation then
begin
SavedResult := TDownhillSimplexDecision(
Simplex.Items[Highest]).Evaluation;
TryResult := TryNewDecision(Highest, 0.5);
if TryResult >= SavedResult then
begin
for i := 0 to Simplex.Count - 1 do
if i <> Lowest then
begin
for j := 0 to ParametersNumber - 1 do
TDownhillSimplexDecision(Simplex.Items[i]
).Parameters[j] := 0.5 *
(
TDownhillSimplexDecision(Simplex.Items[i]
).Parameters[j] +
TDownhillSimplexDecision(Simplex.Items[Lowest]
).Parameters[j]
);
EvaluateDecision(Self,
TDownhillSimplexDecision(Simplex.Items[i]));
end;
GetParametersSum;
end;
end;
end;
end;
end;
procedure TDownhillSimplexAlgorithm.AlgorithmRealization;
var Highest, NextHighest, Lowest: LongInt;
Tolerance: Double;
EvalHi, EvalLo: Double;
SavedLoEval: Double;
begin
if not Assigned(DownhillSimplexServer) then
raise EDownhillSimplexAlgorithm.Create('Server is not assigned...');
Start;
SavedLoEval := GetActuallyLowestDecision.Evaluation;
with DownhillSimplexServer do
while not EndOfCalculation(Self) do
begin
GetIndicativeDecisions(Highest, NextHighest, Lowest);
EvalHi := TDownhillSimplexDecision(
Simplex.Items[Highest]).Evaluation;
EvalLo := TDownhillSimplexDecision(
Simplex.Items[Lowest]).Evaluation;
Tolerance := 2 * Abs(EvalHi - EvalLo) /
(Abs(EvalHi) + Abs(EvalLo) + TINY);
if FinalTolDefined then if Tolerance < FinalTolerance then
begin
if (Abs(
GetActuallyLowestDecision.Evaluation - SavedLoEval
) > ExitDerivative) and (not RestartDisabled) then
begin
SavedLoEval := GetActuallyLowestDecision.Evaluation;
Restart;
Continue;
end else Exit;
end;
BasicCalcCycle(Highest, NextHighest, Lowest);
end;
end;
procedure TDownhillSimplexSAAlgorithm.AlgorithmRealization;
var Highest, NextHighest, Lowest: LongInt;
Tolerance: Double;
EvalHi, EvalLo: Double;
SavedLoEval: Double;
CycleCounter: LongInt;
begin
if not Assigned(DownhillSimplexServer) then
raise EDownhillSimplexAlgorithm.Create('Server is not assigned...');
Randomize;
Start;
SavedLoEval := GetActuallyLowestDecision.Evaluation;
CycleCounter := 0;
with DownhillSimplexServer do
while not EndOfCalculation(Self) do
begin
GetIndicativeDecisions(Highest, NextHighest, Lowest);
EvalHi := TDownhillSimplexSADecision(
Simplex.Items[Highest]).FluctEvaluation;
EvalLo := TDownhillSimplexSADecision(
Simplex.Items[Lowest]).FluctEvaluation;
Tolerance := 2 * Abs(EvalHi - EvalLo) /
(Abs(EvalHi) + Abs(EvalLo) + TINY);
if FinalTolDefined and (Tolerance < FinalTolerance) then
begin
if GetActuallyLowestDecision.Evaluation < SavedLoEval then
begin
SavedLoEval := GetActuallyLowestDecision.Evaluation;
Restart;
Continue;
end else Exit;
end;
BasicCalcCycle(Highest, NextHighest, Lowest);
Inc(CycleCounter);
if CycleCounter = 1000 then
begin
CycleCounter := 0;
Temperature := Temperature * 0.95;
end;
end;
end;
constructor TDownhillSimplexAlgorithm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Simplex := TComponentList.Create(nil);
end;
procedure TDownhillSimplexAlgorithm.SetFinalTolerance(AFinalTolerance: Double);
begin
FFinalTolerance := AFinalTolerance;
FinalTolDefined := True;
end;
procedure TDownhillSimplexAlgorithm.SetParametersNumber(AParametersNumber: LongInt);
begin
SetLength(ParametersSum, AParametersNumber);
end;
function TDownhillSimplexAlgorithm.GetParametersNumber: LongInt;
begin
if Assigned(ParametersSum) then Result := Length(ParametersSum)
else Result := 0;
end;
destructor TDownhillSimplexAlgorithm.Destroy;
begin
UtilizeObject(Simplex);
UtilizeObject(BestDecision);
inherited Destroy;
end;
function TDownhillSimplexSAAlgorithm.GetRandomFluct: Double;
begin
Result := (-1) * Temperature * Ln(Random + TINY);
end;
function TDownhillSimplexDecision.GetCopy: TDownhillSimplexDecision;
begin
Result := TDownhillSimplexDecision(inherited GetCopy);
end;
function TDownhillSimplexSADecision.GetCopy: TDownhillSimplexSADecision;
var i: LongInt;
TempDecision: TDownhillSimplexSADecision;
begin
TempDecision := TDownhillSimplexSADecision.Create(nil);
TempDecision.ParametersNumber := ParametersNumber;
for i := 0 to ParametersNumber - 1 do
TempDecision.Parameters[i] := Parameters[i];
TempDecision.Evaluation := Evaluation;
TempDecision.FluctEvaluation := FluctEvaluation;
Result := TempDecision;
end;
initialization
RegisterClass(TDownhillSimplexAlgorithm);
RegisterClass(TDownhillSimplexSAAlgorithm);
RegisterClass(TDownhillSimplexDecision);
RegisterClass(TDownhillSimplexSADecision);
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This component is an extended TStatusBar with posibilities
to define a list of fixed panels with automatic refresing
information about system:
pmGDIResource
pmSystemResource
pmUserResource
pmTotalPageFile
pmAvailPageFile
pmTotalVirtual
pmAvailVirtual
pmTotalMemory
pmAvailMemory
pmMemoryInUse
pmKeyStatus
pmDate
pmTime
}
unit SMBar;
interface
{$I SMVersion.inc}
uses
Windows, Messages, Classes, Graphics, Controls;
const
BevelWidth = 1;
Offset = 2;
type
TPanelAlignment = (paLeft, paRight);
TPanelMode = (pmGDIResource, pmSystemResource, pmUserResource,
pmTotalPageFile, pmAvailPageFile,
pmTotalVirtual, pmAvailVirtual,
pmTotalMemory, pmAvailMemory, pmMemoryInUse,
pmKeyStatus, pmDate, pmTime);
TPanelModes = set of TPanelMode;
TPanels = array[TPanelMode] of string;
TPanelBevel = (pbNone, pbLowered, pbRaised);
const
KeyCaption: array[1..3] of string[4] = ('NUM', 'CAPS', 'SCRL');
PanelsCaption: TPanels = ('GDI: ', 'SYSTEM: ', 'USER: ',
'TotalPageFile: ', 'AvailPageFile: ',
'TotalVirtual: ', 'AvailVirtual: ',
'Memory: ', 'AvailMemory: ', 'MemoryInUse: ',
'', '', '');
type
TSystembar = class;
TDrawPanelEvent = procedure(StatusBar: TSystemBar; Panel: TPanelMode; const Rect: TRect) of object;
TSMPanelPos = record
Left: Integer;
Width: Integer;
end;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSystembar = class(TCustomControl)
private
{ Private declarations }
FAutoHint: Boolean;
FFormatTime: string;
FFormatDate: string;
FSimpleText: string;
FPanels: TPanels;
FPanelsPos: array[TPanelMode] of TSMPanelPos;
FPanelModes: TPanelModes;
FAlignment: TPanelAlignment;
FPanelBevel: TPanelBevel;
FOnDrawPanel: TDrawPanelEvent;
FOnResize: TNotifyEvent;
{$IFDEF SMForDelphi5}
FOnHint: TNotifyEvent;
{$ENDIF}
procedure SetPanelBevel(Value: TPanelBevel);
procedure SetSimpleText(Value: string);
procedure SetFormatTime(Value: string);
procedure SetFormatDate(Value: string);
procedure SetPanelModes(Value: TPanelModes);
procedure SetAlignment(Value: TPanelAlignment);
procedure Frame3D(Canvas: TCanvas; Rect: TRect; TopColor, BottomColor: TColor; Width: Integer);
procedure CalcPanelsWidth;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
protected
{ Protected declarations }
FHintText: string;
procedure Paint; override;
procedure Resize; {$IFDEF SMForDelphi5}
override;
{$ELSE}
dynamic;
{$ENDIF}
procedure WMDestroy(var Msg: TMsg); message WM_Destroy;
procedure WMCreate(var Msg: TMsg); message WM_Create;
procedure WMTimer(var Msg: TMsg); message WM_Timer;
{$IFDEF SMForDelphi5}
function DoHint: Boolean; virtual;
{$ENDIF}
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
{$IFDEF SMForDelphi5}
function ExecuteAction(Action: TBasicAction): Boolean; override;
{$ENDIF}
property Canvas;
published
{ Published declarations }
property AutoHint: Boolean read FAutoHint write FAutoHint default False;
property Alignment: TPanelAlignment read FAlignment write SetAlignment;
property PanelBevel: TPanelBevel read FPanelBevel write SetPanelBevel;
property FormatDate: string read FFormatDate write SetFormatDate;
property FormatTime: string read FFormatTime write SetFormatTime;
property PanelModes: TPanelModes read FPanelModes write SetPanelModes;
property SimpleText: string read FSimpleText write SetSimpleText;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HelpContext;
property Hint;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawPanel: TDrawPanelEvent read FOnDrawPanel write FOnDrawPanel;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
property OnStartDrag;
{$IFDEF SMForDelphi5}
property OnHint: TNotifyEvent read FOnHint write FOnHint;
{$ENDIF}
end;
procedure Register;
implementation
uses SysUtils
{$IFDEF SMForDelphi5}
, StdActns
{$ENDIF}
;
procedure Register;
begin
RegisterComponents('SMComponents', [TSystembar]);
end;
function Min(X, Y: Integer): Integer;
begin
if (X < Y) then
Result := X
else
Result := Y;
end;
constructor TSystembar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFormatDate := 'ddd dd-mmm-yyyy'; //'dddd dd/mmmm/yyyy';
FFormatTime := 'hh:nn'; //'hh:nn:ss'
FPanelModes := [pmTotalMemory, pmAvailMemory,
pmKeyStatus, pmDate, pmTime];
FAlignment := paRight;
FPanelBevel := pbLowered;
Align := alBottom;
Height := 19;
end;
procedure TSystembar.SetSimpleText(Value: string);
begin
if (FSimpleText <> Value) then
begin
FSimpleText := Value;
Invalidate;
end;
end;
procedure TSystembar.SetPanelBevel(Value: TPanelBevel);
begin
if (FPanelBevel <> Value) then
begin
FPanelBevel := Value;
Invalidate;
end;
end;
procedure TSystembar.SetFormatTime(Value: string);
begin
if (Value <> FFormatTime) then
begin
FFormatTime := Value;
Invalidate
end;
end;
procedure TSystembar.SetFormatDate(Value: string);
begin
if (Value <> FFormatDate) then
begin
FFormatDate := Value;
Invalidate
end;
end;
procedure TSystembar.SetPanelModes(Value: TPanelModes);
var Msg: TMsg;
begin
FPanels := PanelsCaption;
if (FPanelModes <> Value) then
begin
FPanelModes := Value;
WMTimer(Msg);
end;
end;
procedure TSystembar.SetAlignment(Value: TPanelAlignment);
begin
if (Value <> FAlignment) then
begin
FAlignment := Value;
Invalidate
end;
end;
procedure TSystembar.WMDestroy(var Msg: TMsg);
begin
KillTimer(Handle, 1);
inherited
end;
procedure TSystembar.WMCreate(var Msg: TMsg);
begin
SetTimer(Handle, 1, 200, nil);
inherited;
end;
procedure TSystembar.WMTimer(var Msg: TMsg);
var MemStatus: TMemoryStatus;
boolNeedRepaint: Boolean;
s: string;
begin
boolNeedRepaint := False;
if (pmTime in PanelModes) then
begin
if (FPanels[pmTime] <> PanelsCaption[pmTime] + FormatDateTime(FFormatTime, Now)) then
begin
FPanels[pmTime] := PanelsCaption[pmTime] + FormatDateTime(FFormatTime, Now);
boolNeedRepaint := True
end
end
else
FPanels[pmTime] := '';
if (pmDate in PanelModes) then
begin
if (FPanels[pmDate] <> PanelsCaption[pmDate] + FormatDateTime(FFormatDate, Date)) then
begin
FPanels[pmDate] := PanelsCaption[pmDate] + FormatDateTime(FFormatDate, Date);
boolNeedRepaint := True
end
end
else
FPanels[pmDate] := '';
if (pmKeyStatus in PanelModes) then
begin
if (GetKeyState(VK_NUMLOCK) and $01) <> 0 then
s := 'NUM'
else
s := ' ';
if (GetKeyState(VK_CAPITAL) and $01) <> 0 then
s := s + ' CAPS'
else
s := s + ' ';
if (GetKeyState(VK_SCROLL) and $01) <> 0 then
s := s + ' SCRL'
else
s := s + ' ';
if (FPanels[pmKeyStatus] <> s) then
begin
FPanels[pmKeyStatus] := s;
boolNeedRepaint := True
end;
end
else
FPanels[pmKeyStatus] := '';
MemStatus.dwLength := SizeOf(TMemoryStatus);
GlobalMemoryStatus(MemStatus);
if (pmGDIResource in PanelModes) then
begin
// GetFreeSystemResources(GFSR_GDIResources);
if (FPanels[pmGDIResource] <> (PanelsCaption[pmGDIResource] + '%')) then
begin
FPanels[pmGDIResource] := (PanelsCaption[pmGDIResource] + '%');
boolNeedRepaint := True
end
end
else
FPanels[pmGDIResource] := '';
if (pmUserResource in PanelModes) then
begin
// GetFreeSystemResources(GFSR_UserResources);
if (FPanels[pmUserResource] <> (PanelsCaption[pmUserResource] + '%')) then
begin
FPanels[pmUserResource] := (PanelsCaption[pmUserResource] + '%');
boolNeedRepaint := True
end
end
else
FPanels[pmUserResource] := '';
if (pmSystemResource in PanelModes) then
begin
// GetFreeSystemResources(GFSR_SYSTEMRESOURCES);
if (FPanels[pmSystemResource] <> PanelsCaption[pmSystemResource] + '%') then
begin
FPanels[pmSystemResource] := PanelsCaption[pmSystemResource] + '%';
boolNeedRepaint := True
end
end
else
FPanels[pmSystemResource] := '';
if (pmTotalPageFile in PanelModes) then
begin
if (FPanels[pmTotalPageFile] <> (PanelsCaption[pmTotalPageFile] + IntToStr(MemStatus.dwTotalPageFile div 1024) + 'Kb')) then
begin
FPanels[pmTotalPageFile] := (PanelsCaption[pmTotalPageFile] + IntToStr(MemStatus.dwTotalPageFile div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmTotalPageFile] := '';
if (pmAvailPageFile in PanelModes) then
begin
if (FPanels[pmAvailPageFile] <> (PanelsCaption[pmAvailPageFile] + IntToStr(MemStatus.dwAvailPageFile div 1024) + 'Kb')) then
begin
FPanels[pmAvailPageFile] := (PanelsCaption[pmAvailPageFile] + IntToStr(MemStatus.dwAvailPageFile div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmAvailPageFile] := '';
if (pmTotalVirtual in PanelModes) then
begin
if (FPanels[pmTotalVirtual] <> (PanelsCaption[pmTotalVirtual] + IntToStr(MemStatus.dwTotalVirtual div 1024) + 'Kb')) then
begin
FPanels[pmTotalVirtual] := (PanelsCaption[pmTotalVirtual] + IntToStr(MemStatus.dwTotalVirtual div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmTotalVirtual] := '';
if (pmAvailVirtual in PanelModes) then
begin
if (FPanels[pmAvailVirtual] <> (PanelsCaption[pmAvailVirtual] + IntToStr(MemStatus.dwAvailVirtual div 1024) + 'Kb')) then
begin
FPanels[pmAvailVirtual] := (PanelsCaption[pmAvailVirtual] + IntToStr(MemStatus.dwAvailVirtual div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmAvailVirtual] := '';
if (pmTotalMemory in PanelModes) then
begin
if (FPanels[pmTotalMemory] <> (PanelsCaption[pmTotalMemory] + IntToStr(MemStatus.dwTotalPhys div 1024) + 'Kb')) then
begin
FPanels[pmTotalMemory] := (PanelsCaption[pmTotalMemory] + IntToStr(MemStatus.dwTotalPhys div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmTotalMemory] := '';
if (pmAvailMemory in PanelModes) then
begin
if (FPanels[pmAvailMemory] <> (PanelsCaption[pmAvailMemory] + IntToStr(MemStatus.dwAvailPhys div 1024) + 'Kb')) then
begin
FPanels[pmAvailMemory] := (PanelsCaption[pmAvailMemory] + IntToStr(MemStatus.dwAvailPhys div 1024) + 'Kb');
boolNeedRepaint := True
end
end
else
FPanels[pmAvailMemory] := '';
if (pmMemoryInUse in PanelModes) then
begin
if (FPanels[pmMemoryInUse] <> (PanelsCaption[pmMemoryInUse] + IntToStr(MemStatus.dwMemoryLoad) + '%')) then
begin
FPanels[pmMemoryInUse] := (PanelsCaption[pmMemoryInUse] + IntToStr(MemStatus.dwMemoryLoad) + '%');
boolNeedRepaint := True
end
end
else
FPanels[pmMemoryInUse] := '';
if boolNeedRepaint then
Paint;
inherited;
end;
procedure TSystembar.CalcPanelsWidth;
var i: TPanelMode;
intOffset: Integer;
s: string;
begin
if (FAlignment = paLeft) then
begin
intOffset := 0;
for i := pmGDIResource to pmTime do
begin
FPanelsPos[i].Left := intOffset;
if (i = pmKeyStatus) and (i in FPanelModes) then
s := 'NUM CAPS SCRL'
else
s := FPanels[i];
FPanelsPos[i].Width := Canvas.TextWidth(s);
if FPanelsPos[i].Width <> 0 then
Inc(intOffset, FPanelsPos[i].Width + 2*BevelWidth + 2*Offset);
end;
end
else
begin
intOffset := ClientRect.Right;
for i := pmTime downto pmGDIResource do
begin
if (i = pmKeyStatus) and (i in FPanelModes) then
s := 'NUM CAPS SCRL'
else
s := FPanels[i];
FPanelsPos[i].Width := Canvas.TextWidth(s);
if FPanelsPos[i].Width <> 0 then
Dec(intOffset, FPanelsPos[i].Width + 2*BevelWidth + 2*Offset);
FPanelsPos[i].Left := intOffset;
end;
end
end;
procedure TSystembar.Frame3D(Canvas: TCanvas; Rect: TRect;
TopColor, BottomColor: TColor; Width: Integer);
procedure DoRect;
var TopRight, BottomLeft: TPoint;
begin
with Canvas, Rect do
begin
TopRight.X := Right;
TopRight.Y := Top;
BottomLeft.X := Left;
BottomLeft.Y := Bottom;
Pen.Color := TopColor;
PolyLine([BottomLeft, TopLeft, TopRight]);
Pen.Color := BottomColor;
Dec(BottomLeft.X);
PolyLine([TopRight, BottomRight, BottomLeft]);
end;
end;
begin
Canvas.Pen.Width := 1;
Dec(Rect.Bottom);
Dec(Rect.Right);
while Width > 0 do
begin
Dec(Width);
DoRect;
InflateRect(Rect, -1, -1);
end;
Inc(Rect.Bottom);
Inc(Rect.Right);
end;
procedure TSystembar.Paint;
var StatusRect: TRect;
i: TPanelMode;
TopColor, BottomColor: TColor;
begin
// inherited Paint;
{calculate widths for all panels}
CalcPanelsWidth;
Canvas.Font := Self.Font;
TopColor := clBtnShadow;
BottomColor := clBtnHighlight;
StatusRect := ClientRect;
Canvas.Brush.Color := Self.Color;
Canvas.FillRect(StatusRect);
for i := pmGDIResource to pmTime do
begin
StatusRect.Left := FPanelsPos[i].Left + Offset;
StatusRect.Right := FPanelsPos[i].Left + FPanelsPos[i].Width + 2*BevelWidth + 2*Offset;
if Assigned(FOnDrawPanel) then
FOnDrawPanel(Self, i, StatusRect);
if (FPanels[i] <> '') then
begin
case FPanelBevel of
pbLowered: Frame3D(Canvas, StatusRect, TopColor, BottomColor, BevelWidth);
pbRaised: Frame3D(Canvas, StatusRect, BottomColor, TopColor, BevelWidth);
else// pbNone
end;
DrawText(Canvas.Handle, PChar(FPanels[i]), Length(FPanels[i]), StatusRect,
DT_CENTER or DT_VCENTER or DT_SINGLELINE)
end;
end;
if (FAlignment = paLeft) then
begin
StatusRect.Left := FPanelsPos[pmTime].Left + FPanelsPos[pmTime].Width + 2*BevelWidth + 2*Offset + 2;
StatusRect.Right := ClientRect.Right - 2;
end
else
begin
StatusRect.Left := ClientRect.Left + 2;
StatusRect.Right := FPanelsPos[pmGDIResource].Left - BevelWidth - 2;
end;
if Assigned(FOnDrawPanel) then
FOnDrawPanel(Self, TPanelMode(0), StatusRect);
if (FSimpleText <> '') then
DrawText(Canvas.Handle, PChar(FSimpleText), Length(FSimpleText), StatusRect,
DT_LEFT or DT_VCENTER or DT_SINGLELINE)
else
if (FHintText <> '') then
DrawText(Canvas.Handle, PChar(FHintText), Length(FHintText), StatusRect,
DT_LEFT or DT_VCENTER or DT_SINGLELINE)
end;
procedure TSystembar.WMSize(var Message: TWMSize);
begin
{ Eat WM_SIZE message to prevent control from doing alignment }
if not (csLoading in ComponentState) then Resize;
Repaint;
end;
{$IFDEF SMForDelphi5}
function TSystembar.ExecuteAction(Action: TBasicAction): Boolean;
begin
if AutoHint and (Action is THintAction) and not DoHint then
begin
FHintText := THintAction(Action).Hint;
Result := True;
end
else
Result := inherited ExecuteAction(Action);
end;
{$ENDIF}
procedure TSystembar.Resize;
begin
if Assigned(FOnResize) then FOnResize(Self);
end;
{$IFDEF SMForDelphi5}
function TSystembar.DoHint: Boolean;
begin
if Assigned(FOnHint) then
begin
FOnHint(Self);
Result := True;
end
else
Result := False;
end;
{$ENDIF}
end.
|
(* BinFilter: MM, 2020-04-01 *)
(* ------ *)
(* Simple filter program for binary files *)
(* ========================================================================= *)
PROGRAM BinFilter;
CONST
BUFFER_SIZE = 10240;
TYPE
BufferType = ARRAY [1..BUFFER_SIZE] OF CHAR;
PROCEDURE CheckIOError(message: STRING);
VAR error: INTEGER;
BEGIN (* CheckIOError *)
error := IOResult;
IF (error <> 0) THEN BEGIN
WriteLn('ERROR: ', message, '(Code: ', error, ')');
HALT;
END; (* IF *)
END; (* CheckIOError *)
PROCEDURE Transform(VAR b: BufferType; size: INTEGER);
VAR i: INTEGER;
BEGIN (* TransformText *)
FOR i := 1 TO size DO BEGIN
b[i] := UpCase(b[i]);
END; (* FOR *)
END; (* TransformText *)
VAR
inputFileName, outputFileName: STRING;
inputFile, outputFile: FILE;
readBytes, writtenBytes: LONGINT;
blocksRead, blocksWritten: LONGINT;
buffer: BufferType;
BEGIN (* BinFilter *)
IF (ParamCount <> 2) THEN BEGIN
WriteLn('ERROR: Invalid number of arguments.');
WriteLn('Usage: BinFilter.exe <input.dat> <output.dat>');
HALT;
END; (* IF *)
inputFileName := ParamStr(1);
Assign(inputFile, inputFileName);
{$I-}
Reset(inputFile, 1);
CheckIOError('Cannot open input file.');
{$I+}
outputFileName := ParamStr(2);
Assign(outputFile, outputFileName);
{$I-}
Rewrite(outputFile);
CheckIOError('Cannot write to output file.');
{$I+}
blocksRead := 0;
blocksWritten := 0;
BlockRead(inputFile, buffer, BUFFER_SIZE, readBytes);
Inc(blocksRead);
WHILE (readBytes > 0) DO BEGIN
Transform(buffer, readBytes);
BlockWrite(outputFile, buffer, readBytes, writtenBytes);
Inc(blocksWritten);
IF (readBytes <> writtenBytes) THEN BEGIN
WriteLn('ERROR: Number of written Bytes and read Bytes not equal');
HALT;
END; (* IF *)
BlockRead(inputFile, buffer, BUFFER_SIZE, readBytes);
Inc(blocksRead);
END; (* WHILE *)
Close(inputFile);
Close(outputFile);
WriteLn('Status: ', blocksRead, ' block read, ', blocksWritten, ' block written.');
END. (* BinFilter *) |
unit MediaStream.FrameQueue;
interface
uses
Windows,SysUtils, Classes, SyncObjs, Generics.Collections, Collections.Lists,
MediaProcessing.Definitions,MediaStream.Frame;
type
TMediaStreamFrameQueue = class
private
FFreeItemsLists: array [TMediaType] of TLinkedList<TMediaStreamFrame>;
FItems: TLinkedList<TMediaStreamFrame>;
FLock : TCriticalSection;
FMaxCount: integer;
procedure SetMaxCount(const Value: integer);
function FindAppropriateFreeItemToUse(aMT: TMediaType; aDataSize:cardinal; aInfoSize: cardinal): TMediaStreamFrame;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
procedure Add(aData: pointer; aDataSize:cardinal; const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal);
function ExtractFirstOrDefault: TMediaStreamFrame;
procedure Clear;
procedure FreeItem(aItem: TMediaStreamFrame);
function Count: integer;
function Length: cardinal; //длительность в мс
property MaxCount: integer read FMaxCount write SetMaxCount;
end;
implementation
{ TMediaStreamFrameQueue }
procedure TMediaStreamFrameQueue.Add(aData: pointer; aDataSize: cardinal;
const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal);
var
aFrame: TMediaStreamFrame;
begin
Lock;
try
while Count>=MaxCount do
FreeItem(ExtractFirstOrDefault);
aFrame:=FindAppropriateFreeItemToUse(aFormat.biMediaType, aDataSize,aInfoSize);
if aFrame=nil then
aFrame:=TMediaStreamFrame.Create(aFormat, aData,aDataSize,aInfo,aInfoSize)
else
aFrame.Assign(aFormat,aData,aDataSize,aInfo,aInfoSize);
FItems.Add(aFrame);
finally
Unlock;
end;
end;
procedure TMediaStreamFrameQueue.Clear;
var
aItem: TLinkedListItem<TMediaStreamFrame>;
begin
FLock.Enter;
try
aItem:=FItems.First;
while aItem<>nil do
begin
FreeItem(aItem.Value);
aItem:=FItems.Next(aItem);
end;
FItems.Clear;
finally
FLock.Leave;
end;
end;
function TMediaStreamFrameQueue.Count: integer;
begin
Lock;
try
result:=FItems.Size;
finally
Unlock;
end;
end;
constructor TMediaStreamFrameQueue.Create;
var
aMT: TMediaType;
begin
FLock:=TCriticalSection.Create;
FItems:=TLinkedList<TMediaStreamFrame>.Create;
for aMT := Low(TMediaType) to High(TMediaType) do
FFreeItemsLists[aMT]:=TLinkedList<TMediaStreamFrame>.Create;
SetMaxCount(100);
end;
destructor TMediaStreamFrameQueue.Destroy;
var
aMT: TMediaType;
aItem: TLinkedListItem<TMediaStreamFrame>;
begin
Clear;
//Очищаем кэш
for aMT := Low(TMediaType) to High(TMediaType) do
begin
aItem:=FFreeItemsLists[aMT].First;
while aItem<>nil do
begin
FreeAndNil(aItem.Value);
aItem:=FFreeItemsLists[aMT].Next(aItem);
end;
FreeAndNil(FFreeItemsLists[aMT]);
end;
FreeAndNil(FItems);
FreeAndNil(FLock);
inherited;
end;
function TMediaStreamFrameQueue.ExtractFirstOrDefault: TMediaStreamFrame;
begin
self.Lock;
try
result:=nil;
if Count>0 then
begin
result:=FItems.First.Value;
FItems.Delete(FItems.First);
end;
finally
self.Unlock;
end;
end;
function TMediaStreamFrameQueue.FindAppropriateFreeItemToUse(aMT: TMediaType; aDataSize, aInfoSize: cardinal): TMediaStreamFrame;
var
aItem: TLinkedListItem<TMediaStreamFrame>;
begin
result:=nil;
aItem:=FFreeItemsLists[aMT].First;
while aItem<>nil do
begin
if (aItem.Value.DataAllocatedBlockSize>=aDataSize) and (aItem.Value.InfoAllocatedBlockSize>=aInfoSize) then
begin
result:=aItem.Value;
FFreeItemsLists[aMT].Delete(aItem);
exit;
end;
aItem:=FFreeItemsLists[aMT].Next(aItem);
end;
//Если ничего не нашли, то применим первую попавшуюся
if FFreeItemsLists[aMT].First<>nil then
begin
result:=FFreeItemsLists[aMT].First.Value;
FFreeItemsLists[aMT].Delete(FFreeItemsLists[aMT].First);
end;
end;
procedure TMediaStreamFrameQueue.FreeItem(aItem: TMediaStreamFrame);
begin
Assert(aItem<>nil);
self.Lock;
try
if FFreeItemsLists[aItem.Format.biMediaType].Size<FMaxCount div 10 then //10%
begin
FFreeItemsLists[aItem.Format.biMediaType].Add(aItem);
end
else begin
FreeAndNil(aItem);
end;
finally
self.Unlock;
end;
end;
function TMediaStreamFrameQueue.Length: cardinal;
var
aStart,aStop: cardinal;
begin
result:=0;
Lock;
try
if Count>1 then
begin
aStart:=FItems.First.Value.Format.TimeStampMs;
aStop:=FItems.Last.Value.Format.TimeStampMs;
if aStart<aStop then
result:=aStop-aStart;
end;
finally
Unlock;
end;
end;
procedure TMediaStreamFrameQueue.Lock;
begin
FLock.Enter;
end;
procedure TMediaStreamFrameQueue.SetMaxCount(const Value: integer);
begin
Assert(value>0);
FLock.Enter;
try
FMaxCount := Value;
finally
FLock.Leave;
end;
end;
procedure TMediaStreamFrameQueue.Unlock;
begin
FLock.Leave;
end;
end.
|
program PeopleLister;
type
Person = record
id: integer;
Name: string;
sex: (male, female);
link: integer;
end;
procedure PrintPerson(const person: Person);
begin
with person do
begin
Write(id);
Write(' ');
Write(Name);
Write(' ');
Write(sex);
Write(' ');
Write(link);
Write(' ');
WriteLn();
end;
end;
function GetPersonById(const people: array of Person; const id: integer): Person;
begin
GetPersonById := people[id - 1];
end;
function GetSucc(const people: array of Person; const pred: Person;
const curr: Person): Person;
var
succId: integer;
begin
succId := pred.id + curr.link;
GetSucc := GetPersonById(people, succId);
end;
function GetPred(const people: array of Person; const succ: Person;
const curr: Person): Person;
var
predId: integer;
begin
predId := succ.id - curr.link;
GetPred := GetPersonById(people, predId);
end;
const
n = 10;
var
people: array[1..n] of Person;
i, Count: integer;
pred, curr, succ: Person;
begin
{ See Section 1.7 of A + DS = P by NW }
with people[1] do
begin
id := 1;
Name := 'Carolyn';
sex := female;
link := 2;
end;
with people[2] do
begin
id := 2;
Name := 'Chris';
sex := male;
link := 2;
end;
with people[3] do
begin
id := 3;
Name := 'Tina';
sex := female;
link := 5;
end;
with people[4] do
begin
id := 4;
Name := 'Robert';
sex := male;
link := 3;
end;
with people[5] do
begin
id := 5;
Name := 'Jonathan';
sex := male;
link := 3;
end;
with people[6] do
begin
id := 6;
Name := 'Jennifer';
sex := female;
link := 5;
end;
with people[7] do
begin
id := 7;
Name := 'Raytheon';
sex := male;
link := 5;
end;
with people[8] do
begin
id := 8;
Name := 'Mary';
sex := female;
link := 3;
end;
with people[9] do
begin
id := 9;
Name := 'Anne';
sex := female;
link := 1;
end;
with people[10] do
begin
id := 10;
Name := 'Mathias';
sex := male;
link := 3;
end;
WriteLn('Print the people');
for i := 1 to n do
PrintPerson(people[i]);
WriteLn('Count the women');
Count := 0;
for i := 1 to n do
with people[i] do
if sex = female then
Count := Count + 1;
Write('There are ');
Write(Count);
WriteLn(' women.');
WriteLn('Traverse the women');
pred := GetPersonById(people, 1);
curr := GetPersonById(people, 3);
succ := GetSucc(people, pred, curr);
PrintPerson(succ);
pred := curr;
curr := succ;
succ := GetSucc(people, pred, curr);
PrintPerson(succ);
pred := curr;
curr := succ;
succ := GetSucc(people, pred, curr);
PrintPerson(succ);
pred := curr;
curr := succ;
succ := GetSucc(people, pred, curr);
PrintPerson(succ);
WriteLn('Traverse the men backwards');
succ := GetPersonById(people, 10);
curr := GetPersonById(people, 7);
pred := GetPred(people, succ, curr);
PrintPerson(pred);
succ := curr;
curr := pred;
pred := GetPred(people, succ, curr);
PrintPerson(pred);
succ := curr;
curr := pred;
pred := GetPred(people, succ, curr);
PrintPerson(pred);
succ := curr;
curr := pred;
pred := GetPred(people, succ, curr);
PrintPerson(pred);
end.
|
(* ustritem.pas -- (c) 1989 by Tom Swan *)
unit ustritem;
interface
uses uitem;
type
strItemPtr = ^strItem;
strItem = object( item )
sp : ^string;
constructor init( s : string );
destructor done; virtual;
function getString : string;
function putString( s : string ) : Boolean; virtual;
procedure upperString; virtual;
end;
implementation
{ ----- Initialize a new string item, allocating heap space for the
string's characters and addressing that space with the object's sp
pointer. }
constructor strItem.init( s : string );
begin
sp := nil;
if putstring( s ) then item.init else
begin
done; { Clean up any partially allocated structures }
fail; { Out of memory error }
end;
end;
{ ----- Dispose of the allocated heap space and any memory assigned
to the string item object. }
destructor strItem.done;
begin
if sp <> nil
then freemem( sp, length( sp^ ) + 1 );
item.done;
end;
{ ----- Return the value of the string. }
function strItem.getString : string;
begin
getString := sp^;
end;
{ ----- Assign or replace the object's character string. Disposes any
current string and returns true for success; false if out of memory. }
function strItem.putString( s : string ) : Boolean;
begin
if sp <> nil
then freemem( sp, length( sp^ ) + 1 );
getmem( sp, length( s ) + 1 );
if sp = nil then putString := false else
begin
sp^ := s;
putString := true;
end;
end;
{ ----- Convert string to all uppercase. }
procedure strItem.upperString;
var
i : integer;
begin
if sp <> nil then
for i := 1 to length( sp^ ) do
sp^[ i ] := upcase( sp^[ i ] );
end;
end.
|
unit LoanReleaseDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, Data.DB, Vcl.Grids,
Vcl.DBGrids, RzDBGrid, RzDBEdit, Vcl.StdCtrls, Vcl.Mask, RzEdit, RzButton,
RzTabs, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
RzPanel, RzGrids, ReleaseRecipient, LoanCharge, RzRadChk, Math, Vcl.DBCtrls,
RzDBCmbo, RzCmboBx;
type
TfrmLoanReleaseDetail = class(TfrmBasePopupDetail)
urlReleaseToClient: TRzURLLabel;
pcAssessment: TRzPageControl;
tsRecipients: TRzTabSheet;
tsCharges: TRzTabSheet;
RzPanel1: TRzPanel;
btnRemove: TRzShapeButton;
RzPanel2: TRzPanel;
btnAdd: TRzShapeButton;
grReleaseRecipient: TRzStringGrid;
grCharges: TRzStringGrid;
urlApprovedAmount: TRzURLLabel;
edReleasedAmount: TRzNumericEdit;
edAdvancePaymentMonths: TRzNumericEdit;
cmbPromissoryNotes: TRzComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
lblNetProceeds: TLabel;
lblAppliedAmount: TLabel;
lblCharges: TLabel;
lblAdvancePayment: TLabel;
lblAdvancePaymentMonths: TLabel;
Label7: TLabel;
procedure FormShow(Sender: TObject);
procedure grReleaseRecipientDblClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure urlReleaseToClientClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure pcAssessmentChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure urlApprovedAmountClick(Sender: TObject);
procedure edReleasedAmountChange(Sender: TObject);
procedure cmbPromissoryNotesChange(Sender: TObject);
private
{ Private declarations }
procedure AddRow(rec: TReleaseRecipient);
procedure AddRowCharge(const charge: TLoanCharge);
procedure PopulateReleaseRecipient;
procedure PopulateCharges;
procedure ModifyRemove(const remove: boolean = false);
procedure ClearRow(grid: TRzStringGrid; const row: integer);
procedure PopulatePromissoryNotes;
function GetTotalReleased: currency;
function ConfirmRelease: string;
function ConfirmAdvancePayment: string;
public
{ Public declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
implementation
{$R *.dfm}
uses
Loan, ReleaseRecipientDetail, LoanData, FormsUtil, IFinanceGlobal,
Recipient, IFinanceDialogs, LoanClassAdvance;
procedure TfrmLoanReleaseDetail.ClearRow(grid: TRzStringGrid; const row: Integer);
var
rw, cl: integer;
begin
// clear the object in the deleted row
grid.Objects[0,row] := nil;
// move up all rows
for rw := row + 1 to grid.RowCount - 1 do
begin
for cl := 0 to grid.ColCount - 1 do
grid.Cells[cl,rw-1] := grid.Cells[cl,rw];
if Assigned(grid.Objects[0,rw]) then grid.Objects[0,rw-1] := grid.Objects[0,rw];
end;
// decrease row count
grid.RowCount := grid.RowCount - 1;
end;
procedure TfrmLoanReleaseDetail.cmbPromissoryNotesChange(Sender: TObject);
begin
inherited;
ln.PromissoryNote := cmbPromissoryNotes.Text;
end;
procedure TfrmLoanReleaseDetail.ModifyRemove(const remove: boolean);
const
CONF = 'Are you sure you want to remove the selected recipient?';
var
r: integer;
recipient, method, locationCode, locationName: string;
rec: TReleaseRecipient;
begin
inherited;
with dmLoan.dstLoanRelease, grReleaseRecipient do
begin
if not Assigned(Objects[0,Row]) then Exit;
r := Row;
rec := (Objects[0,r] as TReleaseRecipient);
recipient := (Objects[0,r] as TReleaseRecipient).Recipient.Id;
method := (Objects[0,r] as TReleaseRecipient).ReleaseMethod.Id;
locationCode := (Objects[0,r] as TReleaseRecipient).LocationCode;
locationName := (Objects[0,r] as TReleaseRecipient).LocationName;
// locate the record in the dataset
Locate('recipient;rel_method;loc_code',VarArrayOf([recipient,method,locationCode]),[]);
end;
if not remove then
begin
with TfrmReleaseRecipientDetail.Create(self) do
begin
rrp := rec;
ShowModal;
// update row
if ModalResult = mrOk then
begin
grReleaseRecipient.Cells[0,r] := FormatDateTime('mm/dd/yyyy',rrp.Date);
grReleaseRecipient.Cells[1,r] := rrp.Recipient.Name;
grReleaseRecipient.Cells[2,r] := rrp.LocationName;
grReleaseRecipient.Cells[3,r] := rrp.ReleaseMethod.Name;
grReleaseRecipient.Cells[4,r] := FormatCurr('###,###,##0.00',rrp.Amount);
grReleaseRecipient.Objects[0,r] := rrp;
end;
Free;
end;
end
else
begin
if ShowDecisionBox(CONF) = mrYes then
begin
ln.RemoveReleaseRecipient(rec);
ClearRow(grReleaseRecipient,r);
end;
end;
end;
procedure TfrmLoanReleaseDetail.pcAssessmentChange(Sender: TObject);
begin
PopulateCharges;
ExtendLastColumn(grCharges);
end;
procedure TfrmLoanReleaseDetail.AddRow(rec: TReleaseRecipient);
var
r: integer;
begin
with grReleaseRecipient do
begin
RowCount := RowCount + 1;
r := RowCount - 2;
Cells[0,r] := FormatDateTime('mm/dd/yyyy',rec.Date);
Cells[1,r] := rec.Recipient.Name;
Cells[2,r] := rec.LocationName;
Cells[3,r] := rec.ReleaseMethod.Name;
Cells[4,r] := FormatCurr('###,###,##0.00',rec.Amount);
Objects[0,r] := rec;
end;
end;
procedure TfrmLoanReleaseDetail.AddRowCharge(const charge: TLoanCharge);
var
r: integer;
begin
with grCharges do
begin
RowCount := RowCount + 1;
r := RowCount - 2;
Cells[0,r] := charge.ChargeName;
Cells[1,r] := FormatCurr('###,###,##0.00',charge.Amount);
Objects[0,r] := charge;
end;
end;
procedure TfrmLoanReleaseDetail.BindToObject;
begin
inherited;
end;
procedure TfrmLoanReleaseDetail.PopulateReleaseRecipient;
var
i, cnt: integer;
begin
with grReleaseRecipient do
begin
RowCount := RowCount + 1;
FixedRows := 1;
// headers
Cells[0,0] := 'Date';
Cells[1,0] := 'Recipient';
Cells[2,0] := 'Branch';
Cells[3,0] := 'Method';
Cells[4,0] := 'Amount';
// widths
ColWidths[0] := 80;
ColWidths[1] := 150;
ColWidths[2] := 100;
ColWidths[3] := 60;
ColWidths[4] := 75;
cnt := ln.ReleaseRecipientCount;
for i := 0 to cnt - 1 do
AddRow(ln.ReleaseRecipients[i]);
end;
end;
procedure TfrmLoanReleaseDetail.PopulateCharges;
var
i, cnt: integer;
begin
// clear rows
grCharges.RowCount := 1;
with grCharges do
begin
RowCount := RowCount + 1;
FixedRows := 1;
// headers
Cells[0,0] := 'Charge';
Cells[1,0] := 'Amount';
// widths
ColWidths[0] := 200;
ColWidths[1] := 80;
cnt := ln.LoanChargeCount;
for i := 0 to cnt - 1 do
AddRowCharge(ln.LoanCharges[i]);
end;
end;
procedure TfrmLoanReleaseDetail.PopulatePromissoryNotes;
var
i, cnt: integer;
begin
with cmbPromissoryNotes, ln.Client do
begin
Clear;
GetAvailablePromissoryNotes;
cnt := PromissoryNotesCount - 1;
for i := 0 to cnt do Items.Add(PromissoryNotes[i]);
end;
end;
procedure TfrmLoanReleaseDetail.Save;
begin
ln.Save;
end;
procedure TfrmLoanReleaseDetail.urlApprovedAmountClick(Sender: TObject);
begin
inherited;
if (ln.Action = laReleasing) and (ln.IsApproved) then
begin
edReleasedAmount.Value := ln.ApprovedAmount;
ln.ReleaseAmount := ln.ApprovedAmount;
ln.ComputeCharges;
PopulateCharges;
ExtendLastColumn(grCharges);
end;
end;
procedure TfrmLoanReleaseDetail.urlReleaseToClientClick(Sender: TObject);
var
error: string;
begin
inherited;
if ln.Action = laReleasing then
begin
if edReleasedAmount.Value > 0 then
begin
ln.ReleaseAmount := edReleasedAmount.Value;
ln.ComputeCharges;
rrp := TReleaseRecipient.Create;
rrp.Recipient := TRecipient.Create(ln.Client.Id,ln.Client.Name);
rrp.Date := ifn.AppDate;
rrp.Amount := ln.ReleaseAmount - ln.TotalCharges - ln.TotalAdvancePayment;
rrp.ReleaseMethod := TReleaseMethod.Create('C','Cash');
rrp.LocationCode := ifn.LocationCode;
rrp.LocationName := ifn.GetLocationNameByCode(ifn.LocationCode);
if ln.ReleaseRecipientExists(rrp.Recipient.Id,rrp.LocationCode,rrp.ReleaseMethod.Id) then
begin
error := 'Release details already exists.';
ShowErrorBox(error);
end
else
begin
ln.AppendReleaseRecipient(rrp);
ln.AddReleaseRecipient(rrp);
AddRow(rrp);
end;
end
else ShowErrorBox('Pleae enter release amount.');
end;
end;
procedure TfrmLoanReleaseDetail.btnAddClick(Sender: TObject);
begin
if edReleasedAmount.Value > 0 then
begin
ln.ReleaseAmount := edReleasedAmount.Value;
ln.AppendReleaseRecipient;
with TfrmReleaseRecipientDetail.Create(self) do
begin
rrp := TReleaseRecipient.Create;
ShowModal;
if ModalResult = mrOk then AddRow(ln.ReleaseRecipients[ln.ReleaseRecipientCount - 1]);
Free;
end;
end
else if edReleasedAmount.Value <= 0 then ShowErrorBox('Please enter release amount.');
end;
procedure TfrmLoanReleaseDetail.btnCancelClick(Sender: TObject);
begin
ln.ClearReleaseRecipients;
ln.ClearLoanCharges;
inherited;
end;
procedure TfrmLoanReleaseDetail.btnRemoveClick(Sender: TObject);
begin
inherited;
ModifyRemove(true);
end;
procedure TfrmLoanReleaseDetail.Cancel;
begin
ln.Cancel;
end;
procedure TfrmLoanReleaseDetail.FormCreate(Sender: TObject);
begin
inherited;
PopulatePromissoryNotes;
// applied amount
lblAppliedAmount.Caption := FormatCurr('###,##0.00',ln.AppliedAmount);
// approved amount
urlApprovedAmount.Caption := FormatCurr('###,##0.00',ln.ApprovedAmount);
end;
procedure TfrmLoanReleaseDetail.FormShow(Sender: TObject);
begin
inherited;
PopulateReleaseRecipient;
ExtendLastColumn(grReleaseRecipient);
if ln.LoanClass.HasAdvancePayment then
begin
edAdvancePaymentMonths.IntValue := ln.LoanClass.AdvancePayment.NumberOfMonths;
edAdvancePaymentMonths.Enabled := ln.LoanClass.AdvancePayment.AdvanceMethod = amUponRelease;
end;
end;
procedure TfrmLoanReleaseDetail.grReleaseRecipientDblClick(Sender: TObject);
begin
ModifyRemove;
end;
function TfrmLoanReleaseDetail.ValidEntry: boolean;
var
error: string;
begin
if ln.NetProceeds <= 0 then
error := 'Net proceeds cannot be less than zero.'
else if ln.ReleaseRecipientCount = 0 then
error := 'Please add at least one recipient.'
else if ln.ReleaseAmount > ln.ApprovedAmount then
error := 'Release amount is greater than the approved amount.'
else if GetTotalReleased <> Ceil(ln.NetProceeds * 100/100) then
error := 'TOTAL amount released is not equal to the NET proceeds.'
else if (ln.LoanClass.HasAdvancePayment)
and (ln.LoanClass.AdvancePayment.AdvanceMethod = amUponRelease)
and (ln.LoanClass.AdvancePayment.NumberOfMonths < 0) then
error := 'Invalid value for advance payment.'
else if (ln.LoanClass.HasAdvancePayment)
and (ln.LoanClass.AdvancePayment.AdvanceMethod = amUponRelease)
and (ln.LoanClass.AdvancePayment.NumberOfMonths = 0) then
error := ConfirmAdvancePayment
else if ln.ReleaseAmount < ln.ApprovedAmount then
error := ConfirmRelease;
Result := error = '';
if not Result then ShowErrorBox(error);
end;
function TfrmLoanReleaseDetail.GetTotalReleased: currency;
var
total: currency;
i, cnt: integer;
begin
total := 0;
cnt := ln.ReleaseRecipientCount - 1;
for i := 0 to cnt do total := total + ln.ReleaseRecipients[i].Amount;
Result := Ceil(total * 100 / 100);
end;
function TfrmLoanReleaseDetail.ConfirmAdvancePayment: string;
var
msg: string;
begin
msg := 'Advance payment has not been entered. Do you want to proceed?';
if ShowDecisionBox(msg) = mrYes then Result := ''
else Result := 'Releasing process cancelled.';
end;
function TfrmLoanReleaseDetail.ConfirmRelease: string;
var
msg: string;
begin
msg := 'Release amount is less than the approved amount. Do you want to proceed?';
if ShowDecisionBox(msg) = mrYes then Result := ''
else Result := 'Releasing process cancelled.';
end;
procedure TfrmLoanReleaseDetail.edReleasedAmountChange(Sender: TObject);
begin
ln.ReleaseAmount := edReleasedAmount.Value;
ln.ComputeCharges;
if ln.LoanClass.HasAdvancePayment then
begin
if ln.LoanClass.AdvancePayment.AdvanceMethod = amPreset then
edAdvancePaymentMonths.Value := ln.LoanClass.AdvancePayment.NumberOfMonths
else
ln.LoanClass.AdvancePayment.Interest := edAdvancePaymentMonths.IntValue;
if ln.LoanClass.AdvancePayment.IncludePrincipal then
ln.LoanClass.AdvancePayment.Principal := edAdvancePaymentMonths.IntValue;
if ln.LoanClass.AdvancePayment.IncludePrincipal then
lblAdvancePaymentMonths.Caption :=
IntToStr(ln.LoanClass.AdvancePayment.NumberOfMonths) + ' months'
else
lblAdvancePaymentMonths.Caption :=
IntToStr(ln.LoanClass.AdvancePayment.NumberOfMonths) + ' months (Interest only)';
end
else lblAdvancePaymentMonths.Caption := 'No advance payment required';
lblCharges.Caption := FormatCurr('###,###,##0.00',ln.TotalCharges);
lblAdvancePayment.Caption := FormatCurr('###,###,##0.00',ln.TotalAdvancePayment);
lblNetProceeds.Caption := FormatCurr('###,###,##0.00',ln.NetProceeds);
end;
end.
|
program gcd_program(input,output);
var x,y:integer;
function gcd(a,b:integer):integer;
begin
if b=0 then gcd:=a
else gcd:=gcd(b, a mod b)
end;
begin
write_string('Input a, b:');
read_int(x);
read_int(y);
write_int(gcd(x, y));
end.
|
unit DataMsg;
interface
uses SysUtils, Classes;
type
TDataMsg = class(TObject)
public
SourceID: Integer;
TargetID: Integer;
ParamsList: TStringList;
Data: TMemoryStream;
constructor Create();
destructor Destroy; override;
function ToStream(AStream: TStream): boolean;
function FromStream(AStream: TStream): Boolean;
end;
implementation
//============================================
// TDataMsg
//============================================
constructor TDataMsg.Create();
begin
Self.ParamsList:=TStringList.Create();
Self.Data:=TMemoryStream.Create();
end;
destructor TDataMsg.Destroy;
begin
FreeAndNil(Self.Data);
FreeAndNil(Self.ParamsList);
end;
function TDataMsg.ToStream(AStream: TStream): boolean;
var
ms: TMemoryStream;
iParamsSize, iDataSize: Cardinal;
begin
Result:=False;
if not Assigned(AStream) then Exit;
iParamsSize:=Length(Self.ParamsList.Text);
iDataSize:=Self.Data.Size;
ms:=TMemoryStream.Create();
ms.Write(Self.SourceID, SizeOf(Self.SourceID));
ms.Write(Self.TargetID, SizeOf(Self.TargetID));
ms.Write(iParamsSize, SizeOf(iParamsSize));
Self.ParamsList.SaveToStream(ms);
ms.Write(iDataSize, SizeOf(iDataSize));
Self.Data.Seek(0, soFromBeginning);
ms.CopyFrom(Self.Data, iDataSize);
ms.Seek(0, soFromBeginning);
AStream.Size:=ms.Size;
AStream.Seek(0, soFromBeginning);
ms.SaveToStream(AStream);
FreeAndNil(ms);
Result:=true;
end;
function TDataMsg.FromStream(AStream: TStream): Boolean;
var
ms: TMemoryStream;
iParamsSize, iDataSize: Cardinal;
begin
Result:=False;
if not Assigned(AStream) then Exit;
AStream.Seek(0, soFromBeginning);
AStream.Read(Self.SourceID, SizeOf(Self.SourceID));
AStream.Read(Self.TargetID, SizeOf(Self.TargetID));
AStream.Read(iParamsSize, SizeOf(iParamsSize));
Self.ParamsList.Clear();
ms:=TMemoryStream.Create();
ms.CopyFrom(AStream, iParamsSize);
ms.Seek(0, soFromBeginning);
Self.ParamsList.LoadFromStream(ms);
FreeAndNil(ms);
Self.Data.Clear();
AStream.Read(iDataSize, SizeOf(iDataSize));
Self.Data.CopyFrom(AStream, iDataSize);
Result:=True;
end;
end.
|
_______________________________________________________________
TEXTURE.PAS Accompanies "Mimicking Mountains," by Tom Jeffery,
BYTE, December 1987, page 337
______________________________________________________________
program textures;
const
size = 64;
var
srf : array[0..size, 0..size] of longint;
ans : string[30];
srfile : file of longint;
col, row : longint;
procedure SetUpDrawing;
var
R : Rect;
begin
HideAll;
SetRect(R, 0, 38, 511, 341);
SetDrawingRect(R);
ShowDrawing
end;
procedure paintpt (row, col : longint);
var
pt, pt2 : point;
rct : rect;
begin
pt.v := row;
pt.h := col;
pt2.v := row + 1;
pt2.h := col + 1;
rct.topleft := pt;
rct.botright := pt2;
paintrect(rct);
end;
procedure CoastDisp;
{Displays coastline}
var
col, row, int : longint;
begin
for row := 0 to size do
for col := 0 to size do
begin
if srf[row, col] > 0 then
penpat(black)
else
penpat(white);
paintpt(row, col);
end;
end;
procedure StripeDisp;
{Displays stripes for heights defined by int}
var
col, row, int : longint;
begin
write('Interval?');
readln(int);
if int > 0 then
begin
for row := 0 to size do
for col := 0 to size do
begin
if odd(srf[row, col] div int) then
penpat(black)
else
penpat(white);
paintpt(row, col);
end;
end;
end;
procedure TopoDisp;
{Displays contours separated by int}
var
col, row, int : longint;
begin
write('Interval?');
readln(int);
if int > 0 then
begin
for row := 0 to size - 1 do
for col := 0 to size - 1 do
begin
if ((srf[row, col] div int) = (srf[row, col + 1] div int)) and ((srf[row, col] div int) = (srf[row + 1, col] div int)) then
penpat(white)
else
penpat(black);
paintpt(row, col);
end;
end;
end;
procedure GrainDisp;
{Displays wood grain, grain spacing: int}
var
col, row, int, res, sp, drk, gr, lt : longint;
begin
write('Interval?');
readln(int);
if int > 0 then
begin
sp := int div 7;
drk := sp * 2;
gr := sp * 3;
lt := sp * 4;
for row := 0 to size do
for col := 0 to size do
begin
res := srf[row, col] mod int;
if res < sp then
penpat(black)
else if res < drk then
penpat(dkgray)
else if res < gr then
penpat(gray)
else if res < lt then
penpat(ltgray)
else
penpat(white);
paintpt(row, col);
end;
end;
end;
begin
open(srfile, oldfileName('Surface File'));
for row := 0 to size do
for col := 0 to size do
read(srfile, srf[row, col]);
close(srfile);
setorigin(-10, -10);
write('(c)oastline, (s)tripe, (t)opo, (g)rain, or (q)uit?');
readln(ans);
repeat
if ans[1] = 'c' then
coastdisp
else if ans[1] = 's' then
stripedisp
else if ans[1] = 't' then
topodisp
else if ans[1] = 'g' then
graindisp;
write('Save?');
readln(ans);
if ans[1] = 'y' then
begin
write('Filename?');
readln(ans);
savedrawing(ans);
end;
write('(c)oastline, (s)tripe, (t)opo, (g)rain, or (q)uit?');
readln(ans);
until ans[1] = 'q';
end. |
CalcException = class(Exception)
public
constructor create(code: Integer);
function getCode: Integer;
class procedure checkException(status: Status);
class procedure catchException(status: Status; e: Exception);
class procedure setVersionError(status: Status; interfaceName: string;
currentVersion, expectedVersion: NativeInt);
private
code: Integer;
end;
|
unit myunion_s;
{This file was generated on 11 Aug 2000 20:17:46 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file myunion.idl. }
{Delphi Pascal unit : myunion_s }
{derived from IDL module : default }
interface
uses
CORBA,
myunion_i,
myunion_c;
type
TAccountSkeleton = class;
TAccountSkeleton = class(CORBA.TCorbaObject, myunion_i.Account)
private
FImplementation : Account;
public
constructor Create(const InstanceName: string; const Impl: Account);
destructor Destroy; override;
function GetImplementation : Account;
function balance ( const myUnion : myunion_i.UnionType): Single;
published
procedure _balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TAccountSkeleton.Create(const InstanceName : string; const Impl : myunion_i.Account);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'Account', 'IDL:Account:1.0');
FImplementation := Impl;
end;
destructor TAccountSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TAccountSkeleton.GetImplementation : myunion_i.Account;
begin
result := FImplementation as myunion_i.Account;
end;
function TAccountSkeleton.balance ( const myUnion : myunion_i.UnionType): Single;
begin
Result := FImplementation.balance( myUnion);
end;
procedure TAccountSkeleton._balance(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_myUnion : myunion_i.UnionType;
_Result : Single;
begin
_myUnion := myunion_c.TUnionTypeHelper.Read(_Input);
_Result := balance( _myUnion);
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
initialization
end. |
PROGRAM SortMonth(INPUT, OUTPUT);
USES DateIO;
VAR
Mo1, Mo2: Month;
BEGIN
ReadMonth(INPUT, Mo1);
ReadMonth(INPUT, Mo2);
IF ((Mo1 = NoMonth) OR (Mo2 = NoMonth))
THEN
WRITE('Входные данные записаны неверно')
ELSE
IF (Mo1 < Mo2)
THEN
BEGIN
WriteMonth(OUTPUT, Mo1);
WRITE(' предшествует ');
WriteMonth(OUTPUT, Mo2);
END
ELSE
IF (Mo1 > Mo2)
THEN
BEGIN
WriteMonth(OUTPUT, Mo1);
WRITE(' следует ');
WriteMonth(OUTPUT, Mo2);
END
ELSE
BEGIN
WRITE('Оба месяца ');
WriteMonth(OUTPUT, Mo1);
END;
WRITELN
END.
|
{ A benchmark that tests many short-lived threads with many transient small objects. }
unit WildThreadsBenchmarkUnit;
interface
uses Windows, BenchmarkClassUnit, Classes, Math;
type
TWildThreads = class(TFastcodeMMBenchmark)
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses SysUtils;
type
TAWildThread = class(TThread)
procedure Execute; override;
end;
procedure TAWildThread.Execute;
const
REPEATCOUNT = 4;
var
i, j, k, n : Integer;
p : array [1..151] of Pointer;
begin
for j := 1 to REPEATCOUNT do
begin
// 151 is a prime number, so no trivial cyclicity with 256 (the size)
for i:=Low(p) to High(p) do
GetMem(p[i], i);
k:=Low(p);
for i:=1 to 100000 do begin
n:=(i and 255)+1;
FreeMem(p[k]);
GetMem(p[k], n);
// use memory
PChar(p[k])[n-1]:=#0;
PChar(p[k])[0]:=#0;
Inc(k);
if k>High(p) then k:=Low(p);
end;
for i:=Low(p) to High(p) do
FreeMem(p[i]);
end;
end;
{ TWildThreads }
class function TWildThreads.GetBenchmarkDescription: string;
begin
Result := 'A benchmark that tests many short-lived threads with many '
+ 'transient small objects. For meaningful results, do not run this '
+ 'benchmark in the Delphi IDE. Benchmark submitted by Eric Grange.';
end;
class function TWildThreads.GetBenchmarkName: string;
begin
Result := 'Transient threaded objects';
end;
class function TWildThreads.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadAllocAndFree;
end;
procedure TWildThreads.RunBenchmark;
var
n : Integer;
wild : TAWildThread;
threads : TList;
begin
inherited;
RandSeed:=0;
threads:=TList.Create;
// create threads - would be a thread pool in RealWorld (tm)
for n:=1 to 96 do begin
wild:=TAWildThread.Create(True);
wild.FreeOnTerminate:=False;
threads.Add(wild);
end;
// start all threads at the same time
Sleep(0); // ensure timeslice is ours
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_ABOVE_NORMAL);
for n:=0 to threads.Count-1 do begin
wild:=TAWildThread(threads.Items[n]);
wild.Resume;
end;
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_NORMAL);
// wait for completion of the threads
for n:=0 to threads.Count-1 do begin
UpdateUsageStatistics;
wild:=TAWildThread(threads.Items[n]);
wild.WaitFor;
wild.Free;
end;
threads.Free;
end;
end.
|
unit UErrorConst;
interface
const
// 服务器端错误代码
ERRCODE_SERVER = 000;
ERRCODE_SERVER_ConnectDB = ERRCODE_SERVER + 1;
ERRCODE_SERVER_GetServerDateTime = ERRCODE_SERVER + 2;
ERRCODE_SERVER_ReadDataSet = ERRCODE_SERVER + 3;
ERRCODE_SERVER_ReadMultipleDataSets = ERRCODE_SERVER + 4;
ERRCODE_SERVER_ReadTableHead = ERRCODE_SERVER + 5;
ERRCODE_SERVER_QueryData = ERRCODE_SERVER + 6;
ERRCODE_SERVER_GetSQLStringValue = ERRCODE_SERVER + 7;
ERRCODE_SERVER_GetSQLIntegerValue = ERRCODE_SERVER + 8;
ERRCODE_SERVER_DataSetIsEmpty = ERRCODE_SERVER + 9;
ERRCODE_SERVER_ApplyUpdates = ERRCODE_SERVER + 10;
ERRCODE_SERVER_ExecuteSQL = ERRCODE_SERVER + 11;
ERRCODE_SERVER_ExecuteBatchSQL = ERRCODE_SERVER + 12;
ERRCODE_SERVER_ParamsMethod = ERRCODE_SERVER + 13;
// 客户端错误代码
ERRCODE_CLIENT = 100;
ERRCODE_CLIENT_ConnectDB = ERRCODE_CLIENT + 1;
ERRCODE_CLIENT_GetServerDateTime = ERRCODE_CLIENT + 2;
ERRCODE_CLIENT_ReadDataSet = ERRCODE_CLIENT + 3;
ERRCODE_CLIENT_ReadMultipleDataSets = ERRCODE_CLIENT + 4;
ERRCODE_CLIENT_ReadTableHead = ERRCODE_CLIENT + 5;
ERRCODE_CLIENT_QueryData = ERRCODE_CLIENT + 6;
ERRCODE_CLIENT_GetSQLStringValue = ERRCODE_CLIENT + 7;
ERRCODE_CLIENT_GetSQLIntegerValue = ERRCODE_CLIENT + 8;
ERRCODE_CLIENT_DataSetIsEmpty = ERRCODE_CLIENT + 9;
ERRCODE_CLIENT_ApplyUpdates = ERRCODE_CLIENT + 10;
ERRCODE_CLIENT_ExecuteSQL = ERRCODE_CLIENT + 11;
ERRCODE_CLIENT_ExecuteBatchSQL = ERRCODE_CLIENT + 12;
ERRCODE_CLIENT_ParamsMethod = ERRCODE_CLIENT + 13;
ERRCODE_CLIENT_GetServerLastError = ERRCODE_CLIENT + 14;
implementation
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
//GLS
GLScene, GLObjects, GLCoordinates, GLCadencer, GLNGDManager,
GLSimpleNavigation, GLWin32Viewer, GLCrossPlatform, GLBaseClasses,
GLVectorFileObjects, GLGeomObjects, GLHUDObjects,
GLFile3ds, GLVectorGeometry, GlMaterial, GLKeyboard, GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLSimpleNavigation1: TGLSimpleNavigation;
GLNGDManager1: TGLNGDManager;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLDummyCube1: TGLDummyCube;
World: TGLDummyCube;
GLLines1: TGLLines;
Beer: TGLFreeForm;
Mushroom: TGLFreeForm;
Chair: TGLFreeForm;
Teapot: TGLFreeForm;
Map: TGLFreeForm;
GLHUDCross: TGLHUDSprite;
Body: TGLTorus;
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
procedure ScaleMesh(freeform: TGLFreeForm; val: Single);
procedure MoveCam(const deltaTime, newTime: Double);
procedure MoveGrab;
public
{ Publiques declarations }
grabJoint: TNGDJoint;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir;
// Set Mesh and scale their vertice position
// because matrix scale is not supported in newton
Map.LoadFromFile('ngdmap1.3ds');
Map.Direction.SetVector(0, 1, 0);
Map.Translate(0, -3, 0);
Beer.LoadFromFile('beer.3ds');
ScaleMesh(Beer, 0.25);
Beer.Translate(-5, 10, 10);
Mushroom.LoadFromFile('mushroom.3ds');
ScaleMesh(Mushroom, 0.1);
Mushroom.Direction.SetVector(0, 1, 0);
Mushroom.Translate(0, 0, -10);
Mushroom.Material.FaceCulling := fcNoCull;
Mushroom.Material.FrontProperties.Emission.SetColor(1, 0.5, 0.5, 0.5);
Chair.LoadFromFile('ngdchair.3ds');
Chair.Direction.SetVector(0, 1, 0);
Chair.Translate(0, 0, -5);
Teapot.LoadFromFile('teapot.3ds');
ScaleMesh(Teapot, 0.05);
Teapot.Direction.SetVector(0, 1, 0);
Teapot.Translate(0, 0, 10);
// Create Physic behavior
GetOrCreateNGDStatic(Map).NGDNewtonCollisions := nc_Tree;
GetNGDStatic(Map).Manager := GLNGDManager1;
// nc_Convex use ConvexCollisionTolerance at creation wich is the resolution
// for collision shape. Bigger the value, lower the collision match,
// but give higher performance (use mdShowGeometry to see the difference at runtime)
GetOrCreateNGDDynamic(Chair).NGDNewtonCollisions := nc_Convex;
GetNGDDynamic(Chair).Manager := GLNGDManager1;
GetOrCreateNGDDynamic(Beer).NGDNewtonCollisions := nc_Convex;
GetNGDDynamic(Beer).Manager := GLNGDManager1;
GetOrCreateNGDDynamic(Teapot).NGDNewtonCollisions := nc_Convex;
GetNGDDynamic(Teapot).Manager := GLNGDManager1;
GetOrCreateNGDDynamic(Mushroom).NGDNewtonCollisions := nc_Convex;
GetNGDDynamic(Mushroom).Manager := GLNGDManager1;
// Move camera in target
GLCamera1.Parent := GLCamera1.TargetObject;
// Create the PickJoint
grabJoint := TNGDJoint.Create(GLNGDManager1.NewtonJoint);
grabJoint.JointType := nj_KinematicController;
grabJoint.KinematicControllerOptions.PickModeLinear := True;
grabJoint.KinematicControllerOptions.LinearFriction := 100;
// Set some parameters
GetNGDDynamic(Body).AutoSleep := False;
GLHUDCross.Height := 2;
GLHUDCross.Width := 2;
GLCamera1.NearPlaneBias := 0.1;
GLCamera1.DepthOfView := 1E15;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
var
newFreeform: TGLFreeForm;
I, rand: Integer;
begin
if Key = 'x' then
begin
newFreeform := TGLFreeForm.CreateAsChild(GLDummyCube1);
newFreeform.LoadFromFile('HighPolyObject.3ds');
ScaleMesh(newFreeform, 0.05);
// Keep only one mesh in this newFreeform
for I := 0 to newFreeform.MeshObjects.Count - 2 do
begin
rand := Random(newFreeform.MeshObjects.Count);
newFreeform.MeshObjects.Delete(rand);
end;
GetOrCreateNGDDynamic(newFreeform).NGDNewtonCollisions := nc_Convex;
GetNGDDynamic(newFreeform).Manager := GLNGDManager1;
end;
if Key = 'c' then
GetNGDDynamic(Body).NewtonBodyMatrix := IdentityHmgMatrix;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
GLNGDManager1.Step(deltaTime);
MoveCam(deltaTime, newTime);
MoveGrab;
// Set a point on screen to see where you shoot or grab
GLHUDCross.Position.X := GLSceneViewer1.Width div 2;
GLHUDCross.Position.Y := GLSceneViewer1.Height div 2;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Ball: TGLSphere;
delta: Tvector;
PickedSceneObject: TGLBaseSceneObject;
point3d: Tvector;
MyX, MyY: Integer;
begin
// Shoot a Bullet
if Button = TMouseButton(mbLeft) then
begin
Ball := TGLSphere.CreateAsChild(GLDummyCube1);
Ball.Radius := 0.1;
Ball.AbsolutePosition := GLCamera1.TargetObject.AbsolutePosition;
delta := VectorScale(GLCamera1.AbsoluteVectorToTarget, 2);
Ball.Translate(delta.X, delta.Y, delta.Z);
GetOrCreateNGDDynamic(Ball);
GetNGDDynamic(Ball).Manager := GLNGDManager1;
GetNGDDynamic(Ball).Density := 100;
GetNGDDynamic(Ball).LinearDamping := 0.5;
// Add impulse in the camera direction
GetNGDDynamic(Ball).AddImpulse
(VectorScale(GLCamera1.AbsoluteVectorToTarget, 100),
Ball.AbsolutePosition);
end;
// Start Grab
if Button = TMouseButton(mbMiddle) then
begin
MyX := GLSceneViewer1.Width div 2;
MyY := GLSceneViewer1.Height div 2;
PickedSceneObject := GLSceneViewer1.Buffer.GetPickedObject(MyX, MyY);
if Assigned(PickedSceneObject) and Assigned
(GetNGDDynamic(PickedSceneObject)) then
grabJoint.ParentObject := PickedSceneObject
else
exit;
point3d := PickedSceneObject.AbsolutePosition;
// Attach the body
grabJoint.KinematicControllerPick(point3d, paAttach);
end;
end;
procedure TForm1.GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
// Detach the body
if Button = TMouseButton(mbMiddle) then
grabJoint.KinematicControllerPick(NullHmgVector, paDetach);
end;
procedure TForm1.ScaleMesh(freeform: TGLFreeForm; val: Single);
var
I, J: Integer;
begin
for J := 0 to freeform.MeshObjects.Count - 1 do
for I := 0 to freeform.MeshObjects[J].Vertices.Count - 1 do
begin
freeform.MeshObjects[J].Vertices[I] := VectorScale
(freeform.MeshObjects[J].Vertices[I], val);
end;
end;
procedure TForm1.MoveCam(const deltaTime, newTime: Double);
var
f: Tvector;
fup, fdn, flf, frg: Tvector;
Bup, Bdn, Blf, Brg: Boolean;
NGDDyn: TGLNGDDynamic;
begin
Bup := IsKeyDown('w') or IsKeyDown('z') or IsKeyDown(VK_UP);
Bdn := IsKeyDown('s') or IsKeyDown(VK_DOWN);
Blf := IsKeyDown('d') or IsKeyDown(VK_LEFT);
Brg := IsKeyDown('a') or IsKeyDown('q') or IsKeyDown(VK_RIGHT);
if Bup then
fup := GLCamera1.AbsoluteVectorToTarget
else
fup := VectorMake(0, 0, 0, 0);
if Bdn then
fdn := VectorNegate(GLCamera1.AbsoluteVectorToTarget)
else
fdn := VectorMake(0, 0, 0, 0);
if Blf then
frg := GLCamera1.AbsoluteRightVectorToTarget
else
frg := VectorMake(0, 0, 0, 0);
if Brg then
flf := VectorNegate(GLCamera1.AbsoluteRightVectorToTarget)
else
flf := VectorMake(0, 0, 0, 0);
NGDDyn := GetNGDDynamic(GLCamera1.TargetObject);
if Bup or Bdn or Blf or Brg then
begin
// Add every vector
f := VectorAdd(fup, fdn);
f := VectorAdd(f, frg);
f := VectorAdd(f, flf);
f.V[1] := 0; // Do not allow the body to go up or down
NormalizeVector(f);
// Move the body
if NGDDyn.Force.VectorLength < 5 then //before - AppliedVelocity
NGDDyn.AddImpulse(f, GLCamera1.TargetObject.AbsolutePosition);
end
else
begin
// Slow down the body if the user stop pushing keys
if NGDDyn.Force.VectorLength > 3 then //before - AppliedVelocity
NGDDyn.AddImpulse(VectorScale(NGDDyn.AppliedForce.AsVector, 0.5), f); //before - SetVector
end;
end;
procedure TForm1.MoveGrab;
var
point3d: Tvector;
delta: Tvector;
begin
// Move the object in 3 unit front of GLCamera1.TargetObject
if IsKeyDown(VK_MBUTTON) then
begin
point3d := GLCamera1.TargetObject.AbsolutePosition;
delta := GLCamera1.AbsoluteVectorToTarget;
while VectorLength(delta) < 3 do
delta := VectorScale(delta, 2);
point3d := VectorAdd(point3d, delta);
grabJoint.KinematicControllerPick(point3d, paMove);
end;
end;
end.
|
{
ID: nghoang4
PROG: milk
LANG: PASCAL
}
const fi = 'milk.in';
fo = 'milk.out';
maxN = 5000;
type MyData = record
v, c: longint;
end;
var a: array[1..maxN] of MyData;
n, m, s: longint;
procedure Init;
var i: integer;
begin
assign(input,fi); reset(input);
readln(n,m);
for i:=1 to m do
readln(a[i].v,a[i].c);
close(input);
end;
procedure Sort;
var i, j: integer;
tmp: MyData;
begin
for i:=1 to m-1 do
for j:=i+1 to m do
if a[i].v > a[j].v then
begin
tmp:=a[i];
a[i]:=a[j];
a[j]:=tmp;
end;
end;
procedure Solve;
var i: integer;
begin
Sort;
s:=0; i:=0;
while true do
begin
inc(i);
if a[i].c >= n then
begin
s:=s+a[i].v*n;
break;
end;
s:=s+a[i].v*a[i].c;
n:=n-a[i].c;
end;
end;
procedure PrintResult;
begin
assign(output,fo); rewrite(output);
writeln(s);
close(output);
end;
begin
Init;
Solve;
PrintResult;
end. |
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit System.Bindings.Methods;
interface
uses
System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections, System.Classes, System.StrUtils, System.Bindings.Evaluator,
System.Bindings.ObjEval, System.Bindings.EvalProtocol, System.Bindings.EvalSys, System.Bindings.Consts;
type
EBindOutputError = class(Exception);
EBindOutputCallbackError = class(Exception);
EBindConverterError = class(Exception);
EBindMethodError = class(Exception);
/// <summary>Bound Output or LValue custom conversion routine signature.</summary>
TMethodDescription = record
strict private
FInvokable: IInvokable;
FID: string;
FName: string;
FUnitName: string;
FDefaultEnabled: Boolean;
FFrameworkClass: TPersistentClass;
FDescription: string;
public
constructor Create(const AInvokable: IInvokable; const AID, AName, AUnitName: string;
ADefaultEnabled: Boolean; const ADescription: string; AFrameworkClass: TPersistentClass); overload;
property ID: string read FID;
property Name: string read FName;
property UnitName: string read FUnitName;
property DefaultEnabled: Boolean read FDefaultEnabled;
property FrameWorkClass: TPersistentClass read FFrameWorkClass;
property Invokable: IInvokable read FInvokable;
property Description: string read FDescription;
end;
TBindingMethods = class
public type
TMethodList = TDictionary<string, TMethodDescription>;
end;
TBindingMethodsFactory = class
private
class var FRegisteredMethods: TBindingMethods.TMethodList;
public
class constructor Create;
class destructor Destroy;
class function HasMethod(const AID: string): Boolean; overload;
class procedure RegisterMethod(AMethod: TMethodDescription); overload;
class procedure UnRegisterMethod(const AID: string); overload;
class procedure ClearRegisteredMethods;
class function GetRegisteredMethods: TArray<TMethodDescription>;
// class function GetMethods: TBindingMethods;
class function GetMethodScope: IScope; overload;//returns all
class function GetMethodScope(MethodNames: array of string): IScope; overload;
class function GetMethodUnitName(const MethodID: string): string;
class function GetMethodFrameworkClass(const MethodID: string): TPersistentClass;
end;
type
TInvokableBody = reference to function(Args: TArray<IValue>): IValue;
function MakeInvokable(const ABody: TInvokableBody): IInvokable;
function MakeLocation(AType: PTypeInfo; const AGetter: TLocationWrapper.TValueGetter;
const ASetter: TLocationWrapper.TValueSetter): ILocation;
implementation
uses
System.Bindings.NotifierContracts, System.Math;
function MakeLocation(AType: PTypeInfo; const AGetter: TLocationWrapper.TValueGetter;
const ASetter: TLocationWrapper.TValueSetter): ILocation;
begin
Result := TLocationWrapper.Create(AType, AGetter, ASetter);
end;
type
TInvokable = class(TInterfacedObject, IWrapper, IInvokable)
private
FBody: TInvokableBody;
public
constructor Create(const ABody: TInvokableBody);
function Invoke(const Args: TArray<IValue>): IValue;
end;
function MakeInvokable(const ABody: TInvokableBody): IInvokable;
begin
Result := TInvokable.Create(ABody);
end;
{ TInvokable }
constructor TInvokable.Create(const ABody: TInvokableBody);
begin
FBody := ABody;
end;
function TInvokable.Invoke(const Args: TArray<IValue>): IValue;
begin
Result := FBody(Args);
end;
{ TMethodDescription }
constructor TMethodDescription.Create(const AInvokable: IInvokable; const AID, AName,
AUnitName: string; ADefaultEnabled: Boolean; const ADescription: string; AFrameworkClass: TPersistentClass);
begin
FInvokable := AInvokable;
FID := AID;
FName := AName;
FUnitName := AUnitName;
FDefaultEnabled := ADefaultEnabled;
FFrameWorkClass := AFrameworkClass;
FDescription := ADescription;
end;
{ TBindingMethodsFactory }
class procedure TBindingMethodsFactory.ClearRegisteredMethods;
begin
FRegisteredMethods.Clear;
end;
class constructor TBindingMethodsFactory.Create;
begin
FRegisteredMethods := TBindingMethods.TMethodList.Create;
end;
class destructor TBindingMethodsFactory.Destroy;
begin
FRegisteredMethods.Free;
end;
class function TBindingMethodsFactory.GetMethodScope: IScope;
begin
Result := GetMethodScope([]);
end;
class function TBindingMethodsFactory.GetMethodScope(
MethodNames: array of string): IScope;
var
LDictionaryScope: TDictionaryScope;
LMethod: string;
begin
LDictionaryScope := TDictionaryScope.Create;
Result := LDictionaryScope; // Will free if exception
if Length(MethodNames) > 0 then
for LMethod in MethodNames do
begin
if not FRegisteredMethods.ContainsKey(LMethod) then
raise EBindMethodError.Create(Format(sMethodNotFound, [LMethod]));
LDictionaryScope.Map.Add(LMethod, FRegisteredMethods.Items[LMethod].Invokable);
end
else
for LMethod in FRegisteredMethods.Keys do
begin
if FRegisteredMethods.Items[LMethod].DefaultEnabled then
LDictionaryScope.Map.Add(LMethod, FRegisteredMethods.Items[LMethod].Invokable);
end;
end;
class function TBindingMethodsFactory.GetMethodUnitName(
const MethodID: string): string;
begin
Result := '';
if FRegisteredMethods.ContainsKey(MethodID) then
Result := FRegisteredMethods.Items[MethodID].UnitName;
end;
class function TBindingMethodsFactory.GetMethodFrameworkClass(
const MethodID: string): TPersistentClass;
begin
Result := nil;
if FRegisteredMethods.ContainsKey(MethodID) then
Result := FRegisteredMethods.Items[MethodID].FrameWorkClass;
end;
class function TBindingMethodsFactory.GetRegisteredMethods: TArray<TMethodDescription>;
begin
Result := FRegisteredMethods.Values.ToArray;
end;
class function TBindingMethodsFactory.HasMethod(
const AID: string): Boolean;
begin
if FRegisteredMethods.ContainsKey(AID) then
Result := True
else
Result := False;
end;
class procedure TBindingMethodsFactory.RegisterMethod(
AMethod: TMethodDescription);
begin
if FRegisteredMethods.ContainsKey(AMethod.ID) then
raise EBindMethodError.Create(Format(sDuplicatedMethodName, [AMethod.ID]));
FRegisteredMethods.Add(AMethod.ID, AMethod);
end;
class procedure TBindingMethodsFactory.UnRegisterMethod(const AID: string);
begin
FRegisteredMethods.Remove(AID);
end;
function MakeMethodLowerCase: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [1, Length(Args)]));
v := Args[0];
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil))
else
Exit(TValueWrapper.Create(LowerCase(v.GetValue.AsString)));
end);
end;
function MakeMethodUpperCase: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [1, Length(Args)]));
v := Args[0];
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil))
else
Exit(TValueWrapper.Create(UpperCase(v.GetValue.AsString)));
end);
end;
function MakeMethodRound: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [1, Length(Args)]));
v := Args[0];
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil))
else
Exit(TValueWrapper.Create(Round(v.GetValue.AsExtended)));
end);
end;
function MakeMethodFormatDateTime: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v1: IValue;
LDate: TDateTime;
formatted: string;
begin
if Length(Args) <> 2 then
raise EEvaluatorError.Create(sFormatArgError);
v1 := Args[0];
if not (v1.GetType.Kind in [tkString, tkUString, tkWString]) then
raise EEvaluatorError.Create(sFormatExpectedStr);
if Args[1].GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil)) // Handle null
else
begin
LDate := Args[1].GetValue.AsExtended;
formatted := FormatDateTime(v1.GetValue.AsString, LDate);
end;
Result := TValueWrapper.Create(formatted);
end);
end;
function MakeMethodStrToDateTime: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
LDate: TDateTime;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(sFormatArgError);
v:= Args[0];
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil))
else
LDate := StrToDateTime(Args[0].GetValue.AsString);
Result := TValueWrapper.Create(LDate);
end);
end;
function MakeMethodFormat: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
FmtArgs: array of TVarRec;
ArgVals: array of TValue;
I: Integer;
str, formatted: string;
LNull: Boolean;
begin
LNull := False;
if Length(Args) < 2 then
raise EEvaluatorError.Create(sFormatArgError);
v := Args[0];
if not (v.GetType.Kind in [tkString, tkUString, tkWString]) then
raise EEvaluatorError.Create(sFormatExpectedStr);
formatted := '';
str := v.GetValue.AsString;
SetLength(FmtArgs, Length(Args)-1);
SetLength(ArgVals, Length(Args)-1);
for I := 0 to Length(FmtArgs) - 1 do
try
if Args[I+1].GetValue.IsEmpty then
begin
LNull := True;
break;
end;
// Do not use Args[I+1].GetValue.AsVarRec, because GetValue will put
// TValue on stack, TValue.AsVarRec calls GetReferenceToRawData, and
// it returns reference to TValue stack location. So, multiple args
// of tkFloat or tkInt64 type will point to the same last arg.
ArgVals[I] := Args[I+1].GetValue;
FmtArgs[I] := ArgVals[I].AsVarRec;
except
on E: EInvalidCast do
raise EBindMethodError.Create(Format(sFormatUnexpectedType, [Args[I+1].GetType.NameFld.ToString]));
end;
if LNull then
Exit(TValueWrapper.Create(nil))
else
formatted := Format(str, FmtArgs);
Result := TValueWrapper.Create(formatted);
end);
end;
function MakeMethodToNotifyEvent: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
LRttiChild: IRttiChild;
LNotifyEvent: TNotifyEvent;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [1, Length(Args)]));
v := Args[0];
if v.GetValue.IsEmpty then
begin
if Supports(v, IRttiChild, LRttiChild) and
(LRttiChild.Member is TRttiMethod) then
begin
TMethod(LNotifyEvent).Code := TRttiMethod(LRttiChild.Member).CodeAddress;
TMethod(LNotifyEvent).Data := LRttiChild.Parent;
Exit(TValueWrapper.Create(TValue.From<TNotifyEvent>(LNotifyEvent)));
end;
end;
Exit(TValueWrapper.Create(nil));
end);
end;
// From System.Rtti
function GetEnumBaseType(ATypeInfo: PTypeInfo): PTypeInfo;
var
pResult: PPTypeInfo;
begin
if (ATypeInfo = nil) or (ATypeInfo^.Kind <> tkEnumeration) then
Exit(nil);
Result := ATypeInfo;
while True do
begin
pResult := GetTypeData(Result)^.BaseType;
if (pResult <> nil) and (pResult^ <> nil) and (pResult^ <> Result) then
Result := pResult^
else
Break;
end;
end;
function IsBoolType(ATypeInfo: PTypeInfo): Boolean;
begin
ATypeInfo := GetEnumBaseType(ATypeInfo);
Result := (ATypeInfo = System.TypeInfo(Boolean)) or
(ATypeInfo = System.TypeInfo(ByteBool)) or
(ATypeInfo = System.TypeInfo(WordBool)) or
(ATypeInfo = System.TypeInfo(LongBool));
end;
function MakeMethodToVariant: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
LVariant: Variant;
procedure TryConvert;
begin
try
LVariant := v.GetValue.AsVariant;
except on E: EInvalidCast do
raise EBindMethodError.Create(Format(sConversionUnavailable, [v.GetType.Name, 'Variant']))
end;
end;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [1, Length(Args)]));
v := Args[0];
// Non-bidi ToVariant()
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil));
case v.GetType.Kind of
tkInteger, tkInt64: LVariant := v.GetValue.AsInteger;
tkFloat: LVariant := v.GetValue.AsExtended;
tkString, tkLString, tkWString, tkUString: LVariant := v.GetValue.AsString;
tkVariant: LVariant := v.GetValue.AsVariant;
tkClass: LVariant := v.GetValue.AsClass.ClassName;
tkEnumeration:
if IsBoolType(v.GetType) then
LVariant := v.GetValue.AsBoolean
else TryConvert;
else TryConvert;
end;
Exit(TValueWrapper.Create(TValue.From<Variant>(LVariant)));
end);
end;
function MakeMethodToStr: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(sToStrArgCount);
v := Args[0];
// Non-bidi ToStr()
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil)); // Do not localize
case v.GetType.Kind of
tkInteger, tkInt64: Exit(TValueWrapper.Create(IntToStr(v.GetValue.AsInteger)));
tkFloat: Exit(TValueWrapper.Create(FloatToStr(v.GetValue.AsExtended)));
tkWChar, tkChar, tkString, tkLString, tkWString, tkUString: Exit(TValueWrapper.Create(v.GetValue.AsString));
tkVariant: Exit(TValueWrapper.Create(String(v.GetValue.AsVariant)));
tkRecord, tkMRecord, tkClass: Exit(TValueWrapper.Create(v.GetType.NameFld.ToString));
tkEnumeration: Exit(TValueWrapper.Create(GetEnumName(v.GetType, v.GetValue.AsOrdinal)))
else
begin
if v.GetType <> nil then
Exit(TValueWrapper.Create(v.GetType.NameFld.ToString))
else
Exit(TValueWrapper.Create(nil));
end;
end;
end);
end;
function MakeMethodMin: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v1: IValue;
v2: IValue;
LInt1, LInt2: Int64;
begin
if Length(Args) <> 2 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [2, Length(Args)]));
v1 := Args[0];
v2 := Args[1];
if v1.GetValue.IsEmpty or v2.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil)); // Do not localize
if v1.GetValue.TryAsType<Int64>(LInt1) and
v2.GetValue.TryAsType<Int64>(LInt2) then
Exit(TValueWrapper.Create(Min(LInt1, LInt2)))
else
Exit(TValueWrapper.Create(Min(v1.GetValue.AsExtended, v2.GetValue.AsExtended)));
end);
end;
function MakeMethodMax: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v1: IValue;
v2: IValue;
LInt1, LInt2: Int64;
begin
if Length(Args) <> 2 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [2, Length(Args)]));
v1 := Args[0];
v2 := Args[1];
if v1.GetValue.IsEmpty or v2.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil)); // Do not localize
if v1.GetValue.TryAsType<Int64>(LInt1) and
v2.GetValue.TryAsType<Int64>(LInt2) then
Exit(TValueWrapper.Create(Max(LInt1, LInt2)))
else
Exit(TValueWrapper.Create(Max(v1.GetValue.AsExtended, v2.GetValue.AsExtended)));
end);
end;
function MakeIfAll: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
I: Integer;
const
sMaxArgs = 100;
begin
if Length(Args) > sMaxArgs then
raise EEvaluatorError.Create(Format(sMaxArgsExceeded, [sMaxArgs]));
for I := 0 to Length(Args) - 1 do
begin
v := Args[I];
if v.GetValue.IsEmpty then
Exit(TValueWrapper.Create(False));
if not v.GetValue.IsType<Boolean> then
Exit(TValueWrapper.Create(False));
if not v.GetValue.AsType<Boolean> then
Exit(TValueWrapper.Create(False));
end;
Exit(TValueWrapper.Create(True));
end);
end;
function MakeIfAny: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v: IValue;
I: Integer;
const
sMaxArgs = 100;
begin
if Length(Args) > sMaxArgs then
raise EEvaluatorError.Create(Format(sMaxArgsExceeded, [sMaxArgs]));
for I := 0 to Length(Args) - 1 do
begin
v := Args[I];
if not v.GetValue.IsEmpty then
if v.GetValue.IsType<Boolean> then
if v.GetValue.AsType<Boolean> then
Exit(TValueWrapper.Create(True));
end;
Exit(TValueWrapper.Create(False));
end);
end;
function MakeIfThen: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
v1: IValue;
v2: IValue;
v3: IValue;
begin
if Length(Args) <> 3 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [3, Length(Args)]));
v1 := Args[0];
v2 := Args[1];
v3 := Args[2];
if v1.GetValue.IsEmpty then
Exit(TValueWrapper.Create(nil)); // Do not localize
if v1.GetValue.AsType<Boolean> then
Exit(TValueWrapper.Create(v2.GetValue))
else
Exit(TValueWrapper.Create(v3.GetValue))
end);
end;
function MakeSubString: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
LString: IValue;
LIndex: Integer;
LLength: Integer;
begin
if Length(Args) > 3 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [3, Length(Args)]));
if Length(Args) < 2 then
raise EEvaluatorError.Create(Format(sUnexpectedArgCount, [2, Length(Args)]));
LString := Args[0];
LIndex := Args[1].GetValue.AsType<Integer>;
if Length(Args) > 2 then
LLength := Args[2].GetValue.AsType<integer>
else
LLength := MaxInt;
Result := MakeLocation(TypeInfo(TValue),
function: TValue
begin
if LString.GetValue.IsEmpty then
Result := TValue.Empty
else
Result := LString.GetValue.AsType<string>.SubString(LIndex, LLength)
end,
procedure(x: TValue)
begin
//SetSelectedValue(v.GetValue.AsObject, x);
if LString.GetValue.IsEmpty then
Exit
else
begin
//Result := LString.GetValue.AsType<string>.SubString(LIndex, LLength);
Assert(False);
end;
end);
end);
end;
const
sIDToStr = 'ToStr';
sIDToVariant = 'ToVariant';
sIDToNotifyEvent = 'ToNotifyEvent';
sIDRound = 'Round';
sIDFormat = 'Format';
sIDUpperCase = 'UpperCase';
sIDLowerCase = 'LowerCase';
sIDFormatDateTime = 'FormatDateTime';
sIDStrToDateTime = 'StrToDateTime';
sIDMin = 'Math_Min';
sIDMax = 'Math_Max';
sIDIfThen = 'IfThen';
sIDIfAny = 'IfAny';
sIDIfAll = 'IfAll';
sIDSubString = 'SubString';
procedure RegisterBasicMethods;
begin
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodFormat,
sIDFormat,
sIDFormat, '', True,
sFormatDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodFormatDateTime,
sIDFormatDateTime,
sIDFormatDateTime, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodStrToDateTime,
sIDStrToDateTime,
sIDStrToDateTime, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodLowerCase,
sIDLowerCase,
sIDLowerCase, '', True,
sLowerCaseDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodUpperCase,
sIDUpperCase,
sIDUpperCase, '', True,
sUpperCaseDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodToStr,
sIDToStr,
sIDToStr, '', True,
sToStrDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodToVariant,
sIDToVariant,
sIDToVariant, '', True,
sToVariantDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodToNotifyEvent,
sIDToNotifyEvent,
sIDToNotifyEvent, '', True,
sToNotifyEventDesc,
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodRound,
sIDRound,
sIDRound, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodMin,
sIDMin,
sIDMin, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeMethodMax,
sIDMax,
sIDMax, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeIfThen,
sIDIfThen,
sIDIfThen, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeIfAll,
sIDIfAll,
sIDIfAll, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeIfAny,
sIDIfAny,
sIDIfAny, '', True,
'',
nil));
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeSubString,
sIDSubString,
sIDSubString, '', True,
'',
nil));
end;
initialization
RegisterBasicMethods;
finalization
end.
|
unit uVitals;
{ Old class TVital currently not used - commented out at bottom of unit }
{$DEFINE CCOWBROKER}
interface
uses
SysUtils, Dialogs, Controls, Windows, Classes, ORClasses, ORCtrls, ORFn, Forms,
TRPCB, rMisc, WinAPI.Messages;
const
NoVitalOverrideValue = '^None^';
type
TVitalType = (vtUnknown, vtTemp, vtPulse, vtResp, vtBP, vtHeight, vtWeight, vtPain,
vtPO2, vtCVP, vtCircum);
TValidVitalTypes = vtTemp..vtCircum;
procedure InitPainCombo(cboPain: TORComboBox);
procedure ConvertVital(VType: TVitalType; var VValue, VUnit: string);
function GetVitalStr(VType: TVitalType; rte, unt, UserStr, DateStr: string): string;
function GetVitalUser: string;
procedure AssignVitals2List(List: TStrings; ADateTime: TFMDateTime;
ALocation, ABP, ATemp, ATempUnits,
AResp, APulse, AHeight, AHeightUnits,
AWeight, AWeightUnits, APain: string);
function VitalInvalid(VitalControl: TControl; UnitsControl: TControl = nil;
OverrideValue: string = NoVitalOverrideValue): boolean;
function VitalControlTag(VType: TVitalType; UnitControl: boolean = FALSE): integer;
function ConvertHeight2Inches(Ht: string): string;
function FormatVitalForNote(VitalStr: string):String;
function ConvertVitalData(const Value: string; VitalType: TVitalType; UnitType: string = ''): string;
procedure VitalsFrameCreated(Frame: TFrame);
function ValidVitalsDate(var ADate: TFMDateTime; SkipFirst: boolean = FALSE; Show: boolean = true): boolean;
function IsNumericWeight(const x: string): Boolean;
procedure CloseVitalsDLL;
const
VitalPCECodes: array[TValidVitalTypes] of string =
{ vtTemp } ('TMP',
{ vtPulse } 'PU',
{ vtResp } 'RS',
{ vtBP } 'BP',
{ vtHeight } 'HT',
{ vtWeight } 'WT',
{ vtPain } 'PN',
{ vtPO2 } 'PO2',
{ vtCVP } 'CVP',
{ vtCircum } 'CG');
VitalCodes: array[TValidVitalTypes] of string =
{ vtTemp } ('T',
{ vtPulse } 'P',
{ vtResp } 'R',
{ vtBP } 'BP',
{ vtHeight } 'HT',
{ vtWeight } 'WT',
{ vtPain } 'PN',
{ vtPO2 } 'PO2',
{ vtCVP } 'CVP',
{ vtCircum } 'CG');
TAG_VITTEMP = 2;
TAG_VITPULSE = 4;
TAG_VITRESP = 3;
TAG_VITBP = 1;
TAG_VITHEIGHT = 5;
TAG_VITWEIGHT = 6;
TAG_VITTEMPUNIT= 7;
TAG_VITHTUNIT = 8;
TAG_VITWTUNIT = 9;
TAG_VITPAIN = 10;
TAG_VITDATE = 11;
VitalDateStr = 'VST^DT^';
VitalPatientStr = 'VST^PT^';
VitalLocationStr = 'VST^HL^';
GMV_CONTEXT = 'OR CPRS GUI CHART';
GMV_APP_SIGNATURE = 'CPRS';
GMV_DEFAULT_TEMPLATE = '';
type
VitalTags = TAG_VITBP..TAG_VITPAIN;
TGMV_VitalsEnterForm = function(
RPCBrokerV: TRPCBroker;
aPatient, aLocation, aTemplate,aSignature:string;
aDateTime:TDateTime): TCustomForm; stdcall;
TGMV_VitalsEnterDLG = function(
RPCBrokerV: TRPCBroker;
aDFN, aLocation, aTemplate,aSignature:string;
aDateTime:TDateTime;
aName,anInfo:string): Integer; stdcall;
TGFM_VitalsViewDLG = function(
RPCBrokerV: TRPCBroker;
aDFN, aLocation,
DateStart, DateStop,
aSignature,
aContextIn,aContextOut,
aName,anInfo,aHospitalName:string): Integer; stdcall;
TGMV_VitalsViewForm = function(
RPCBrokerV: TRPCBroker;
aDFN, aLocation,
DateStart, DateStop,
aSignature,
aContextIn,aContextOut,
aName,anInfo,
aDynamicParameter {HospitalName^Vital Type Abbreviation} :string): TCustomForm; stdcall;
TGMV_LatestVitalsList = function (
RPCBrokerV: TRPCBroker;
aDFN,
aDelim:string;
bSilent:Boolean
): TStringList; stdcall;
TGMV_VitalsExit = Procedure;
var
VitalsDLLHandle : THandle = 0;
const
VitalsDLLName = 'GMV_VitalsViewEnter.dll';
Function LoadVitalsDLL(): TDllRtnRec;
procedure UnloadVitalsDLL;
procedure ShutdownVitals;
const
VitalTagSet = [TAG_VITBP..TAG_VITPAIN];
VitalDateTagSet = [TAG_VITBP..TAG_VITDATE];
VitalTagCodes: array[VitalTags] of TVitalType =
{ TAG_VITBP } (vtBP,
{ TAG_VITTEMP } vtTemp,
{ TAG_VITRESP } vtResp,
{ TAG_VITPULSE } vtPulse,
{ TAG_VITHEIGHT } vtHeight,
{ TAG_VITWEIGHT } vtWeight,
{ TAG_VITTEMPUNIT } vtTemp,
{ TAG_VITHTUNIT } vtHeight,
{ TAG_VITWTUNIT } vtWeight,
{ TAG_VITPAIN } vtPain);
VitalDesc: array[TVitalType] of string =
{ vtUnknown } ('Unknown',
{ vtTemp } 'Temperature',
{ vtPulse } 'Pulse',
{ vtResp } 'Respiration',
{ vtBP } 'Blood Pressure',
{ vtHeight } 'Height',
{ vtWeight } 'Weight',
{ vtPain } 'Pain Score',
{ vtPO2 } 'Pulse Oximetry',
{ vtCVP } 'Central Venous Pressure',
{ vtCircum } 'Circumference/Girth');
VitalFormatedDesc: array[TValidVitalTypes] of string =
{ vtTemp } ('Temperature ',
{ vtPulse } 'Pulse ',
{ vtResp } 'Resp ',
{ vtBP } 'Blood Press. ',
{ vtHeight } 'Height ',
{ vtWeight } 'Weight ',
{ vtPain } 'Pain Scale. ',
{ vtPO2 } 'Pulse Ox. ',
{ vtCVP } 'Cnt Vns Pres ',
{ vtCircum } 'Circum/Girth ');
vnumType = 2;
vnumValue = 3;
vnumDate = 4;
implementation
uses
uCore, rCore, rVitals, Contnrs, fVitalsDate, VAUtils;
var
uVitalFrames: TComponentList = nil;
procedure CloseVitalsDLL;
var
VitalsExit : TGMV_VitalsExit;
begin
if VitalsDLLHandle <> 0 then
begin
@VitalsExit := GetProcAddress(VitalsDLLHandle,PChar('GMV_VitalsExit'));
if assigned(VitalsExit) then
VitalsExit();
UnloadVitalsDLL;
end;
end;
function VitalErrorText(VType: TVitalType): string;
begin
case VType of
vtTemp, vtHeight, vtWeight:
Result := '- check rate and unit.';
else
Result := 'reading entered.';
end;
Result := 'Invalid ' + VitalDesc[VType] + ' ' + Result;
end;
procedure InitPainCombo(cboPain: TORComboBox);
begin
cboPain.Items.Clear;
cboPain.Items.Add('0^ - no pain');
cboPain.Items.Add('1^ - slightly uncomfortable');
cboPain.Items.Add('2^');
cboPain.Items.Add('3^');
cboPain.Items.Add('4^');
cboPain.Items.Add('5^');
cboPain.Items.Add('6^');
cboPain.Items.Add('7^');
cboPain.Items.Add('8^');
cboPain.Items.Add('9^');
cboPain.Items.Add('10^ - worst imaginable');
cboPain.Items.Add('99^ - unable to respond');
end;
procedure ConvertVital(VType: TVitalType; var VValue, VUnit: string);
begin
case VType of
vtTemp: if(VUnit = 'C') then //if metric, convert to standard
begin
if StrToFloat(VValue) > 0 then
//VValue := FloatToStr(StrToFloat(VValue) * 9.0 / 5.0 +32.0);
VValue := FloatToStr(Round((StrToFloat(VValue) * 9.0 / 5.0 +32.0)*100)/100);
VUnit := 'F';
end;
vtHeight: if VUnit = 'CM' then
begin
if StrToFloat(VValue) > 0 then
//VValue := FloatToStr(StrtoFloat(VValue) / 2.54);
VValue := FloatToStr(Round((StrtoFloat(VValue) / 2.54)*1000)/1000);
VUnit := 'IN';
end;
vtWeight: if VUnit = 'KG' then
begin
if StrToFloat(VValue) > 0 then
//VValue := FloatToStr(StrtoFloat(VValue) * 2.2046);
//
// the vitals package uses 2.2 (not 2.2046), so the GUI needs to use the
// same so conversions back & forth don't lead to errors
// this probably shouldn't even be done here - it should be done by the
// vitals package - KCM
//
VValue := FloatToStr(Round(StrtoFloat(VValue) * 2.2{046} *1000)/1000);
VUnit := 'LB';
end;
end;
end;
function GetVitalStr(VType: TVitalType; rte, unt, UserStr, DateStr: string): string;
begin
Result := '';
ConvertVital(VType, rte, unt);
if rte <> '' then
begin
if(VType = vtPain) then unt := U;
Result := 'VIT'+U+VitalPCECodes[VType]+U+U+U+rte+U+UserStr+U+unt+U+DateStr;
end;
end;
function GetVitalUser: string;
var
UserID: Int64;
begin
UserID := Encounter.Provider;
if UserID <= 0 then
UserID := User.DUZ;
Result := IntToStr(UserID);
end;
procedure AssignVitals2List(List: TStrings; ADateTime: TFMDateTime;
ALocation, ABP, ATemp, ATempUnits,
AResp, APulse, AHeight, AHeightUnits,
AWeight, AWeightUnits, APain: string);
var
UserStr, DateStr: string;
procedure AddVital(VType: TVitalType; ARte: string; AUnit: string = '');
var
VStr: string;
begin
VStr := GetVitalStr(VType, ARte, AUnit, UserStr, DateStr);
if(VStr <> '') then
List.Add(VStr);
end;
begin
with List do
begin
UserStr := GetVitalUser;
DateStr := FloatToStr(ADateTime);
clear;
Add(VitalDateStr + DateStr);
Add(VitalPatientStr + Patient.DFN); // encounter Patient //*DFN*
Add(VitalLocationStr + ALocation);
AddVital(vtBP, ABP); // Blood Pressure
AddVital(vtTemp, ATemp, ATempUnits); // Temperature
AddVital(vtResp, AResp); // Resp
AddVital(vtPulse, APulse); // Pulse
AddVital(vtHeight, AHeight, AHeightUnits); // Height
AddVital(vtWeight, AWeight, AWeightUnits); // Weight
AddVital(vtPain, APain); // Pain
end;
end;
function VitalInvalid(VitalControl: TControl; UnitsControl: TControl = nil;
OverrideValue: string = NoVitalOverrideValue): boolean;
var
rte, unt: string;
Tag: integer;
VType: TVitalType;
begin
Tag := -1;
if(OverrideValue = NoVitalOverrideValue) then
begin
if(assigned(VitalControl)) then
begin
rte := TORExposedControl(VitalControl).Text;
Tag := VitalControl.Tag;
end
else
rte := '';
end
else
begin
rte := OverrideValue;
if(assigned(VitalControl)) then
Tag := VitalControl.Tag;
end;
if(assigned(UnitsControl)) then
begin
unt := TORExposedControl(UnitsControl).Text;
if(Tag < 0) then
Tag := UnitsControl.Tag;
end
else
unt := '';
if(Tag >= low(VitalTags)) and (Tag <= high(VitalTags)) then
VType := VitalTagCodes[Tag]
else
VType := vtUnknown;
//pain does not need to be validated because the combo box limits the selection.
if(VType = vtPain) then
Result := FALSE
else
begin
Result := TRUE;
if(VType <> vtUnknown) then
begin
if (rte = '') then
Result := FALSE
else
if (VerifyVital(VitalPCECodes[VType],rte,unt) = True) then
Result := FALSE;
end;
end;
// GRE 2/12/03 added to disallow user entering "lb" with weight NOIS MWV-0103-22037
if VType = vtWeight then
begin
if (IsNumericWeight(rte) = FALSE) then
Result := True;
end;
if(Result) then
ShowMsg(VitalErrorText(VType));
end;
function VitalControlTag(VType: TVitalType; UnitControl: boolean = FALSE): integer;
var
i,cnt: integer;
begin
if UnitControl then
cnt := 0
else
cnt := 1;
Result := -1;
for i := low(VitalTags) to high(VitalTags) do
begin
if(VitalTagCodes[i] = VType) then
begin
inc(cnt);
if(cnt = 2) then
begin
Result := i;
break;
end;
end;
end;
end;
function ConvertHeight2Inches(Ht: string): string;
var
c: char;
i: integer; //counter
inchstr,feetstr : string;
feet: boolean;
v: double;
begin
feet := False;
result := '';
feetstr := '';
inchstr := '';
// check for feet
for i := 1 to (length(Ht)) do
begin
c := Ht[i];
if (c = '''') then feet := True;
end;
if (feet = True) then
begin
i := 1;
while (Ht[i] <> '''') do
begin
if CharInSet(Ht[i], ['0'..'9']) or (Ht[i] = '.') then
feetstr := feetstr + Ht[i];
inc(i);
end;
while (i <= length(Ht)) and (Ht[i] <> '"') and
(Ht[i] <> '') do
begin
if CharInSet(Ht[i], ['0'..'9']) or (Ht[i] = '.') then
inchstr := inchstr + Ht[i];
inc(i);
end;
v := 0;
if (feetstr <> '') then
v := v + (StrTofloat(feetstr)*12);
if(inchstr <> '') then
v := v + StrToFloat(inchstr);
result := floatToStr(v);
//add here to convert to CM if CM is the unit
end
else //no feet
begin
for i := 1 to (length(Ht)) do
begin
c := Ht[i]; //first character
if CharInSet(c, ['0'..'9']) or (c = '.') then
result := result + c;
if (c = '"') then break;
end;
end;
end;
{
1215^T^98.6^2991108.11^98.6 F^(37.0 C)
1217^P^70^2991108.11^70
1216^R^18^2991108.11^18
1214^BP^120/70^2991108.11^120/70
1218^HT^70^2991108.11^70 in^(177.8 cm)
1219^WT^200^2991108.11^200 lb^(90.0 kg)
1220^PN^1^2991108.11^1
}
//format string as it should appear on the PCE panel.
function FormatVitalForNote(VitalStr: string):String;
var
Code, Value: string;
v: TVitalType;
begin
Code := UpperCase(Piece(VitalStr, U, vnumType));
for v := low(TValidVitalTypes) to high(TValidVitalTypes) do
begin
if(Code = VitalCodes[v]) then
begin
Value := ConvertVitalData(Piece(VitalStr, U, vnumValue), v);
if(v = vtPain) and (Value = '99') then
Value := 'Unable to respond.';
Result := VitalFormatedDesc[v] + Value + ' ' +
FormatFmDateTime('mmm dd,yyyy hh:nn',(StrToFloat(Piece(VitalStr, U, vnumDate))));
end
end;
end;
function ConvertVitalData(const Value: string; VitalType: TVitalType; UnitType: string = ''): string;
var
dbl: Double;
begin
Result := Value;
if(VitalType in [vtTemp, vtHeight, vtWeight]) then
begin
try
dbl := StrToFloat(Value);
except
on EConvertError do
dbl := 0
else
raise;
end;
if(dbl <> 0) then
begin
UnitType := UpperCase(UnitType);
case VitalType of
vtTemp:
begin
if(UnitType = 'C') then
begin
dbl := dbl * (9/5);
dbl := dbl + 32;
dbl := round(dbl * 10) / 10;
Result := FloatToStr(dbl) + ' F (' + Result + ' C)';
end
else
begin
dbl := dbl - 32;
dbl := dbl * (5/9);
dbl := round(dbl * 10) / 10;
Result := Result + ' F (' + FloatToStr(dbl) + ' C)';
end;
end;
vtHeight:
begin
if(UnitType = 'CM') then
begin
dbl := dbl / 2.54;
dbl := round(dbl * 10) / 10;
Result := FloatToStr(dbl) + ' in [' + Result + ' cm)';
end
else
begin
dbl := dbl * 2.54;
dbl := round(dbl * 10) / 10;
Result := Result + ' in [' + FloatToStr(dbl) + ' cm)';
end;
end;
vtWeight:
begin
if(UnitType = 'KG') then
begin
dbl := dbl * 2.2;
dbl := round(dbl * 10) / 10;
Result := FloatToStr(dbl) + ' lb (' + Result + ' kg)';
end
else
begin
dbl := dbl / 2.2;
dbl := round(dbl * 10) / 10;
Result := Result + ' lb (' + FloatToStr(dbl) + ' kg)';
end;
end;
end;
end;
end;
end;
procedure VitalsFrameCreated(Frame: TFrame);
begin
if not assigned(uVitalFrames) then
uVitalFrames := TComponentList.Create(FALSE);
uVitalFrames.Add(Frame);
end;
function ValidVitalsDate(var ADate: TFMDateTime; SkipFirst: boolean = FALSE; Show: boolean = true): boolean; //AGP Change 26.1
var
frmVitalsDate: TfrmVitalsDate;
ok: boolean;
begin
Result := TRUE;
while (Result and (SkipFirst or (ADate > FMNow))) do
begin
if(SkipFirst) then
begin
ok := TRUE;
SkipFirst := FALSE;
end
else
ok := (InfoBox('Vital sign Date/Time entered (' + FormatFMDateTime('mmm dd yyyy hh:nn', ADate) +
') cannot be in the future.' + CRLF +
'If you do not change the entered date/time vitals information will be lost.' + CRLF +
'Do you want to enter a new Date/Time?',
'Invalid Vital Entry Date/Time',
MB_YESNO + MB_ICONWARNING) = ID_YES);
if ok then
begin
frmVitalsDate := TfrmVitalsDate.Create(Application);
try
frmVitalsDate.dteVitals.FMDateTime := ADate;
frmVitalsDate.btnNow.Visible := Show; //AGP Change 26.1
if frmVitalsDate.ShowModal = mrOK then
ADate := frmVitalsDate.dteVitals.FMDateTime;
finally
frmVitalsDate.Free;
end;
end
else
Result := FALSE;
end;
end;
function IsNumericWeight(const x: string): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(x) do if not CharInSet(x[i], ['0'..'9','.']) then Result := False;
end;
function LoadVitalsDLL(): TDllRtnRec;
// If error then set VitalsDLLHandle to -1 and show error
begin
if VitalsDLLHandle = 0 then
begin
Result := LoadDll(VitalsDLLName);
VitalsDLLHandle := Result.DLL_HWND;
end;
end;
procedure UnloadVitalsDLL;
begin
if VitalsDLLHandle <> 0 then
begin
FreeLibrary(VitalsDLLHandle);
VitalsDLLHandle := 0;
end;
end;
procedure ShutdownVitals;
var
vHandle: TList;
i: Integer;
function FindThreadWindow(Window: HWND; var vitals: TList): BOOL; stdcall;
var
clsName: string;
begin
SetLength(clsName, 256);
SetLength(clsName, GetClassName(Window, PChar(clsName), Length(clsName) - 1));
if (clsName = 'TfrmVitals') or (clsName = 'TfrmGMV_InputLite') then
vitals.Add(Pointer(Window));
Result := True;
end;
begin
vHandle := TList.Create;
try
EnumThreadWindows(GetCurrentThreadID, @FindThreadWindow, Integer(@vHandle));
for i := 0 to vHandle.Count - 1 do
PostMessage(HWND(vHandle[i]), WM_CLOSE, 0, 0);
finally
FreeAndNil(vHandle);
end;
end;
(* Old class currently not used
{$OPTIMIZATION OFF} // REMOVE AFTER UNIT IS DEBUGGED
interface
uses SysUtils, Classes;
type
TVital = class(TObject)
{class for vital}
Private
Fsend: Boolean; //do we need this?
public
Typ: String; //type
Value: Single;
Unt: String; //unit
Provider: Integer;
procedure Assign(Src: TVital); //will we need assign?
procedure Clear;
procedure SetFromString(const x: string);
function DelimitedStr: string;
end;
implementation
uses ORFn, fPCEEdit, uPCE;
Procedure TVital.Assign(Src: TVital);
{assigns the values from one vital to another}
begin
Fsend := Src.Fsend;
Typ := Src.Typ;
Value := Src.Value;
Unt := Src.Unt;
provider := Src.Provider;
end;
procedure Tvital.Clear;
{clear all fields}
begin
Fsend := False;
Typ := '';
Value := 0.0;
Unt := ''; //will default to Inches/LBs/Farenheit on M side,
//depending on the Type
//Provider := UProvider;
end;
Procedure TVital.SetFromString(const X: string);
begin
Typ := Piece(x, U, 2);
Value := StrToFloat(Piece(x, U, 5));
Provider := StrToInt(Piece(x, U, 6));
Unt := Piece(x, U, 7);
end;
function TVital.DelimitedStr: string;
begin
Result := 'VIT' + U + Typ + U + U + U + FloatToStr(Value) + U +
IntToStr(Provider) + U + Unt;
end;
*)
initialization
finalization
KillObj(@uVitalFrames);
end.
|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Transcode.Utf16ToUtf8;
interface
uses
Deltics.Unicode.Types;
procedure _Utf16BeToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer);
procedure _Utf16LeToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer);
implementation
uses
Deltics.Unicode;
procedure _Utf16BeToUtf8(var aUtf16: PWideChar;
var aUtf16Count: Integer;
var aUtf8: PUtf8Char;
var aUtf8Count: Integer);
type
TState = (ExpectingCharOrHiSurrogate, ExpectingLoSurrogate);
var
state: TState;
ch: WideChar;
hi: WideChar;
code: CodePoint;
begin
hi := #$0000;
state := ExpectingCharOrHiSurrogate;
while (aUtf16Count > 0) and (aUtf8Count > 0) do
begin
ch := WideChar(((Word(aUtf16^) and $ff00) shr 8) or ((Word(aUtf16^) and $ff) shl 8));
case state of
ExpectingCharOrHiSurrogate : begin
if Unicode.IsHiSurrogate(ch) then
begin
hi := ch;
state := ExpectingLoSurrogate;
end
// else if StrictEncoding and Unicode.IsLoSurrogate(aUtf16^) then
// raise EInvalidEncoding.Create('Orphan Low Surrogate');
else
Unicode.CodepointToUtf8(Codepoint(ch), aUtf8, aUtf8Count);
Inc(aUtf16);
Dec(aUtf16Count);
end;
ExpectingLoSurrogate : if Unicode.IsLoSurrogate(ch) then
begin
code := Unicode.SurrogatesToCodepoint(hi, ch);
Unicode.CodepointToUtf8(code, aUtf8, aUtf8Count);
Inc(aUtf16);
Dec(aUtf16Count);
state := ExpectingCharOrHiSurrogate;
end;
// else if StrictEncoding then
// raise EInvalidEncoding.Create('Orphan High Surrogate');
end;
end;
end;
procedure _Utf16LeToUtf8(var aUtf16: PWideChar;
var aUtf16Count: Integer;
var aUtf8: PUtf8Char;
var aUtf8Count: Integer);
type
TState = (ExpectingCharOrHiSurrogate, ExpectingLoSurrogate);
var
state: TState;
hi: WideChar;
code: CodePoint;
begin
hi := #$0000;
state := ExpectingCharOrHiSurrogate;
while (aUtf16Count > 0) and (aUtf8Count > 0) do
begin
case state of
ExpectingCharOrHiSurrogate : begin
if Unicode.IsHiSurrogate(aUtf16^) then
begin
hi := aUtf16^;
state := ExpectingLoSurrogate;
end
// else if StrictEncoding and Unicode.IsLoSurrogate(aUtf16^) then
// raise EInvalidEncoding.Create('Orphan Low Surrogate');
else
Unicode.CodepointToUtf8(Codepoint(aUtf16^), aUtf8, aUtf8Count);
Inc(aUtf16);
Dec(aUtf16Count);
end;
ExpectingLoSurrogate : if Unicode.IsLoSurrogate(aUtf16^) then
begin
code := Unicode.SurrogatesToCodepoint(hi, aUtf16^);
Unicode.CodepointToUtf8(code, aUtf8, aUtf8Count);
Inc(aUtf16);
Dec(aUtf16Count);
state := ExpectingCharOrHiSurrogate;
end;
// else if StrictEncoding then
// raise EInvalidEncoding.Create('Orphan High Surrogate');
end;
end;
end;
end.
|
unit uConexaoBanco;
interface
uses
uRESTDWPoolerDB;
type
TConexaoBanco = class
private
class var FConexao: TRESTDWDataBase;
class var FInstance: TConexaoBanco;
constructor CreatePrivate;
procedure PreencherDadosConexao;
public
class function GetInstance: TConexaoBanco;
class property Conexao: TRESTDWDataBase read FConexao;
end;
implementation
uses
SysUtils, IniFiles;
procedure TConexaoBanco.PreencherDadosConexao;
const
SECAO = 'CONEXAO_CLIENTE';
begin
with TIniFile.Create(ExtractFilePath(ParamStr(0))+'Config.ini') do
begin
FConexao.PoolerService := ReadString(SECAO, 'Service', EmptyStr);
FConexao.PoolerPort := ReadInteger(SECAO, 'Port', 0);
FConexao.PoolerName := ReadString(SECAO, 'Name', EmptyStr);
FConexao.Login := ReadString(SECAO, 'Login', EmptyStr);
FConexao.Password := ReadString(SECAO, 'Password', EmptyStr);
FConexao.Open;
Free;
end;
end;
constructor TConexaoBanco.CreatePrivate;
begin
inherited Create;
FConexao := TRESTDWDataBase.Create(nil);
PreencherDadosConexao;
end;
class function TConexaoBanco.GetInstance: TConexaoBanco;
begin
if not Assigned(FInstance) then
FInstance := TConexaoBanco.CreatePrivate;
Result := FInstance;
end;
end.
|
unit Unit_Piano;
interface
uses
Main, Classes, Forms, SysUtils, ExtCtrls, Graphics,
mmSystem, Notes_MIDI, Musiques;
type
TPiano = Class(TThread)
private
idNote, BPM: integer;
procedure OnTerminateProcedure(Sender : TObject);
protected
procedure ToucheDown;
procedure ToucheUp;
procedure Execute; override;
public
ThreadTerminated : Boolean;
constructor Create(Suspended : Boolean);
end;
implementation
constructor TPiano.Create(Suspended: Boolean);
begin
FreeOnTerminate := True;
inherited Create(Suspended);
OnTerminate := OnTerminateProcedure;
ThreadTerminated := False;
end;
procedure TPiano.ToucheDown;
begin
Form1.PianoToucheDown(Musique1_01[idNote].Note1);
end;
procedure TPiano.ToucheUp;
begin
Form1.PianoToucheUp(Musique1_01[idNote].Note1);
end;
procedure TPiano.Execute;
var
i: integer;
begin
// 1000 millisecondes : BPM = 60 (1 battement par seconde, 60 par minute)
// 500 millisecondes : BPM = 120 (1 battement par 1/2 seconde, 120 par minute)
// Temps[ms] = (60/BPM)*1000
BPM := 150;
// Choix de l'instrument (38 = trompette)
Instrument := '38';
for i := 0 to Length(Musique1_01)-1 do
begin
if ThreadTerminated then exit;
idNote := i;
if Musique1_01[i].Note1<>'' then
Synchronize(ToucheDown);
//Application.ProcessMessages;
Sleep(Round(((60/BPM)*1000) * Musique1_01[i].Duree));
if Musique1_01[i].Note1<>'' then
Synchronize(ToucheUp);
Form1.repaint;
end;
end;
procedure TPiano.OnTerminateProcedure(Sender: TObject);
begin
ThreadTerminated:=True;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit MeshPreviewUI;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MeshPreview, VertexList, Vcl.ExtCtrls,
Vcl.Buttons, Vcl.StdCtrls, VectorMath, Vcl.ComCtrls, JvExExtCtrls,
JvExtComponent, JvOfficeColorButton, JvExControls, JvColorBox, JvColorButton,
SpeedButtonEx, BulbTracerUITools;
type
TMeshPreviewFrm = class(TForm)
NaviPanel: TPanel;
DisplayStyleGrp: TRadioGroup;
GroupBox1: TGroupBox;
AppearancePageCtrl: TPageControl;
MaterialSheet: TTabSheet;
LightSheet: TTabSheet;
Label17: TLabel;
SurfaceColorBtn: TJvOfficeColorButton;
Label1: TLabel;
EdgesColorBtn: TJvOfficeColorButton;
Label2: TLabel;
WireframeColorBtn: TJvOfficeColorButton;
Label3: TLabel;
PointsColorBtn: TJvOfficeColorButton;
Label4: TLabel;
MatAmbientColorBtn: TJvOfficeColorButton;
MatDiffuseColorLbl: TLabel;
MatDiffuseColorBtn: TJvOfficeColorButton;
Label6: TLabel;
MatSpecularColorBtn: TJvOfficeColorButton;
Label7: TLabel;
MatShininessEdit: TEdit;
MatShininessBtn: TUpDown;
Label8: TLabel;
LightAmbientBtn: TJvOfficeColorButton;
Label9: TLabel;
LightDiffuseBtn: TJvOfficeColorButton;
Label5: TLabel;
LightPositionXEdit: TEdit;
LightPositionXBtn: TUpDown;
Label10: TLabel;
LightPositionYEdit: TEdit;
LightPositionYBtn: TUpDown;
Label11: TLabel;
LightPositionZEdit: TEdit;
LightPositionZBtn: TUpDown;
ConstAttenuationEdit: TEdit;
QuadraticAttenuationBtn: TUpDown;
QuadraticAttenuationEdit: TEdit;
Label12: TLabel;
LinearAttenuationBtn: TUpDown;
LinearAttenuationEdit: TEdit;
Label13: TLabel;
ConstAttenuationBtn: TUpDown;
Label14: TLabel;
LightingEnabledCBx: TCheckBox;
ColorDialog: TColorDialog;
Label15: TLabel;
Label16: TLabel;
Label18: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure DisplayStyleGrpClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure MatShininessBtnClick(Sender: TObject; Button: TUDBtnType);
procedure MatShininessEditExit(Sender: TObject);
procedure SurfaceColorBtnColorChange(Sender: TObject);
procedure LightPositionXBtnClick(Sender: TObject; Button: TUDBtnType);
procedure LightPositionYBtnClick(Sender: TObject; Button: TUDBtnType);
procedure LightPositionZBtnClick(Sender: TObject; Button: TUDBtnType);
procedure ConstAttenuationBtnClick(Sender: TObject; Button: TUDBtnType);
procedure LinearAttenuationBtnClick(Sender: TObject; Button: TUDBtnType);
procedure QuadraticAttenuationBtnClick(Sender: TObject; Button: TUDBtnType);
procedure LightingEnabledCBxClick(Sender: TObject);
procedure SurfaceColorBtnClick(Sender: TObject);
procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure NaviPanelDblClick(Sender: TObject);
procedure FormDblClick(Sender: TObject);
private
{ Private declarations }
FDragging: Boolean;
FXPosition, FYPosition: Double;
FXAngle, FYAngle, FScale: Double;
FStartMouseX, FStartMouseY: Integer;
FOpenGLHelper: TOpenGLHelper;
FRefreshing: Boolean;
procedure SetWindowCaption(const Msg: String);
procedure AppearanceToUI;
procedure UIToAppearance;
public
{ Public declarations }
procedure UpdateMesh(const FacesList: TFacesList); overload;
procedure UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList); overload;
end;
var
MeshPreviewFrm: TMeshPreviewFrm;
implementation
uses
OpenGLPreviewUtil;
{$R *.dfm}
const
MOVE_SCALE: Double = 0.001;
SIZE_SCALE: Double = 0.01;
ROTATE_SCALE: Double = 0.2;
procedure TMeshPreviewFrm.ConstAttenuationBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(ConstAttenuationEdit.Text, FOpenGLHelper.MeshAppearance.LightConstantAttenuation) + UpDownBtnValue(Button, 0.05);
if Value < 0.0 then
Value := 0.0;
ConstAttenuationEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.DisplayStyleGrpClick(Sender: TObject);
begin
case DisplayStyleGrp.ItemIndex of
0: FOpenGLHelper.SetDisplayStyle(dsPoints);
1: FOpenGLHelper.SetDisplayStyle(dsWireframe);
2: FOpenGLHelper.SetDisplayStyle(dsFlatSolid);
3: FOpenGLHelper.SetDisplayStyle(dsFlatSolidWithEdges);
4: FOpenGLHelper.SetDisplayStyle(dsSmoothSolid);
5: FOpenGLHelper.SetDisplayStyle(dsSmoothSolidWithEdges);
end;
end;
procedure TMeshPreviewFrm.FormCreate(Sender: TObject);
begin
FOpenGLHelper := TOpenGLHelper.Create(Canvas);
FOpenGLHelper.SetWindowCaptionEvent := SetWindowCaption;
AppearancePageCtrl.ActivePage := MaterialSheet;
AppearanceToUI;
DisplayStyleGrpClick(Sender);
end;
procedure TMeshPreviewFrm.FormDblClick(Sender: TObject);
begin
NaviPanel.Visible := not NaviPanel.Visible;
end;
procedure TMeshPreviewFrm.FormDestroy(Sender: TObject);
begin
FOpenGLHelper.Free;
end;
procedure TMeshPreviewFrm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FStartMouseX := X;
FStartMouseY := Y;
FDragging := True;
FXPosition := FOpenGLHelper.XPosition;
FYPosition := FOpenGLHelper.YPosition;
FXAngle := FOpenGLHelper.XAngle;
FYAngle := FOpenGLHelper.YAngle;
FScale := FOpenGLHelper.Scale;
end;
procedure TMeshPreviewFrm.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FDragging then begin
if ssMiddle in Shift then begin
FOpenGLHelper.Scale := FScale - SIZE_SCALE * (FStartMouseX - X);
end;
if ssLeft in Shift then begin
FOpenGLHelper.XPosition := FXPosition - MOVE_SCALE * (FStartMouseX - X);
FOpenGLHelper.YPosition := FYPosition + MOVE_SCALE * (FStartMouseY - Y);
end;
if ssRight in Shift then begin
FOpenGLHelper.XAngle := FXAngle - ROTATE_SCALE * (FStartMouseX - X);
FOpenGLHelper.YAngle := FYAngle + ROTATE_SCALE * (FStartMouseY - Y);
end;
end;
end;
procedure TMeshPreviewFrm.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
end;
procedure TMeshPreviewFrm.FormMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
FOpenGLHelper.Scale := FOpenGLHelper.Scale - SIZE_SCALE * 3.0;
end;
procedure TMeshPreviewFrm.FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
FOpenGLHelper.Scale := FOpenGLHelper.Scale + SIZE_SCALE * 3.0;
end;
procedure TMeshPreviewFrm.FormResize(Sender: TObject);
begin
FOpenGLHelper.AfterResize(ClientWidth, ClientHeight);
end;
procedure TMeshPreviewFrm.FormShow(Sender: TObject);
begin
FOpenGLHelper.InitGL;
AppearanceToUI;
end;
procedure TMeshPreviewFrm.LightingEnabledCBxClick(Sender: TObject);
begin
SurfaceColorBtnColorChange(Sender);
end;
procedure TMeshPreviewFrm.LightPositionXBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(LightPositionXEdit.Text, FOpenGLHelper.MeshAppearance.LightPosition.X) + UpDownBtnValue(Button, 0.1);
LightPositionXEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.LightPositionYBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(LightPositionYEdit.Text, FOpenGLHelper.MeshAppearance.LightPosition.Y) + UpDownBtnValue(Button, 0.1);
LightPositionYEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.LightPositionZBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(LightPositionZEdit.Text, FOpenGLHelper.MeshAppearance.LightPosition.Z) + UpDownBtnValue(Button, 0.1);
LightPositionZEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.LinearAttenuationBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(LinearAttenuationEdit.Text, FOpenGLHelper.MeshAppearance.LightLinearAttenuation) + UpDownBtnValue(Button, 0.0005);
if Value < 0.0 then
Value := 0.0;
LinearAttenuationEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.MatShininessBtnClick(Sender: TObject; Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(MatShininessEdit.Text, FOpenGLHelper.MeshAppearance.MatShininess) + UpDownBtnValue(Button, 1.0);
if Value < 0.0 then
Value := 0.0;
MatShininessEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.MatShininessEditExit(Sender: TObject);
begin
UIToAppearance;
end;
procedure TMeshPreviewFrm.NaviPanelDblClick(Sender: TObject);
begin
NaviPanel.Visible := False;
end;
procedure TMeshPreviewFrm.QuadraticAttenuationBtnClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(QuadraticAttenuationEdit.Text, FOpenGLHelper.MeshAppearance.LightQuadraticAttenuation) + UpDownBtnValue(Button, 0.0005);
if Value < 0.0 then
Value := 0.0;
QuadraticAttenuationEdit.Text := FloatToStr(Value);
UIToAppearance;
end;
procedure TMeshPreviewFrm.UpdateMesh(const FacesList: TFacesList);
begin
FOpenGLHelper.UpdateMesh(FacesList);
end;
procedure TMeshPreviewFrm.UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList);
begin
FOpenGLHelper.UpdateMesh(VertexList, ColorList);
end;
procedure TMeshPreviewFrm.SetWindowCaption(const Msg: String);
begin
Caption := Msg;
end;
procedure TMeshPreviewFrm.AppearanceToUI;
function ToRGBSpace(const V: Double): Integer;
begin
Result := Round(255.0 * V);
if Result < 0 then
Result := 0
else if Result > 255 then
Result := 255;
end;
function VecToColor(const V: TPS3Vector): TColor;
begin
Result := ToRGBSpace(V^.X) + ToRGBSpace(V^.Y) shl 8 + ToRGBSpace(V^.Z) shl 16;
end;
begin
FRefreshing := True;
try
with FOpenGLHelper.MeshAppearance do begin
SurfaceColorBtn.SelectedColor := VecToColor(@SurfaceColor);
EdgesColorBtn.SelectedColor := VecToColor(@EdgesColor);
WireframeColorBtn.SelectedColor := VecToColor(@WireframeColor);
PointsColorBtn.SelectedColor := VecToColor(@PointsColor);
MatAmbientColorBtn.SelectedColor := VecToColor(@MatAmbient);
MatDiffuseColorBtn.SelectedColor := VecToColor(@MatDiffuse);
MatSpecularColorBtn.SelectedColor := VecToColor(@MatSpecular);
MatShininessEdit.Text := FloatToStr(MatShininess);
LightAmbientBtn.SelectedColor := VecToColor(@LightAmbient);
LightDiffuseBtn.SelectedColor := VecToColor(@LightDiffuse);
LightPositionXEdit.Text := FloatToStr(LightPosition.X);
LightPositionYEdit.Text := FloatToStr(LightPosition.Y);
LightPositionZEdit.Text := FloatToStr(LightPosition.Z);
ConstAttenuationEdit.Text := FloatToStr(LightConstantAttenuation);
LinearAttenuationEdit.Text := FloatToStr(LightLinearAttenuation);
QuadraticAttenuationEdit.Text := FloatToStr(LightQuadraticAttenuation);
LightingEnabledCBx.Checked := LightingEnabled;
end;
finally
FRefreshing := False;
end;
end;
procedure TMeshPreviewFrm.SurfaceColorBtnClick(Sender: TObject);
begin
if (Sender<>nil) and (Sender is TJvOfficeColorButton) then begin
ColorDialog.Color := TJvOfficeColorButton(Sender).SelectedColor;
if ColorDialog.Execute(Self.Handle) then begin
TJvOfficeColorButton(Sender).SelectedColor := ColorDialog.Color;
UIToAppearance;
end;
end;
end;
procedure TMeshPreviewFrm.SurfaceColorBtnColorChange(Sender: TObject);
begin
UIToAppearance;
end;
procedure TMeshPreviewFrm.UIToAppearance;
procedure ColorToVec(const Color: TColor; const V: TPS3Vector);
begin
V^.X := (Color and $FF)/255.0;
V^.Y := ((Color shr 8) and $FF)/255.0;
V^.Z := ((Color shr 16) and $FF)/255.0;
end;
begin
if FRefreshing then
Exit;
with FOpenGLHelper.MeshAppearance do begin
ColorToVec(SurfaceColorBtn.SelectedColor, @SurfaceColor);
ColorToVec(EdgesColorBtn.SelectedColor, @EdgesColor);
ColorToVec(WireframeColorBtn.SelectedColor, @WireframeColor);
ColorToVec(PointsColorBtn.SelectedColor, @PointsColor);
ColorToVec(MatAmbientColorBtn.SelectedColor, @MatAmbient);
ColorToVec(MatDiffuseColorBtn.SelectedColor, @MatDiffuse);
ColorToVec(MatSpecularColorBtn.SelectedColor, @MatSpecular);
MatShininess := StrToFloatSafe(MatShininessEdit.Text, MatShininess);
if MatShininess < 0.0 then
MatShininess := 0.0
else if MatShininess > 100.0 then
MatShininess := 100.0;
ColorToVec(LightAmbientBtn.SelectedColor, @LightAmbient);
ColorToVec(LightDiffuseBtn.SelectedColor, @LightDiffuse);
LightPosition.X := StrToFloatSafe(LightPositionXEdit.Text, LightPosition.X);
LightPosition.Y := StrToFloatSafe(LightPositionYEdit.Text, LightPosition.Y);
LightPosition.Z := StrToFloatSafe(LightPositionZEdit.Text, LightPosition.Z);
LightConstantAttenuation := StrToFloatSafe(ConstAttenuationEdit.Text, LightConstantAttenuation);
LightLinearAttenuation := StrToFloatSafe(LinearAttenuationEdit.Text, LightLinearAttenuation);
LightQuadraticAttenuation := StrToFloatSafe(QuadraticAttenuationEdit.Text, LightQuadraticAttenuation);
LightingEnabled := LightingEnabledCBx.Checked;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLPlugInManager<p>
An old PlugIn Manager unit. Don't know if if ever wa used...<p>
<b>Historique : </b><font size=-1><ul>
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>28/07/01 - EG - Initial version
</ul></font>
}
unit GLPlugInManager;
interface
{$I GLScene.inc}
uses
Winapi.Windows, System.Classes, System.SysUtils,
VCL.Dialogs, VCL.Forms,
GLPlugInIntf;
type
PPlugInEntry = ^TPlugInEntry;
TPlugInEntry = record
Path: TFileName;
Handle: HINST;
FileSize: Integer;
FileDate: TDateTime;
EnumResourcenames: TEnumResourceNames;
GetServices: TGetServices;
GetVendor: TGetVendor;
GetDescription: TGetDescription;
GetVersion: TGetVersion;
end;
TPlugInManager = class;
TResourceManager = class(TComponent)
public
procedure Notify(Sender: TPlugInManager; Operation: TOperation;
Service: TPIServiceType; PlugIn: Integer); virtual; abstract;
end;
TPlugInList = class(TStringList)
private
FOwner: TPlugInManager;
function GetPlugInEntry(Index: Integer): PPlugInEntry;
procedure SetPlugInEntry(Index: Integer; AEntry: PPlugInEntry);
protected
procedure DefineProperties(Filer: TFiler); override;
procedure ReadPlugIns(Reader: TReader);
procedure WritePlugIns(Writer: TWriter);
public
constructor Create(AOwner: TPlugInManager); virtual;
procedure ClearList;
property Objects[Index: Integer]: PPlugInEntry read GetPlugInEntry
write SetPlugInEntry; default;
property Owner: TPlugInManager read FOwner;
end;
PResManagerEntry = ^TResManagerEntry;
TResManagerEntry = record
Manager: TResourceManager;
Services: TPIServices;
end;
TPlugInManager = class(TComponent)
private
FLibraryList: TPlugInList;
FResManagerList: TList;
protected
procedure DoNotify(Operation: TOperation; Service: TPIServiceType;
PlugIn: Integer);
function FindResManager(AManager: TResourceManager): PResManagerEntry;
function GetIndexFromFilename(FileName: String): Integer;
function GetPlugInFromFilename(FileName: String): PPlugInEntry;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddPlugIn(Path: TFileName): Integer;
procedure EditPlugInList;
procedure RegisterResourceManager(AManager: TResourceManager;
Services: TPIServices);
procedure RemovePlugIn(Index: Integer);
procedure UnRegisterRessourceManager(AManager: TResourceManager;
Services: TPIServices);
published
property PlugIns: TPlugInList read FLibraryList write FLibraryList;
end;
// ------------------------------------------------------------------------------
implementation
// ----------------- TPlugInList ------------------------------------------------
constructor TPlugInList.Create(AOwner: TPlugInManager);
begin
inherited Create;
FOwner := AOwner;
Sorted := False;
Duplicates := DupAccept;
end;
// ------------------------------------------------------------------------------
procedure TPlugInList.ClearList;
begin
while Count > 0 do
FOwner.RemovePlugIn(0);
end;
// ------------------------------------------------------------------------------
function TPlugInList.GetPlugInEntry(Index: Integer): PPlugInEntry;
begin
Result := PPlugInEntry( inherited Objects[Index]);
end;
// ------------------------------------------------------------------------------
procedure TPlugInList.SetPlugInEntry(Index: Integer; AEntry: PPlugInEntry);
begin
inherited Objects[Index] := Pointer(AEntry);
end;
// ------------------------------------------------------------------------------
procedure TPlugInList.WritePlugIns(Writer: TWriter);
var
I: Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do
Writer.WriteString(Objects[I].Path);
Writer.WriteListEnd;
end;
// ------------------------------------------------------------------------------
procedure TPlugInList.ReadPlugIns(Reader: TReader);
begin
ClearList;
Reader.ReadListBegin;
while not Reader.EndOfList do
FOwner.AddPlugIn(Reader.ReadString);
Reader.ReadListEnd;
end;
// ------------------------------------------------------------------------------
procedure TPlugInList.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty('Paths', ReadPlugIns, WritePlugIns, Count > 0);
end;
// ----------------- TPlugInManager ---------------------------------------------
constructor TPlugInManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLibraryList := TPlugInList.Create(Self);
FResManagerList := TList.Create;
end;
// ------------------------------------------------------------------------------
destructor TPlugInManager.Destroy;
var
I: Integer;
begin
FLibraryList.ClearList;
FLibraryList.Free;
for I := 0 to FResManagerList.Count - 1 do
FreeMem(PResManagerEntry(FResManagerList[I]), SizeOf(TResManagerEntry));
FResManagerList.Free;
inherited Destroy;
end;
// ------------------------------------------------------------------------------
function TPlugInManager.AddPlugIn(Path: TFileName): Integer;
// open the given DLL and read its properties, to identify
// whether it's a valid plug-in or not
var
NewPlugIn: PPlugInEntry;
OldError: Integer;
NewHandle: HINST;
ServiceFunc: TGetServices;
SearchRec: TSearchRec;
Service: TPIServiceType;
Services: TPIServices;
begin
Result := -1;
OldError := SetErrorMode(SEM_NOOPENFILEERRORBOX);
if Length(Path) > 0 then
try
Result := GetIndexFromFilename(Path);
// plug-in already registered?
if Result > -1 then
Exit;
// first step is loading the file into client memory
NewHandle := LoadLibrary(PChar(Path));
// loading failed -> exit
if NewHandle = 0 then
Abort;
// get the service function address to identify the plug-in
ServiceFunc := GetProcAddress(NewHandle, 'GetServices');
if not assigned(ServiceFunc) then
begin
// if address not found then the given library is not valid
// release it from client memory
FreeLibrary(NewHandle);
Abort;
end;
// all went fine so far, we just loaded a valid plug-in
// allocate a new entry for the plug-in list and fill it
New(NewPlugIn);
NewPlugIn.Path := Path;
with NewPlugIn^ do
begin
Handle := NewHandle;
FindFirst(Path, faAnyFile, SearchRec);
FileSize := SearchRec.Size;
FileDate := SearchRec.TimeStamp;
FindClose(SearchRec);
GetServices := ServiceFunc;
EnumResourcenames := GetProcAddress(Handle, 'EnumResourceNames');
GetVendor := GetProcAddress(Handle, 'GetVendor');
GetVersion := GetProcAddress(Handle, 'GetVersion');
GetDescription := GetProcAddress(Handle, 'GetDescription');
end;
Result := FLibraryList.Add(string(NewPlugIn.GetVendor));
FLibraryList.Objects[Result] := NewPlugIn;
// now notify (for all provided services) all registered resource managers
// for which these services are relevant
Services := NewPlugIn.GetServices;
for Service := Low(TPIServiceType) to High(TPIServiceType) do
if Service in Services then
DoNotify(opInsert, Service, Result);
finally
SetErrorMode(OldError);
end;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManager.DoNotify(Operation: TOperation;
Service: TPIServiceType; PlugIn: Integer);
var
I: Integer;
begin
for I := 0 TO FResManagerList.Count - 1 do
if Service in PResManagerEntry(FResManagerList[I]).Services then
PResManagerEntry(FResManagerList[I]).Manager.Notify(Self, Operation,
Service, PlugIn);
end;
// ------------------------------------------------------------------------------
function TPlugInManager.FindResManager(AManager: TResourceManager)
: PResManagerEntry;
var
I: Integer;
begin
Result := nil;
for I := 0 to FResManagerList.Count - 1 do
if PResManagerEntry(FResManagerList[I]).Manager = AManager then
begin
Result := PResManagerEntry(FResManagerList[I]);
Exit;
end;
end;
// ------------------------------------------------------------------------------
function TPlugInManager.GetIndexFromFilename(FileName: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to FLibraryList.Count - 1 do
if CompareText(FLibraryList[I].Path, FileName) = 0 then
begin
Result := I;
Exit;
end;
end;
// ------------------------------------------------------------------------------
function TPlugInManager.GetPlugInFromFilename(FileName: String): PPlugInEntry;
var
I: Integer;
begin
I := GetIndexFromFilename(FileName);
if I > -1 then
Result := FLibraryList[I]
else
Result := nil;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManager.RegisterResourceManager(AManager: TResourceManager;
Services: TPIServices);
var
ManagerEntry: PResManagerEntry;
begin
ManagerEntry := FindResManager(AManager);
if assigned(ManagerEntry) then
ManagerEntry.Services := ManagerEntry.Services + Services
else
begin
New(ManagerEntry);
ManagerEntry.Manager := AManager;
ManagerEntry.Services := Services;
FResManagerList.Add(ManagerEntry);
end;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManager.RemovePlugIn(Index: Integer);
var
Entry: PPlugInEntry;
Service: TPIServiceType;
Services: TPIServices;
begin
Entry := FLibraryList.Objects[Index];
Services := Entry.GetServices;
// notify for all services to be deleted all registered resource managers
// for which these services are relevant
for Service := Low(TPIServiceType) to High(TPIServiceType) do
if Service in Services then
DoNotify(opRemove, Service, Index);
FreeLibrary(Entry.Handle);
Dispose(Entry);
FLibraryList.Delete(Index);
end;
// ------------------------------------------------------------------------------
procedure TPlugInManager.EditPlugInList;
begin
///TPlugInManagerEditor.EditPlugIns(Self); //Circular call to edit Listbox items?
end;
// ------------------------------------------------------------------------------
procedure TPlugInManager.UnRegisterRessourceManager(AManager: TResourceManager;
Services: TPIServices);
var
ManagerEntry: PResManagerEntry;
Index: Integer;
begin
ManagerEntry := FindResManager(AManager);
if assigned(ManagerEntry) then
begin
ManagerEntry.Services := ManagerEntry.Services - Services;
if ManagerEntry.Services = [] then
begin
Index := FResManagerList.IndexOf(ManagerEntry);
Dispose(ManagerEntry);
FResManagerList.Delete(Index);
end;
end;
end;
// ------------------------------------------------------------------------------
end.
|
{******************************************************************************}
{ Unit description: }
{ Developer: josking Date: 2009/11/29 }
{ Modifier: Date: }
{ Copyright(GBM) EMS , All right reserved }
{******************************************************************************}
unit clsAuthorizationContent;
interface
type
TclsAuthorizationContent=Class(TObject)
private
PID:string;
PName:string;
PDesc:string;
PFunctionList:String;
PBuilder:string;
PbDate:string;
Previser:string;
PrDate:string;
public
property FID:string read PID write PID;
property FName:string read PName write PName;
property FDesc:string read PDesc write PDesc;
property FFunctionList:string read PFunctionList write PFunctionList;
property FBuilder:string read PBuilder write PBuilder;
property FbDate:string read PbDate write PbDate;
property Freviser:string read Previser write Previser;
property FrDate:string read PrDate write PrDate;
end;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.