text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ Interface RTTI Support }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Soap.IntfInfo;
interface
{$IFDEF CPUX64}
{$DEFINE PUREPASCAL}
{$ENDIF CPUX64}
uses
System.SysUtils, System.TypInfo;
type
PIntfParamEntry = ^TIntfParamEntry;
TIntfParamEntry = record
Flags: TParamFlags;
Name: string;
Info: PTypeInfo;
end;
TIntfParamEntryArray = array of TIntfParamEntry;
TCallConv = System.TypInfo.TCallConv;
PIntfMethEntry = ^TIntfMethEntry;
TIntfMethEntry = record
Name: string;
CC: TCallConv; { Calling convention }
Pos: Integer; { Index (relative to whole interface VMT) }
ParamCount: Integer;
ResultInfo: PTypeInfo;
SelfInfo: PTypeInfo;
Params: TIntfParamEntryArray;
HasRTTI: Boolean;
end;
TIntfMethEntryArray = array of TIntfMethEntry;
TPIntfMethEntryArray = array of PIntfMethEntry;
{ Governs how the MDA array is filled }
TFillMethodArrayOpt = (fmoAllBaseMethods, fmoRTTIBaseMethods, fmoNoBaseMethods);
PIntfMetaData = ^TIntfMetaData;
TIntfMetaData = record
Name: string;
UnitName: string;
MDA: TIntfMethEntryArray;
IID: TGUID;
Info: PTypeInfo;
AncInfo: PTypeInfo;
NumAnc: Integer; { #Methods in base interfaces }
end;
EInterfaceRTTIException = class(Exception);
procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; MethodArrayOpt: TFillMethodArrayOpt); overload;
procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; IncludeAllAncMethods: Boolean = False); overload;
function GetMethNum(const IntfMD: TIntfMetaData; const MethName: string;
ParamCount: Integer = -1): Integer;
{ Dynamic Array RTTI helpers }
procedure GetDynArrayElTypeInfo(typeInfo: PTypeInfo; var EltInfo: PTypeInfo; var Dims: Integer);
function GetDynArrayNextInfo(typeInfo: PTypeInfo): PTypeInfo;
function GetDynArrayNextInfo2(typeInfo: PTypeInfo; var Name: string): PTypeInfo;
function TypeNamesMatch(const RegName: string; const OtherName: string): boolean;
function OtherTypeName(const TypeName: string): string;
function SameTypeInfo(const RegInfo: PTypeInfo; const OtherInfo: PTypeInfo): boolean;
function GetPropListFlat(TypeInfo: PTypeInfo; out PropList: PPropList): Integer;
function IsStoredPropConst(Instance: TObject; PropInfo: PPropInfo): Boolean;
function GetClsMemberTypeInfo(const ObjectTypeInfo: PTypeInfo; const MemberName: string = ''): PTypeInfo;
{ The following routines are used from C++ to validate the compatibility of C++ interface generation}
{$IFDEF DEVELOPERS}
function ReadString(var P: Pointer): String;
function ReadByte(var P: Pointer): Byte;
function ReadWord(var P: Pointer): Word;
function ReadLong(var P: Pointer): Integer;
procedure FillMethodArray(P: Pointer; IntfMD: PIntfMetaData; Offset, Methods: Integer);
function GetNumAncMeths(P: Pointer; WithRTTIOnly: Boolean = False): Integer;
function WalkAncestors(PP: PPTypeInfo; AddMeths: Boolean; IntfMD: PIntfMetaData; WithRTTIOnly: Boolean): Integer;
{$ENDIF}
const
CallingConventionName: array[ccReg..ccSafeCall] of string =
('REGISTER', 'CDECL', 'PASCAL', 'STDCALL', 'SAFECALL'); { do not localize }
TypeInfoNames: array[0..37] of string = ( 'Boolean', 'bool', { do not localize }
{$IFNDEF UNICODE}
'Char', 'char', { do not localize }
'Char', 'signed char', { do not localize }
'WideChar', 'wchar_t', { do not localize }
{$ELSE}
'AnsiChar', 'char', { do not localize }
'AnsiChar', 'signed char', { do not localize }
'Char', 'wchar_t', { do not localize }
{$ENDIF}
'Byte', 'unsigned char', { do not localize }
'SmallInt', 'short', { do not localize }
'Word', 'unsigned short', { do not localize }
'Integer', 'int', { do not localize }
'Cardinal', 'unsigned int', { do not localize }
'Integer', 'long', { do not localize }
'Cardinal', 'unsigned long', { do not localize }
'Int64', '__int64', { do not localize }
'Int64', 'unsigned __int64', { do not localize }
'Single', 'float', { do not localize }
'Double', 'double', { do not localize }
'Extended', 'long double', { do not localize }
{$IFNDEF UNICODE}
'string', 'AnsiString', { do not localize }
'UnicodeString', 'UnicodeString', { do not localize }
{$ELSE}
'string', 'UnicodeString', { do not localize }
'AnsiString', 'AnsiString', { do not localize }
{$ENDIF}
'WideString', 'WideString'); { do not localize }
implementation
uses
System.Classes, Soap.SOAPConst;
const
CCMap: array[0..4] of TCallConv = (ccReg, ccCdecl, ccPascal, ccStdCall, ccSafeCall);
function GetMethNum(const IntfMD: TIntfMetaData; const MethName: string;
ParamCount: Integer = -1): Integer;
function CalcParamCount(const Start: Integer; const Entry: TIntfMethEntry): Integer;
var
I: Integer;
begin
Result := Start;
{ Not needed for C++ Builder }
for I := 0 to Entry.ParamCount do
if pfOut in Entry.Params[I].Flags then
Inc(Result);
end;
var
I, NumNames, ExpCount: Integer;
begin
NumNames := 0;
Result := -1;
for I := 0 to Length(IntfMD.MDA) - 1 do
begin
if SameText(IntfMD.MDA[I].Name, MethName) then
begin
if ParamCount <> -1 then
begin
ExpCount := CalcParamCount(ParamCount, IntfMD.MDA[I]);
if ExpCount <> IntfMD.MDA[I].ParamCount then
continue;
end;
Result := I;
Inc(NumNames);
end;
end;
if (NumNames = 0) and (ParamCount <> -1) then
Result := GetMethNum(IntfMD, MethName, -1);
if NumNames > 1 then
Result := -1;
end;
function ReadString(var P: Pointer): String;
var
B: Byte;
{$IFDEF UNICODE}
AStr: AnsiString;
{$ENDIF}
begin
B := Byte(P^);
{$IFDEF UNICODE}
SetLength(AStr, B);
P := Pointer(NativeInt(P)+1);
Move(P^, AStr[1], Integer(B));
Result := UTF8ToString(AStr);
{$ELSE}
SetLength(Result, B);
P := Pointer( NativeInt(P) + 1);
Move(P^, Result[1], Integer(B));
{$ENDIF}
P := Pointer( NativeInt(P) + B );
end;
function ReadByte(var P: Pointer): Byte;
begin
Result := Byte(P^);
P := Pointer(NativeInt(P) + 1);
end;
function ReadWord(var P: Pointer): Word;
begin
Result := Word(P^);
P := Pointer( NativeInt(P) + 2);
end;
function ReadLong(var P: Pointer): Integer;
begin
Result := Integer(P^);
P := Pointer( NativeInt(P) + 4);
end;
function ReadPointer(var P: Pointer): Pointer;
begin
Result := Pointer(P^);
P := Pointer( NativeInt(P) + SizeOf(Pointer));
end;
procedure FillMethodArray(P: Pointer; IntfMD: PIntfMetaData; Offset, Methods: Integer);
var
S: string;
I, J, K: Integer;
PPInfo: PPTypeInfo;
ParamCount: Integer;
Kind, Flags: Byte;
ParamInfo: PTypeInfo;
ParamName: string;
IntfMethod: PIntfMethEntry;
IntfParam: PIntfParamEntry;
begin
for I := 0 to Methods -1 do
begin
IntfMethod := @IntfMD.MDA[Offset];
IntfMethod.Name := ReadString(P);
Kind := ReadByte(P); { tkKind }
IntfMethod.CC := CCMap[ReadByte(P)];
ParamCount := ReadByte(P); { Param count including self }
IntfMethod.ParamCount := ParamCount - 1;
IntfMethod.Pos := Offset;
IntfMethod.HasRTTI := True;
SetLength(IntfMethod.Params, ParamCount);
K := 0;
for J := 0 to ParamCount - 1 do
begin
Flags := ReadByte(P); { Flags }
ParamName := ReadString(P); { Param name }
S := ReadString(P); { Param type name }
PPInfo := ReadPointer(P); { Param Type Info }
Inc(PByte(P), PWord(P)^); { skip attributes }
if PPInfo <> nil then
ParamInfo := PPInfo^
else
raise EInterfaceRTTIException.CreateFmt(SNoRTTIParam, [ParamName, IntfMethod.Name, IntfMD.UnitName + '.' + IntfMd.Name]);
if J = 0 then
IntfMethod.SelfInfo := ParamInfo
else
begin
IntfParam := @IntfMethod.Params[K];
IntfParam.Flags := TParamFlags(Flags);
IntfParam.Name := ParamName;
IntfParam.Info := ParamInfo;
Inc(K);
end;
end;
if Kind = Byte(mkFunction) then
begin
S := ReadString(P);
IntfMethod.ResultInfo := PPTypeInfo(ReadPointer(P))^;
end;
Inc(PByte(P), PWord(P)^); // skip attributes
Inc(Offset);
end;
end;
function WalkAncestors(PP: PPTypeInfo; AddMeths: Boolean; IntfMD: PIntfMetaData; WithRTTIOnly: Boolean): Integer;
var
S: string;
AncTP: Pointer;
P: Pointer;
B: Byte;
NumMethods, NumAncMeths, I: Integer;
HasRTTI: Boolean;
begin
P := Pointer(PP^);
ReadByte(P); // Kind
S := ReadString(P); // Symbol name
AncTP := ReadPointer(P); // Ancestor TypeInfo
P := Pointer(Integer(P) + 17); // Intf.flags and GUID
B := Byte(P^); // Length
P := Pointer(Integer(P) + B + 1); // Unit name and count
NumMethods := ReadWord(P); // # methods
I := ReadWord(P); // $FFFF if no RTTI, # methods again if has RTTI
HasRTTI := (I <> $FFFF);
{ Compute the number of methods }
if (AncTP <> nil) and (HasRTTI or (WithRTTIOnly = False)) then
begin
NumAncMeths := WalkAncestors(AncTP, False, nil, WithRTTIOnly);
end else
NumAncMeths := 0;
{ Ancestor count }
Result := NumAncMeths;
{ Plus our own }
if (HasRTTI or (WithRTTIOnly = False)) then
Result := Result + NumMethods;
{ Do we need to fill in method information too? }
if AddMeths then
begin
if HasRTTI then
begin
FillMethodArray(P, IntfMD, NumAncMeths, NumMethods);
if NumAncMeths > 0 then
WalkAncestors(AncTP, AddMeths, IntfMD, WithRTTIOnly);
end;
end;
end;
function GetNumAncMeths(P: Pointer; WithRTTIOnly: Boolean = False): Integer;
var
B: Byte;
Anc: Pointer;
begin
Result := 0;
ReadByte(P); // tkKind
B := Byte(P^); // Symbol length
P := Pointer(Integer(P) + B + 1); // Skip sym name and count
Anc := ReadPointer(P); // Ancestor pointer
if Anc <> nil then
Result := WalkAncestors(Anc, False, nil, WithRTTIOnly);
end;
procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; MethodArrayOpt: TFillMethodArrayOpt);
var
I, Offset: Integer;
Methods: Integer;
BaseRTTIMethods: Integer;
HasRTTI: Integer;
PP: PPTypeInfo;
P: Pointer;
SelfMethCount: Integer;
begin
P := Pointer(Info);
{ Get total number of ancestor methods }
IntfMD.NumAnc := GetNumAncMeths(P);
{ Get base methods we could expose }
BaseRTTIMethods := GetNumAncMeths(P, True);
IntfMD.Info := Info;
{ tkKind }
ReadByte(P);
IntfMD.Name := ReadString(P);
PP := PPTypeInfo(ReadPointer(P));
{ Ancestor typeinfo }
if PP <> nil then
IntfMD.AncInfo := PP^
else
IntfMD.AncInfo := nil;
{ Interface flags }
ReadByte(P);
IntfMD.IID.D1 := LongWord(ReadLong(P));
IntfMD.IID.D2 := ReadWord(P);
IntfMD.IID.D3 := ReadWord(P);
for I := 0 to 7 do
IntfMD.IID.D4[I] := ReadByte(P);
IntfMD.UnitName := ReadString(P);
Methods := ReadWord(P); { # methods }
HasRTTI := ReadWord(P); { $FFFF if no RTTI, # methods again if has RTTI }
if HasRTTI = $FFFF then
raise EInterfaceRTTIException.CreateFmt(SNoRTTI, [IntfMD.UnitName + '.' + IntfMd.Name]);
{ Save my method count }
SelfMethCount := Methods;
{ Update count of methods }
if (MethodArrayOpt = fmoAllBaseMethods) then
begin
Methods := Methods + IntfMD.NumAnc;
Offset := IntfMD.NumAnc;
end else
if (MethodArrayOpt = fmoRTTIBaseMethods) then
begin
Methods := Methods + BaseRTTIMethods;
Offset := BaseRTTIMethods;
end else
Offset := 0;
{ Size array and fill in information }
SetLength(IntfMD.MDA, Methods);
FillMethodArray(P, @IntfMD, Offset, SelfMethCount);
{ Include method info. of base methods too?? }
if (MethodArrayOpt = fmoAllBaseMethods) or
(MethodArrayOpt = fmoRTTIBaseMethods) then
begin
if PP <> nil then
WalkAncestors(PP, True, @IntfMD, (MethodArrayOpt = fmoRTTIBaseMethods));
end;
end;
procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; IncludeAllAncMethods: Boolean);
var
FillMethodArrayOpt: TFillMethodArrayOpt;
begin
if (IncludeAllAncMethods) then
FillMethodArrayOpt := fmoAllBaseMethods
else
FillMethodArrayOpt := fmoRTTIBaseMethods;
GetIntfMetaData(Info, IntfMD, FillMethodArrayOpt);
end;
procedure GetDynArrayElTypeInfo(typeInfo: PTypeInfo; var EltInfo: PTypeInfo; var Dims: Integer);
var
S: string;
P: Pointer;
ppInfo: PPTypeInfo;
Info: PTypeInfo;
CleanupInfo: Boolean;
begin
CleanupInfo := False;
Dims := 0;
P := Pointer(typeInfo);
ReadByte(P); { kind }
S := ReadString(P); { symname }
ReadLong(P); { elsize }
ppInfo := ReadPointer(P);
{ Here we rely on Cleanup TypeInfo. However, that's not
reliable, specially in the case of C++ where the concept
of cleanup is muddled since the Dynamic Array class
destructor handles the clean up. Hence, we'll handle both styles
of RTTI }
if (ppInfo <> nil) then
begin
CleanupInfo := True;
Info := ppInfo^;
if Info.Kind = tkDynArray then
begin
GetDynArrayElTypeInfo(Info, EltInfo, Dims);
end;
end;
ReadLong(P); { vartype }
ppInfo := ReadPointer(P); { elttype, even if not destructable, 0 if type has no RTTI }
if ppInfo <> nil then
begin
EltInfo := ppInfo^;
if not CleanupInfo then
begin
Info := EltInfo;
if Info.Kind = tkDynArray then
GetDynArrayElTypeInfo(Info, EltInfo, Dims);
end;
end;
Inc(Dims);
end;
function GetDynArrayNextInfo(typeInfo: PTypeInfo): PTypeInfo;
var
S: string;
begin
Result := GetDynArrayNextInfo2(typeInfo, S);
end;
function GetDynArrayNextInfo2(typeInfo: PTypeInfo; var Name: string): PTypeInfo;
var
P: Pointer;
ppInfo: PPTypeInfo;
begin
Result := nil;
P := Pointer(typeInfo);
ReadByte(P); { kind }
Name := ReadString(P); { synmame }
ReadLong(P); { elsize }
ppInfo := ReadPointer(P);
if ppInfo <> nil then
Result := ppInfo^ { eltype or 0 if not destructable }
else
begin
ReadLong(P); { vartype }
ppInfo := ReadPointer(P); { elttype, even if not destructable, 0 if type has no RTTI }
if ppInfo <> nil then
Result := ppInfo^;
end;
end;
function SameTypeInfo(const RegInfo: PTypeInfo; const OtherInfo: PTypeInfo): boolean;
begin
Result := (RegInfo = OtherInfo) or
((RegInfo.Kind=OtherInfo.Kind) and
{$IFDEF UNICODE}
// Technically we don't need to decode since we're looking for
// a known set of type names but for completeness we pass the
// real type name.
TypeNamesMatch(UTF8ToString(RegInfo^.Name),
UTF8ToString(OtherInfo^.Name)));
{$ELSE}
TypeNamesMatch(RegInfo^.Name,
OtherInfo^.Name));
{$ENDIF}
end;
function TypeNamesMatch(const RegName: string; const OtherName: string): boolean;
var
I: Integer;
begin
Result := (RegName = OtherName);
if (not Result) then
begin
I := 1; { Start at one since we check OtherName first }
while (I < Length(TypeInfoNames)) do
begin
if (OtherName = TypeInfoNames[I]) then
begin
Result := (RegName = TypeInfoNames[I-1]);
Exit;
end;
I := I+2;
end;
end;
end;
function OtherTypeName(const TypeName: string): string;
var
I: Integer;
begin
I := 0;
while (I < (Length(TypeInfoNames)-1)) do
begin
if (TypeName = TypeInfoNames[I]) then
begin
Result := TypeInfoNames[I+1];
Exit;
end;
I := I+2;
end;
end;
function AfterString(Str: PShortString): Pointer; inline;
begin
Result := Pointer(PByte(Str) + Length(Str^) + 1);
end;
{ Similar to TypInfo's GetPropInfos except that we don't walk up the base classes }
procedure GetPropInfosFlat(TypeInfo: PTypeInfo; PropList: PPropList); assembler;
var
TypeData: PTypeData;
PropData: PPropData;
PropInfo: PPropInfo;
I: Integer;
begin
TypeData := GetTypeData(TypeInfo);
FillChar(PropList^, Sizeof(PPropInfo) * TypeData.PropCount, #0);
PropData := AfterString(@(TypeData^.UnitName));
PropInfo := PPropInfo(@PropData^.PropList);
for I := 1 to PropData^.PropCount do
begin
if PropList^[PropInfo.NameIndex] = nil then
PropList^[PropInfo.NameIndex] := PropInfo;
PropInfo := AfterString(@PropInfo^.Name);
end;
end;
function GetPropListFlat(TypeInfo: PTypeInfo; out PropList: PPropList): Integer;
begin
Result := GetTypeData(TypeInfo)^.PropCount;
if Result > 0 then
begin
GetMem(PropList, Result * SizeOf(Pointer));
try
FillChar(PropList^, Result * SizeOf(Pointer), 0);
GetPropInfosFlat(TypeInfo, PropList);
except
FreeMem(PropList);
PropList := nil;
raise;
end;
end;
end;
{ Similar to TypInfo's IsStoredProp although this version only handles cases
where the attribute was assigned 'true' or 'false' directly. IOW, this version
will always assume stored is true unless the value 'false' was assigned directly
to the property.
NOTE: the 'Instance' parameter is not used nor required. }
function IsStoredPropConst(Instance: TObject; PropInfo: PPropInfo): Boolean;
type
TStoredProc = function(Instance: TObject): Boolean;
begin
Result := True;
// if is constant
if (NativeUInt(PropInfo^.StoredProc) and (not NativeUInt($FF))) = 0 then
Exit(Boolean(NativeUInt(PropInfo^.StoredProc) and $FF));
end;
{ Returns the TypeInfo of a class member }
function GetClsMemberTypeInfo(const ObjectTypeInfo: PTypeInfo; const MemberName: string): PTypeInfo;
var
PropList: PPropList;
Size, Props: Integer;
begin
Result := nil;
Size := GetPropListFlat(ObjectTypeInfo, PropList);
if Size > 0 then
begin
try
for Props := 0 to Size -1 do
begin
if PropList[Props] <> nil then
begin
{ Either there's a match or send the only member's TypeInfo back }
{$IFDEF UNICODE}
if SameText(UTF8ToUnicodeString(PropList[Props].Name), MemberName)
{$ELSE}
if SameText(PropList[Props].Name, MemberName)
{$ENDIF}
or ((MemberName = '') and (Size = 1)) then
begin
Result := PropList[Props].PropType^;
Exit;
end;
end;
end;
finally
FreeMem(PropList);
end;
end;
end;
end.
|
unit uTranslateSystemRTLConsts;
interface
uses
Windows,
System.RTLConsts,
uTranslate;
Type
TTranslateSystemRTLConsts = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateSystemRTLConsts.ChangeValues;
begin
SetResourceString(@SAncestorNotFound, 'Ancestral para %s não encontrado');
SetResourceString(@SAssignError, 'Impossível indicar um %s para um %s');
SetResourceString(@SBitsIndexError, 'Indice de bits fora de faixa');
SetResourceString(@SBucketListLocked, 'Lista esta travada durante um ForEach ativo');
SetResourceString(@SCantWriteResourceStreamError, 'Impossível gravar em um canal de recursos Somente-para-leitura');
SetResourceString(@SCharExpected, '"%s" experado');
SetResourceString(@SCheckSynchronizeError, 'CheckSynchronize chamado de um linha $%x, que não é a linha principal');
SetResourceString(@SClassNotFound, 'Classe %s não encontrada');
SetResourceString(@SDelimiterQuoteCharError, 'Propriedade Delimiter e QuoteChar não podem ter o mesmo valor');
SetResourceString(@SDuplicateClass, 'A classe chamada %s já existe');
SetResourceString(@SDuplicateItem, 'Lista não suporta duplicatas ($0%x)');
SetResourceString(@SDuplicateName, 'Um componente chamado %s já existe');
SetResourceString(@SDuplicateString, 'Lista de String não suporta duplicatas');
SetResourceString(@SFCreateError, 'Impossível criar arquivo %s');
SetResourceString(@SFCreateErrorEx, 'Impossível criar arquivo "%s". %s');
SetResourceString(@SFixedColTooBig, 'Contador fixado da coluna precisa ser menor que um contador de coluna');
SetResourceString(@SFixedRowTooBig, 'Contador fixado da linha precisa ser menor que um contador de linha');
SetResourceString(@SFOpenError, 'Impossível abrir arquivo %s');
SetResourceString(@SFOpenErrorEx, 'Impossível abrir arquivo %s. %s');
SetResourceString(@SGridTooLarge, 'Grade muito grande para operação');
SetResourceString(@SIdentifierExpected, 'Identificador esperado');
SetResourceString(@SIndexOutOfRange, 'Indice de grade fora de faixa');
SetResourceString(@SIniFileWriteError, 'Impossível gravar para %s');
SetResourceString(@SInvalidActionCreation, 'Ação de criação inválida');
SetResourceString(@SInvalidActionEnumeration, 'Ação de Enumeração inválida');
SetResourceString(@SInvalidActionRegistration, 'Ação de Registro inválido');
SetResourceString(@SInvalidActionUnregistration, 'Ação de Desregistro inválido');
SetResourceString(@StrNoClientClass, 'O cliente não pode ser uma instância da classe %s');
SetResourceString(@StrEActionNoSuported, 'A classe %s não suporta a ação');
SetResourceString(@SInvalidBinary, 'Valor binario inválido');
SetResourceString(@SInvalidFileName, 'Nome de arquiv inválido - %s');
SetResourceString(@SInvalidImage, 'Formato de canal inválido');
SetResourceString(@SInvalidMask, '"%s" é uma mascara inválida em (%d)');
SetResourceString(@SInvalidName, '"%s" não é um nome de componente válido');
SetResourceString(@SInvalidProperty, 'Valor da propriedade inválido');
SetResourceString(@SInvalidPropertyElement, 'Elemento da propriedade inválido: %s');
SetResourceString(@SInvalidPropertyPath, 'Caminho da propriedade inválida');
SetResourceString(@SInvalidPropertyType, 'Tipo de propriedade inválida: %s');
SetResourceString(@SInvalidPropertyValue, 'Valor da propriedade inválido');
SetResourceString(@SInvalidRegType, 'Tipo de dados inválido para ''%s''');
SetResourceString(@SInvalidString, 'A String constante é inválida');
SetResourceString(@SInvalidStringGridOp, 'Impossível inserir ou apager linhas da grade');
SetResourceString(@SItemNotFound, 'Item não encontrado ($0%x)');
SetResourceString(@SLineTooLong, 'Linha muito grande');
SetResourceString(@SListCapacityError, 'Capacidade de listagem fora de faixa (%d)');
SetResourceString(@SListCountError, 'Contador de listagem fora de faixa (%d)');
SetResourceString(@SListIndexError, 'Indice de listagem fora de faixa (%d)');
SetResourceString(@SMaskErr, 'Valor de entrada inválido');
SetResourceString(@SMaskEditErr, 'Valor de entrada inválido. Use a tecla ESC para abandonar as alterações');
SetResourceString(@SMemoryBufferOverrun, 'Memory Buffer overrun');
SetResourceString(@SMemoryStreamError, 'Sem memória enquanto espandindo canal de memória');
SetResourceString(@SNoComSupport, '%s não foi registrado como uma classe COM');
SetResourceString(@SNotPrinting, 'A impressora não está atualmente imprimindo');
SetResourceString(@SNumberExpected, 'Número esperado');
SetResourceString(@SAnsiUTF8Expected, 'ANSI or UTF8 encoding expected');
SetResourceString(@SParseError, '%s na linha %d');
SetResourceString(@SComponentNameTooLong, 'Nome do componente "%s" excede o limite de 64 caracteres');
SetResourceString(@SPropertyException, 'Erro lendo %s%s%s: %s');
SetResourceString(@SPrinting, 'Impressão em progresso');
SetResourceString(@SReadError, 'Erro lendo canal');
SetResourceString(@SReadOnlyProperty, 'Propriedade é somente-para-leitura');
SetResourceString(@SRegCreateFailed, 'Falha ao criar chave %s');
SetResourceString(@SRegGetDataFailed, 'Falha ao passar dados para "%s"');
SetResourceString(@SRegisterError, 'Registro de componente inválido');
SetResourceString(@SRegSetDataFailed, 'Falha ao definir dados para "%s"');
SetResourceString(@SResNotFound, 'Recurso %s não encontrado');
SetResourceString(@SSeekNotImplemented, '%s.Seek não implementada');
SetResourceString(@SSortedListError, 'Operação não suportada em uma lista classificada');
SetResourceString(@SStringExpected, 'String esperada');
SetResourceString(@SSymbolExpected, '%s esperado');
SetResourceString(@STooManyDeleted, 'Muitas linhas ou colunas apagadas');
SetResourceString(@SUnknownGroup, '%s não está em um grupo de registro de classe');
SetResourceString(@SUnknownProperty, 'Propriedade %s não existe');
SetResourceString(@SWriteError, 'Erro gravando canal');
SetResourceString(@SStreamSetSize, 'Falha em Stream.SetSize');
SetResourceString(@SThreadCreateError, 'Erro criando linha: %s');
SetResourceString(@SThreadError, 'Erro na linha: %s (%d)');
SetResourceString(@SThreadExternalTerminate, 'Cannot terminate an externally created thread');
SetResourceString(@SThreadExternalWait, 'Cannot wait for an externally created thread');
SetResourceString(@SThreadStartError, 'Cannot call Start on a running or suspended thread');
SetResourceString(@SThreadExternalCheckTerminated, 'Cannot call CheckTerminated on an externally created thread');
SetResourceString(@SThreadExternalSetReturnValue, 'Cannot call SetReturnValue on an externally create thread');
SetResourceString(@SParamIsNil, 'Parametro "%s" não pode ser null');
SetResourceString(@SParamIsNegative, 'Parametro "%s" não pode ser negativo');
SetResourceString(@SInputBufferExceed, 'Input buffer exceeded for %s = %d, %s = %d');
SetResourceString(@SInvalidCharsInPath, 'Invalid characters in path');
SetResourceString(@SInvalidCharsInFileName, 'Invalid characters in file name');
SetResourceString(@SInvalidCharsInSearchPattern, 'Invalid characters in search pattern');
SetResourceString(@SPathTooLong, 'The specified path is too long');
SetResourceString(@SPathNotFound, 'The specified path was not found');
SetResourceString(@SPathFormatNotSupported, 'The path format is not supported');
SetResourceString(@SDirectoryNotEmpty, 'The specified directory is not empty');
SetResourceString(@SDirectoryAlreadyExists, 'The specified directory already exists');
SetResourceString(@SDirectoryInvalid, 'The specified directory name is invalid');
SetResourceString(@SSourceDirIsDestDir, 'The source directory is the same as the destination directory');
SetResourceString(@SSourceFileIsDestFile, 'The source file is the same as the destination file');
SetResourceString(@SPathToFileNeeded, 'The path must specify a file');
SetResourceString(@SSameRootDrive, 'The source and destination paths must contain the same root drive');
SetResourceString(@SDriveNotFound, 'The drive cannot be found');
SetResourceString(@SFileNotFound, 'The specified file was not found');
SetResourceString(@SFileAlreadyExists, 'The specified file already exists');
SetResourceString(@SInvalidDateDay, '(%d, %d) não é um par DateDay válido');
SetResourceString(@SInvalidDateWeek, '(%d, %d, %d) não é um trio DateWeek válido');
SetResourceString(@SInvalidDateMonthWeek, '(%d, %d, %d, %d) não é uma DateMonthWeek válido');
SetResourceString(@SInvalidDayOfWeekInMonth, '(%d, %d, %d, %d) não é um DayOfWeekInMonth válido');
SetResourceString(@SInvalidJulianDate, 'valor "%f" no calendário Juliano não pode ser representado como um valor DateTime');
SetResourceString(@SMissingDateTimeField, '?');
SetResourceString(@SMinimumDateError, 'Datas antes do ano 1 não são suportadas');
SetResourceString(@SLocalTimeInvalid, 'The given "%s" local time is invalid (situated within the missing period prior to DST).');
SetResourceString(@SConvIncompatibleTypes2, 'Conversão de tipos incompatíveis [%s, %s]');
SetResourceString(@SConvIncompatibleTypes3, 'Conversão de tipos incompatíveis [%s, %s, %s]');
SetResourceString(@SConvIncompatibleTypes4, 'Conversão de tipos incompatíveis [%s - %s, %s - %s]');
SetResourceString(@SConvUnknownType, 'Tipo de conversão desconhecido %s');
SetResourceString(@SConvDuplicateType, 'Tipo de conversão (%s) já foi registrada');
SetResourceString(@SConvUnknownFamily, 'Familia de conversão %s desconhecida');
SetResourceString(@SConvDuplicateFamily, 'Familia de conversão (%s) já foi registrada');
// SetResourceString(@SConvUnknownDescription, '[%.8x]');
SetResourceString(@SConvUnknownDescriptionWithPrefix, '[%s%.8x]');
SetResourceString(@SConvIllegalType, 'Tipo Ilegal');
SetResourceString(@SConvIllegalFamily, 'Familia Ilegal');
SetResourceString(@SConvFactorZero, '%s tem um fator de zero');
SetResourceString(@SConvStrParseError, 'Impossível válidar %s');
SetResourceString(@SFailedToCallConstructor, 'Descendente de TStrings %s falhou ao chamar construtor herdeiro');
SetResourceString(@sWindowsSocketError, 'Erro no Socket do Windows: %s (%d), on API ''%s''');
SetResourceString(@sAsyncSocketError, 'Erro %d de sincronia do socket');
SetResourceString(@sNoAddress, 'Nenhum endereço especificado');
SetResourceString(@sCannotListenOnOpen, 'Impossível lista em um socket aberto');
SetResourceString(@sCannotCreateSocket, 'Impossível criar um novo socket');
SetResourceString(@sSocketAlreadyOpen, 'Socket já está aberto');
SetResourceString(@sCantChangeWhileActive, 'Impossível mudar valor enquanto socket esta ativo');
SetResourceString(@sSocketMustBeBlocking, 'O Socket precisa estar em modo de bloqueio');
SetResourceString(@sSocketIOError, '%s error %d, %s');
SetResourceString(@sSocketRead, 'Ler');
SetResourceString(@sSocketWrite, 'Gravar');
SetResourceString(@SCmplxCouldNotParseImaginary, 'Impossível validar porção imaginária');
SetResourceString(@SCmplxCouldNotParseSymbol, 'Impossível validar símbolo ''%s'' requirido');
SetResourceString(@SCmplxCouldNotParsePlus, 'Impossível validar símbolo ''+'' (or ''-'') requerido');
SetResourceString(@SCmplxCouldNotParseReal, 'Impossível validar porção real');
SetResourceString(@SCmplxUnexpectedEOS, 'Fim inesperado da string [%s]');
SetResourceString(@SCmplxUnexpectedChars, 'Caracteres Inesperadas');
SetResourceString(@SCmplxErrorSuffix, '%s [%s<?>%s]');
SetResourceString(@hNoSystem, 'Não instalado o Gerenciador de Ajuda.');
SetResourceString(@hNoTopics, 'Não instalado Base de Tópico da Ajuda.');
SetResourceString(@hNoContext, 'Não instalado contexto – sensitivo da Ajuda.');
SetResourceString(@hNoContextFound, 'Help não encontrado para o contexto %d.');
SetResourceString(@hNothingFound, 'Nenhuma Ajuda encontrada para "%s"');
SetResourceString(@hNoTableOfContents, 'Nenhum índice encontrado.');
SetResourceString(@hNoFilterViewer, 'No help viewer that supports filters');
SetResourceString(@sArgumentInvalid, 'Argumento inválido');
SetResourceString(@sArgumentOutOfRange_InvalidHighSurrogate, 'A valid high surrogate character is >= $D800 and <= $DBFF');
SetResourceString(@sArgumentOutOfRange_InvalidLowSurrogate, 'A valid low surrogate character is >= $DC00 and <= $DFFF');
SetResourceString(@sArgumentOutOfRange_Index, 'Index out of range (%d). Must be >= 0 and < %d');
SetResourceString(@sArgumentOutOfRange_StringIndex, 'String index out of range (%d). Must be >= %d and <= %d');
SetResourceString(@sArgumentOutOfRange_InvalidUTF32, 'Invalid UTF32 character value. Must be >= 0 and <= $10FFFF, excluding surrogate pair ranges');
SetResourceString(@sArgument_InvalidHighSurrogate, 'High surrogate char without a following low surrogate char at index: %d. Check that the string is encoded properly');
SetResourceString(@sArgument_InvalidLowSurrogate, 'Low surrogate char without a preceding high surrogate char at index: %d. Check that the string is encoded properly');
SetResourceString(@sArgumentOutOfRange_NeedNonNegValue, 'Argument, %s, must be >= 0');
SetResourceString(@sArgumentOutOfRange_OffLenInvalid, 'Offset and length are invalid for the given array');
SetResourceString(@sInvalidStringAndObjectArrays, 'Length of Strings and Objects arrays must be equal');
SetResourceString(@sSameArrays, 'Source and Destination arrays must not be the same');
SetResourceString(@sNoConstruct, 'Class %s is not intended to be constructed');
SetResourceString(@sCannotCallAcquireOnConditionVar, 'Cannot call Acquire on TConditionVariable. Must call WaitFor with an external TMutex');
SetResourceString(@sInvalidTimeoutValue, 'Invalid Timeout value: %s');
SetResourceString(@sNamedSyncObjectsNotSupported, 'Named synchronization objects not supported on this platform');
SetResourceString(@sInvalidInitialSemaphoreCount, 'Invalid InitialCount: %d');
SetResourceString(@sInvalidMaxSemaphoreCount, 'Invalid MaxCount: %d');
SetResourceString(@sSemaphoreCanceled, 'Invalid operation. Semaphore canceled');
SetResourceString(@sInvalidSemaphoreReleaseCount, 'Invalid semaphore release count: %d');
SetResourceString(@sSemaphoreReachedMaxCount, 'Semaphore reached MaxCount');
SetResourceString(@sErrorCreatingSemaphore, 'Error Creating Semaphore');
SetResourceString(@sErrorCreatingEvent, 'Error Creating Event');
SetResourceString(@sSpinCountOutOfRange, 'SpinCount out of range. Must be between 0 and %d');
SetResourceString(@sCountdownEventCanceled, 'Countdown canceled');
SetResourceString(@sInvalidResetCount, 'Invalid Reset Count: %d');
SetResourceString(@sInvalidInitialCount, 'Invalid Count: %d');
SetResourceString(@sInvalidDecrementCount, 'Invalid Decrement Count: %d');
SetResourceString(@sInvalidIncrementCount, 'Invalid Increment Count: %d');
SetResourceString(@sInvalidDecrementOperation, 'Decrement amount will cause invalid results: Count: %d, CurCount: %d');
SetResourceString(@sInvalidIncrementOperation, 'Count already max: Amount: %d, CurCount: %d');
SetResourceString(@sCountdownAlreadyZero, 'Countdown already reached zero (0)');
SetResourceString(@sTimespanTooLong, 'Timespan too long');
SetResourceString(@sInvalidTimespanDuration, 'The duration cannot be returned because the absolute value exceeds the value of TTimeSpan.MaxValue');
SetResourceString(@sTimespanValueCannotBeNan, 'Value cannot be NaN');
SetResourceString(@sCannotNegateTimespan, 'Negating the minimum value of a Timespan is invalid');
SetResourceString(@sInvalidTimespanFormat, 'Invalid Timespan format');
SetResourceString(@sTimespanElementTooLong, 'Timespan element too long');
{ ************************************************************************* }
{ Distance's family type }
SetResourceString(@SDistanceDescription, 'Distancia');
{ Distance's various conversion types }
SetResourceString(@SMicromicronsDescription, 'Micromicrons');
SetResourceString(@SAngstromsDescription, 'Angstroms');
SetResourceString(@SMillimicronsDescription, 'Millimicrons');
SetResourceString(@SMicronsDescription, 'Microns');
SetResourceString(@SMillimetersDescription, 'Millímetros');
SetResourceString(@SCentimetersDescription, 'Centímetros');
SetResourceString(@SDecimetersDescription, 'Decímetros');
SetResourceString(@SMetersDescription, 'Metros');
SetResourceString(@SDecametersDescription, 'Decametros');
SetResourceString(@SHectometersDescription, 'Hectometros');
SetResourceString(@SKilometersDescription, 'Kilometros');
SetResourceString(@SMegametersDescription, 'Megametros');
SetResourceString(@SGigametersDescription, 'Gigametros');
SetResourceString(@SInchesDescription, 'Polegadas');
SetResourceString(@SFeetDescription, 'Pés');
SetResourceString(@SYardsDescription, 'Jardas');
SetResourceString(@SMilesDescription, 'Milhas');
SetResourceString(@SNauticalMilesDescription, 'Milhas náuticas');
SetResourceString(@SAstronomicalUnitsDescription, 'Unidades astronômicas');
SetResourceString(@SLightYearsDescription, 'Anos luz');
SetResourceString(@SParsecsDescription, 'Parsecs');
SetResourceString(@SCubitsDescription, 'Cubits');
SetResourceString(@SFathomsDescription, 'Fathoms');
SetResourceString(@SFurlongsDescription, 'Furlongs');
SetResourceString(@SHandsDescription, 'mãos');
SetResourceString(@SPacesDescription, 'Passos');
SetResourceString(@SRodsDescription, 'Varas');
SetResourceString(@SChainsDescription, 'Cadeias');
SetResourceString(@SLinksDescription, 'Ligações');
SetResourceString(@SPicasDescription, 'Picas');
SetResourceString(@SPointsDescription, 'Pontos');
{ ************************************************************************* }
{ Area's family type }
SetResourceString(@SAreaDescription, 'Area');
{ Area's various conversion types }
SetResourceString(@SSquareMillimetersDescription, 'Milímetros quadrados');
SetResourceString(@SSquareCentimetersDescription, 'Centímetros quadrados');
SetResourceString(@SSquareDecimetersDescription, 'Decímetros quadrados');
SetResourceString(@SSquareMetersDescription, 'Metros quadrados');
SetResourceString(@SSquareDecametersDescription, 'Decametros quadrados');
SetResourceString(@SSquareHectometersDescription, 'Hectometros quadrados');
SetResourceString(@SSquareKilometersDescription, 'Quilometros quadrados');
SetResourceString(@SSquareInchesDescription, 'Polegadas quadradas');
SetResourceString(@SSquareFeetDescription, 'Pés quadrados');
SetResourceString(@SSquareYardsDescription, 'Jardas quadradas');
SetResourceString(@SSquareMilesDescription, 'Milhas quadradas');
SetResourceString(@SAcresDescription, 'Acres');
SetResourceString(@SCentaresDescription, 'Centares');
SetResourceString(@SAresDescription, 'Ares');
SetResourceString(@SHectaresDescription, 'Hectares');
SetResourceString(@SSquareRodsDescription, 'Varas quadradas');
{ ************************************************************************* }
{ Volume's family type }
SetResourceString(@SVolumeDescription, 'Volume');
{ Volume's various conversion types }
SetResourceString(@SCubicMillimetersDescription, 'Milímetros cúbicos');
SetResourceString(@SCubicCentimetersDescription, 'Centímetros cúbicos');
SetResourceString(@SCubicDecimetersDescription, 'Decímetros cúbicos');
SetResourceString(@SCubicMetersDescription, 'Metros cúbicos');
SetResourceString(@SCubicDecametersDescription, 'Decametros cúbicos');
SetResourceString(@SCubicHectometersDescription, 'Hectometros cúbicos');
SetResourceString(@SCubicKilometersDescription, 'Quilometros cúbicos');
SetResourceString(@SCubicInchesDescription, 'Polegadas cúbicas');
SetResourceString(@SCubicFeetDescription, 'Pés cúbicos');
SetResourceString(@SCubicYardsDescription, 'Jardas cúbicas');
SetResourceString(@SCubicMilesDescription, 'Milhas cúbicas');
SetResourceString(@SMilliLitersDescription, 'Mililitros');
SetResourceString(@SCentiLitersDescription, 'Centilitros');
SetResourceString(@SDeciLitersDescription, 'Decilitros');
SetResourceString(@SLitersDescription, 'Litros');
SetResourceString(@SDecaLitersDescription, 'Decalitros');
SetResourceString(@SHectoLitersDescription, 'Hectolitros');
SetResourceString(@SKiloLitersDescription, 'Quilolitros');
SetResourceString(@SAcreFeetDescription, 'Acres de pés');
SetResourceString(@SAcreInchesDescription, 'Acres de polegadas');
SetResourceString(@SCordsDescription, 'Cordas');
SetResourceString(@SCordFeetDescription, 'Pés de cordas');
SetResourceString(@SDecisteresDescription, 'DeciBois');
SetResourceString(@SSteresDescription, 'Bois');
SetResourceString(@SDecasteresDescription, 'DecaBois');
{ American Fluid Units }
SetResourceString(@SFluidGallonsDescription, 'Galões fluidos');
SetResourceString(@SFluidQuartsDescription, 'Quartos fluidos');
SetResourceString(@SFluidPintsDescription, 'Quartilhos fluidos');
SetResourceString(@SFluidCupsDescription, 'Xícaras fluidas');
SetResourceString(@SFluidGillsDescription, 'Brânquias fluidas');
SetResourceString(@SFluidOuncesDescription, 'Onças fluidas');
SetResourceString(@SFluidTablespoonsDescription, 'Colheres de sopa');
SetResourceString(@SFluidTeaspoonsDescription, 'Colheres de chá');
{ American Dry Units }
SetResourceString(@SDryGallonsDescription, 'Galões secos');
SetResourceString(@SDryQuartsDescription, 'Quartos secos');
SetResourceString(@SDryPintsDescription, 'Quartilhos secos');
SetResourceString(@SDryPecksDescription, 'Bicadas secas');
SetResourceString(@SDryBucketsDescription, 'Baldes secos');
SetResourceString(@SDryBushelsDescription, 'Alqueires secos');
{ English Imperial Fluid/Dry Units }
SetResourceString(@SUKGallonsDescription, 'Galões inglêses');
SetResourceString(@SUKPottlesDescription, 'Potes inglêses');
SetResourceString(@SUKQuartsDescription, 'Quartos inglêses');
SetResourceString(@SUKPintsDescription, 'Quatrilhos inglêses');
SetResourceString(@SUKGillsDescription, 'Brânquia inglêsas');
SetResourceString(@SUKOuncesDescription, 'Onças inglêsas');
SetResourceString(@SUKPecksDescription, 'Bicadas inglêsas');
SetResourceString(@SUKBucketsDescription, 'Baldes inglêses');
SetResourceString(@SUKBushelsDescription, 'Alqueires inglêses');
{ ************************************************************************* }
{ Mass's family type }
SetResourceString(@SMassDescription, 'Massa');
{ Mass's various conversion types }
SetResourceString(@SNanogramsDescription, 'Nanogramas');
SetResourceString(@SMicrogramsDescription, 'Microgramas');
SetResourceString(@SMilligramsDescription, 'Miligramas');
SetResourceString(@SCentigramsDescription, 'Centigramas');
SetResourceString(@SDecigramsDescription, 'Decigramas');
SetResourceString(@SGramsDescription, 'Gramas');
SetResourceString(@SDecagramsDescription, 'Decagramas');
SetResourceString(@SHectogramsDescription, 'Hectogramas');
SetResourceString(@SKilogramsDescription, 'Quiogramas');
SetResourceString(@SMetricTonsDescription, 'Toneladas métricas');
SetResourceString(@SDramsDescription, 'Dracmas');
SetResourceString(@SGrainsDescription, 'Grãos');
SetResourceString(@STonsDescription, 'Toneladas');
SetResourceString(@SLongTonsDescription, 'Toneladas longas');
SetResourceString(@SOuncesDescription, 'Onças');
SetResourceString(@SPoundsDescription, 'Libras');
SetResourceString(@SStonesDescription, 'Pedras');
{ ************************************************************************* }
{ Temperature's family type }
SetResourceString(@STemperatureDescription, 'Temperatura');
{ Temperature's various conversion types }
SetResourceString(@SCelsiusDescription, 'Celsius');
SetResourceString(@SKelvinDescription, 'Kelvin');
SetResourceString(@SFahrenheitDescription, 'Fahrenheit');
SetResourceString(@SRankineDescription, 'Rankine');
SetResourceString(@SReaumurDescription, 'Reaumur');
{ ************************************************************************* }
{ Time's family type }
SetResourceString(@STimeDescription, 'Tempo');
{ Time's various conversion types }
SetResourceString(@SMilliSecondsDescription, 'Milisegundos');
SetResourceString(@SSecondsDescription, 'Segundos');
SetResourceString(@SMinutesDescription, 'Minutos');
SetResourceString(@SHoursDescription, 'Horas');
SetResourceString(@SDaysDescription, 'Dias');
SetResourceString(@SWeeksDescription, 'Semanas');
SetResourceString(@SFortnightsDescription, 'Quinzenas');
SetResourceString(@SMonthsDescription, 'Meses');
SetResourceString(@SYearsDescription, 'Anos');
SetResourceString(@SDecadesDescription, 'Decadas');
SetResourceString(@SCenturiesDescription, 'Centurias');
SetResourceString(@SMillenniaDescription, 'Milênio');
SetResourceString(@SDateTimeDescription, 'Data e Hora');
SetResourceString(@SJulianDateDescription, 'Data Juliana');
SetResourceString(@SModifiedJulianDateDescription, 'Data Juliana modificada');
// SetResourceString(@SInvalidDate, '"%s" não é uma data válida');
// SetResourceString(@SInvalidDateTime, '"%s" não é um valor de Data e Hora válidos');
// SetResourceString(@SInvalidInteger, '"%s" não é um valor inteiro válido');
// SetResourceString(@SInvalidTime, '"%s" não é uma hora válida');
// SetResourceString(@STimeEncodeError, 'Argumento para codificação de hora inválido');
SetResourceString(@SGUIDAlreadyDefined, 'GUID ''%s'' was previously registered');
SetResourceString(@SNoComComponent, 'Constructing COM object ''%s'' for which there is no wrapper component');
SetResourceString(@SNoComClass, '%s.GetComClass returned nil');
SetResourceString(@SNoCOMClassSpecified, 'No ComClass specified');
SetResourceString(@SNoCOMClassesRegistered, 'No COM classes have been registered');
SetResourceString(@SNoContext, 'No context-sensitive help installed');
SetResourceString(@SNoContextFound, 'No help found for context %d');
SetResourceString(@SNoIndex, 'Unable to open Index');
SetResourceString(@SNoSearch, 'Unable to open Search');
SetResourceString(@SNoTableOfContents, 'Unable to find a Table of Contents');
SetResourceString(@SNoTopics, 'No topic-based help system installed');
SetResourceString(@SNothingFound, 'No help found for %s');
SetResourceString(@SMethodNotFound, 'Method %s of class %s not found');
SetResourceString(@STypeMisMatch, 'Type mismatch in parameter %d for method %s');
SetResourceString(@SInvalidDispID, 'Invalid DispID for parameter %d in method %s');
SetResourceString(@SParamRequired, 'Parameter %d required for method %s');
SetResourceString(@SMethodOver, 'Method definition for %s has over %d parameters');
SetResourceString(@STooManyParams, 'Too many parameters for method %s');
SetResourceString(@SNoRTTIInfoType, 'Unable to invoke method %s that use unpublished type');
SetResourceString(@SResultIsExtended, '10bytes-Extended type in method %s'' return type is not supported');
SetResourceString(@SParamIsExtended, '10bytes-Extended type in parameter %d in method %s is not supported');
SetResourceString(@SArgumentOutOfRange, 'Argument out of range');
SetResourceString(@SArgumentNil, 'Argument must not be nil');
SetResourceString(@SErrorCantModifyWhileIterating, 'Cannot modify a collection while iterating');
SetResourceString(@SUnbalancedOperation, 'Unbalanced stack or queue operation');
SetResourceString(@SGenericItemNotFound, 'Item not found');
SetResourceString(@SGenericDuplicateItem, 'Duplicates not allowed');
SetResourceString(@SSpinLockInvalidOperation, 'Thread tracking isn''t enabled');
SetResourceString(@SSpinLockReEntered, 'SpinLock has been re-entered on the same thread');
SetResourceString(@SSpinLockNotOwned, 'SpinLock not owned by the current thread');
SetResourceString(@SInsufficientRtti, 'Insufficient RTTI available to support this operation');
SetResourceString(@SParameterCountMismatch, 'Parameter count mismatch');
SetResourceString(@SParameterCountExceeded, 'Parameter count exceeded');
SetResourceString(@SConversionError, 'Incompatible type');
SetResourceString(@SNonPublicType, 'Type ''%s'' is not declared in the interface section of a unit');
SetResourceString(@SByRefArgMismatch, 'VAR and OUT arguments must match parameter type exactly');
SetResourceString(@SInsufficientReadBuffer, 'Insufficient buffer for requested data');
SetResourceString(@SInvalid7BitEncodedInteger, 'Invalid 7 bit integer stream encoding');
SetResourceString(@SNoSurrogates, 'Surrogates not allowed as a single char');
SetResourceString(@SInvalidStringLength, 'Invalid string length');
SetResourceString(@SReadPastEndOfStream, 'Attempt to read past end of stream');
SetResourceString(@SInvalidGuidArray, 'Byte array for GUID must be exactly %d bytes long');
SetResourceString(@SServiceNotFound, 'Specified Login Credential Service not found');
{ Class group report strings }
SetResourceString(@sClassGroupHeader, 'Group[%d] - Active: %s');
SetResourceString(@sGroupClassesHeader, ' Group Classes');
SetResourceString(@sClassListHeader, ' Classes');
SetResourceString(@sClassAliasesHeader, ' Class Aliases');
{$IFDEF MACOS}
SetResourceString(@sInvalidConversion, 'Invalid conversion from %s to %s');
SetResourceString(@sInvalidPListType, 'Invalid CFPropertyList type');
SetResourceString(@sConvertArrayArray, 'Cannot convert CFArray of CFArray');
SetResourceString(@sConvertArrayDictionary, 'Cannot convert CFArray of CFDictionary');
SetResourceString(@sConvertDictionary, 'Cannot translate CFDictionary to Delphi type');
SetResourceString(@sKeyNotPresent, 'Key not present');
SetResourceString(@SFailedClassCreate, 'Unable to create class ''%s''');
SetResourceString(@SObjCSelectorNotFound, 'Selector ''%s'' not found');
SetResourceString(@SObjCClassRegistrationFailed, 'Unable to register class ''%s''');
SetResourceString(@SInvalidObjCType, 'The type ''%s'' is not supported with ObjectiveC interoperability');
SetResourceString(@SFatalInvoke, 'Fatal error during function invocation');
{$ENDIF MACOS}
{$IFDEF MSWINDOWS}
{ TOSVersion strings }
SetResourceString(@SVersionStr, '%s (Version %d.%d, Build %d, %5:s)');
SetResourceString(@SSPVersionStr, '%s Service Pack %4:d (Version %1:d.%2:d, Build %3:d, %5:s)');
SetResourceString(@SVersion32, '32-bit Edition');
SetResourceString(@SVersion64, '64-bit Edition');
SetResourceString(@SWindows, 'Windows');
SetResourceString(@SWindowsVista, 'Windows Vista');
SetResourceString(@SWindowsServer2008, 'Windows Server 2008');
SetResourceString(@SWindows7, 'Windows 7');
SetResourceString(@SWindowsServer2008R2, 'Windows Server 2008 R2');
SetResourceString(@SWindows2000, 'Windows 2000');
SetResourceString(@SWindowsXP, 'Windows XP');
SetResourceString(@SWindowsServer2003, 'Windows Server 2003');
SetResourceString(@SWindowsServer2003R2, 'Windows Server 2003 R2');
SetResourceString(@SWindowsServer2012, 'Windows Server 2012');
SetResourceString(@SWindowsServer2012R2, 'Windows Server 2012 R2');
SetResourceString(@SWindows8, 'Windows 8');
SetResourceString(@SWindows8Point1, 'Windows 8.1');
SetResourceString(@SWindows10, 'Windows 10');
SetResourceString(@SItaskbarInterfaceException, '%s interface is not supported on this OS version');
SetResourceString(@SHookException, 'Could not hook messages, buttons and preview events will not work');
SetResourceString(@SInitializeException, 'Could not initialize taskbar. Error: %d');
SetResourceString(@SInstanceException, 'There is another taskbar control instance');
SetResourceString(@SButtonsLimitException, 'Windows taskbar only supports %d buttons on preview tabs');
SetResourceString(@SCouldNotRegisterTabException, 'Could not register tab. Error %d');
SetResourceString(@SInvalidProgressValueException, '%d is incorrect. Should be between 0 and %d');
SetResourceString(@SThumbPreviewException, 'Failed to set bitmap as thumbnail preview. Error: %d');
SetResourceString(@SBitmapPreviewException, 'Failed to set bitmap as preview. Error: %d');
{ WinRT support strings }
SetResourceString(@SWinRTNoRTTI, 'No RTTI information found for class %s');
SetResourceString(@SWinRTInstanceError, 'Cannot create instance of class %s');
SetResourceString(@SWinRTICreatedError, 'The created instance of class %s is wrong');
SetResourceString(@SWinRTHStringError, 'Error creating HString for %s');
SetResourceString(@SWinRTFactoryError, 'Cannot get factory for class %s');
SetResourceString(@SWinRTWrongFactoryError, 'The factory obtained for %s is wrong');
SetResourceString(@SWinRTInteropError, 'Cannot create interop class');
{$ENDIF}
{$IF defined(MACOS) or defined(ANDROID) or defined(LINUX)}
SetResourceString(@SVersionStr, '%s (Version %d.%d.%d)');
{$ENDIF}
{ Zip Strings}
SetResourceString(@SZipErrorRead , 'Error reading zip file');
SetResourceString(@SZipErrorWrite , 'Error writing zip file');
SetResourceString(@SZipInvalidLocalHeader , 'Invalid Zip Local Header signature');
SetResourceString(@SZipInvalidCentralHeader, 'Invalid Zip Central Header signature');
SetResourceString(@SZipNotSupported , 'Support for compression method not registered: %s');
SetResourceString(@SZipNotOpen , 'File must be open');
SetResourceString(@SZipNoWrite , 'File must be open for writing');
SetResourceString(@SZipNoRead , 'File must be open for reading');
SetResourceString(@SZipNotEmpty , 'Zip file must be empty');
SetResourceString(@SZipFileNameEmpty , 'File name must not be empty');
SetResourceString(@sObserverUnsupported, 'Observer is not supported');
SetResourceString(@sObserverMultipleSingleCast, 'Cannot have multiple single cast observers added to the observers collection');
SetResourceString(@sObserverNoInterface, 'The object does not implement the observer interface');
SetResourceString(@sObserverNoSinglecastFound, 'No single cast observer with ID %d was added to the observer collection');
SetResourceString(@sObserverNoMulticastFound, 'No multi cast observer with ID %d was added to the observer collection');
SetResourceString(@sObserverNotAvailable, 'Observer is not available');
SetResourceString(@SGeocodeMultipleRequests, 'Cannot initiate two or more geocoding requests at the same time');
SetResourceString(@SLocationSensorStarted, 'The location sensor is started');
SetResourceString(@SSensorIndexError, 'The sensor on the specified index (%d) is not found');
{IFDEF MACOS}
SetResourceString(@SLocationServiceUnauthorized, 'Unauthorized to use location services');
SetResourceString(@SLocationServiceDisabled, 'Location services are disabled');
{ENDIF}
{$IFDEF ANDROID}
SetResourceString(@SAssetFileNotFound, 'Cannot deploy, "%s" file not found in assets');
SetResourceString(@SExternalExtorageNotAvailable, 'Cannot have access to external storage on device');
{$ENDIF}
{ System.DateUtils }
SetResourceString(@SInvalidDateString, 'Invalid date string: %s');
SetResourceString(@SInvalidTimeString, 'Invalid time string: %s');
SetResourceString(@SInvalidOffsetString, 'Invalid time Offset string: %s');
{ System.Devices }
SetResourceString(@sCannotManuallyConstructDevice, 'Manual construction of TDeviceInfo is not supported');
SetResourceString(@sAttributeExists, 'Attribute ''%s'' already exists');
SetResourceString(@sDeviceExists, 'Device ''%s'' already exists');
{ System.Hash }
SetResourceString(@SHashCanNotUpdateMD5, 'MD5: Cannot update a finalized hash');
SetResourceString(@SHashCanNotUpdateSHA1, 'SHA1: Cannot update a finalized hash');
SetResourceString(@SHashCanNotUpdateSHA2, 'SHA2: Cannot update a finalized hash');
{ System.NetEncoding }
SetResourceString(@sErrorDecodingURLText, 'Error decoding URL style (%%XX) encoded string at position %d');
SetResourceString(@sInvalidURLEncodedChar, 'Invalid URL encoded character (%s) at position %d');
SetResourceString(@sInvalidHTMLEncodedChar, 'Invalid HTML encoded character (%s) at position %d');
{ System.Threading }
SetResourceString(@sStopAfterBreak, 'The Break method was previously called. Break and Stop may not be used in combination in iterations of the same loop');
SetResourceString(@sBreakAfterStop, 'The Stop method was previously called. Break and Stop may not be used in combination in iterations of the same loop');
SetResourceString(@sInvalidTaskConstruction, 'Cannot construct an ITask in this manner');
SetResourceString(@sEmptyJoinTaskList, 'List of tasks to Join method empty');
SetResourceString(@sWaitNilTask, 'At least one task in array nil');
SetResourceString(@sCannotStartCompletedTask, 'Cannot start a task that has already completed');
SetResourceString(@sOneOrMoreTasksCancelled, 'One or more tasks were cancelled');
SetResourceString(@sDefaultAggregateExceptionMsg, 'One or more errors occurred');
{ System.Types }
SetResourceString(@sMustWaitOnOneEvent, 'Must wait on at least one event');
{ TComponent.BeginInvoke }
SetResourceString(@sBeginInvokeDestroying, 'Cannot call BeginInvoke on a TComponent in the process of destruction');
{ System.ShareContract }
SetResourceString(@SShareContractNotAvailable, 'ShareContract not available');
SetResourceString(@SShareContractNotSupported, 'Sharing not supported under %s');
SetResourceString(@SShareContractNotInitialized, 'TShareContract.OnProcessMessages event must be assigned first');
{ WinRT.Bluetooth }
SetResourceString(@SNoAsyncInfo, 'The object does not implement the IAsyncInfo interface');
end;
End. |
PROGRAM TestBin;
{$I FLOAT.INC}
{$DEFINE DEBUG}
uses MathLib0;
CONST
OutToDisk = FALSE;
initial_default = 0.1;
v_default = 0.2;
VAR
out : text;
steps : WORD;
initial, { starting value }
v, { volatility in percent per period }
Result : Float;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE GetParams;
VAR
err : INTEGER;
BEGIN
val(paramstr(1),v,err);
IF err > 0 THEN v := v_default;
val(paramstr(2),initial,err);
IF err > 0 THEN initial := initial_default;
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
FUNCTION ExpectedValue ( Steps : WORD; { periods }
intial, { one period rate }
Vol : Float ) : Float;
CONST
MaxSteps = 100;
MaxStepsx2 = 201;
VAR
BondPrices : ARRAY[1..MaxSteps] OF FLOAT;
EndRate : ARRAY[1..MaxStepsx2] OF FLOAT;
p, pComp : FLOAT; { prob. of an up move and it's complement }
UP, DN,
DiscRate,
move : FLOAT;
StepsPlus1,
j, k, i : WORD;
BEGIN
If Steps > MaxSteps THEN Steps := MaxSteps;
StepsPlus1 := Steps + 1;
{ adjust inputs for time and precompute some constants }
UP := 1 + Vol;
DN := 1/UP;
IF Vol = 0.0 THEN
p := 0.5
ELSE
p := (1-dn)/(Up-Dn); { will be close to 0.5 }
pComp := 1 - p;
{ make arrays of ending values and intrinsic values }
EndRate[StepsPlus1] := 1+Initial;
move := 1;
FOR i := 1 to Steps DO BEGIN
move := move * up; { equiv to (1+up) raised to the i }
j := StepsPlus1 + i;
k := StepsPlus1 - i;
EndRate[j] := 1 + (Initial * move);
EndRate[k] := 1 + (Initial / move);
END; {FOR}
{ assign ending rates as terminal bond prices }
FOR i := 1 to StepsPlus1 DO BEGIN
BondPrices[i] := 1 / EndRate[2*i-1];
END;
{ Works backward down the binomial tree }
FOR i := Steps DOWNTO 1 DO BEGIN
FOR j := 1 to i DO BEGIN
k := Steps - i + 2*j;
DiscRate := EndRate[k];
{ expected values discounted one period }
BondPrices[j] := ( p* BondPrices[j+1] +
pComp * BondPrices[j] ) / DiscRate;
END;
END;
ExpectedValue := BondPrices[1];
END; { Expected Value }
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
BEGIN
GetParams;
IF OutToDisk THEN BEGIN
Assign(out,'f:\art\test2.prn');
Rewrite(out);
END;
FOR steps := 1 TO 5 DO BEGIN
Result := ExpectedValue(steps,initial,v);
IF OutToDisk THEN
Writeln(out,'Steps ',steps:2,' Result ',Result:8:3)
ELSE
Writeln('Steps ',steps:2,' Result ',power(1/Result,1/(Steps+1))-1:8:3);
END;
IF OutToDisk THEN Close(out);
END. |
unit ULogin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, Vcl.Imaging.GIFImg, Vcl.ExtCtrls, Data.DB, MemDS, Vcl.Imaging.pngimage, Vcl.Menus,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Vcl.StdCtrls, Vcl.Imaging.jpeg, ShellApi;
type
TFLogin = class(TForm)
UniPanel1: TPanel;
eddeLogin: TEdit;
eddeSenha: TEdit;
lbdeLogin: TLabel;
lbdeSenha: TLabel;
btEntrar: TButton;
lbCopyright: TLabel;
lbAcessoRestrito: TLabel;
btFechar: TButton;
imLogoCliente: TImage;
procedure btEntrarClick(Sender: TObject);
procedure eddeLoginKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure eddeSenhaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btFecharClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FLogin: TFLogin;
implementation
{$R *.dfm}
uses
uDmERP, UTelaInicial, UTrocarSenha, UFuncoes, UHashes;
procedure TFLogin.btEntrarClick(Sender: TObject);
begin
if Trim(eddeLogin.Text) = '' then
Aviso('Nome de usuário não informado.')
else if Trim(eddeSenha.Text) = '' then
Aviso('Senha não informada.')
else if (LowerCase(Trim(eddeSenha.Text)) = 'erp123') then
begin
DmERP.qyUsuarioPesq.Close;
DmERP.qyUsuarioPesq.MacroByName('filtro').Value := ' WHERE LOWER(deLogin) = ' + QuotedStr(LowerCase(eddeLogin.Text)) +
' AND deSenha = ''erp123'' ' +
' AND flAtivo = ''S'' ';
DmERP.qyUsuarioPesq.Open;
if DmERP.qyUsuarioPesq.IsEmpty then
Aviso('Usuário inválido.')
else
begin
FTrocarSenha := TFTrocarSenha.Create(Application);
try
FTrocarSenha.eddeLogin.Text := Trim(eddeLogin.Text);
FTrocarSenha.ShowModal;
finally
FreeAndNil(FTrocarSenha);
end;
end;
end
else
begin
DmERP.qyUsuarioPesq.Close;
DmERP.qyUsuarioPesq.MacroByName('filtro').Value := ' WHERE LOWER(deLogin) = ' + QuotedStr(LowerCase(eddeLogin.Text)) +
' AND deSenha = ' + QuotedStr(CalcHash2(eddeSenha.Text, haSHA1));
DmERP.qyUsuarioPesq.Open;
if DmERP.qyUsuarioPesq.IsEmpty then
Aviso('Usuário ou senha inválido.')
else
begin
if DmERP.qyUsuarioPesq.FieldByName('flAtivo').AsString <> 'S' then
Aviso('Usuário informado está inativo.')
else
begin
FTelaInicial.FcdUsuario := DmERP.qyUsuarioPesq.FieldByName('cdUsuario').AsInteger;
FTelaInicial.FnmUsuario := DmERP.qyUsuarioPesq.FieldByName('nmUsuario').AsString;
FTelaInicial.FdeLogin := DmERP.qyUsuarioPesq.FieldByName('deLogin').AsString;
FTelaInicial.FdeSenha := DmERP.qyUsuarioPesq.FieldByName('deSenha').AsString;
FTelaInicial.FdeEmail := DmERP.qyUsuarioPesq.FieldByName('deEmail').AsString;
FTelaInicial.FcdSetorUsuario := 0;
FTelaInicial.FdeSetorUsuario := '';
if not DmERP.qyUsuarioPesq.FieldByName('cdSetor').IsNull then
begin
FTelaInicial.FcdSetorUsuario := DmERP.qyUsuarioPesq.FieldByName('cdSetor').AsInteger;
FTelaInicial.FdeSetorUsuario := DmERP.qyUsuarioPesq.FieldByName('deSetor').AsString;
end;
FTelaInicial.FcdColaborador := 0;
if not DmERP.qyUsuarioPesq.FieldByName('cdColaborador').IsNull then
FTelaInicial.FcdColaborador := DmERP.qyUsuarioPesq.FieldByName('cdColaborador').AsInteger;
FTelaInicial.FbLoginOK := True;
FTelaInicial.lbInfoSistema.Caption := 'Usuário: ' + FTelaInicial.FnmUsuario;
Close;
end;
end;
end;
end;
procedure TFLogin.eddeSenhaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
btEntrar.Click;
end;
procedure TFLogin.FormCreate(Sender: TObject);
var
stConfig : TStringList;
sVersaoAtual : String;
begin
if not (FileExists(ExtractFilePath(Application.ExeName) + 'ERP.ini')) then
begin
Erro('Arquivo de configuração não encontrado.');
Application.Terminate;
end
else
begin
stConfig := TStringList.Create;
stConfig.LoadFromFile(ExtractFilePath(Application.ExeName) + 'ERP.ini');
if stConfig.Count <> FiNumLinhasConfigERP then
begin
Erro('Arquivo de configuração incorreto.');
Application.Terminate;
end
else
begin
sVersaoAtual := GetBuildInfo;
FTelaInicial.FsPathServidor := stConfig.Values['PathServidor'];
FTelaInicial.FsNomeClienteERP := stConfig.Values['NomeClienteERP'];
Self.Caption := '..: ' + FTelaInicial.FsNomeClienteERP + ' :.. | ' +
FsNomeSistema + ' - Versão: ' + sVersaoAtual;
FTelaInicial.Caption := Self.Caption;
if (not FileExists(ExtractFilePath(Application.ExeName) + '\LogoLogin.jpg')) and
(FileExists(FTelaInicial.FsPathServidor + '\LogoLogin.jpg')) then
CopyFile(PWideChar(FTelaInicial.FsPathServidor + '\LogoLogin.jpg'), PWideChar(ExtractFilePath(Application.ExeName) + 'LogoLogin.jpg'), True);
if (not FileExists(ExtractFilePath(Application.ExeName) + '\LogoERP.jpg')) and
(FileExists(FTelaInicial.FsPathServidor + '\LogoERP.jpg')) then
CopyFile(PWideChar(FTelaInicial.FsPathServidor + '\LogoERP.jpg'), PWideChar(ExtractFilePath(Application.ExeName) + 'LogoERP.jpg'), True);
stConfig.Clear;
stConfig.LoadFromFile(FTelaInicial.FsPathServidor + '\VersaoERP.ini');
if (stConfig.Count > 0) and (sVersaoAtual <> stConfig.Values['VersaoERP']) and
(FileExists(FTelaInicial.FsPathServidor + '\ERPnovo.exe')) then
begin
// CopyFile(PChar(sPathServidor + '\ERPnovo.exe'), PChar(ExtractFilePath(Application.ExeName) + 'ERPnovo.exe'), False);
Aviso('*** O sistema será atualizado! ***' + #13 + 'Pressione "OK" para continuar.');
stConfig.Clear;
// stConfig.Add('ping -n 10 -w 1000 0.0.0.1 > nul');
// stConfig.Add('tskill ERP /a'); //taskkill /F /IM ERP.exe /T
// stConfig.Add('ping -n 3 -w 1000 0.0.0.1 > nul');
// stConfig.Add('del ' + ExtractFilePath(Application.ExeName) + 'ERP.exe');
// stConfig.Add('ren ' + ExtractFilePath(Application.ExeName) + 'ERPnovo.exe ERP.exe');
// stConfig.Add(ExtractFilePath(Application.ExeName) + 'ERP.exe');
// stConfig.SaveToFile(ExtractFilePath(Application.ExeName) + 'Update.bat');
// WinExec(PAnsiChar(ExtractFilePath(Application.ExeName) + 'Update.bat'), SW_HIDE);
// RunAsAdmin(Handle, ExtractFilePath(Application.ExeName) + 'Update.bat', '');
ShellExecute(Handle, 'open', PWideChar(ExtractFilePath(Application.ExeName) + 'UpdateERP.exe'), '', '', SW_HIDE);
Application.Terminate;
end;
end;
if Assigned(stConfig) then
FreeAndNil(stConfig);
end;
end;
procedure TFLogin.FormShow(Sender: TObject);
{var
jpg : TJPEGImage;
bmp : TBitmap;
X, Y: Integer; }
begin
if (FileExists(ExtractFilePath(Application.ExeName) + 'LogoLogin.jpg')) then
begin
imLogoCliente.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + 'LogoLogin.jpg');
{
bmp := TBitmap.Create;
jpg := TJPEGImage.Create;
jpg.LoadFromFile(ExtractFilePath(Application.ExeName) + 'LogoLogin.jpg');
bmp.Assign(jpg);
jpg.Destroy;
bmp.PixelFormat := pf24bit;
// AddWatermark(bmp, 0.5, 'i was here');
Canvas.Draw(0, 0, bmp);
brush.style := bsClear;
for y := 0 to imLogoCliente.height - 1 do
for x := 0 to imLogoCliente.width - 1 do
begin
if (x mod 2)=(y mod 2) then
imLogoCliente.canvas.pixels[x, y] := clWhite;
end;
imLogoCliente.Picture.Assign(bmp);
bmp.Destroy;
}
end;
end;
procedure TFLogin.btFecharClick(Sender: TObject);
begin
Self.Close;
end;
procedure TFLogin.eddeLoginKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
btEntrar.Click;
end;
end.
|
unit Demo.Main;
interface
uses
WHATWG.Console, WHATWG.XHR, ECMA.TypedArray, W3C.DOM4, W3C.Html5,
W3C.FileAPI, W3C.WebAudio, SimpleSofaFile,
Demo.Framework, Demo.Audio, Demo.Hrtf;
type
TFileSelect = class(TDivElement)
private
FInputFile: TInputFileElement;
public
procedure AfterConstructor; override;
property InputFile: TInputFileElement read FInputFile;
property OnLoad: procedure(Buffer: JArrayBuffer);
end;
THeader = class(TDivElement)
private
FHeading: TH1Element;
FFileSelect: TFileSelect;
public
procedure AfterConstructor; override;
property FileSelect: TFileSelect read FFileSelect;
end;
TPlane2D = class(TCanvas2dElement)
public
procedure Resize; override;
procedure Paint;
end;
TGlyph = class(TImageElement)
private
FName: String;
public
constructor Create(Owner: IHtmlElementOwner; TrackName: String); overload;
property Name: String read FName;
end;
TMainScreen = class(TDivElement)
private
FHeader: THeader;
FTextArea: TTextAreaElement;
FSofaFile: TSofaFile;
FPlane2D: TPlane2D;
FGlyphs: array of TGlyph;
FTracks: array of TTrack;
FHrtfs: THrtfs;
procedure AddText(Text: String);
procedure LoadSofaFile(Buffer: JArrayBuffer);
procedure PrepareHrtfs;
procedure RandomizeHrtfPositions;
procedure PrintFileInformation;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
procedure InitializeAudioEngine;
end;
var
MainScreen: TMainScreen;
implementation
uses
W3C.CSSOMView;
const
CTrackNames = ['Vocal', 'Piano', 'Bass', 'Drums'];
{ TFileSelect }
procedure TFileSelect.AfterConstructor;
begin
FInputFile := TInputFileElement.Create(Self as IHtmlElementOwner);
FInputFile.InputElement.accept := '.sofa';
FInputFile.InputElement.addEventListener('change',
lambda(Event: JEvent)
var Files : JFileList = JFileList(Variant(Event.target).files);
var Reader := JFileReader.Create;
Reader.onload := lambda
if Assigned(OnLoad) then
OnLoad(JArrayBuffer(Reader.result));
Result := nil;
end;
Reader.readAsArrayBuffer(Files[0]);
end);
end;
{ THeader }
procedure THeader.AfterConstructor;
begin
FHeading := TH1Element.Create(Self as IHtmlElementOwner);
FHeading.Text := 'WebSofa Demo';
FFileSelect := TFileSelect.Create(Self as IHtmlElementOwner);
end;
{ TPlane2D }
procedure TPlane2D.Resize;
begin
var R := CanvasElement.getBoundingClientRect;
var MinSize := Round(min(Window.innerWidth - R.left, Window.innerHeight - R.top));
Style.width := IntToStr(MinSize) + 'px';
Style.height := IntToStr(MinSize) + 'px';
R := CanvasElement.getBoundingClientRect;
CanvasElement.Width := Round(Application.PixelRatio * R.width);
CanvasElement.Height := Round(Application.PixelRatio * R.height);
Paint;
end;
procedure TPlane2D.Paint;
begin
var Size := Min(CanvasElement.Width, CanvasElement.Height);
Context.strokeStyle := '#CA3631';
Context.lineWidth := 4;
var R := 0.5 * Size - Context.lineWidth;
Context.beginPath;
Context.arc(0.5 * Size, 0.5 * Size, R, 0, 2 * Pi);
Context.stroke;
Context.beginPath;
Context.moveTo(0.5 * Size, 0.5 * Size - 0.07 * R);
Context.arc(0.5 * Size, 0.5 * Size, 0.05 * R, 0.3 - 0.5 * Pi, 2 * Pi - 0.3 - 0.5 * Pi);
Context.ClosePath;
Context.stroke;
end;
{ TGlyph }
constructor TGlyph.Create(Owner: IHtmlElementOwner; TrackName: String);
begin
inherited Create(Owner);
FName := TrackName;
ImageElement.src := 'SVG\' + TrackName + '.svg';
ImageElement.style.display := 'none';
end;
{ TMainScreen }
constructor TMainScreen.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
MainScreen := Self;
DivElement.ID := 'main';
// Create Header
FHeader := THeader.Create(Self as IHtmlElementOwner);
FHeader.FileSelect.OnLoad := lambda(Buffer: JArrayBuffer)
LoadSofaFile(Buffer);
end;
FTextArea := TTextAreaElement.Create(Self as IHtmlElementOwner);
FTextArea.TextAreaElement.Rows := 10;
FTextArea.TextAreaElement.readOnly := True;
FTextArea.TextAreaElement.placeholder := 'please load any SOFA file first';
FPlane2D := TPlane2D.Create(Self as IHtmlElementOwner);
FPlane2D.Resize;
FPlane2D.CanvasElement.style.display := 'none';
Window.addEventListener('resize', lambda
FPlane2D.Resize;
end);
InitializeAudioEngine;
(*
var Request := JXMLHttpRequest.Create;
Request.onload := lambda
LoadSofaFile(JArrayBuffer(Request.response));
Result := nil;
end;
Request.responseType := 'arraybuffer';
Request.open('GET', 'default.sofa', true);
Request.send;
*)
end;
procedure TMainScreen.LoadSofaFile(Buffer: JArrayBuffer);
begin
FSofaFile := sofaLoadFile(Buffer);
PrintFileInformation;
PrepareHrtfs;
end;
procedure TMainScreen.InitializeAudioEngine;
begin
GAudioContext.sampleRate := 44100;
for var TrackName in CTrackNames do
begin
var Track := TTrack.Create(TrackName, lambda(Sender: TObject) end);
// loop track if it ends
Track.OnEnded := lambda(Sender: TObject);
TTrack(Sender).AudioBufferSource.Start(GAudioContext.currentTime);
end;
FTracks.Add(Track);
FGlyphs.Add(TGlyph.Create(Self as IHtmlElementOwner, TrackName));
end;
end;
procedure TMainScreen.PrintFileInformation;
begin
FTextArea.Value := '';
procedure PrintAttribute(Name: String);
begin
if FSofaFile.Attributes.has(Name) then
if FSofaFile.Attributes.get(Name) <> '' then
AddText(Name + ': ' + FSofaFile.Attributes.get(Name));
end;
PrintAttribute('Title');
PrintAttribute('DataType');
PrintAttribute('RoomType');
PrintAttribute('RoomLocation');
PrintAttribute('DateCreated');
PrintAttribute('DateModified');
PrintAttribute('APIName');
PrintAttribute('APIVersion');
PrintAttribute('AuthorContact');
PrintAttribute('Organization');
PrintAttribute('License');
PrintAttribute('ApplicationName');
PrintAttribute('Comment');
PrintAttribute('History');
PrintAttribute('References');
PrintAttribute('Origin');
AddText('');
AddText('Number of Measurements: ' + IntToStr(FSofaFile.NumberOfMeasurements));
AddText('Number of Receivers: ' + IntToStr(FSofaFile.NumberOfReceivers));
AddText('Number of Emitters: ' + IntToStr(FSofaFile.NumberOfEmitters));
AddText('Number of DataSamples: ' + IntToStr(FSofaFile.NumberOfDataSamples));
AddText('SampleRate: ' + FloatToStr(FSofaFile.SampleRate[0]));
AddText('Delay: ' + FloatToStr(FSofaFile.Delay[0]));
end;
procedure TMainScreen.AddText(Text: String);
begin
FTextArea.Value := FTextArea.Value + Text + #13;
end;
procedure TMainScreen.PrepareHrtfs;
begin
FHrtfs := THrtfs.Create(FSofaFile);
RandomizeHrtfPositions;
end;
procedure TMainScreen.RandomizeHrtfPositions;
begin
FPlane2D.Style.removeProperty('display');
var StartTime := GAudioContext.currentTime;
for var Track in FTracks do
begin
var Index := RandomInt(FHRTFs.MeasurementCount);
var CurrentPosition := FHRTFs.Measurement[Index].Position;
for var Glyph in FGlyphs do
begin
if Glyph.Name = Track.Text then
begin
var R := FPlane2D.CanvasElement.getBoundingClientRect;
var Scale := Sqrt(Sqr(CurrentPosition[0]) + Sqr(CurrentPosition[1]));
Glyph.Style.removeProperty('display');
Glyph.Style.left := FloatToStr(R.left + 0.5 * R.width - 0.45 * CurrentPosition[1] / Scale * R.width - 16) + 'px';
Glyph.Style.top := FloatToStr(R.top + 0.5 * R.height - 0.45 * CurrentPosition[0] / Scale * R.height - 16) + 'px';
end;
end;
Track.FromHrtf(FHRTFs, Index);
Track.AudioBufferSource.Start(StartTime);
end;
end;
end. |
{
gir2pascal.lpr
Copyright (C) 2011 Andrew Haines andrewd207@aol.com
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
program gir2pascal;
{$mode objfpc}{$H+}
{ $DEFINE CreatePascalClasses}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils,CommandLineOptions, DOM, XMLRead, girNameSpaces, girFiles,
girpascalwriter, girErrors, girCTypesMapping, girTokens, girObjects,
girPascalClassWriter, girpascalwritertypes{$IFDEF UNIX}, baseunix, termio{$ENDIF};
type
{ TGirConsoleConverter }
TGirConsoleConverter = class
private
FCmdOptions: TCommandLineOptions;
FWriteCount: Integer;
FPaths: TStringList;
FOutPutDirectory : String;
FFileToConvert: String;
FUnitPrefix: String;
FOverWriteFiles: Boolean;
FOptions: TgirOptions;
procedure AddDefaultPaths;
procedure AddPaths(APaths: String);
procedure VerifyOptions;
procedure Convert;
// options
function CheckOptions: String;
//callbacks
function NeedGirFile(AGirFile: TObject; NamespaceName: String) : TXMLDocument;
// AName is the whole name unit.pas or file.c
procedure WriteFile(Sender: TObject; AName: String; AStream: TStringStream);
procedure Terminate;
protected
procedure DoRun; //override;
public
constructor Create;
destructor Destroy; override;
procedure WriteHelp; virtual;
procedure Run;
end;
{ TGirConsoleConverter }
procedure TGirConsoleConverter.AddDefaultPaths;
begin
FPaths.Add('/usr/share/gir-1.0/');
end;
procedure TGirConsoleConverter.AddPaths(APaths: String);
var
Strs: TStringList;
Str: String;
begin
Strs := TStringList.Create;
Strs.Delimiter:=':';
Strs.StrictDelimiter:=True;
Strs.DelimitedText:=APaths;
// so we can add the delimiter
for Str in Strs do
FPaths.Add(IncludeTrailingPathDelimiter(Str));
Strs.Free;
end;
procedure TGirConsoleConverter.VerifyOptions;
begin
if not DirectoryExists(FOutPutDirectory) then
begin
WriteLn(Format('Output directory "%s" does not exist!', [FOutPutDirectory]));
Terminate;
end;
if FFileToConvert = '' then
begin
WriteLn('No input file specified! See -h for options.');
Terminate;
Halt;
end;
if FCmdOptions.HasOption('objects') and FCmdOptions.HasOption('classes') then
begin
WriteLn('Cannot use options ''--objects'' and ''--classes'' together!.');
Terminate;
Halt;
end;
end;
function TGirConsoleConverter.NeedGirFile(AGirFile: TObject; NamespaceName: String): TXMLDocument;
var
Sr: TSearchRec;
Path: String;
begin
WriteLn('Looking for gir file: ', NamespaceName);
Result := nil;
for Path in FPaths do
begin
WriteLn('Looking in path: ', Path);
if FindFirst(Path+NamespaceName+'.gir', faAnyFile, Sr) = 0 then
begin
ReadXMLFile(Result, Path+Sr.Name);
Exit;
end;
FindClose(Sr);
end;
if Result = nil then
WriteLn('Fatal: Unable to find gir file: ',NamespaceName);
end;
procedure TGirConsoleConverter.WriteFile(Sender: TObject; AName: String; AStream: TStringStream);
var
SStream: TFileStream;
OutFileName: String;
begin
Inc(FWriteCount);
OutFileName:=FOutPutDirectory+LowerCase(AName);
if not FileExists(OutFileName)
or (FileExists(OutFileName) and FOverWriteFiles) then
begin
WriteLn(Format('Writing: %s', [OutFileName]));
AStream.Position:=0;
ForceDirectories(FOutPutDirectory);
SStream := TFileStream.Create(OutFileName, fmCreate or fmOpenReadWrite);
SStream.CopyFrom(AStream,AStream.Size);
SStream.Free;
AStream.Free;
end
else
begin
WriteLn(Format('File %s already exists! Stopping.', [OutFileName]));
Terminate;
Halt;
end;
end;
procedure TGirConsoleConverter.Terminate;
begin
Halt(1);
end;
procedure TGirConsoleConverter.Convert;
var
Doc: TXMLDocument;
girFile: TgirFile;
Writer: TgirPascalWriter;
StartTime, EndTime:TDateTime;
begin
StartTime := Now;
ReadXMLFile(Doc, FFileToConvert);
girFile := TgirFile.Create(Self, FCmdOptions);
girFile.OnNeedGirFile:=@NeedGirFile;
girFile.ParseXMLDocument(Doc);
Doc.Free;
Writer := TgirPascalWriter.Create(girFile.NameSpaces, FOptions, FUnitPrefix);
Writer.OnUnitWriteEvent:= @WriteFile;
Writer.GenerateUnits;
Writer.Free;
EndTime := Now;
EndTime := EndTime-StartTime;
WriteLn(Format('Converted %d file(s) in %f seconds',[FWriteCount, DateTimeToTimeStamp(EndTime).Time / 1000]));
end;
function TGirConsoleConverter.CheckOptions: String;
begin
Result := '';
//FCmdOptions.SetOptions(ShortOpts, LongOpts);
with FCmdOptions do
begin
AddOption(['h', 'help'], False ,'Show this help message.');
AddOption(['i', 'input'], True ,'.gir filename to convert.');
AddOption(['o', 'output-directory'], True ,'Directory to write the resulting .pas files to. If not specified then the current working directory is used.');
AddOption(['D', 'dynamic'], False , 'Use unit dynlibs and link at runtime');
{$IFDEF CreatePascalClasses}
AddOption(['s', 'seperate-units'], False ,'Creates seperate units for each gir file: (xConsts, xTypes, xFunctions, [xClasses, xObjects].');
AddOption(['C', 'classes'], False ,'Create Pascal classes that envelope/wrap the GObjects. Also forces ''-s''');
AddOption(['O', 'objects'], False ,'OPTION NOT IMPLEMENTED YET. See Note below. '+
'Creates a seperate unit for pascal Objects (not classes). Forces ''-s'' '+
'Note: If -C or -O are not used then pascal Objects and consts '+
'are in a single unit.');
{$ENDIF CreatePascalClasses}
AddOption(['N', 'no-wrappers'], False ,'Do not create wrappers for objects.');
AddOption(['w', 'overwrite-files'], False ,'If the output .pas file(s) already exists then overwrite them.');
AddOption(['n', 'no-default'], False ,'/usr/share/gir-1.0 is not added as a search location for needed .gir files.');
AddOption(['p', 'paths'], True ,'List of paths seperated by ":" to search for needed .gir files.');
AddOption(['d', 'deprecated'], False, 'Include fields and methods marked as deprecated.');
AddOption(['t', 'test'], False ,'Creates a test program per unit to verify struct sizes.');
AddOption(['P', 'unit-prefix'], True, 'Set a prefix to be added to each unitname.');
AddOption(['M', 'max-version'], True, 'Do not include symbols introduced after <max-version>. Can be used multiple times. i.e "-M gtk-3.12 -M glib-2.23"');
AddOption(['k', 'keep-deprecated-version'], True, 'Include deprecated symbols that are >= to $version. Uses the same format as --max-version. Has no effect if --deprecated is defined');
end;
FCmdOptions.ReadOptions;
if FCmdOptions.OptionsMalformed then
REsult := 'Error reading arguments';
end;
procedure TGirConsoleConverter.DoRun;
begin
// quick check parameters
CheckOptions;//('hnp:o:i:wtDCsO',['help','no-default','paths','output-directory', 'input', 'overwrite-files', 'test', 'dynamic', 'classes', 'seperate-units', 'objects']);
// parse parameters
if FCmdOptions.OptionsMalformed then
begin
WriteLn('See -h for options.');
Terminate;
Halt;
end;
if FCmdOptions.HasOption('help') then begin
WriteHelp;
Terminate;
Exit;
end;
if not FCmdOptions.HasOption('input') then
begin
WriteLn('No input file specified! See -h for options.');
Terminate;
Halt;
end;
if not FCmdOptions.HasOption('no-default') then
AddDefaultPaths;
if FCmdOptions.HasOption('output-directory') then
FOutPutDirectory:=IncludeTrailingPathDelimiter(FCmdOptions.OptionValue('output-directory'))
else
FOutPutDirectory:=IncludeTrailingPathDelimiter(GetCurrentDir);
FFileToConvert:=FCmdOptions.OptionValue('input');
AddPaths(ExtractFilePath(FFileToConvert));
if FCmdOptions.HasOption('unit-prefix') then
FUnitPrefix := FCmdOptions.OptionValue('unit-prefix');
if FCmdOptions.HasOption('paths') then
AddPaths(FCmdOptions.OptionValue('paths'));
if FCmdOptions.HasOption('overwrite-files') then
FOverWriteFiles:=True;
if FCmdOptions.HasOption('test') then
Include(FOptions, goWantTest);
if FCmdOptions.HasOption('dynamic') then
Include(FOptions, goLinkDynamic);
if FCmdOptions.HasOption('deprecated') then
Include(FOptions, goIncludeDeprecated);
if FCmdOptions.HasOption('classes') then
begin
Include(FOptions, goClasses);
Include(FOptions, goSeperateConsts);
end;
if FCmdOptions.HasOption('no-wrappers') then
Include(FOptions, goNoWrappers);
if FCmdOptions.HasOption('objects') then
begin
Include(FOptions, goObjects);
Include(FOptions, goSeperateConsts);
end;
if FCmdOptions.HasOption('seperate-units') then
Include(FOptions, goSeperateConsts);
if FCmdOptions.HasOption('unit-prefix') then
FUnitPrefix:=FCmdOptions.OptionValue('unit-prefix')
else
FUnitPrefix:='';
VerifyOptions;
// does all the heavy lifting
Convert;
// stop program loop
Terminate;
end;
constructor TGirConsoleConverter.Create;
begin
//inherited Create(TheOwner);
FCmdOptions := TCommandLineOptions.Create;
FPaths := TStringList.Create;
end;
destructor TGirConsoleConverter.Destroy;
begin
FPaths.Free;
FCmdOptions.Free;
inherited Destroy;
end;
procedure TGirConsoleConverter.WriteHelp;
var
{$IFDEF UNIX}
w: winsize;
{$ENDIF}
ConsoleWidth: Integer;
begin
ConsoleWidth:=80;
{$IFDEF UNIX}
fpioctl(0, TIOCGWINSZ, @w);
ConsoleWidth:=w.ws_col;
{$ENDIF}
Writeln('Usage: ',ExtractFileName(ParamStr(0)),' [options] -i filename');
with FCmdOptions.PrintHelp(ConsoleWidth) do
begin
WriteLn(Text);
Free;
end;
{
Writeln('');
writeln(' Usage: ',ExtractFileName(ParamStr(0)),' [options] -i filename');
Writeln('');
Writeln('');
Writeln(' -i --input= .gir filename to convert.');
Writeln(' -o --output-directory= Directory to write the resulting .pas files to. If not');
Writeln(' specified then the current working directory is used.');
WriteLn(' -D --dynamic Use unit dynlibs and link at runtime');
WriteLn(' -s --seperate-units Creates seperate units for each gir file:');
WriteLn(' (xConsts, xTypes, xFunctions, [xClasses, xObjects].');
WriteLn(' -C --classes Create Pascal classes that envelope/wrap the GObjects.');
WriteLn(' Also forces ''-s''');
WriteLn(' -O --objects OPTION NOT IMPLEMENTED YET. See Note below');
WriteLn(' Creates a seperate unit for pascal Objects (not classes). Forces ''-s''');
WriteLn(' Note: If -C or -O are not used then pascal Objects and consts');
WriteLn(' are in a single unit.');
Writeln(' -w --overwrite-files If the output .pas file(s) already exists then overwrite them.');
Writeln(' -n --no-default /usr/share/gir-1.0 is not added as a search location for ');
Writeln(' needed .gir files.');
Writeln(' -p --paths= List of paths seperated by ":" to search for needed .gir files.');
Writeln(' -t --test Creates a test program and a test c file per unit to verify struct sizes.');
Writeln('');
}
end;
procedure TGirConsoleConverter.Run;
begin
DoRun;
end;
var
Application: TGirConsoleConverter;
{$R *.res}
begin
Application:=TGirConsoleConverter.Create;
Application.Run;
Application.Free;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit PropertyCategories;
interface
uses System.TypInfo, System.Classes, System.Masks, System.Contnrs, DesignIntf, DesignEditors;
{ Property Categories Classes
The following three components make up the category management system.
Access to them is usually managed by the following support functions.
TPropertyCategoryList
Contains and maintains the list of TPropertyCategories. There are numerous
'As a whole' access and manipulation methods for categories as well as
simplified access functions.
TPropertyCategory
Contains and maintains the list of TPropertyFilters. There are numerous
'As a whole' access and manipulation methods for filters as well as data
about the category itself.
TPropertyFilter
Maintains the information about a single filter associated with a particular
category. Along with its filter specific data it also encapsulates the
matching algorithm. }
type
TPropertyFilter = class(TObject)
private
FMask: TMask;
FGroup: Integer;
public
constructor Create(const APropertyName: string; AGroup: Integer);
destructor Destroy; override;
function Match(const APropertyName: string; const DesignObject: IDesignObject;
const AProperty: IProperty = nil): Boolean; overload; virtual;
end;
TComponentPropertyFilter = class(TPropertyFilter)
private
FComponentClass: TClass;
FPropertyType: PTypeInfo;
public
constructor Create(const APropertyName: string; AComponentClass: TClass;
APropertyType: PTypeInfo);
function Match(const APropertyName: string; const DesignObject: IDesignObject;
const AProperty: IProperty = nil): Boolean; overload; override;
function Match(const APropertyName: string; AComponentClass: TClass;
APropertyType: PTypeInfo): Boolean; overload;
property ComponentClass: TClass read FComponentClass;
property PropertyType: PTypeInfo read FPropertyType;
end;
TPropertyCategory = class(TObject)
private
FList: TObjectList;
FMatchCount: Integer;
FEditor: TPropertyEditor;
FEnabled: Boolean;
FGroup: Integer;
FName: string;
FVisible: Boolean;
protected
function GetFilter(Index: Integer): TPropertyFilter;
public
constructor Create(const AName: string);
destructor Destroy; override;
function Add(AFilter: TPropertyFilter): TPropertyFilter;
procedure Remove(AFilter: TPropertyFilter);
function Count: Integer;
function Match(const APropertyName: string; const DesignObject: IDesignObject;
const AProperty: IProperty = nil): Boolean; overload;
function Match(const APropertyName: string; AComponentClass: TClass;
APropertyType: PTypeInfo): Boolean; overload;
procedure ClearMatches;
procedure FreeEditorGroup(AGroup: Integer);
property Filters[Index: Integer]: TPropertyFilter read GetFilter;
property MatchCount: Integer read FMatchCount;
property Visible: Boolean read FVisible write FVisible;
property Editor: TPropertyEditor read FEditor write FEditor;
property Name: string read FName;
end;
TPropertyCategoryClass = class of TPropertyCategory;
TPropertyCategoryVisibleMode = (pcvAll, pcvToggle, pcvNone, pcvNotListed,
pcvOnlyListed);
TPropertyCategoryList = class(TObject)
private
FList: TObjectList;
FMiscCategory: TPropertyCategory;
FHiddenCategories: TStringList;
protected
function GetCategory(Index: Integer): TPropertyCategory;
public
constructor Create;
destructor Destroy; override;
function FindCategory(const ACategoryName: string): TPropertyCategory;
function IndexOf(const ACategoryName: string): Integer;
procedure ClearMatches;
procedure FreeEditorGroup(AGroup: Integer);
function MiscCategory: TPropertyCategory;
function Count: integer;
function Match(const APropertyName: string; const DesignObject: IDesignObject;
const AProperty: IProperty = nil): Boolean; overload;
function Match(const APropertyName: string; AComponentClass: TClass;
APropertyType: PTypeInfo = nil): Boolean; overload;
function ChangeVisibility(AMode: TPropertyCategoryVisibleMode): Boolean; overload;
function ChangeVisibility(AMode: TPropertyCategoryVisibleMode;
const ANames: array of string): Boolean; overload;
property Categories[Index: Integer]: TPropertyCategory read GetCategory; default;
procedure LoadHiddenCategories;
procedure SaveHiddenCategories;
end;
{ Property Category Query Functions }
function IsPropertyInCategory(const Category: string; ComponentClass: TClass;
const PropertyName: string): Boolean; overload;
function IsPropertyInCategory(const Category: string; const ClassName,
PropertyName: string): Boolean; overload;
function PropertyCategoryList: TPropertyCategoryList;
var
GetHiddenCategoriesProc: function: string;
SetHiddenCategoriesProc: procedure(const Value: string);
implementation
uses System.SysUtils;
{ TPropertyFilter }
constructor TPropertyFilter.Create(const APropertyName: string; AGroup: Integer);
begin
inherited Create;
if APropertyName <> '' then
FMask := TMask.Create(APropertyName);
FGroup := AGroup;
end;
destructor TPropertyFilter.Destroy;
begin
FMask.Free;
inherited Destroy;
end;
function TPropertyFilter.Match(const APropertyName: string;
const DesignObject: IDesignObject; const AProperty: IProperty): Boolean;
begin
Result := not Assigned(FMask) or FMask.Matches(APropertyName);
end;
{ TVCLPropertyFilter }
constructor TComponentPropertyFilter.Create(const APropertyName: string;
AComponentClass: TClass; APropertyType: PTypeInfo);
begin
inherited Create(APropertyName, CurrentGroup);
FComponentClass := AComponentClass;
FPropertyType := APropertyType;
end;
function TComponentPropertyFilter.Match(const APropertyName: string;
AComponentClass: TClass; APropertyType: PTypeInfo): Boolean;
function MatchName: Boolean;
begin
Result := not Assigned(FMask) or FMask.Matches(APropertyName);
end;
function MatchClass: Boolean;
begin
Result := Assigned(AComponentClass) and
((ComponentClass = AComponentClass) or
(AComponentClass.InheritsFrom(ComponentClass)));
end;
function MatchType: Boolean;
begin
Result := Assigned(APropertyType) and ((PropertyType = APropertyType) or
((PropertyType^.Kind = tkClass) and (APropertyType^.Kind = tkClass) and
GetTypeData(APropertyType)^.ClassType.InheritsFrom(GetTypeData(PropertyType)^.ClassType)));
end;
begin
if Assigned(ComponentClass) then
if Assigned(PropertyType) then
Result := MatchClass and MatchType and MatchName
else
Result := MatchClass and MatchName
else
if Assigned(PropertyType) then
Result := MatchType and MatchName
else
Result := MatchName;
end;
function TComponentPropertyFilter.Match(const APropertyName: string;
const DesignObject: IDesignObject; const AProperty: IProperty): Boolean;
var
LPersistent: IDesignPersistent;
LPropInfo: PPropInfo;
LTypeInfo: PTypeInfo;
LPropertyName: string;
begin
Result := False;
LPropertyName := APropertyName;
if (LPropertyName = '') and (AProperty <> nil) then
LPropertyName := AProperty.GetName;
if Supports(DesignObject, IDesignPersistent, LPersistent) then
begin
LTypeInfo := nil;
if AProperty <> nil then
LTypeInfo := AProperty.GetPropType
else
begin
LPropInfo := GetPropInfo(PTypeInfo(LPersistent.Persistent.ClassInfo), APropertyName);
if Assigned(LPropInfo) then
LTypeInfo := LPropInfo.PropType^;
end;
Result := Match(LPropertyName, LPersistent.Persistent.ClassType, LTypeInfo);
end;
end;
{ TPropertyCategory }
function TPropertyCategory.Add(AFilter: TPropertyFilter): TPropertyFilter;
begin
FList.Insert(0, AFilter);
Result := AFilter;
end;
procedure TPropertyCategory.ClearMatches;
begin
FMatchCount := 0;
end;
function TPropertyCategory.Count: Integer;
begin
Result := FList.Count;
end;
constructor TPropertyCategory.Create(const AName: string);
begin
inherited Create;
FName := AName;
FList := TObjectList.Create;
FVisible := True;
FEnabled := True;
FGroup := CurrentGroup;
end;
destructor TPropertyCategory.Destroy;
begin
FList.Free;
inherited Destroy;
end;
procedure TPropertyCategory.FreeEditorGroup(AGroup: Integer);
var
I: Integer;
begin
for I := Count - 1 downto 0 do
if Filters[I].FGroup = AGroup then
FList.Delete(I);
end;
function TPropertyCategory.GetFilter(Index: Integer): TPropertyFilter;
begin
Result := TPropertyFilter(FList[Index])
end;
function TPropertyCategory.Match(const APropertyName: string;
AComponentClass: TClass; APropertyType: PTypeInfo): Boolean;
var
I: Integer;
LPropInfo: PPropInfo;
Filter: TPropertyFilter;
begin
Result := False;
if not Assigned(APropertyType) and
Assigned(AComponentClass) then
begin
LPropInfo := GetPropInfo(PTypeInfo(AComponentClass.ClassInfo), APropertyName);
if Assigned(LPropInfo) then
APropertyType := LPropInfo.PropType^;
end;
for I := 0 to Count - 1 do
begin
Filter := Filters[I];
if (Filter is TComponentPropertyFilter) and
TComponentPropertyFilter(Filter).Match(APropertyName, AComponentClass, APropertyType) then
begin
Result := True;
Break;
end;
end;
if Result then
Inc(FMatchCount);
end;
function TPropertyCategory.Match(const APropertyName: string;
const DesignObject: IDesignObject; const AProperty: IProperty): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
if Filters[I].Match(APropertyName, DesignObject, AProperty) then
begin
Result := True;
Break;
end;
if Result then
Inc(FMatchCount);
end;
procedure TPropertyCategory.Remove(AFilter: TPropertyFilter);
begin
FList.Remove(AFilter);
end;
{ TPropertyCategoryList }
function TPropertyCategoryList.ChangeVisibility(AMode: TPropertyCategoryVisibleMode): Boolean;
begin
Result := ChangeVisibility(AMode, ['']);
end;
function TPropertyCategoryList.ChangeVisibility(AMode: TPropertyCategoryVisibleMode;
const ANames: array of string): Boolean;
var
I: Integer;
LChanged: Boolean;
procedure ChangeIfNot(ACategory: TPropertyCategory; Value: Boolean);
begin
if (ACategory.Visible <> Value) and (ACategory.MatchCount > 0) then
begin
ACategory.Visible := Value;
LChanged := True;
end;
end;
function ListedCategory(const AName: string): Boolean;
var
I: Integer;
begin
Result := False;
if ANames[Low(ANames)] <> '' then
for I := Low(ANames) to High(ANames) do
if AName = ANames[I] then
begin
Result := True;
break;
end;
end;
begin
LChanged := False;
for I := 0 to Count - 1 do
case AMode of
pcvAll: ChangeIfNot(Categories[I], True);
pcvToggle: ChangeIfNot(Categories[I], not Categories[I].Visible);
pcvNone: ChangeIfNot(Categories[I], False);
pcvNotListed: ChangeIfNot(Categories[I], not ListedCategory(Categories[I].Name));
pcvOnlyListed: ChangeIfNot(Categories[I], ListedCategory(Categories[I].Name));
end;
Result := LChanged;
end;
procedure TPropertyCategoryList.ClearMatches;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Categories[I].ClearMatches;
end;
function TPropertyCategoryList.Count: integer;
begin
Result := FList.Count
end;
constructor TPropertyCategoryList.Create;
begin
inherited Create;
FList := TObjectList.Create;
FHiddenCategories := TStringList.Create;
end;
destructor TPropertyCategoryList.Destroy;
begin
FList.Free;
FHiddenCategories.Free;
inherited Destroy;
end;
function TPropertyCategoryList.FindCategory(const ACategoryName: string): TPropertyCategory;
var
I: Integer;
begin
I := IndexOf(ACategoryName);
if I <> -1 then
Result := Categories[I]
else
begin
Result := TPropertyCategory.Create(ACategoryName);
FList.Insert(0, Result);
Result.Visible := FHiddenCategories.IndexOf(Result.Name) = -1;
end;
end;
procedure TPropertyCategoryList.FreeEditorGroup(AGroup: Integer);
var
I: Integer;
begin
for I := Count - 1 downto 0 do
if Categories[I] <> MiscCategory then
if Categories[I].FGroup = AGroup then
FList.Delete(I)
else
Categories[I].FreeEditorGroup(AGroup);
end;
function TPropertyCategoryList.GetCategory(Index: Integer): TPropertyCategory;
begin
Result := TPropertyCategory(FList[Index])
end;
function TPropertyCategoryList.IndexOf(const ACategoryName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if Categories[I].Name = ACategoryName then
begin
Result := I;
break;
end;
end;
procedure TPropertyCategoryList.LoadHiddenCategories;
var
I: Integer;
begin
Assert(Assigned(GetHiddenCategoriesProc));
if Assigned(GetHiddenCategoriesProc) then
FHiddenCategories.CommaText := GetHiddenCategoriesProc;
for I := 0 to Count - 1 do
Categories[I].Visible := FHiddenCategories.IndexOf(Categories[I].Name) = -1;
end;
function TPropertyCategoryList.Match(const APropertyName: String;
AComponentClass: TClass; APropertyType: PTypeInfo = nil): Boolean;
var
I: Integer;
LThisMatch, LAnyMatches: Boolean;
LPropInfo: PPropInfo;
begin
// assume the worst
Result := False;
LAnyMatches := False;
// make sure we have good data
if not Assigned(APropertyType) and
Assigned(AComponentClass) then
begin
LPropInfo := GetPropInfo(PTypeInfo(AComponentClass.ClassInfo), APropertyName);
if Assigned(LPropInfo) then
APropertyType := LPropInfo.PropType^;
end;
// for each category...
for I := 0 to Count - 1 do
if Categories[I] <> MiscCategory then begin
// found something?
LThisMatch := Categories[I].Match(APropertyName, AComponentClass, APropertyType);
LAnyMatches := LAnyMatches or LThisMatch;
// if this is a good match and its visible then...
Result := LThisMatch and Categories[I].Visible;
if Result then
break;
end;
// if no matches then check the misc category
if not LAnyMatches then
begin
LThisMatch := MiscCategory.Match(APropertyName, AComponentClass, APropertyType);
Result := LThisMatch and MiscCategory.Visible;
end;
end;
function TPropertyCategoryList.Match(const APropertyName: string;
const DesignObject: IDesignObject; const AProperty: IProperty): Boolean;
var
I: Integer;
LThisMatch, LAnyMatches: Boolean;
begin
Result := False; // Supress false warning
LAnyMatches := False;
// for each category...
for I := 0 to Count - 1 do
if Categories[I] <> MiscCategory then begin
// found something?
LThisMatch := Categories[I].Match(APropertyName, DesignObject, AProperty);
LAnyMatches := LAnyMatches or LThisMatch;
// if this is a good match and its visible then...
Result := LThisMatch and Categories[I].Visible;
if Result then
Break;
end;
// if no matches then check the misc category
if not LAnyMatches then
begin
LThisMatch := MiscCategory.Match(APropertyName, DesignObject, AProperty);
Result := LThisMatch and MiscCategory.Visible;
end;
end;
function TPropertyCategoryList.MiscCategory: TPropertyCategory;
begin
if FMiscCategory = nil then
FMiscCategory := FindCategory(sMiscellaneousCategoryName);
Result := FMiscCategory;
end;
procedure TPropertyCategoryList.SaveHiddenCategories;
var
I: Integer;
begin
FHiddenCategories.Clear;
for I := 0 to Count - 1 do
if not Categories[I].Visible then
FHiddenCategories.Add(Categories[I].Name);
SetHiddenCategoriesProc(FHiddenCategories.CommaText);
end;
var
InternalPropertyCategoryList: TPropertyCategoryList;
function IsPropertyInCategory(const Category: string;
ComponentClass: TClass; const PropertyName: string): Boolean;
begin
Result := PropertyCategoryList.FindCategory(Category).Match(PropertyName,
ComponentClass, nil);
end;
function IsPropertyInCategory(const Category: string; const ClassName: string;
const PropertyName: string): Boolean;
begin
Result := PropertyCategoryList.FindCategory(Category).Match(PropertyName,
FindClass(ClassName), nil);
end;
function PropertyCategoryList: TPropertyCategoryList;
begin
// if it doesn't exists then make it
if not Assigned(InternalPropertyCategoryList) then
begin
InternalPropertyCategoryList := TPropertyCategoryList.Create;
// add the catch all misc category
InternalPropertyCategoryList.MiscCategory.Add(TPropertyFilter.Create('', -1));
InternalPropertyCategoryList.MiscCategory.Add(TComponentPropertyFilter.Create('', nil, nil));
// Find out what is hidden
InternalPropertyCategoryList.LoadHiddenCategories;
end;
// ok return it then
Result := InternalPropertyCategoryList;
end;
procedure RegisterPropertyInCategory(const CategoryName: string;
ComponentClass: TClass; PropertyType: PTypeInfo; const PropertyName: string); export;
begin
PropertyCategoryList.FindCategory(CategoryName).Add(TComponentPropertyFilter.Create(PropertyName,
ComponentClass, PropertyType));
end;
procedure FreeCategoryGroup(Group: Integer); export;
begin
if InternalPropertyCategoryList <> nil then
InternalPropertyCategoryList.FreeEditorGroup(Group);
end;
initialization
DesignIntf.RegisterPropertyInCategoryProc := RegisterPropertyInCategory;
NotifyGroupChange(FreeCategoryGroup);
finalization
UnnotifyGroupChange(FreeCategoryGroup);
DesignIntf.RegisterPropertyInCategoryProc := nil;
InternalPropertyCategoryList.Free;
end.
|
unit FIToolkit.ProjectGroupParser.Consts;
interface
uses
FIToolkit.Localization;
const
{ XML consts for a project group file format. Do not localize! }
// <Project>\<ItemGroup>\<Projects Include="%RELATIVE_PATH_TO_DPROJ%">
STR_GPROJ_ROOT_NODE = 'Project';
STR_GPROJ_PROJECTS_GROUP_NODE = 'ItemGroup';
STR_GPROJ_INCLUDED_PROJECT_NODE = 'Projects';
STR_GPROJ_INCLUDED_PROJECT_ATTRIBUTE = 'Include';
{ XML consts for a project file format. Do not localize! }
// <Project>\<PropertyGroup>\<MainSource>
STR_DPROJ_ROOT_NODE = 'Project';
STR_DPROJ_PROPERTY_GROUP_NODE = 'PropertyGroup';
STR_DPROJ_MAIN_SOURCE_NODE = 'MainSource';
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
implementation
end.
|
(********************************************************************************************
** PROGRAM : cgiform
** VERSION : 1.0.0
** DESCRIPTION : Demonstrates how to process HTML forms in CGI programs.
** AUTHOR : Stuart King
** COPYRIGHT : Copyright (c) Irie Tools, 2002. All Rights Reserved.
** NOTES :
** This sample program is distributed with Irie Pascal, and was written to illustrate
** how to process HTML forms. To make best use of this sample you should have a basic
** understanding of Pascal as well as a basic understanding of the Common Gateway Interface
** (CGI).
**
** HTML forms provide a way for websites to receive input from visitors, and to process
** this input in some way. HTML forms contain different kinds of input elements in order
** to conveniently receive different kinds of visitor input. The most common kinds of
** input elements are:
** 1. One line text entry boxes
** 2. Multi-line text entry boxes
** 3. Checkboxes
** 4. Radio buttons
** 5. Hidden fields
** 6. Selection lists (Drop-down menus and List boxes).
** 7. Reset button
** 8. Submit button
**
** HTML forms have action attributes that indicate what should happen when the submit
** button is clicked. It is very common for the action attribute to point at the URL of
** a CGI program. In this case when the submit button is pressed the CGI program is executed
** and the form's input is passed to the program for processing. Each input element in the
** form has a name and the form's input is sent to the CGI program in the form of name/value
** pairs, where the values are the input received by the input elements.
**
** What this program actually does is retrieve any form input passed to it. If it receives
** form input then this program just displays the name/value pairs, along with a link that
** can be used to execute the program again. If the program does not receive any form input
** then it displays a form with a variaty of input elements. The form's action element points
** back to the program, so that the program will receive the input from the form when the
** submit button is pressed.
**********************************************************************************************)
program cgiform;
const
MAX_BUFFER = 8000;
MAX_NAME = 20;
MAX_VALUE = 400;
type
positive = 0..maxint;
BufferType = string[MAX_BUFFER];
NameValuePair = record
Name : string[MAX_NAME];
Value : string[MAX_VALUE]
end;
var
buffer : BufferType;
NameValuePairs : list of NameValuePair;
ScriptName : filename;
function EscapeCharacters(s : string) : string; forward;
//PURPOSE: Initializes the program
//NOTES:
// Initializes the list that will be used to store the name/value pairs
//passed to the program. The program also retrieves it's name so that it can
//refer to itself in the generated response.
procedure Initialize;
begin (* Initialize *)
new(NameValuePairs);
ScriptName := getenv('SCRIPT_NAME');
end; (* Initialize *)
//PURPOSE: Retrieves the information passed to the CGI applications.
//GLOBAL(s) - buffer - Used to store the GET or POST information passed to the CGI program
procedure GetCGIData;
var
RequestMethod : string;
//PURPOSE: Retrieves information sent to by a GET request (i.e. in the QUERY_STRING
// environment variable).
procedure GetRequest;
begin (* GetRequest *)
buffer := getenv('QUERY_STRING')
end; (* GetRequest *)
//PURPOSE: Retrieves information sent to by a POST request (i.e. through the standard
// input stream, with the length of the data in the environment variable
// CONTENT_LENGTH).
procedure PostRequest;
var
len, i : positive;
err : integer;
ContentLength : string;
c : char;
begin (* PostRequest *)
buffer := '';
ContentLength := getenv('CONTENT_LENGTH');
if ContentLength <> '' then
val(ContentLength, len, err)
else
len := 0;
if len <= MAX_BUFFER then
for i := 1 to len do
begin
read(c);
buffer := buffer + c
end
end; (* PostRequest *)
begin (* GetCGIData *)
RequestMethod := getenv('REQUEST_METHOD');
if RequestMethod = 'GET' then
GetRequest
else
PostRequest
end; (* GetCGIData *)
//PURPOSE: Process the data passed to the program.
//NOTES: This is the main part of the program. After retreiving
// the information passed to the program this procedure is
// called to perform the required processing.
procedure ProcessCGIData;
var
i, num, p : integer;
EncodedVariable, DecodedVariable, name, value : string;
//PURPOSE: Processes the named value pairs sent with the GET or POST request.
// Which in this case is the information entered by the user about the
// cookie to add or delete.
//ARGUMENT(s): name - name part of the name/value pair
// value - value part of name/value pair
//NOTES:
// The information entered by the user is sent as name/value pairs (i.e. name-value)
//with the name part being the name of the form element holding the information and
//the value part being the actual information held by the form element.
procedure ProcessNameValuePair(var name, value : string);
var
pair : NameValuePair;
begin (* ProcessNameValuePair *)
pair.name := name;
pair.value := value;
insert(pair, NameValuePairs);
end; (* ProcessNameValuePair *)
begin (* ProcessCGIData *)
//Retrieve each name/value pair from the form and processes them.
num := CountWords(buffer, '&');
for i := 1 to num do
begin
EncodedVariable := CopyWord(buffer, i, '&');
DecodedVariable := URLDecode(EncodedVariable);
p := pos('=', DecodedVariable);
if p > 0 then
begin
name := lowercase(trim(copy(DecodedVariable, 1, p-1)));
value := trim(copy(DecodedVariable, p+1));
ProcessNameValuePair(name, value);
end
end;
end; (* ProcessCGIData *)
//PURPOSE: Generates the response to send back to the browser.
procedure GenerateResponse;
procedure GenerateHeader;
begin (* GenerateHeader *)
//Generate the response headers (including the blank line at the end).
writeln('content-type: text/html');
writeln;
writeln('<html>');
writeln('<head>');
writeln('<title>Irie Pascal sample CGI application</title>');
writeln('<h1>CGIFORM</h1>');
writeln('<h2>This program displays the data entered into a form.</h2>');
writeln('</head>');
writeln(' <hr>');
end; (* GenerateHeader *)
procedure GenerateBody;
procedure WriteForm;
begin (* WriteForm *)
writeln('<form method="POST" action="', ScriptName, '">');
writeln(' <h2>One Line Text Box:</h2>');
writeln(' <p>OneLine <input type="text" name="OneLine" size="20"></p>');
writeln(' <hr>');
writeln(' <h2>Scrolling Text Box:</h2>');
writeln(' <p>Scrolling <textarea rows="2" name="Scrolling" cols="20"></textarea></p>');
writeln(' <hr>');
writeln(' <h2>Check Boxes</h2>');
writeln(' <p>Box1 <input type="checkbox" name="Box1" value="1">');
writeln(' Box2 <input type="checkbox" name="Box2"');
writeln(' value="1"></p>');
writeln(' <p>Box3 <input type="checkbox" name="Box3" value="1">');
writeln(' Box4 <input type="checkbox" name="Box4"');
writeln(' value="1"></p>');
writeln(' <hr>');
writeln(' <h2>Radio Buttons</h2>');
writeln(' <p>Radio1 <input type="radio" value="1" checked name="Radio1">');
writeln(' Radio2 <input type="radio" name="Radio2"');
writeln(' value="2"></p>');
writeln(' <p>Radio3 <input type="radio" name="Radio3" value="3">');
writeln(' Radio4 <input type="radio" name="Radio4"');
writeln(' value="4"></p>');
writeln(' <hr>');
writeln(' <h2>Drop-Down Menu</h2>');
writeln(' <p>DropDown <select name="DropDown" size="1">');
writeln(' <option value="Choice1">Choice1</option>');
writeln(' <option value="Choice2">Choice2</option>');
writeln(' <option value="Choice3">Choice3</option>');
writeln(' <option value="Choice4">Choice4</option>');
writeln(' <option value="Choice5">Choice5</option>');
writeln(' <option value="Choice6">Choice6</option>');
writeln(' </select></p>');
writeln(' <hr>');
writeln(' <p><input type="submit" value="Submit" name="Submit"><input type="reset" value="Reset"');
writeln(' name="Reset"></p>');
writeln('</form>');
end; (* WriteForm *)
procedure WriteFormData;
var
pair : NameValuePair;
i : positive;
begin (* WriteFormData *)
writeln('<h1>Form Data</h1>');
for i := 1 to length(NameValuePairs) do
begin
pair := NameValuePairs[i];
writeln('<h3>', EscapeCharacters(pair.name), ' = ', EscapeCharacters(pair.value), '</h3>');
end;
writeln('<hr>');
writeln('<p>Click <a href="', ScriptName, '">here</a> to go back to the form.</p>');
end; (* WriteFormData *)
begin (* GenerateBody *)
writeln('<body>');
if length(NameValuePairs) = 0 then
begin
//Generate the HTML for the form
WriteForm;
end
else
begin
//Generate the HTML that displays the form data
WriteFormData;
end;
writeln('</body>');
end; (* GenerateBody *)
procedure GenerateFooter;
begin (* GenerateFooter *)
writeln('</html>');
end; (* GenerateFooter *)
begin (* GenerateResponse *)
GenerateHeader;
GenerateBody;
GenerateFooter;
end; (* GenerateResponse *)
procedure Shutdown;
begin (* Shutdown *)
dispose(NameValuePairs);
end; (* Shutdown *)
//*************************************************************************
//PURPOSE: This function converts certain characters that have a
// special meaning in HTML documents to their HTML representation.
//ARGUMENT(s): s - The string to be escaped.
//RETURNS: The string with all special characters escaped.
//NOTES: The characters converted are < > "
function EscapeCharacters;
const
LessThanChar = '<';
GreaterThanChar = '>';
QuoteChar = '"';
HTMLLessThan = '<';
HTMLGreaterThan = '>';
HTMLQuote = '"';
var
i : positive;
procedure ReplaceChar(var strBuffer : string; strReplace : string; i : positive);
begin (* ReplaceChar *)
delete(strBuffer, i, 1);
insert(strReplace, strBuffer, i)
end; (* ReplaceChar *)
begin (* EscapeCharacters *)
repeat
i := pos(LessThanChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLLessThan, i)
until i = 0;
repeat
i := pos(GreaterThanChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLGreaterThan, i)
until i = 0;
repeat
i := pos(QuoteChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLQuote, i)
until i = 0;
EscapeCharacters := s;
end; (* EscapeCharacters *)
begin
Initialize;
GetCGIData;
ProcessCGIData;
GenerateResponse;
Shutdown;
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_DetourCrowd;
interface
uses Math, SysUtils, RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourNavMeshQuery, RN_DetourObstacleAvoidance,
RN_DetourLocalBoundary, RN_DetourPathCorridor, RN_DetourProximityGrid, RN_DetourPathQueue;
/// The maximum number of neighbors that a crowd agent can take into account
/// for steering decisions.
/// @ingroup crowd
const DT_CROWDAGENT_MAX_NEIGHBOURS = 6;
/// The maximum number of corners a crowd agent will look ahead in the path.
/// This value is used for sizing the crowd agent corner buffers.
/// Due to the behavior of the crowd manager, the actual number of useful
/// corners will be one less than this number.
/// @ingroup crowd
const DT_CROWDAGENT_MAX_CORNERS = 4;
/// The maximum number of crowd avoidance configurations supported by the
/// crowd manager.
/// @ingroup crowd
/// @see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(), dtCrowd::getObstacleAvoidanceParams(),
/// dtCrowdAgentParams::obstacleAvoidanceType
const DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS = 8;
/// The maximum number of query filter types supported by the crowd manager.
/// @ingroup crowd
/// @see dtQueryFilter, dtCrowd::getFilter() dtCrowd::getEditableFilter(),
/// dtCrowdAgentParams::queryFilterType
const DT_CROWD_MAX_QUERY_FILTER_TYPE = 16;
/// Provides neighbor data for agents managed by the crowd.
/// @ingroup crowd
/// @see dtCrowdAgent::neis, dtCrowd
type
PdtCrowdNeighbour = ^TdtCrowdNeighbour;
TdtCrowdNeighbour = record
idx: Integer; ///< The index of the neighbor in the crowd.
dist: Single; ///< The distance between the current agent and the neighbor.
end;
/// The type of navigation mesh polygon the agent is currently traversing.
/// @ingroup crowd
TCrowdAgentState =
(
DT_CROWDAGENT_STATE_INVALID, ///< The agent is not in a valid state.
DT_CROWDAGENT_STATE_WALKING, ///< The agent is traversing a normal navigation mesh polygon.
DT_CROWDAGENT_STATE_OFFMESH ///< The agent is traversing an off-mesh connection.
);
/// Configuration parameters for a crowd agent.
/// @ingroup crowd
PdtCrowdAgentParams = ^TdtCrowdAgentParams;
TdtCrowdAgentParams = record
radius: Single; ///< Agent radius. [Limit: >= 0]
height: Single; ///< Agent height. [Limit: > 0]
maxAcceleration: Single; ///< Maximum allowed acceleration. [Limit: >= 0]
maxSpeed: Single; ///< Maximum allowed speed. [Limit: >= 0]
/// Defines how close a collision element must be before it is considered for steering behaviors. [Limits: > 0]
collisionQueryRange: Single;
pathOptimizationRange: Single; ///< The path visibility optimization range. [Limit: > 0]
/// How aggresive the agent manager should be at avoiding collisions with this agent. [Limit: >= 0]
separationWeight: Single;
/// Flags that impact steering behavior. (See: #UpdateFlags)
updateFlags: Byte;
/// The index of the avoidance configuration to use for the agent.
/// [Limits: 0 <= value <= #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
obstacleAvoidanceType: Byte;
/// The index of the query filter used by this agent.
queryFilterType: Byte;
/// User defined data attached to the agent.
userData: Pointer;
end;
TMoveRequestState =
(
DT_CROWDAGENT_TARGET_NONE = 0,
DT_CROWDAGENT_TARGET_FAILED,
DT_CROWDAGENT_TARGET_VALID,
DT_CROWDAGENT_TARGET_REQUESTING,
DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE,
DT_CROWDAGENT_TARGET_WAITING_FOR_PATH,
DT_CROWDAGENT_TARGET_VELOCITY
);
/// Represents an agent managed by a #dtCrowd object.
/// @ingroup crowd
PPdtCrowdAgent = ^PdtCrowdAgent;
PdtCrowdAgent = ^TdtCrowdAgent;
TdtCrowdAgent = record
/// True if the agent is active, false if the agent is in an unused slot in the agent pool.
active: Boolean;
/// The type of mesh polygon the agent is traversing. (See: #CrowdAgentState)
state: TCrowdAgentState;
/// True if the agent has valid path (targetState == DT_CROWDAGENT_TARGET_VALID) and the path does not lead to the requested position, else false.
partial: Boolean;
/// The path corridor the agent is using.
corridor: TdtPathCorridor;
/// The local boundary data for the agent.
boundary: TdtLocalBoundary;
/// Time since the agent's path corridor was optimized.
topologyOptTime: Single;
/// The known neighbors of the agent.
neis: array [0..DT_CROWDAGENT_MAX_NEIGHBOURS-1] of TdtCrowdNeighbour;
/// The number of neighbors.
nneis: Integer;
/// The desired speed.
desiredSpeed: Single;
npos: array [0..2] of Single; ///< The current agent position. [(x, y, z)]
disp: array [0..2] of Single;
dvel: array [0..2] of Single; ///< The desired velocity of the agent. [(x, y, z)]
nvel: array [0..2] of Single;
vel: array [0..2] of Single; ///< The actual velocity of the agent. [(x, y, z)]
/// The agent's configuration parameters.
params: TdtCrowdAgentParams;
/// The local path corridor corners for the agent. (Staight path.) [(x, y, z) * #ncorners]
cornerVerts: array [0..DT_CROWDAGENT_MAX_CORNERS*3-1] of Single;
/// The local path corridor corner flags. (See: #dtStraightPathFlags) [(flags) * #ncorners]
cornerFlags: array [0..DT_CROWDAGENT_MAX_CORNERS-1] of Byte;
/// The reference id of the polygon being entered at the corner. [(polyRef) * #ncorners]
cornerPolys: array [0..DT_CROWDAGENT_MAX_CORNERS-1] of TdtPolyRef;
/// The number of corners.
ncorners: Integer;
targetState: TMoveRequestState; ///< State of the movement request.
targetRef: TdtPolyRef; ///< Target polyref of the movement request.
targetPos: array [0..2] of Single; ///< Target position of the movement request (or velocity in case of DT_CROWDAGENT_TARGET_VELOCITY).
targetPathqRef: TdtPathQueueRef; ///< Path finder ref.
targetReplan: Boolean; ///< Flag indicating that the current path is being replanned.
targetReplanTime: Single; /// <Time since the agent's target was replanned.
end;
PdtCrowdAgentAnimation = ^TdtCrowdAgentAnimation;
TdtCrowdAgentAnimation = record
active: Boolean;
initPos, startPos, endPos: array [0..2] of Single;
polyRef: TdtPolyRef;
t, tmax: Single;
end;
/// Crowd agent update flags.
/// @ingroup crowd
/// @see dtCrowdAgentParams::updateFlags
const
DT_CROWD_ANTICIPATE_TURNS = 1;
DT_CROWD_OBSTACLE_AVOIDANCE = 2;
DT_CROWD_SEPARATION = 4;
DT_CROWD_OPTIMIZE_VIS = 8; ///< Use #dtPathCorridor::optimizePathVisibility() to optimize the agent path.
DT_CROWD_OPTIMIZE_TOPO = 16; ///< Use dtPathCorridor::optimizePathTopology() to optimize the agent path.
type
PdtCrowdAgentDebugInfo = ^TdtCrowdAgentDebugInfo;
TdtCrowdAgentDebugInfo = record
idx: Integer;
optStart, optEnd: array [0..2] of Single;
vod: TdtObstacleAvoidanceDebugData;
end;
/// Provides local steering behaviors for a group of agents.
/// @ingroup crowd
TdtCrowd = class
private
m_maxAgents: Integer;
m_agents: PdtCrowdAgent;
m_activeAgents: PPdtCrowdAgent;
m_agentAnims: PdtCrowdAgentAnimation;
m_pathq: TdtPathQueue;
m_obstacleQueryParams: array [0..DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS-1] of TdtObstacleAvoidanceParams;
m_obstacleQuery: TdtObstacleAvoidanceQuery;
m_grid: TdtProximityGrid;
m_pathResult: PdtPolyRef;
m_maxPathResult: Integer;
m_ext: array [0..2] of Single;
m_filters: array [0..DT_CROWD_MAX_QUERY_FILTER_TYPE-1] of TdtQueryFilter;
m_maxAgentRadius: Single;
m_velocitySampleCount: Integer;
m_navquery: TdtNavMeshQuery;
procedure updateTopologyOptimization(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
procedure updateMoveRequest(const dt: Single);
procedure checkPathValidity(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
function getAgentIndex(agent: PdtCrowdAgent): Integer; { return (int)(agent - m_agents); }
function requestMoveTargetReplan(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
procedure purge();
public
constructor Create;
destructor Destroy; override;
/// Initializes the crowd.
/// @param[in] maxAgents The maximum number of agents the crowd can manage. [Limit: >= 1]
/// @param[in] maxAgentRadius The maximum radius of any agent that will be added to the crowd. [Limit: > 0]
/// @param[in] nav The navigation mesh to use for planning.
/// @return True if the initialization succeeded.
function init(const maxAgents: Integer; const maxAgentRadius: Single; nav: TdtNavMesh): Boolean;
/// Sets the shared avoidance configuration for the specified index.
/// @param[in] idx The index. [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
/// @param[in] params The new configuration.
procedure setObstacleAvoidanceParams(const idx: Integer; const params: PdtObstacleAvoidanceParams);
/// Gets the shared avoidance configuration for the specified index.
/// @param[in] idx The index of the configuration to retreive.
/// [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
/// @return The requested configuration.
function getObstacleAvoidanceParams(const idx: Integer): PdtObstacleAvoidanceParams;
/// Gets the specified agent from the pool.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return The requested agent.
function getAgent(const idx: Integer): PdtCrowdAgent;
/// Gets the specified agent from the pool.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return The requested agent.
function getEditableAgent(const idx: Integer): PdtCrowdAgent;
/// The maximum number of agents that can be managed by the object.
/// @return The maximum number of agents.
function getAgentCount(): Integer;
/// Adds a new agent to the crowd.
/// @param[in] pos The requested position of the agent. [(x, y, z)]
/// @param[in] params The configutation of the agent.
/// @return The index of the agent in the agent pool. Or -1 if the agent could not be added.
function addAgent(const pos: PSingle; const params: PdtCrowdAgentParams): Integer;
/// Updates the specified agent's configuration.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] params The new agent configuration.
procedure updateAgentParameters(const idx: Integer; const params: PdtCrowdAgentParams);
/// Removes the agent from the crowd.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
procedure removeAgent(const idx: Integer);
/// Submits a new move request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] ref The position's polygon reference.
/// @param[in] pos The position within the polygon. [(x, y, z)]
/// @return True if the request was successfully submitted.
function requestMoveTarget(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
/// Submits a new move request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] vel The movement velocity. [(x, y, z)]
/// @return True if the request was successfully submitted.
function requestMoveVelocity(const idx: Integer; const vel: PSingle): Boolean;
/// Resets any request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return True if the request was successfully reseted.
function resetMoveTarget(const idx: Integer): Boolean;
/// Gets the active agents int the agent pool.
/// @param[out] agents An array of agent pointers. [(#dtCrowdAgent *) * maxAgents]
/// @param[in] maxAgents The size of the crowd agent array.
/// @return The number of agents returned in @p agents.
function getActiveAgents(agents: PPdtCrowdAgent; const maxAgents: Integer): Integer;
/// Updates the steering and positions of all agents.
/// @param[in] dt The time, in seconds, to update the simulation. [Limit: > 0]
/// @param[out] debug A debug object to load with debug information. [Opt]
procedure update(const dt: Single; debug: PdtCrowdAgentDebugInfo);
/// Gets the filter used by the crowd.
/// @return The filter used by the crowd.
function getFilter(const i: Integer): TdtQueryFilter; { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
/// Gets the filter used by the crowd.
/// @return The filter used by the crowd.
function getEditableFilter(const i: Integer): TdtQueryFilter; { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
/// Gets the search extents [(x, y, z)] used by the crowd for query operations.
/// @return The search extents used by the crowd. [(x, y, z)]
function getQueryExtents(): PSingle; { return m_ext; }
/// Gets the velocity sample count.
/// @return The velocity sample count.
property getVelocitySampleCount: Integer read m_velocitySampleCount;
/// Gets the crowd's proximity grid.
/// @return The crowd's proximity grid.
property getGrid: TdtProximityGrid read m_grid;
/// Gets the crowd's path request queue.
/// @return The crowd's path request queue.
property getPathQueue: TdtPathQueue read m_pathq;
/// Gets the query object used by the crowd.
property getNavMeshQuery: TdtNavMeshQuery read m_navquery;
end;
/// Allocates a crowd object using the Detour allocator.
/// @return A crowd object that is ready for initialization, or null on failure.
/// @ingroup crowd
function dtAllocCrowd(): TdtCrowd;
/// Frees the specified crowd object using the Detour allocator.
/// @param[in] ptr A crowd object allocated using #dtAllocCrowd
/// @ingroup crowd
procedure dtFreeCrowd(var ptr: TdtCrowd);
//Delphi. Added to be accessible from outside this unit, for debug render
procedure calcSmoothSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
(**
@defgroup crowd Crowd
Members in this module implement local steering and dynamic avoidance features.
The crowd is the big beast of the navigation features. It not only handles a
lot of the path management for you, but also local steering and dynamic
avoidance between members of the crowd. I.e. It can keep your agents from
running into each other.
Main class: #dtCrowd
The #dtNavMeshQuery and #dtPathCorridor classes provide perfectly good, easy
to use path planning features. But in the end they only give you points that
your navigation client should be moving toward. When it comes to deciding things
like agent velocity and steering to avoid other agents, that is up to you to
implement. Unless, of course, you decide to use #dtCrowd.
Basically, you add an agent to the crowd, providing various configuration
settings such as maximum speed and acceleration. You also provide a local
target to more toward. The crowd manager then provides, with every update, the
new agent position and velocity for the frame. The movement will be
constrained to the navigation mesh, and steering will be applied to ensure
agents managed by the crowd do not collide with each other.
This is very powerful feature set. But it comes with limitations.
The biggest limitation is that you must give control of the agent's position
completely over to the crowd manager. You can update things like maximum speed
and acceleration. But in order for the crowd manager to do its thing, it can't
allow you to constantly be giving it overrides to position and velocity. So
you give up direct control of the agent's movement. It belongs to the crowd.
The second biggest limitation revolves around the fact that the crowd manager
deals with local planning. So the agent's target should never be more than
256 polygons aways from its current position. If it is, you risk
your agent failing to reach its target. So you may still need to do long
distance planning and provide the crowd manager with intermediate targets.
Other significant limitations:
- All agents using the crowd manager will use the same #dtQueryFilter.
- Crowd management is relatively expensive. The maximum agents under crowd
management at any one time is between 20 and 30. A good place to start
is a maximum of 25 agents for 0.5ms per frame.
@note This is a summary list of members. Use the index or search
feature to find minor members.
@struct dtCrowdAgentParams
@see dtCrowdAgent, dtCrowd::addAgent(), dtCrowd::updateAgentParameters()
@var dtCrowdAgentParams::obstacleAvoidanceType
@par
#dtCrowd permits agents to use different avoidance configurations. This value
is the index of the #dtObstacleAvoidanceParams within the crowd.
@see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(),
dtCrowd::getObstacleAvoidanceParams()
@var dtCrowdAgentParams::collisionQueryRange
@par
Collision elements include other agents and navigation mesh boundaries.
This value is often based on the agent radius and/or maximum speed. E.g. radius * 8
@var dtCrowdAgentParams::pathOptimizationRange
@par
Only applicalbe if #updateFlags includes the #DT_CROWD_OPTIMIZE_VIS flag.
This value is often based on the agent radius. E.g. radius * 30
@see dtPathCorridor::optimizePathVisibility()
@var dtCrowdAgentParams::separationWeight
@par
A higher value will result in agents trying to stay farther away from each other at
the cost of more difficult steering in tight spaces.
*)
implementation
uses RN_DetourCommon, RN_DetourStatus;
function dtAllocCrowd(): TdtCrowd;
begin
Result := TdtCrowd.Create;
end;
procedure dtFreeCrowd(var ptr: TdtCrowd);
begin
FreeAndNil(ptr);
end;
const MAX_ITERS_PER_UPDATE = 100;
const MAX_PATHQUEUE_NODES = 4096;
const MAX_COMMON_NODES = 512;
function tween(const t, t0, t1: Single): Single;
begin
Result := dtClamp((t-t0) / (t1-t0), 0.0, 1.0);
end;
procedure integrate(ag: PdtCrowdAgent; const dt: Single);
var maxDelta, ds: Single; dv: array [0..2] of Single;
begin
// Fake dynamic constraint.
maxDelta := ag.params.maxAcceleration * dt;
dtVsub(@dv[0], @ag.nvel[0], @ag.vel[0]);
ds := dtVlen(@dv[0]);
if (ds > maxDelta) then
dtVscale(@dv[0], @dv[0], maxDelta/ds);
dtVadd(@ag.vel[0], @ag.vel[0], @dv[0]);
// Integrate
if (dtVlen(@ag.vel[0]) > 0.0001) then
dtVmad(@ag.npos[0], @ag.npos[0], @ag.vel[0], dt)
else
dtVset(@ag.vel[0],0,0,0);
end;
function overOffmeshConnection(const ag: PdtCrowdAgent; const radius: Single): Boolean;
var offMeshConnection: Boolean; distSq: Single;
begin
if (ag.ncorners = 0) then
Exit(false);
offMeshConnection := (ag.cornerFlags[ag.ncorners-1] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0;
if (offMeshConnection) then
begin
distSq := dtVdist2DSqr(@ag.npos[0], @ag.cornerVerts[(ag.ncorners-1)*3]);
if (distSq < radius*radius) then
Exit(true);
end;
Result := false;
end;
function getDistanceToGoal(const ag: PdtCrowdAgent; const range: Single): Single;
var endOfPath: Boolean;
begin
if (ag.ncorners = 0) then
Exit(range);
endOfPath := (ag.cornerFlags[ag.ncorners-1] and Byte(DT_STRAIGHTPATH_END)) <> 0;
if (endOfPath) then
Exit(dtMin(dtVdist2D(@ag.npos[0], @ag.cornerVerts[(ag.ncorners-1)*3]), range));
Result := range;
end;
procedure calcSmoothSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
var ip0, ip1: Integer; p0, p1: PSingle; dir0, dir1: array [0..2] of Single; len0, len1: Single;
begin
if (ag.ncorners = 0) then
begin
dtVset(dir, 0,0,0);
Exit;
end;
ip0 := 0;
ip1 := dtMin(1, ag.ncorners-1);
p0 := @ag.cornerVerts[ip0*3];
p1 := @ag.cornerVerts[ip1*3];
dtVsub(@dir0[0], p0, @ag.npos[0]);
dtVsub(@dir1[0], p1, @ag.npos[0]);
dir0[1] := 0;
dir1[1] := 0;
len0 := dtVlen(@dir0[0]);
len1 := dtVlen(@dir1[0]);
if (len1 > 0.001) then
dtVscale(@dir1[0],@dir1[0],1.0/len1);
dir[0] := dir0[0] - dir1[0]*len0*0.5;
dir[1] := 0;
dir[2] := dir0[2] - dir1[2]*len0*0.5;
dtVnormalize(dir);
end;
procedure calcStraightSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
begin
if (ag.ncorners = 0) then
begin
dtVset(dir, 0,0,0);
Exit;
end;
dtVsub(dir, @ag.cornerVerts[0], @ag.npos[0]);
dir[1] := 0;
dtVnormalize(dir);
end;
function addNeighbour(const idx: Integer; const dist: Single;
neis: PdtCrowdNeighbour; const nneis, maxNeis: Integer): Integer;
var nei: PdtCrowdNeighbour; i, tgt, n: Integer;
begin
// Insert neighbour based on the distance.
if (nneis = 0) then
begin
nei := @neis[nneis];
end
else if (dist >= neis[nneis-1].dist) then
begin
if (nneis >= maxNeis) then
Exit(nneis);
nei := @neis[nneis];
end
else
begin
for i := 0 to nneis - 1 do
if (dist <= neis[i].dist) then
break;
tgt := i+1;
n := dtMin(nneis-i, maxNeis-tgt);
Assert(tgt+n <= maxNeis);
if (n > 0) then
Move(neis[i], neis[tgt], sizeof(TdtCrowdNeighbour)*n);
nei := @neis[i];
end;
FillChar(nei^, sizeof(TdtCrowdNeighbour), 0);
nei.idx := idx;
nei.dist := dist;
Result := dtMin(nneis+1, maxNeis);
end;
function getNeighbours(const pos: PSingle; const height, range: Single;
const skip: PdtCrowdAgent; reslt: PdtCrowdNeighbour; const maxResult: Integer;
agents: PPdtCrowdAgent; const nagents: Integer; grid: TdtProximityGrid): Integer;
const MAX_NEIS = 32;
var n, nids, i: Integer; ids: array [0..MAX_NEIS-1] of Word; ag: PdtCrowdAgent; diff: array [0..2] of Single; distSqr: Single;
begin
n := 0;
nids := grid.queryItems(pos[0]-range, pos[2]-range,
pos[0]+range, pos[2]+range,
@ids[0], MAX_NEIS);
for i := 0 to nids - 1 do
begin
ag := agents[ids[i]];
if (ag = skip) then continue;
// Check for overlap.
dtVsub(@diff[0], pos, @ag.npos[0]);
if (Abs(diff[1]) >= (height+ag.params.height)/2.0) then
continue;
diff[1] := 0;
distSqr := dtVlenSqr(@diff[0]);
if (distSqr > Sqr(range)) then
continue;
n := addNeighbour(ids[i], distSqr, reslt, n, maxResult);
end;
Result := n;
end;
function addToOptQueue(newag: PdtCrowdAgent; agents: PPdtCrowdAgent; const nagents, maxAgents: Integer): Integer;
var slot, i, tgt, n: Integer;
begin
// Insert neighbour based on greatest time.
if (nagents = 0) then
begin
slot := nagents;
end
else if (newag.topologyOptTime <= agents[nagents-1].topologyOptTime) then
begin
if (nagents >= maxAgents) then
Exit(nagents);
slot := nagents;
end
else
begin
for i := 0 to nagents - 1 do
if (newag.topologyOptTime >= agents[i].topologyOptTime) then
break;
tgt := i+1;
n := dtMin(nagents-i, maxAgents-tgt);
Assert(tgt+n <= maxAgents);
if (n > 0) then
Move(agents[i], agents[tgt], sizeof(PdtCrowdAgent)*n);
slot := i;
end;
agents[slot] := newag;
Result := dtMin(nagents+1, maxAgents);
end;
function addToPathQueue(newag: PdtCrowdAgent; agents: PPdtCrowdAgent; const nagents, maxAgents: Integer): Integer;
var slot, i, tgt, n: Integer;
begin
// Insert neighbour based on greatest time.
if (nagents = 0) then
begin
slot := nagents;
end
else if (newag.targetReplanTime <= agents[nagents-1].targetReplanTime) then
begin
if (nagents >= maxAgents) then
Exit(nagents);
slot := nagents;
end
else
begin
for i := 0 to nagents - 1 do
if (newag.targetReplanTime >= agents[i].targetReplanTime) then
break;
tgt := i+1;
n := dtMin(nagents-i, maxAgents-tgt);
Assert(tgt+n <= maxAgents);
if (n > 0) then
Move(agents[i], agents[tgt], sizeof(PdtCrowdAgent)*n);
slot := i;
end;
agents[slot] := newag;
Result := dtMin(nagents+1, maxAgents);
end;
(**
@class dtCrowd
@par
This is the core class of the @ref crowd module. See the @ref crowd documentation for a summary
of the crowd features.
A common method for setting up the crowd is as follows:
-# Allocate the crowd using #dtAllocCrowd.
-# Initialize the crowd using #init().
-# Set the avoidance configurations using #setObstacleAvoidanceParams().
-# Add agents using #addAgent() and make an initial movement request using #requestMoveTarget().
A common process for managing the crowd is as follows:
-# Call #update() to allow the crowd to manage its agents.
-# Retrieve agent information using #getActiveAgents().
-# Make movement requests using #requestMoveTarget() when movement goal changes.
-# Repeat every frame.
Some agent configuration settings can be updated using #updateAgentParameters(). But the crowd owns the
agent position. So it is not possible to update an active agent's position. If agent position
must be fed back into the crowd, the agent must be removed and re-added.
Notes:
- Path related information is available for newly added agents only after an #update() has been
performed.
- Agent objects are kept in a pool and re-used. So it is important when using agent objects to check the value of
#dtCrowdAgent::active to determine if the agent is actually in use or not.
- This class is meant to provide 'local' movement. There is a limit of 256 polygons in the path corridor.
So it is not meant to provide automatic pathfinding services over long distances.
@see dtAllocCrowd(), dtFreeCrowd(), init(), dtCrowdAgent
*)
constructor TdtCrowd.Create;
var i: Integer;
begin
m_maxAgents := 0;
m_agents := nil;
m_activeAgents := nil;
m_agentAnims := nil;
m_obstacleQuery := nil;
m_grid := nil;
m_pathResult := nil;
m_maxPathResult := 0;
m_maxAgentRadius := 0;
m_velocitySampleCount := 0;
m_navquery := nil;
m_pathq := TdtPathQueue.Create; // Delphi: Assume C++ invokes constructor
for i := 0 to DT_CROWD_MAX_QUERY_FILTER_TYPE-1 do
m_filters[i] := TdtQueryFilter.Create;
end;
destructor TdtCrowd.Destroy;
var i: Integer;
begin
purge();
m_pathq.Free; // Delphi: Assume C++ invokes destructor
for i := 0 to DT_CROWD_MAX_QUERY_FILTER_TYPE-1 do
m_filters[i].Free;
inherited;
end;
procedure TdtCrowd.purge();
var i: Integer;
begin
// Delphi: Release objects we have created in Init (see m_agents comments there)
for i := 0 to m_maxAgents - 1 do
begin
FreeAndNil(m_agents[i].corridor);
FreeAndNil(m_agents[i].boundary);
end;
FreeMem(m_agents);
m_agents := nil;
m_maxAgents := 0;
FreeMem(m_activeAgents);
m_activeAgents := nil;
FreeMem(m_agentAnims);
m_agentAnims := nil;
FreeMem(m_pathResult);
m_pathResult := nil;
dtFreeProximityGrid(m_grid);
m_grid := nil;
dtFreeObstacleAvoidanceQuery(m_obstacleQuery);
m_obstacleQuery := nil;
dtFreeNavMeshQuery(m_navquery);
m_navquery := nil;
end;
/// @par
///
/// May be called more than once to purge and re-initialize the crowd.
function TdtCrowd.init(const maxAgents: Integer; const maxAgentRadius: Single; nav: TdtNavMesh): Boolean;
var i: Integer; params: PdtObstacleAvoidanceParams;
begin
purge();
m_maxAgents := maxAgents;
m_maxAgentRadius := maxAgentRadius;
dtVset(@m_ext[0], m_maxAgentRadius*2.0,m_maxAgentRadius*1.5,m_maxAgentRadius*2.0);
m_grid := dtAllocProximityGrid();
if (m_grid = nil) then
Exit(false);
if (not m_grid.init(m_maxAgents*4, maxAgentRadius*3)) then
Exit(false);
m_obstacleQuery := dtAllocObstacleAvoidanceQuery();
if (m_obstacleQuery = nil) then
Exit(false);
if (not m_obstacleQuery.init(6, 8)) then
Exit(false);
// Init obstacle query params.
FillChar(m_obstacleQueryParams[0], sizeof(m_obstacleQueryParams), 0);
for i := 0 to DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS - 1 do
begin
params := @m_obstacleQueryParams[i];
params.velBias := 0.4;
params.weightDesVel := 2.0;
params.weightCurVel := 0.75;
params.weightSide := 0.75;
params.weightToi := 2.5;
params.horizTime := 2.5;
params.gridSize := 33;
params.adaptiveDivs := 7;
params.adaptiveRings := 2;
params.adaptiveDepth := 5;
end;
// Allocate temp buffer for merging paths.
m_maxPathResult := 256;
GetMem(m_pathResult, sizeof(TdtPolyRef)*m_maxPathResult);
if (not m_pathq.init(m_maxPathResult, MAX_PATHQUEUE_NODES, nav)) then
Exit(false);
GetMem(m_agents, sizeof(TdtCrowdAgent)*m_maxAgents);
GetMem(m_activeAgents, sizeof(PdtCrowdAgent)*m_maxAgents);
GetMem(m_agentAnims, sizeof(TdtCrowdAgentAnimation)*m_maxAgents);
for i := 0 to m_maxAgents - 1 do
begin
// Delphi: Objects are auto-created in C++ struct, so I've been told and so does the code below expects
m_agents[i].corridor := TdtPathCorridor.Create;
m_agents[i].boundary := TdtLocalBoundary.Create;
m_agents[i].active := false;
if (not m_agents[i].corridor.init(m_maxPathResult)) then
Exit(false);
end;
for i := 0 to m_maxAgents - 1 do
begin
m_agentAnims[i].active := false;
end;
// The navquery is mostly used for local searches, no need for large node pool.
m_navquery := dtAllocNavMeshQuery();
if (dtStatusFailed(m_navquery.init(nav, MAX_COMMON_NODES))) then
Exit(false);
Result := true;
end;
procedure TdtCrowd.setObstacleAvoidanceParams(const idx: Integer; const params: PdtObstacleAvoidanceParams);
begin
if (idx >= 0) and (idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)then
Move(params^, m_obstacleQueryParams[idx], sizeof(TdtObstacleAvoidanceParams));
end;
function TdtCrowd.getObstacleAvoidanceParams(const idx: Integer): PdtObstacleAvoidanceParams;
begin
if (idx >= 0) and (idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) then
Exit(@m_obstacleQueryParams[idx]);
Result := nil;
end;
function TdtCrowd.getAgentCount(): Integer;
begin
Result := m_maxAgents;
end;
/// @par
///
/// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
function TdtCrowd.getAgent(const idx: Integer): PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(nil);
Result := @m_agents[idx];
end;
///
/// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
function TdtCrowd.getEditableAgent(const idx: Integer): PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(nil);
Result := @m_agents[idx];
end;
procedure TdtCrowd.updateAgentParameters(const idx: Integer; const params: PdtCrowdAgentParams);
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit;
Move(params^, m_agents[idx].params, sizeof(TdtCrowdAgentParams));
end;
/// @par
///
/// The agent's position will be constrained to the surface of the navigation mesh.
function TdtCrowd.addAgent(const pos: PSingle; const params: PdtCrowdAgentParams): Integer;
var idx, i: Integer; ag: PdtCrowdAgent; nearest: array [0..2] of Single; ref: TdtPolyRef; status: TdtStatus;
begin
// Find empty slot.
idx := -1;
for i := 0 to m_maxAgents - 1 do
begin
if (not m_agents[i].active) then
begin
idx := i;
break;
end;
end;
if (idx = -1) then
Exit(-1);
ag := @m_agents[idx];
updateAgentParameters(idx, params);
// Find nearest position on navmesh and place the agent there.
ref := 0;
dtVcopy(@nearest[0], pos);
status := m_navquery.findNearestPoly(pos, @m_ext[0], m_filters[ag.params.queryFilterType], @ref, @nearest[0]);
if (dtStatusFailed(status)) then
begin
dtVcopy(@nearest[0], pos);
ref := 0;
end;
ag.corridor.reset(ref, @nearest[0]);
ag.boundary.reset();
ag.partial := false;
ag.topologyOptTime := 0;
ag.targetReplanTime := 0;
ag.nneis := 0;
dtVset(@ag.dvel[0], 0,0,0);
dtVset(@ag.nvel[0], 0,0,0);
dtVset(@ag.vel[0], 0,0,0);
dtVcopy(@ag.npos[0], @nearest[0]);
ag.desiredSpeed := 0;
if (ref <> 0) then
ag.state := DT_CROWDAGENT_STATE_WALKING
else
ag.state := DT_CROWDAGENT_STATE_INVALID;
ag.targetState := DT_CROWDAGENT_TARGET_NONE;
ag.active := true;
Result := idx;
end;
/// @par
///
/// The agent is deactivated and will no longer be processed. Its #dtCrowdAgent object
/// is not removed from the pool. It is marked as inactive so that it is available for reuse.
procedure TdtCrowd.removeAgent(const idx: Integer);
begin
if (idx >= 0) and (idx < m_maxAgents) then
begin
m_agents[idx].active := false;
end;
end;
function TdtCrowd.requestMoveTargetReplan(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
var ag: PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(false);
ag := @m_agents[idx];
// Initialize request.
ag.targetRef := ref;
dtVcopy(@ag.targetPos[0], pos);
ag.targetPathqRef := DT_PATHQ_INVALID;
ag.targetReplan := true;
if (ag.targetRef <> 0) then
ag.targetState := DT_CROWDAGENT_TARGET_REQUESTING
else
ag.targetState := DT_CROWDAGENT_TARGET_FAILED;
Result := true;
end;
/// @par
///
/// This method is used when a new target is set.
///
/// The position will be constrained to the surface of the navigation mesh.
///
/// The request will be processed during the next #update().
function TdtCrowd.requestMoveTarget(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
var ag: PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(false);
if (ref = 0) then
Exit(false);
ag := @m_agents[idx];
// Initialize request.
ag.targetRef := ref;
dtVcopy(@ag.targetPos[0], pos);
ag.targetPathqRef := DT_PATHQ_INVALID;
ag.targetReplan := false;
if (ag.targetRef <> 0) then
ag.targetState := DT_CROWDAGENT_TARGET_REQUESTING
else
ag.targetState := DT_CROWDAGENT_TARGET_FAILED;
Result := true;
end;
function TdtCrowd.requestMoveVelocity(const idx: Integer; const vel: PSingle): Boolean;
var ag: PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(false);
ag := @m_agents[idx];
// Initialize request.
ag.targetRef := 0;
dtVcopy(@ag.targetPos[0], vel);
ag.targetPathqRef := DT_PATHQ_INVALID;
ag.targetReplan := false;
ag.targetState := DT_CROWDAGENT_TARGET_VELOCITY;
Result := true;
end;
function TdtCrowd.resetMoveTarget(const idx: Integer): Boolean;
var ag: PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(false);
ag := @m_agents[idx];
// Initialize request.
ag.targetRef := 0;
dtVset(@ag.targetPos[0], 0,0,0);
ag.targetPathqRef := DT_PATHQ_INVALID;
ag.targetReplan := false;
ag.targetState := DT_CROWDAGENT_TARGET_NONE;
Result := true;
end;
function TdtCrowd.getActiveAgents(agents: PPdtCrowdAgent; const maxAgents: Integer): Integer;
var n, i: Integer;
begin
n := 0;
for i := 0 to m_maxAgents - 1 do
begin
if (not m_agents[i].active) then continue;
if (n < maxAgents) then
begin
agents[n] := @m_agents[i];
Inc(n);
end;
end;
Result := n;
end;
procedure TdtCrowd.updateMoveRequest(const dt: Single);
const PATH_MAX_AGENTS = 8;
const MAX_RES = 32;
const MAX_ITER = 20;
var queue: array [0..PATH_MAX_AGENTS-1] of PdtCrowdAgent; nqueue, i, j, npath: Integer; ag: PdtCrowdAgent; path, res: PdtPolyRef;
reqPos, targetPos, nearest: array [0..2] of Single; reqPath: array [0..MAX_RES-1] of TdtPolyRef; reqPathCount: Integer; status: TdtStatus;
valid: Boolean; nres: Integer;
begin
nqueue := 0;
// Fire off new requests.
for i := 0 to m_maxAgents - 1 do
begin
ag := @m_agents[i];
if (not ag.active) then
continue;
if (ag.state = DT_CROWDAGENT_STATE_INVALID) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_REQUESTING) then
begin
path := ag.corridor.getPath();
npath := ag.corridor.getPathCount();
Assert(npath <> 0);
reqPathCount := 0;
// Quick search towards the goal.
m_navquery.initSlicedFindPath(path[0], ag.targetRef, @ag.npos[0], @ag.targetPos[0], m_filters[ag.params.queryFilterType]);
m_navquery.updateSlicedFindPath(MAX_ITER, nil);
if (ag.targetReplan) then // && npath > 10)
begin
// Try to use existing steady path during replan if possible.
status := m_navquery.finalizeSlicedFindPathPartial(path, npath, @reqPath[0], @reqPathCount, MAX_RES);
end
else
begin
// Try to move towards target when goal changes.
status := m_navquery.finalizeSlicedFindPath(@reqPath[0], @reqPathCount, MAX_RES);
end;
if (not dtStatusFailed(status)) and (reqPathCount > 0) then
begin
// In progress or succeed.
if (reqPath[reqPathCount-1] <> ag.targetRef) then
begin
// Partial path, constrain target position inside the last polygon.
status := m_navquery.closestPointOnPoly(reqPath[reqPathCount-1], @ag.targetPos[0], @reqPos[0], nil);
if (dtStatusFailed(status)) then
reqPathCount := 0;
end
else
begin
dtVcopy(@reqPos[0], @ag.targetPos[0]);
end;
end
else
begin
reqPathCount := 0;
end;
if (reqPathCount = 0) then
begin
// Could not find path, start the request from current location.
dtVcopy(@reqPos[0], @ag.npos[0]);
reqPath[0] := path[0];
reqPathCount := 1;
end;
ag.corridor.setCorridor(@reqPos[0], @reqPath[0], reqPathCount);
ag.boundary.reset();
ag.partial := false;
if (reqPath[reqPathCount-1] = ag.targetRef) then
begin
ag.targetState := DT_CROWDAGENT_TARGET_VALID;
ag.targetReplanTime := 0.0;
end
else
begin
// The path is longer or potentially unreachable, full plan.
ag.targetState := DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE;
end;
end;
if (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE) then
begin
nqueue := addToPathQueue(ag, @queue[0], nqueue, PATH_MAX_AGENTS);
end;
end;
for i := 0 to nqueue - 1 do
begin
ag := queue[i];
ag.targetPathqRef := m_pathq.request(ag.corridor.getLastPoly(), ag.targetRef,
ag.corridor.getTarget(), @ag.targetPos[0], m_filters[ag.params.queryFilterType]);
if (ag.targetPathqRef <> DT_PATHQ_INVALID) then
ag.targetState := DT_CROWDAGENT_TARGET_WAITING_FOR_PATH;
end;
// Update requests.
m_pathq.update(MAX_ITERS_PER_UPDATE);
// Process path results.
for i := 0 to m_maxAgents - 1 do
begin
ag := @m_agents[i];
if (not ag.active) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_PATH) then
begin
// Poll path queue.
status := m_pathq.getRequestStatus(ag.targetPathqRef);
if (dtStatusFailed(status)) then
begin
// Path find failed, retry if the target location is still valid.
ag.targetPathqRef := DT_PATHQ_INVALID;
if (ag.targetRef <> 0) then
ag.targetState := DT_CROWDAGENT_TARGET_REQUESTING
else
ag.targetState := DT_CROWDAGENT_TARGET_FAILED;
ag.targetReplanTime := 0.0;
end
else if (dtStatusSucceed(status)) then
begin
path := ag.corridor.getPath();
npath := ag.corridor.getPathCount();
Assert(npath <> 0);
// Apply results.
dtVcopy(@targetPos[0], @ag.targetPos[0]);
res := m_pathResult;
valid := true;
nres := 0;
status := m_pathq.getPathResult(ag.targetPathqRef, res, @nres, m_maxPathResult);
if dtStatusFailed(status) or (nres = 0) then
valid := false;
if (dtStatusDetail(status, DT_PARTIAL_RESULT)) then
ag.partial := true
else
ag.partial := false;
// Merge result and existing path.
// The agent might have moved whilst the request is
// being processed, so the path may have changed.
// We assume that the end of the path is at the same location
// where the request was issued.
// The last ref in the old path should be the same as
// the location where the request was issued..
if valid and (path[npath-1] <> res[0]) then
valid := false;
if (valid) then
begin
// Put the old path infront of the old path.
if (npath > 1) then
begin
// Make space for the old path.
if ((npath-1)+nres > m_maxPathResult) then
nres := m_maxPathResult - (npath-1);
Move(res^, (res+npath-1)^, sizeof(TdtPolyRef)*nres);
// Copy old path in the beginning.
Move(path^, res^, sizeof(TdtPolyRef)*(npath-1));
Inc(nres, npath-1);
// Remove trackbacks
j := 0;
while (j < nres) do
begin
if (j-1 >= 0) and (j+1 < nres) then
begin
if (res[j-1] = res[j+1]) then
begin
Move((res+(j+1))^, (res+(j-1))^, sizeof(TdtPolyRef)*(nres-(j+1)));
Dec(nres, 2);
Dec(j, 2);
end;
end;
Inc(j);
end;
end;
// Check for partial path.
if (res[nres-1] <> ag.targetRef) then
begin
// Partial path, constrain target position inside the last polygon.
status := m_navquery.closestPointOnPoly(res[nres-1], @targetPos[0], @nearest[0], nil);
if (dtStatusSucceed(status)) then
dtVcopy(@targetPos[0], @nearest[0])
else
valid := false;
end;
end;
if (valid) then
begin
// Set current corridor.
ag.corridor.setCorridor(@targetPos[0], res, nres);
// Force to update boundary.
ag.boundary.reset();
ag.targetState := DT_CROWDAGENT_TARGET_VALID;
end
else
begin
// Something went wrong.
ag.targetState := DT_CROWDAGENT_TARGET_FAILED;
end;
ag.targetReplanTime := 0.0;
end;
end;
end;
end;
procedure TdtCrowd.updateTopologyOptimization(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
const OPT_TIME_THR = 0.5; // seconds
const OPT_MAX_AGENTS = 1;
var ag: PdtCrowdAgent; queue: array [0..OPT_MAX_AGENTS-1] of PdtCrowdAgent; nqueue, i: Integer;
begin
if (nagents = 0) then
Exit;
nqueue := 0;
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
if ((ag.params.updateFlags and DT_CROWD_OPTIMIZE_TOPO) = 0) then
continue;
ag.topologyOptTime := ag.topologyOptTime + dt;
if (ag.topologyOptTime >= OPT_TIME_THR) then
nqueue := addToOptQueue(ag, @queue[0], nqueue, OPT_MAX_AGENTS);
end;
for i := 0 to nqueue - 1 do
begin
ag := queue[i];
ag.corridor.optimizePathTopology(m_navquery, m_filters[ag.params.queryFilterType]);
ag.topologyOptTime := 0;
end;
end;
procedure TdtCrowd.checkPathValidity(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
const CHECK_LOOKAHEAD = 10;
const TARGET_REPLAN_DELAY = 1.0; // seconds
var ag: PdtCrowdAgent; i: Integer; replan: Boolean; idx: Integer; agentPos, nearest: array [0..2] of Single; agentRef: TdtPolyRef;
begin
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
ag.targetReplanTime := ag.targetReplanTime + dt;
replan := false;
// First check that the current location is valid.
idx := getAgentIndex(ag);
agentRef := ag.corridor.getFirstPoly();
dtVcopy(@agentPos[0], @ag.npos[0]);
if (not m_navquery.isValidPolyRef(agentRef, m_filters[ag.params.queryFilterType])) then
begin
// Current location is not valid, try to reposition.
// TODO: this can snap agents, how to handle that?
dtVcopy(@nearest[0], @agentPos[0]);
agentRef := 0;
m_navquery.findNearestPoly(@ag.npos[0], @m_ext[0], m_filters[ag.params.queryFilterType], @agentRef, @nearest[0]);
dtVcopy(@agentPos[0], @nearest[0]);
if (agentRef = 0) then
begin
// Could not find location in navmesh, set state to invalid.
ag.corridor.reset(0, @agentPos[0]);
ag.partial := false;
ag.boundary.reset();
ag.state := DT_CROWDAGENT_STATE_INVALID;
continue;
end;
// Make sure the first polygon is valid, but leave other valid
// polygons in the path so that replanner can adjust the path better.
ag.corridor.fixPathStart(agentRef, @agentPos[0]);
// ag.corridor.trimInvalidPath(agentRef, agentPos, m_navquery, &m_filter);
ag.boundary.reset();
dtVcopy(@ag.npos[0], @agentPos[0]);
replan := true;
end;
// If the agent does not have move target or is controlled by velocity, no need to recover the target nor replan.
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
// Try to recover move request position.
if (ag.targetState <> DT_CROWDAGENT_TARGET_NONE) and (ag.targetState <> DT_CROWDAGENT_TARGET_FAILED) then
begin
if (not m_navquery.isValidPolyRef(ag.targetRef, m_filters[ag.params.queryFilterType])) then
begin
// Current target is not valid, try to reposition.
dtVcopy(@nearest[0], @ag.targetPos[0]);
ag.targetRef := 0;
m_navquery.findNearestPoly(@ag.targetPos[0], @m_ext[0], m_filters[ag.params.queryFilterType], @ag.targetRef, @nearest[0]);
dtVcopy(@ag.targetPos[0], @nearest[0]);
replan := true;
end;
if (ag.targetRef = 0) then
begin
// Failed to reposition target, fail moverequest.
ag.corridor.reset(agentRef, @agentPos[0]);
ag.partial := false;
ag.targetState := DT_CROWDAGENT_TARGET_NONE;
end;
end;
// If nearby corridor is not valid, replan.
if (not ag.corridor.isValid(CHECK_LOOKAHEAD, m_navquery, m_filters[ag.params.queryFilterType])) then
begin
// Fix current path.
// ag.corridor.trimInvalidPath(agentRef, agentPos, m_navquery, &m_filter);
// ag.boundary.reset();
replan := true;
end;
// If the end of the path is near and it is not the requested location, replan.
if (ag.targetState = DT_CROWDAGENT_TARGET_VALID) then
begin
if (ag.targetReplanTime > TARGET_REPLAN_DELAY) and
(ag.corridor.getPathCount() < CHECK_LOOKAHEAD) and
(ag.corridor.getLastPoly() <> ag.targetRef) then
replan := true;
end;
// Try to replan path to goal.
if (replan) then
begin
if (ag.targetState <> DT_CROWDAGENT_TARGET_NONE) then
begin
requestMoveTargetReplan(idx, ag.targetRef, @ag.targetPos[0]);
end;
end;
end;
end;
procedure TdtCrowd.update(const dt: Single; debug: PdtCrowdAgentDebugInfo);
const COLLISION_RESOLVE_FACTOR = 0.7;
var debugIdx: Integer; agents: PPdtCrowdAgent; nagents, i, j, idx, ns, iter, idx0, idx1: Integer; ag, nei: PdtCrowdAgent; p, target, s: PSingle;
r, updateThr, triggerRadius: Single; anim: PdtCrowdAgentAnimation; refs: array [0..1] of TdtPolyRef;
dvel, disp, diff: array [0..2] of Single; vod: TdtObstacleAvoidanceDebugData; adaptive: Boolean; params: PdtObstacleAvoidanceParams;
slowDownRadius, speedScale, separationDist, invSeparationDist, separationWeight, w, distSqr, dist, weight, speedSqr, desiredSqr, pen, iw, ta, tb, u: Single;
begin
m_velocitySampleCount := 0;
if debug <> nil then debugIdx := debug.idx else debugIdx := -1;
agents := m_activeAgents;
nagents := getActiveAgents(agents, m_maxAgents);
// Check that all agents still have valid paths.
checkPathValidity(agents, nagents, dt);
// Update async move request and path finder.
updateMoveRequest(dt);
// Optimize path topology.
updateTopologyOptimization(agents, nagents, dt);
// Register agents to proximity grid.
m_grid.clear();
for i := 0 to nagents - 1 do
begin
ag := agents[i];
p := @ag.npos[0];
r := ag.params.radius;
m_grid.addItem(Word(i), p[0]-r, p[2]-r, p[0]+r, p[2]+r);
end;
// Get nearby navmesh segments and agents to collide with.
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
// Update the collision boundary after certain distance has been passed or
// if it has become invalid.
updateThr := ag.params.collisionQueryRange*0.25;
if (dtVdist2DSqr(@ag.npos[0], ag.boundary.getCenter()) > Sqr(updateThr)) or
(not ag.boundary.isValid(m_navquery, m_filters[ag.params.queryFilterType])) then
begin
ag.boundary.update(ag.corridor.getFirstPoly(), @ag.npos[0], ag.params.collisionQueryRange,
m_navquery, m_filters[ag.params.queryFilterType]);
end;
// Query neighbour agents
ag.nneis := getNeighbours(@ag.npos[0], ag.params.height, ag.params.collisionQueryRange,
ag, @ag.neis[0], DT_CROWDAGENT_MAX_NEIGHBOURS,
agents, nagents, m_grid);
for j := 0 to ag.nneis - 1 do
ag.neis[j].idx := getAgentIndex(agents[ag.neis[j].idx]);
end;
// Find next corner to steer to.
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
// Find corners for steering
ag.ncorners := ag.corridor.findCorners(@ag.cornerVerts[0], @ag.cornerFlags[0], @ag.cornerPolys[0],
DT_CROWDAGENT_MAX_CORNERS, m_navquery, m_filters[ag.params.queryFilterType]);
// Check to see if the corner after the next corner is directly visible,
// and short cut to there.
if ((ag.params.updateFlags and DT_CROWD_OPTIMIZE_VIS) <> 0) and (ag.ncorners > 0) then
begin
target := @ag.cornerVerts[dtMin(1,ag.ncorners-1)*3];
ag.corridor.optimizePathVisibility(target, ag.params.pathOptimizationRange, m_navquery, m_filters[ag.params.queryFilterType]);
// Copy data for debug purposes.
if (debugIdx = i) then
begin
dtVcopy(@debug.optStart[0], ag.corridor.getPos());
dtVcopy(@debug.optEnd[0], target);
end;
end
else
begin
// Copy data for debug purposes.
if (debugIdx = i) then
begin
dtVset(@debug.optStart[0], 0,0,0);
dtVset(@debug.optEnd[0], 0,0,0);
end;
end;
end;
// Trigger off-mesh connections (depends on corners).
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
continue;
// Check
triggerRadius := ag.params.radius*2.25;
if (overOffmeshConnection(ag, triggerRadius)) then
begin
// Prepare to off-mesh connection.
idx := Integer(ag - m_agents);
anim := @m_agentAnims[idx];
// Adjust the path over the off-mesh connection.
if (ag.corridor.moveOverOffmeshConnection(ag.cornerPolys[ag.ncorners-1], @refs[0],
@anim.startPos[0], @anim.endPos[0], m_navquery)) then
begin
dtVcopy(@anim.initPos[0], @ag.npos[0]);
anim.polyRef := refs[1];
anim.active := true;
anim.t := 0.0;
anim.tmax := (dtVdist2D(@anim.startPos[0], @anim.endPos[0]) / ag.params.maxSpeed) * 0.5;
ag.state := DT_CROWDAGENT_STATE_OFFMESH;
ag.ncorners := 0;
ag.nneis := 0;
continue;
end
else
begin
// Path validity check will ensure that bad/blocked connections will be replanned.
end;
end;
end;
// Calculate steering.
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) then
continue;
dvel[0] := 0; dvel[1] := 0; dvel[2] := 0;
if (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
begin
dtVcopy(@dvel[0], @ag.targetPos[0]);
ag.desiredSpeed := dtVlen(@ag.targetPos[0]);
end
else
begin
// Calculate steering direction.
if (ag.params.updateFlags and DT_CROWD_ANTICIPATE_TURNS) <> 0 then
calcSmoothSteerDirection(ag, @dvel[0])
else
calcStraightSteerDirection(ag, @dvel[0]);
// Calculate speed scale, which tells the agent to slowdown at the end of the path.
slowDownRadius := 0.3; // Delphi. Don't slowdown // ag.params.radius*2; // TODO: make less hacky.
speedScale := getDistanceToGoal(ag, slowDownRadius) / slowDownRadius;
ag.desiredSpeed := ag.params.maxSpeed;
dtVscale(@dvel[0], @dvel[0], ag.desiredSpeed * speedScale);
end;
// Separation
if (ag.params.updateFlags and DT_CROWD_SEPARATION) <> 0 then
begin
separationDist := ag.params.collisionQueryRange;
invSeparationDist := 1.0 / separationDist;
separationWeight := ag.params.separationWeight;
w := 0;
disp[0] := 0; disp[1] := 0; disp[2] := 0;
for j := 0 to ag.nneis - 1 do
begin
nei := @m_agents[ag.neis[j].idx];
dtVsub(@diff[0], @ag.npos[0], @nei.npos[0]);
diff[1] := 0;
distSqr := dtVlenSqr(@diff[0]);
if (distSqr < 0.00001) then
continue;
if (distSqr > Sqr(separationDist)) then
continue;
dist := Sqrt(distSqr);
weight := separationWeight * (1.0 - Sqr(dist*invSeparationDist));
dtVmad(@disp[0], @disp[0], @diff[0], weight/dist);
w := w + 1.0;
end;
if (w > 0.0001) then
begin
// Adjust desired velocity.
dtVmad(@dvel[0], @dvel[0], @disp[0], 1.0/w);
// Clamp desired velocity to desired speed.
speedSqr := dtVlenSqr(@dvel[0]);
desiredSqr := Sqr(ag.desiredSpeed);
if (speedSqr > desiredSqr) then
dtVscale(@dvel[0], @dvel[0], desiredSqr/speedSqr);
end;
end;
// Set the desired velocity.
dtVcopy(@ag.dvel[0], @dvel[0]);
end;
// Velocity planning.
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
if (ag.params.updateFlags and DT_CROWD_OBSTACLE_AVOIDANCE) <> 0 then
begin
m_obstacleQuery.reset();
// Add neighbours as obstacles.
for j := 0 to ag.nneis - 1 do
begin
nei := @m_agents[ag.neis[j].idx];
m_obstacleQuery.addCircle(@nei.npos[0], nei.params.radius, @nei.vel[0], @nei.dvel[0]);
end;
// Append neighbour segments as obstacles.
for j := 0 to ag.boundary.getSegmentCount - 1 do
begin
s := ag.boundary.getSegment(j);
if (dtTriArea2D(@ag.npos[0], s, s+3) < 0.0) then
continue;
m_obstacleQuery.addSegment(s, s+3);
end;
vod := nil;
if (debugIdx = i) then
vod := debug.vod;
// Sample new safe velocity.
adaptive := true;
ns := 0;
params := @m_obstacleQueryParams[ag.params.obstacleAvoidanceType];
if (adaptive) then
begin
ns := m_obstacleQuery.sampleVelocityAdaptive(@ag.npos[0], ag.params.radius, ag.desiredSpeed,
@ag.vel[0], @ag.dvel[0], @ag.nvel[0], params, vod);
end
else
begin
ns := m_obstacleQuery.sampleVelocityGrid(@ag.npos[0], ag.params.radius, ag.desiredSpeed,
@ag.vel[0], @ag.dvel[0], @ag.nvel[0], params, vod);
end;
m_velocitySampleCount := m_velocitySampleCount + ns;
end
else
begin
// If not using velocity planning, new velocity is directly the desired velocity.
dtVcopy(@ag.nvel[0], @ag.dvel[0]);
end;
end;
// Integrate.
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
integrate(ag, dt);
end;
// Handle collisions.
for iter := 0 to 3 do
begin
for i := 0 to nagents - 1 do
begin
ag := agents[i];
idx0 := getAgentIndex(ag);
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
dtVset(@ag.disp[0], 0,0,0);
w := 0;
for j := 0 to ag.nneis - 1 do
begin
nei := @m_agents[ag.neis[j].idx];
idx1 := getAgentIndex(nei);
dtVsub(@diff[0], @ag.npos[0], @nei.npos[0]);
diff[1] := 0;
dist := dtVlenSqr(@diff[0]);
if (dist > Sqr(ag.params.radius + nei.params.radius)) then
continue;
dist := Sqrt(dist);
pen := (ag.params.radius + nei.params.radius) - dist;
if (dist < 0.0001) then
begin
// Agents on top of each other, try to choose diverging separation directions.
if (idx0 > idx1) then
dtVset(@diff[0], -ag.dvel[2],0,ag.dvel[0])
else
dtVset(@diff[0], ag.dvel[2],0,-ag.dvel[0]);
pen := 0.01;
end
else
begin
pen := (1.0/dist) * (pen*0.5) * COLLISION_RESOLVE_FACTOR;
end;
dtVmad(@ag.disp[0], @ag.disp[0], @diff[0], pen);
w := w + 1.0;
end;
if (w > 0.0001) then
begin
iw := 1.0 / w;
dtVscale(@ag.disp[0], @ag.disp[0], iw);
end;
end;
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
dtVadd(@ag.npos[0], @ag.npos[0], @ag.disp[0]);
end;
end;
for i := 0 to nagents - 1 do
begin
ag := agents[i];
if (ag.state <> DT_CROWDAGENT_STATE_WALKING) then
continue;
// Move along navmesh.
ag.corridor.movePosition(@ag.npos[0], m_navquery, m_filters[ag.params.queryFilterType]);
// Get valid constrained position back.
dtVcopy(@ag.npos[0], ag.corridor.getPos());
// If not using path, truncate the corridor to just one poly.
if (ag.targetState = DT_CROWDAGENT_TARGET_NONE) or (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
begin
ag.corridor.reset(ag.corridor.getFirstPoly(), @ag.npos[0]);
ag.partial := false;
end;
end;
// Update agents using off-mesh connection.
for i := 0 to m_maxAgents - 1 do
begin
anim := @m_agentAnims[i];
if (not anim.active) then
continue;
ag := agents[i];
anim.t := anim.t + dt;
if (anim.t > anim.tmax) then
begin
// Reset animation
anim.active := false;
// Prepare agent for walking.
ag.state := DT_CROWDAGENT_STATE_WALKING;
continue;
end;
// Update position
ta := anim.tmax*0.15;
tb := anim.tmax;
if (anim.t < ta) then
begin
u := tween(anim.t, 0.0, ta);
dtVlerp(@ag.npos[0], @anim.initPos[0], @anim.startPos[0], u);
end
else
begin
u := tween(anim.t, ta, tb);
dtVlerp(@ag.npos[0], @anim.startPos[0], @anim.endPos[0], u);
end;
// Update velocity.
dtVset(@ag.vel[0], 0,0,0);
dtVset(@ag.dvel[0], 0,0,0);
end;
end;
function TdtCrowd.getAgentIndex(agent: PdtCrowdAgent): Integer; begin Result := Integer(agent - m_agents); end;
function TdtCrowd.getFilter(const i: Integer): TdtQueryFilter; begin if (i >= 0) and (i < DT_CROWD_MAX_QUERY_FILTER_TYPE) then Result := m_filters[i] else Result := nil; end;
function TdtCrowd.getEditableFilter(const i: Integer): TdtQueryFilter; begin if (i >= 0) and (i < DT_CROWD_MAX_QUERY_FILTER_TYPE) then Result := m_filters[i] else Result := nil; end;
function TdtCrowd.getQueryExtents(): PSingle; begin Result := @m_ext[0]; end;
end.
|
unit ClassStack;
interface
type
//==============================================================================
// TStackItem class
//==============================================================================
TStackItem = class
private
FEnglish : string;
FSlovak : string;
FNext : TStackItem;
public
constructor Create( English, Slovak : string; Next : TStackItem );
destructor Destroy; override;
property English : string read FEnglish;
property Slovak : string read FSlovak;
property Next : TStackItem read FNext write FNext;
end;
//==============================================================================
// TStack class
//==============================================================================
TStack = class
private
First : TStackItem;
Last : TStackItem;
procedure FreeStack;
public
constructor Create;
destructor Destroy; override;
procedure Push( NewItem : TStackItem );
function Pop : TStackItem;
end;
implementation
//==============================================================================
//==============================================================================
//
// TStackItem class
//
//==============================================================================
//==============================================================================
constructor TStackItem.Create( English, Slovak : string; Next : TStackItem );
begin
inherited Create;
FEnglish := English;
FSlovak := Slovak;
FNext := Next;
end;
destructor TStackItem.Destroy;
begin
inherited;
end;
//==============================================================================
//==============================================================================
//
// TStack class
//
//==============================================================================
//==============================================================================
constructor TStack.Create;
begin
inherited;
First := nil;
Last := nil;
end;
destructor TStack.Destroy;
begin
FreeStack;
inherited;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
procedure TStack.FreeStack;
var S : TStackItem;
begin
while (First <> nil) do
begin
S := First.Next;
First.Free;
First := S;
end;
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TStack.Push( NewItem : TStackItem );
var S, Before : TStackItem;
begin
Before := nil;
S := First;
if (S = nil) then
begin
First := NewItem;
Last := NewItem;
end
else
begin
repeat
if (NewItem.English < S.English) then
begin
if (S = First) then
begin
First := NewItem;
First.Next := S;
end
else
begin
Before.Next := NewItem;
NewItem.Next := S;
end;
exit;
end;
Before := S;
S := S.Next;
until (S = nil);
Last.Next := NewItem;
Last := NewItem;
end;
end;
function TStack.Pop : TStackItem;
begin
Result := First;
if (First <> nil) then
begin
First := First.Next;
if (First = nil) then
Last := nil;
end;
end;
end.
|
unit uCommon;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;
type
// 1
TSQLDataSource = class(TSQLRecord)
private
fDataSourceType: TSQLDataSourceTypeID;
fDescription: RawUTF8;
published
property DataSourceType: TSQLDataSourceTypeID read fDataSourceType write fDataSourceType;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 2
TSQLDataSourceType = class(TSQLRecord)
private
fName: RawUTF8;
FDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 3
TSQLEmailTemplateSetting = class(TSQLRecord)
private
fEmailType: TSQLEnumerationID;
fDescription: RawUTF8;
fBodyScreenLocation: RawUTF8;
fXslfoAttachScreenLocation: RawUTF8;
fFromAddress: RawUTF8;
fCcAddress: RawUTF8;
fBccAddress: RawUTF8;
fSubject: RawUTF8;
fContentType: RawUTF8;
published
property EmailType: TSQLEnumerationID read fEmailType write fEmailType;
property Description: RawUTF8 read FDescription write FDescription;
property BodyScreenLocation: RawUTF8 read fBodyScreenLocation write fBodyScreenLocation;
property XslfoAttachScreenLocation: RawUTF8 read fXslfoAttachScreenLocation write fXslfoAttachScreenLocation;
property FromAddress: RawUTF8 read fFromAddress write fFromAddress;
property CcAddress: RawUTF8 read fCcAddress write fCcAddress;
property BccAddress: RawUTF8 read fBccAddress write fBccAddress;
property Subject: RawUTF8 read fSubject write fSubject;
property ContentType: RawUTF8 read fContentType write fContentType;
end;
// 4
TSQLEnumeration = class(TSQLRecord)
private
fName: RawUTF8;
fEncode: RawUTF8;
fEnumType: TSQLEnumerationTypeID;
fEnumTypeEncode: RawUTF8;
fEnumCode: RawUTF8;
fSequence: Integer;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Name: RawUTF8 read fName write fName;
property Encode: RawUTF8 read fEncode write fEncode;
property EnumType: TSQLEnumerationTypeID read fEnumType write fEnumType;
property EnumTypeEncode: RawUTF8 read fEnumTypeEncode write fEnumTypeEncode;
property EnumCode: RawUTF8 read fEnumCode write fEnumCode;
property Sequence: Integer read fSequence write fSequence;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 5
TSQLEnumerationType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParent: TSQLEnumerationTypeID;
fParentEncode: RawUTF8;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Parent: TSQLEnumerationTypeID read fParent write fParent;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 6
TSQLCountryCapital = class(TSQLRecord)
private
fCountryCode: RawUTF8;
fCountryCapital: RawUTF8;
published
property CountryCode: RawUTF8 read fCountryCode write fCountryCode;
property CountryCapital: RawUTF8 read fCountryCapital write fCountryCapital;
end;
// 7
TSQLCountryCode = class(TSQLRecord)
private
fCountryCode: RawUTF8;
fCountryAbbr: RawUTF8;
fCountryNumber: RawUTF8;
fCountryName: RawUTF8;
published
property CountryCode: RawUTF8 read fCountryCode write fCountryCode;
property CountryAbbr: RawUTF8 read fCountryAbbr write fCountryAbbr;
property CountryNumber: RawUTF8 read fCountryNumber write fCountryNumber;
property CountryName: RawUTF8 read fCountryName write fCountryName;
end;
// 8
TSQLCountryTeleCode = class(TSQLRecord)
private
fCountryCode: TSQLCountryCodeID;
fTeleCode: RawUTF8;
published
property CountryCode: TSQLCountryCodeID read fCountryCode write fCountryCode;
property TeleCode: RawUTF8 read fTeleCode write fTeleCode;
end;
// 9
TSQLCountryAddressFormat = class(TSQLRecord)
private
fGeo: TSQLGeoID;
fGeoAssocType: TSQLGeoAssocTypeID;
fRequireStateProvince: Integer;
fRequirePostalCode: Boolean;
fPostalCodeRegex: RawUTF8;
fHasPostalCodeExt: Boolean;
fRequirePostalCodeExt: Boolean;
fAddressFormat: RawUTF8;
published
property Geo: TSQLGeoID read fGeo write fGeo;
property GeoAssocType: TSQLGeoAssocTypeID read fGeoAssocType write fGeoAssocType;
property RequireStateProvince: Integer read fRequireStateProvince write fRequireStateProvince;
property RequirePostalCode: Boolean read fRequirePostalCode write fRequirePostalCode;
property PostalCodeRegex: RawUTF8 read fPostalCodeRegex write fPostalCodeRegex;
property HasPostalCodeExt: Boolean read fHasPostalCodeExt write fHasPostalCodeExt;
property RequirePostalCodeExt: Boolean read fRequirePostalCodeExt write fRequirePostalCodeExt;
property AddressFormat: RawUTF8 read fAddressFormat write fAddressFormat;
end;
// 10
TSQLGeo = class(TSQLRecord)
private
fGeoType: TSQLGeoTypeID;
fGeoName: RawUTF8;
fGeoCode: RawUTF8;
fGeoSecCode: RawUTF8;
fAbbreviation: RawUTF8;
fWellKnownText: RawUTF8;
published
property GeoType: TSQLGeoTypeID read fGeoType write fGeoType;
property GeoName: RawUTF8 read fGeoName write fGeoName;
property GeoCode: RawUTF8 read fGeoCode write fGeoCode;
property GeoSecCode: RawUTF8 read fGeoSecCode write fGeoSecCode;
property Abbreviation: RawUTF8 read fAbbreviation write fAbbreviation;
property WellKnownText: RawUTF8 read fWellKnownText write fWellKnownText;
end;
// 11
TSQLGeoAssoc = class(TSQLRecord)
private
fGeo: TSQLGeoID;
fGeoTo: TSQLGeoID;
fGeoAssocType: TSQLGeoAssocTypeID;
published
property Geo: TSQLGeoID read fGeo write fGeo;
property GeoTo: TSQLGeoID read fGeoTo write fGeoTo;
property GeoAssocType: TSQLGeoAssocTypeID read fGeoAssocType write fGeoAssocType;
end;
// 12
TSQLGeoAssocType = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 13
TSQLGeoPoint = class(TSQLRecord)
private
fGeoPointTypeEnum: TSQLEnumerationID;
fDescription: RawUTF8;
fDataSource: TSQLDataSourceID;
fLatitude: RawUTF8;
fLongitude: RawUTF8;
fElevation: Double;
fElevationUom: TSQLUomID;
fInformation: RawUTF8;
published
property GeoPointTypeEnum: TSQLEnumerationID read fGeoPointTypeEnum write fGeoPointTypeEnum;
property Description: RawUTF8 read fDescription write fDescription;
property DataSource: TSQLDataSourceID read fDataSource write fDataSource;
property Latitude: RawUTF8 read fLatitude write fLatitude;
property Longitude: RawUTF8 read fLongitude write fLongitude;
property Elevation: Double read fElevation write fElevation;
property ElevationUom: TSQLUomID read fElevationUom write fElevationUom;
property Information: RawUTF8 read fInformation write fInformation;
end;
// 14
TSQLGeoType = class(TSQLRecord)
private
fParent: TSQLGeoTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLGeoTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 15
TSQLKeywordThesaurus = class(TSQLRecord)
private
fEnteredKeyword: RawUTF8;
fAlternateKeyword: RawUTF8;
fRelationshipEnum: TSQLEnumerationID;
published
property EnteredKeyword: RawUTF8 read fEnteredKeyword write fEnteredKeyword;
property AlternateKeyword: RawUTF8 read fAlternateKeyword write fAlternateKeyword;
property RelationshipEnum: TSQLEnumerationID read fRelationshipEnum write fRelationshipEnum;
end;
// 16
TSQLStandardLanguage = class(TSQLRecord)
private
fLangCode3t: RawUTF8;
fLangCode3b: RawUTF8;
fLangCode2: RawUTF8;
fLangName: RawUTF8;
fLangFamily: RawUTF8;
fLangCharset: RawUTF8;
published
property LangCode3t: RawUTF8 read fLangCode3t write fLangCode3t;
property LangCode3b: RawUTF8 read fLangCode3b write fLangCode3b;
property LangCode2: RawUTF8 read fLangCode2 write fLangCode2;
property LangName: RawUTF8 read fLangName write fLangName;
property LangFamily: RawUTF8 read fLangFamily write fLangFamily;
property LangCharset: RawUTF8 read fLangCharset write fLangCharset;
end;
// 17
TSQLCustomMethod = class(TSQLRecord)
private
fEncode: RawUTF8;
fCustomMethodTypeEncode: RawUTF8;
fCustomMethodType: TSQLCustomMethodTypeID;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property CustomMethodTypeEncode: RawUTF8 read fCustomMethodTypeEncode write fCustomMethodTypeEncode;
property CustomMethodType: TSQLCustomMethodTypeID read fCustomMethodType write fCustomMethodType;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 18
TSQLCustomMethodType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLCustomMethodTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLCustomMethodTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 19
TSQLNoteData = class(TSQLRecord)
private
fNoteName: RawUTF8;
fNoteInfo: RawUTF8;
fNoteDateTime: TDateTime;
published
property NoteName: RawUTF8 read fNoteName write fNoteName;
property NoteInfo: RawUTF8 read fNoteInfo write fNoteInfo;
property NoteDateTime: TDateTime read fNoteDateTime write fNoteDateTime;
end;
// 20
TSQLCustomTimePeriod = class(TSQLRecord)
private
fParentPeriod: TSQLCustomTimePeriodID;
fPeriodType: TSQLPeriodTypeID;
fPeriodNum: Integer;
fPeriodName: RawUTF8;
fFromDate: TDateTime;
fThruDate: TDateTime;
fIsClosed: Boolean;
published
property ParentPeriod: TSQLCustomTimePeriodID read fParentPeriod write fParentPeriod;
property PeriodType: TSQLPeriodTypeID read fPeriodType write fPeriodType;
property PeriodNum: Integer read fPeriodNum write fPeriodNum;
property PeriodName: RawUTF8 read fPeriodName write fPeriodName;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property IsClosed: Boolean read fIsClosed write fIsClosed;
end;
// 21
TSQLPeriodType = class(TSQLRecord)
private
fEncode: RawUTF8;
fUomEncode: RawUTF8;
fName: RawUTF8;
fDescription: RawUTF8;
fPeriodLength: Integer;
fUom: TSQLUomID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property UomEncode: RawUTF8 read fUomEncode write fUomEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property PeriodLength: Integer read fPeriodLength write fPeriodLength;
property Uom: TSQLUomID read fUom write fUom;
end;
// 22
TSQLStatusItem = class(TSQLRecord)
private
fEncode: RawUTF8;
fStatusTypeEncode: RawUTF8;
fStatusType: TSQLStatusTypeID;
fStatusCode: RawUTF8;
fSequence: Integer;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property StatusTypeEncode: RawUTF8 read fStatusTypeEncode write fStatusTypeEncode;
property StatusType: TSQLStatusTypeID read fStatusType write fStatusType;
property StatusCode: RawUTF8 read fStatusCode write fStatusCode;
property Sequence: Integer read fSequence write fSequence;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 23
TSQLStatusType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLStatusTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLStatusTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 24
TSQLStatusValidChange = class(TSQLRecord)
private
fStatusEncode: RawUTF8;
fStatusToEncode: RawUTF8;
fStatus: TSQLStatusItemID;
fStatusTo: TSQLStatusItemID;
fConditionExpression: RawUTF8;
fTransitionName: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property StatusEncode: RawUTF8 read fStatusEncode write fStatusEncode;
property StatusToEncode: RawUTF8 read fStatusToEncode write fStatusToEncode;
property Status: TSQLStatusItemID read fStatus write fStatus;
property StatusTo: TSQLStatusItemID read fStatusTo write fStatusTo;
property ConditionExpression: RawUTF8 read fConditionExpression write fConditionExpression;
property TransitionName: RawUTF8 read fTransitionName write fTransitionName;
end;
// 25
TSQLUom = class(TSQLRecord)
private
fUomType: TSQLUomTypeID;
fAbbreviation: RawUTF8;
fNumericCode: Integer;
fDescription: RawUTF8;
published
property UomType: TSQLUomTypeID read fUomType write fUomType;
property Abbreviation: RawUTF8 read fAbbreviation write fAbbreviation;
property NumericCode: Integer read fNumericCode write fNumericCode;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 26
TSQLUomConversion = class(TSQLRecord)
private
fUom: TSQLUomID;
fUomTo: TSQLUomID;
fConversionFactor: Double;
fCustomMethod: TSQLCustomMethodID;
fDecimalScale: Integer;
fRoundingMode: Integer;
published
property Uom: TSQLUomID read fUom write fUom;
property UomTo: TSQLUomID read fUomTo write fUomTo;
property ConversionFactor: Double read fConversionFactor write fConversionFactor;
property CustomMethod: TSQLCustomMethodID read fCustomMethod write fCustomMethod;
property DecimalScale: Integer read fDecimalScale write fDecimalScale;
property RoundingMode: Integer read fRoundingMode write fRoundingMode;
end;
// 27
TSQLUomConversionDated = class(TSQLRecord)
private
fUom: TSQLUomID;
fUomTo: TSQLUomID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fConversionFactor: Double;
fCustomMethod: TSQLCustomMethodID;
fDecimalScale: Integer;
fRoundingMode: Integer;
fPurposeEnum: TSQLEnumerationID;
published
property Uom: TSQLUomID read fUom write fUom;
property UomTo: TSQLUomID read fUomTo write fUomTo;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property ConversionFactor: Double read fConversionFactor write fConversionFactor;
property CustomMethod: TSQLCustomMethodID read fCustomMethod write fCustomMethod;
property DecimalScale: Integer read fDecimalScale write fDecimalScale;
property RoundingMode: Integer read fRoundingMode write fRoundingMode;
property PurposeEnum: TSQLEnumerationID read fPurposeEnum write fPurposeEnum;
end;
// 28
TSQLUomGroup = class(TSQLRecord)
private
fUom: TSQLUomID;
published
property Uom: TSQLUomID read fUom write fUom;
end;
// 29
TSQLUomType = class(TSQLRecord)
private
fParent: TSQLUomTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLUomTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 30
TSQLUserPreference = class(TSQLRecord)
private
fUserLogin: TSQLUserLoginID;
fUserPrefTypeId: Integer;
fUserPrefGroupType: TSQLUserPrefGroupTypeID;
fUserPrefValue: RawUTF8;
fUserPrefDataType: Integer;
published
property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin;
property UserPrefTypeId: Integer read fUserPrefTypeId write fUserPrefTypeId;
property UserPrefGroupType: TSQLUserPrefGroupTypeID read fUserPrefGroupType write fUserPrefGroupType;
property UserPrefValue: RawUTF8 read fUserPrefValue write fUserPrefValue;
property UserPrefDataType: Integer read fUserPrefDataType write fUserPrefDataType;
end;
// 31
TSQLUserPrefGroupType = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 32
TSQLVisualThemeSet = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 33
TSQLVisualTheme = class(TSQLRecord)
private
fVisualThemeSet: TSQLVisualThemeSetID;
fDescription: RawUTF8;
published
property VisualThemeSet: TSQLVisualThemeSetID read fVisualThemeSet write fVisualThemeSet;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 34
TSQLVisualThemeResource = class(TSQLRecord)
private
fVisualTheme: TSQLVisualThemeID;
fResourceTypeEnum: TSQLEnumerationID;
fSequenceId: Integer;
fResourceValue: RawUTF8;
published
property VisualTheme: TSQLVisualThemeID read fVisualTheme write fVisualTheme;
property ResourceTypeEnum: TSQLEnumerationID read fResourceTypeEnum write fResourceTypeEnum;
property SequenceId: Integer read fSequenceId write fSequenceId;
property ResourceValue: RawUTF8 read fResourceValue write fResourceValue;
end;
// 35
TSQLPortalPortlet = class(TSQLRecord)
private
fPortletName: RawUTF8;
fScreenName: RawUTF8;
fScreenLocation: RawUTF8;
fEditFormName: RawUTF8;
fEditFormLocation: RawUTF8;
fDescription: RawUTF8;
fScreenshot: RawUTF8;
fSecurityServiceName: RawUTF8;
fSecurityMainAction: RawUTF8;
published
property PortletName: RawUTF8 read fPortletName write fPortletName;
property ScreenName: RawUTF8 read fScreenName write fScreenName;
property ScreenLocation: RawUTF8 read fScreenLocation write fScreenLocation;
property EditFormName: RawUTF8 read fEditFormName write fEditFormName;
property EditFormLocation: RawUTF8 read fEditFormLocation write fEditFormLocation;
property Description: RawUTF8 read fDescription write fDescription;
property Screenshot: RawUTF8 read fScreenshot write fScreenshot;
property SecurityServiceName: RawUTF8 read fSecurityServiceName write fSecurityServiceName;
property SecurityMainAction: RawUTF8 read fSecurityMainAction write fSecurityMainAction;
end;
// 36
TSQLPortletCategory = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 37
TSQLPortletPortletCategory = class(TSQLRecord)
private
fPortalPortlet: TSQLPortalPortletID;
fPortletCategory: TSQLPortletCategoryID;
published
property PortalPortlet: TSQLPortalPortletID read fPortalPortlet write fPortalPortlet;
property PortletCategory: TSQLPortletCategoryID read fPortletCategory write fPortletCategory;
end;
// 38
TSQLPortalPage = class(TSQLRecord)
private
fPortalPageName: RawUTF8;
fDescription: RawUTF8;
fOwnerUserLoginId: Integer;
fOriginalPortalPageId: Integer;
fParentPortalPage: TSQLPortalPageID;
fSequenceNum: Integer;
fSecurityGroup: TSQLSecurityGroupID;
published
property PortalPageName: RawUTF8 read fPortalPageName write fPortalPageName;
property Description: RawUTF8 read fDescription write fDescription;
property OwnerUserLoginId: Integer read fOwnerUserLoginId write fOwnerUserLoginId;
property OriginalPortalPageId: Integer read fOriginalPortalPageId write fOriginalPortalPageId;
property ParentPortalPage: TSQLPortalPageID read fParentPortalPage write fParentPortalPage;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
property SecurityGroup: TSQLSecurityGroupID read fSecurityGroup write fSecurityGroup;
end;
// 39
TSQLPortalPageColumn = class(TSQLRecord)
private
fPortalPage: TSQLPortalPageID;
fColumnSeqId: Integer;
fColumnWidthPixels: Integer;
fColumnWidthPercentage: Integer;
published
property PortalPage: TSQLPortalPageID read fPortalPage write fPortalPage;
property ColumnSeqId: Integer read fColumnSeqId write fColumnSeqId;
property ColumnWidthPixels: Integer read fColumnWidthPixels write fColumnWidthPixels;
property ColumnWidthPercentage: Integer read fColumnWidthPercentage write fColumnWidthPercentage;
end;
// 40
TSQLPortalPagePortlet = class(TSQLRecord)
private
fPortalPage: TSQLPortalPageColumnID; //portalPageId, columnSeqId
fPortalPortlet: TSQLPortalPortletID;
fPortletSeqId: Integer;
fSequenceNum: Integer;
published
property PortalPage: TSQLPortalPageColumnID read fPortalPage write fPortalPage;
property PortalPortlet: TSQLPortalPortletID read fPortalPortlet write fPortalPortlet;
property PortletSeqId: Integer read fPortletSeqId write fPortletSeqId;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
end;
// 41
TSQLPortletAttribute = class(TSQLRecord)
private
fPportalPageId: Integer;
fPortalPortletId: Integer;
fPortletSeqId: Integer;
fAttrName: RawUTF8;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
fAttrType: RawUTF8;
published
property PportalPageId: Integer read fPportalPageId write fPportalPageId;
property PortalPortletId: Integer read fPortalPortletId write fPortalPortletId;
property PortletSeqId: Integer read fPortletSeqId write fPortletSeqId;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
property AttrType: RawUTF8 read fAttrType write fAttrType;
end;
// 42
TSQLSystemProperty = class(TSQLRecord)
private
fSystemResourceId: Integer;
fSystemPropertyValue: RawUTF8;
fDescription: RawUTF8;
published
property SystemResourceId: Integer read fSystemResourceId write fSystemResourceId;
property SystemPropertyValue: RawUTF8 read fSystemPropertyValue write fSystemPropertyValue;
property Description: RawUTF8 read fDescription write fDescription;
end;
implementation
uses
Classes, SysUtils;
// 1
class procedure TSQLEnumeration.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLEnumeration;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLEnumeration.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','Enumeration.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update Enumeration set EnumType=(select c.id from EnumerationType c where c.Encode=EnumTypeEncode);');
Server.Execute('update FinAccountType set ReplenishEnum=(select c.id from Enumeration c where c.Encode=FinAccountType.ReplenishEnumEncode);');
finally
Rec.Free;
end;
end;
// 2
class procedure TSQLEnumerationType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLEnumerationType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLEnumerationType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','EnumerationType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update EnumerationType set parent=(select c.id from EnumerationType c where c.Encode=EnumerationType.ParentEncode);');
Server.Execute('update Enumeration set EnumType=(select c.id from EnumerationType c where c.Encode=EnumTypeEncode);');
finally
Rec.Free;
end;
end;
// 3
class procedure TSQLStatusType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLStatusType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLStatusType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','StatusType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update StatusType set Parent=(select c.id from StatusType c where c.Encode=StatusType.ParentEncode);');
Server.Execute('update StatusItem set StatusType=(select c.id from StatusType c where c.Encode=StatusItem.StatusTypeEncode);');
finally
Rec.Free;
end;
end;
// 4
class procedure TSQLStatusItem.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLStatusItem;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLStatusItem.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','StatusItem.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update StatusItem set StatusType=(select c.id from StatusType c where c.Encode=StatusItem.StatusTypeEncode);');
Server.Execute('update StatusValidChange set Status=(select c.id from StatusItem c where c.Encode=StatusValidChange.StatusEncode);');
Server.Execute('update StatusValidChange set StatusTo=(select c.id from StatusItem c where c.Encode=StatusValidChange.StatusToEncode);');
finally
Rec.Free;
end;
end;
// 5
class procedure TSQLStatusValidChange.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLStatusValidChange;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLStatusValidChange.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','StatusValidChange.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update StatusValidChange set Status=(select c.id from StatusItem c where c.Encode=StatusValidChange.StatusEncode);');
Server.Execute('update StatusValidChange set StatusTo=(select c.id from StatusItem c where c.Encode=StatusValidChange.StatusToEncode);');
finally
Rec.Free;
end;
end;
// 6
class procedure TSQLCustomMethodType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCustomMethodType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCustomMethodType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CustomMethodType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CustomMethodType set Parent=(select c.id from CustomMethodType c where c.Encode=CustomMethodType.ParentEncode);');
Server.Execute('update CustomMethod set CustomMethodType=(select c.id from CustomMethodType c where c.Encode=CustomMethodTypeEncode);');
finally
Rec.Free;
end;
end;
// 7
class procedure TSQLCustomMethod.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCustomMethod;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCustomMethod.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CustomMethod.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CustomMethod set CustomMethodType=(select c.id from CustomMethodType c where c.Encode=CustomMethodTypeEncode);');
finally
Rec.Free;
end;
end;
// 8
class procedure TSQLPeriodType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPeriodType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPeriodType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PeriodType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PeriodType set Uom=(select c.id from Uom c where c.Encode=PeriodType.UomEncode);');
finally
Rec.Free;
end;
end;
end.
|
unit Threads.RegularControl;
interface
uses Windows, Classes, SysUtils, GMGenerics, Threads.Base, GMSqlQuery, GMGlobals, Math;
type
TRegularControlledChannel = class
ID_Prm, SourcePrmID: int;
LastControlledDT: LongWord;
bVerified: bool;
end;
TRegularControl = class(TGMThread)
private
FChnList: TGMCollection<TRegularControlledChannel>;
procedure ProcessChannelList;
procedure UpdateRemoteChannelList;
procedure UpdateChannel(q: TGMSqlQuery; obj: pointer);
procedure ProcessChannel(chn: TRegularControlledChannel);
procedure SendControlSignal(chn: TRegularControlledChannel; utime: LongWord; val: double);
protected
procedure SafeExecute; override;
procedure Process;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
implementation
{ TRegularControl }
uses RequestThreadsContainer;
procedure TRegularControl.UpdateChannel(q: TGMSqlQuery; obj: pointer);
var chn, selChn: TRegularControlledChannel;
begin
selChn := nil;
for chn in FChnList do
if chn.ID_Prm = q.FieldByName('ID_Prm').AsInteger then
begin
selChn := chn;
break;
end;
if selChn = nil then
begin
selChn := FChnList.Add();
selChn.ID_Prm := q.FieldByName('ID_Prm').AsInteger;
selChn.SourcePrmID := q.FieldByName('SourcePrmID').AsInteger;
selChn.LastControlledDT := 0;
end
else
begin
if selChn.SourcePrmID <> q.FieldByName('SourcePrmID').AsInteger then
begin
selChn.SourcePrmID := q.FieldByName('SourcePrmID').AsInteger;
selChn.LastControlledDT := 0;
end;
end;
selChn.bVerified := true;
end;
procedure TRegularControl.UpdateRemoteChannelList();
var i: int;
begin
for i := 0 to FChnList.Count - 1 do
FChnList[i].bVerified := false;
ReadFromQuery('select * from Params where coalesce(SourcePrmID, 0) > 0', UpdateChannel);
for i := FChnList.Count - 1 downto 0 do
if not FChnList[i].bVerified then
FChnList.Delete(i);
end;
procedure TRegularControl.AfterConstruction;
begin
FChnList := TGMCollection<TRegularControlledChannel>.Create();
inherited;
end;
procedure TRegularControl.BeforeDestruction;
begin
inherited;
FChnList.Free();
end;
procedure TRegularControl.SendControlSignal(chn: TRegularControlledChannel; utime: LongWord; val: double);
var age: int;
begin
age := NowGM() - utime;
age := Max(Min(age, $FFFF), 0);
ThreadsContainer.SetChannelValue(chn.ID_Prm, val, 0, age);
chn.LastControlledDT := utime;
end;
procedure TRegularControl.ProcessChannel(chn: TRegularControlledChannel);
var utime: LongWord;
val: double;
res: ArrayOfString;
begin
res := QueryResultArray_FirstRow('select Val, UTime from CurrVals where ID_Prm = ' + IntToStr(chn.SourcePrmID));
if Length(res) < 2 then Exit;
val := MyStrToFloatDef(res[0], 0);
utime := StrToIntDef(res[1], 0);
if utime <= chn.LastControlledDT then Exit;
SendControlSignal(chn, utime, val);
end;
procedure TRegularControl.ProcessChannelList();
var chn: TRegularControlledChannel;
begin
for chn in FChnList do
ProcessChannel(chn);
end;
procedure TRegularControl.Process();
begin
UpdateRemoteChannelList();
ProcessChannelList();
end;
procedure TRegularControl.SafeExecute;
var t: int64;
begin
while not Terminated do
begin
t := GetTickCount();
Process();
SleepThread(Max(2000, COMDevicesRequestInterval * 1000 - Abs(t - GetTickCount())));
end;
end;
end.
|
unit ParametersGroupUnit2;
interface
uses
QueryGroupUnit2, System.Classes, ParameterKindsQuery, ParametersQuery,
ParameterTypesQuery, ParamSubParamsQuery, SubParametersQuery2,
System.Generics.Collections, ParametersExcelDataModule, NotifyEvents,
RecordCheck, DSWrap;
type
TParametersGroup2 = class(TQueryGroup2, IParametersGroup)
strict private
function Check(AParametersExcelTable: TParametersExcelTable)
: TRecordCheck; stdcall;
private
FProductCategoryIDValue: Integer;
FqDuplicateParameters: TQueryParameters;
FqParameterKinds: TQueryParameterKinds;
FqParameters: TQueryParameters;
FqParameterTypes: TQueryParameterTypes;
procedure DoBeforeDelete(Sender: TObject);
function GetqParameterKinds: TQueryParameterKinds;
procedure SetProductCategoryIDValue(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
function ApplyAllDuplicateFilter: Boolean;
function ApplyDuplicateFilter: Boolean;
procedure ClearFilter;
procedure Commit; override;
procedure DeleteParamType(AID: Integer);
function Find(const AFieldName, S: string): TArray<String>;
procedure LoadDataFromExcelTable(AParametersExcelTable
: TParametersExcelTable);
function LocateAll(AParameterID: Integer): Boolean;
property ProductCategoryIDValue: Integer read FProductCategoryIDValue
write SetProductCategoryIDValue;
property qParameterKinds: TQueryParameterKinds read GetqParameterKinds;
property qParameters: TQueryParameters read FqParameters;
property qParameterTypes: TQueryParameterTypes read FqParameterTypes;
end;
implementation
uses
System.SysUtils, Data.DB, ParameterKindEnum, ErrorType, System.Variants,
FireDAC.Comp.DataSet;
constructor TParametersGroup2.Create(AOwner: TComponent);
begin
inherited;
// Типы параметров
FqParameterTypes := TQueryParameterTypes.Create(Self);
// Параметры
FqParameters := TQueryParameters.Create(Self);
FqParameters.Name := 'qParameters';
// Дубикаты параметров (чтобы узнать, есть они или их нет)
FqDuplicateParameters := TQueryParameters.Create(Self);
QList.Add(qParameterTypes); // Тип каждого параметра
QList.Add(qParameters); // Сами параметры
// Для каскадного удаления
TNotifyEventWrap.Create(qParameterTypes.W.BeforeDelete, DoBeforeDelete,
EventList);
end;
function TParametersGroup2.ApplyAllDuplicateFilter: Boolean;
begin
// Сначала проверяем, есть дубликаты или их нет
FqDuplicateParameters.ApplyFilter('');
Result := FqDuplicateParameters.FDQuery.RecordCount > 0;
if not Result then
Exit;
SaveBookmark;
qParameterTypes.ApplyFilter('');
qParameters.ApplyFilter('');
RestoreBookmark;
end;
function TParametersGroup2.ApplyDuplicateFilter: Boolean;
var
ATableName: string;
begin
ATableName := qParameters.W.TableName.F.AsString;
Assert(not ATableName.IsEmpty);
// Сначала проверяем, есть ли вообще дубликаты
FqDuplicateParameters.ApplyFilter(ATableName);
Result := FqDuplicateParameters.FDQuery.RecordCount > 0;
if not Result then
Exit;
// Если дубликаты есть
SaveBookmark;
qParameterTypes.ApplyFilter(ATableName);
qParameters.ApplyFilter(ATableName);
RestoreBookmark;
end;
function TParametersGroup2.Check(AParametersExcelTable: TParametersExcelTable)
: TRecordCheck;
var
AFieldNames: string;
AParameterKindID: Integer;
AIDParameterType: Integer;
Arr: Variant;
V: Variant;
begin
Result.ErrorType := etNone;
// Проверяем, что в файле целое число
AParameterKindID :=
StrToIntDef(AParametersExcelTable.ParameterKindID.AsString, -100);
// Если вид параметра задан строкой
if AParameterKindID = -100 then
begin
// Ищем в справочнике видов параметров
AParameterKindID := qParameterKinds.W.GetIDByParameterKind
(AParametersExcelTable.ParameterKindID.AsString);
if AParameterKindID = 0 then
begin
// Запоминаем, что в этой строке ошибка
Result.ErrorType := etError;
Result.Row := AParametersExcelTable.ExcelRow.AsInteger;
Result.Col := AParametersExcelTable.ParameterKindID.Index + 1;
Result.ErrorMessage := AParametersExcelTable.ParameterKindID.AsString;
Result.Description :=
Format('Код вида параметра должен быть целым числом от %d до %d',
[Integer(Неиспользуется), Integer(Строковый_частичный)]);
Exit;
end;
end
else
begin
if (AParameterKindID < Integer(Неиспользуется)) or
(AParameterKindID > Integer(Строковый_частичный)) then
begin
// Запоминаем, что в этой строке ошибка
Result.ErrorType := etError;
Result.Row := AParametersExcelTable.ExcelRow.AsInteger;
Result.Col := AParametersExcelTable.ParameterKindID.Index + 1;
Result.ErrorMessage := AParametersExcelTable.ParameterKindID.AsString;
Result.Description := Format('Код вида параметра должен быть от %d до %d',
[Integer(Неиспользуется), Integer(Строковый_частичный)]);
Exit;
end;
end;
// Определяемся с типом параметра
AIDParameterType := qParameterTypes.W.GetParameterTypeID
(AParametersExcelTable.ParameterType.AsString);
// Если это существующий ранее тип параметра
if AIDParameterType > 0 then
begin
// Возможно это полный дубликат
AFieldNames := Format('%s;%s;%s;%s;%s;%s;%s;%s',
[qParameters.W.Value.FieldName, qParameters.W.ValueT.FieldName,
qParameters.W.CodeLetters.FieldName,
qParameters.W.MeasuringUnit.FieldName, qParameters.W.TableName.FieldName,
qParameters.W.Definition.FieldName,
qParameters.W.IDParameterType.FieldName,
qParameters.W.IDParameterKind.FieldName]);
with AParametersExcelTable do
Arr := VarArrayOf([Value.Value, ValueT.Value, CodeLetters.Value,
MeasuringUnit.Value, TableName.Value, Definition.Value,
AIDParameterType, AParameterKindID]);
// Ищем дубликат
V := qParameters.FDQuery.LookupEx(AFieldNames, Arr,
qParameters.W.PKFieldName, [lxoCaseInsensitive]);
if not VarIsNull(V) then
begin
// Запоминаем, что в этой строке ошибка
Result.ErrorType := etError;
Result.Row := AParametersExcelTable.ExcelRow.AsInteger;
Result.Col := AParametersExcelTable.TableName.Index + 1;
Result.ErrorMessage := AParametersExcelTable.TableName.AsString;
Result.Description :=
'Точно такой же параметр уже есть в справочнике параметров';
Exit;
end;
end;
AFieldNames := Format('%s;%s', [qParameters.W.TableName.FieldName,
qParameters.W.IsCustomParameter.FieldName]);
Arr := VarArrayOf([AParametersExcelTable.TableName.Value, False]);
// Ищем дубликат по табличному имени
V := qParameters.FDQuery.LookupEx(AFieldNames, Arr, qParameters.W.PKFieldName,
[lxoCaseInsensitive]);
if not VarIsNull(V) then
begin
// Запоминаем, что в этой строке ошибка
Result.ErrorType := etWarring;
Result.Row := AParametersExcelTable.ExcelRow.AsInteger;
Result.Col := AParametersExcelTable.TableName.Index + 1;
Result.ErrorMessage := AParametersExcelTable.TableName.AsString;
Result.Description :=
'Параметр с таким табличным именем уже есть в справочнике параметров';
Exit;
end;
end;
procedure TParametersGroup2.ClearFilter;
begin
SaveBookmark;
qParameterTypes.FDQuery.SQL.Text := qParameterTypes.SQL;
qParameters.FDQuery.SQL.Text := qParameters.SQL;
TryOpen;
RestoreBookmark;
end;
procedure TParametersGroup2.Commit;
begin
// Похоже мы в режиме отображения галочек для какой-то категории
if ProductCategoryIDValue > 0 then
TryPost
else
inherited;
end;
procedure TParametersGroup2.DeleteParamType(AID: Integer);
var
ASQL: string;
begin
ASQL := Format('delete from ParameterTypes where ID = %d', [AID]);
Connection.ExecSQL(ASQL);
end;
procedure TParametersGroup2.DoBeforeDelete(Sender: TObject);
var
AIDParameterType: Integer;
begin
AIDParameterType := qParameterTypes.W.PK.Value;
// Каскадно удаляем параметры
qParameters.W.CascadeDelete(AIDParameterType,
qParameters.W.IDParameterType.FieldName);
// cxGrid сместил запись, поэтому возвращаемся на место
qParameterTypes.W.LocateByPK(AIDParameterType, True);
end;
function TParametersGroup2.Find(const AFieldName, S: string): TArray<String>;
var
L: TList<String>;
begin
Assert(not AFieldName.IsEmpty);
L := TList<String>.Create();
try
// Пытаемся искать среди параметров по какому-то полю
if qParameters.W.LocateByF(AFieldName, S,
[lxoCaseInsensitive, lxoPartialKey]) then
begin
qParameterTypes.W.LocateByPK(qParameters.W.IDParameterType.F.Value, True);
// запоминаем что надо искать на первом уровне
L.Add(qParameterTypes.W.ParameterType.F.AsString);
// запоминаем что надо искать на втором уровне
L.Add(S);
end
else
// Пытаемся искать среди типов параметров
if qParameterTypes.W.LocateByF(qParameterTypes.W.ParameterType.FieldName,
S, [lxoCaseInsensitive, lxoPartialKey]) then
begin
L.Add(S);
end;
Result := L.ToArray;
finally
FreeAndNil(L);
end;
end;
function TParametersGroup2.GetqParameterKinds: TQueryParameterKinds;
begin
if FqParameterKinds = nil then
begin
FqParameterKinds := TQueryParameterKinds.Create(Self);
FqParameterKinds.FDQuery.Open;
// FqParameterKinds.W.ParameterKind.F.DisplayLabel := 'Вид параметра';
end;
Result := FqParameterKinds;
end;
procedure TParametersGroup2.LoadDataFromExcelTable(AParametersExcelTable
: TParametersExcelTable);
var
AField: TField;
AParameterKindID: Integer;
AParameterType: string;
I: Integer;
begin
TryPost;
if qParameterKinds.FDQuery.RecordCount = 0 then
raise Exception.Create('Справочник видов параметров не заполнен');
AParametersExcelTable.DisableControls;
qParameterTypes.FDQuery.DisableControls;
qParameters.FDQuery.DisableControls;
try
AParametersExcelTable.First;
AParametersExcelTable.CallOnProcessEvent;
while not AParametersExcelTable.Eof do
begin
AParameterType := AParametersExcelTable.ParameterType.AsString;
qParameterTypes.W.LocateOrAppend(AParameterType);
AParameterKindID :=
StrToIntDef(AParametersExcelTable.ParameterKindID.AsString, -1);
// Если вид параметра не числовой
if AParameterKindID = -1 then
begin
// Если нашли такой вид параметра в справочнике
if qParameterKinds.W.ParameterKind.Locate
(AParametersExcelTable.ParameterKindID.AsString, [lxoCaseInsensitive])
then
AParameterKindID := qParameterKinds.W.PK.AsInteger
else
AParameterKindID := Integer(Неиспользуется);
end
else
begin
// Ищем такой вид параметра в справочнике
if not qParameterKinds.W.LocateByPK(AParameterKindID) then
AParameterKindID := Integer(Неиспользуется);
end;
qParameters.FDQuery.Append;
try
for I := 0 to AParametersExcelTable.FieldCount - 1 do
begin
AField := qParameters.FDQuery.FindField
(AParametersExcelTable.Fields[I].FieldName);
if AField <> nil then
begin
AField.Value := AParametersExcelTable.Fields[I].Value;
end;
end;
qParameters.W.IDParameterType.F.AsInteger :=
qParameterTypes.W.PK.AsInteger;
qParameters.W.IDParameterKind.F.AsInteger := AParameterKindID;
qParameters.FDQuery.Post;
except
qParameters.FDQuery.Cancel;
raise;
end;
AParametersExcelTable.Next;
AParametersExcelTable.CallOnProcessEvent;
end;
finally
AParametersExcelTable.EnableControls;
qParameters.FDQuery.EnableControls;
qParameterTypes.FDQuery.EnableControls;
end;
end;
function TParametersGroup2.LocateAll(AParameterID: Integer): Boolean;
begin
// Сначала ищем параметр
Result := qParameters.W.LocateByPK(AParameterID);
if not Result then
Exit;
// Ищем тип параметра
qParameterTypes.W.LocateByPK(qParameters.W.IDParameterType.F.AsInteger, True);
end;
procedure TParametersGroup2.SetProductCategoryIDValue(const Value: Integer);
begin
if FProductCategoryIDValue = Value then
Exit;
FProductCategoryIDValue := Value;
// qParameters.ProductCategoryIDValue := FProductCategoryIDValue;
// Значение постоянного параметра
qParameters.W.ProductCategoryID.DefaultValue := FProductCategoryIDValue;
end;
end.
|
unit Solutions;
{$mode tp}
{$H+}
interface
uses
Math, SysUtils;
function LargestPalindromeProduct: Int64;
function LargestPrimeFactor(number: Int64): Int64;
function EvenFibonacciNumbers: Int64;
function MultiplesOf3And5: Int64;
implementation
type
IntVector = Array of Int64;
BoolVector = Array of Boolean;
function isPalindrome(number: Int64): Boolean;
var
stringRep: String;
i: Int64;
begin
i := 1;
stringRep := IntToStr(number);
isPalindrome := TRUE;
While i <= ceil64(((Length(stringRep) - 1) div 2)) + Int64(1) do
begin
// Strings are 1-based indexed arrays
If stringRep[i] <> stringRep[Length(stringRep) + Int64(1) - i] then
begin
isPalindrome := FALSE;
Break;
end;
i := i + 1;
end;
end;
{ @param limit is exclusive }
function SieveOfEratosthenes(limit: Int64): IntVector;
var
primes: IntVector;
lattice: BoolVector;
i, j, primesSize: Int64;
begin
If limit < 3 then
begin
WriteLn('Limit should be greater than 2');
end
else
begin
primesSize := 1;
i := 2;
SetLength(lattice, limit);
SetLength(primes, primesSize);
While i <= limit do
begin
If lattice[i] = FALSE then
begin
j := 2;
primes[primesSize - 1] := i;
primesSize := primesSize + 1;
SetLength(primes, primesSize);
While j * i < limit do
begin
lattice[i * j] := TRUE;
j := j + 1;
end;
end;
i := i + 1;
end;
SetLength(primes, primesSize - 1);
SieveOfEratosthenes := primes;
end;
end;
{[Largest palindrome product](https://projecteuler.net/problem=4)}
function LargestPalindromeProduct: Int64;
var
largestPalindrome: Int64;
i, j: Int64;
begin
i := 100;
largestPalindrome := 0;
While i <= 999 do
begin
j := i;
While j <= 999 do
begin
If isPalindrome(i * j) and (largestPalindrome < i * j) then
largestPalindrome := i * j;
j := j + 1;
end;
i := i + 1;
end;
WriteLn('Largest Palindrome Product - ', largestPalindrome);
LargestPalindromeProduct := largestPalindrome;
end;
{(Largest prime factor)[https://projecteuler.net/problem=3]}
function LargestPrimeFactor(number: Int64): Int64;
var
cap, primeFactorsSize, i: Int64;
primesOfInterest, primeFactors: IntVector;
begin
cap := ceil64(sqrt(number));
primeFactorsSize := 0;
i := 0;
SetLength(primeFactors, primeFactorsSize);
primesOfInterest := SieveOfEratosthenes(cap);
While i <= Length(primesOfInterest) - Int64(1) do
begin
If (number mod primesOfInterest[i] = 0) then
begin
primeFactorsSize := primeFactorsSize + 1;
SetLength(primeFactors, primeFactorsSize);
primeFactors[primeFactorsSize - 1] := primesOfInterest[i];
While (number mod primesOfInterest[i] = 0) do
begin
number := number div primesOfInterest[i];
end;
end;
i := i + 1;
end;
WriteLn('Largest Prime Factor - ', primeFactors[primeFactorsSize - 1]);
LargestPrimeFactor := primeFactors[primeFactorsSize - 1];
end;
{(Even Fibonacci numbers)[https://projecteuler.net/problem=2]}
function EvenFibonacciNumbers: Int64;
var
fibPrev, fibCurr, sum: Int64;
cap: Int64;
begin
fibPrev := 1;
fibCurr := 2;
sum := 0;
cap := 4000000;
While fibCurr < cap do
begin
If (fibCurr mod 2 = 0) then sum := sum + fibCurr;
fibCurr := fibCurr + fibPrev;
fibPrev := fibCurr - fibPrev;
end;
WriteLn('Even Fibonacci Numbers - ', sum);
EvenFibonacciNumbers := sum;
end;
{(Multiples of 3 and 5)[https://projecteuler.net/problem=1]}
function MultiplesOf3And5: Int64;
var
i, sum: Int64;
begin
sum := 0;
i := 0;
While i <= 999 do
begin
If (i mod 3 = 0) or (i mod 5 = 0) then sum := sum + i;
i := i + 1;
end;
WriteLn('Multiples Of 3 And 5 - ', sum);
MultiplesOf3And5 := sum;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995,98 Inprise Corporation }
{ }
{*******************************************************}
unit IniFiles;
{$R-}
interface
uses Windows, SysUtils, Classes;
type
TCustomIniFile = class(TObject)
private
FFileName: string;
public
constructor Create(const FileName: string);
function SectionExists(const Section: string): Boolean;
function ReadString(const Section, Ident, Default: string): string; virtual; abstract;
procedure WriteString(const Section, Ident, Value: String); virtual; abstract;
function ReadInteger(const Section, Ident: string; Default: Longint): Longint; virtual;
procedure WriteInteger(const Section, Ident: string; Value: Longint); virtual;
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; virtual;
procedure WriteBool(const Section, Ident: string; Value: Boolean); virtual;
function ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; virtual;
function ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; virtual;
function ReadFloat(const Section, Name: string; Default: Double): Double; virtual;
function ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; virtual;
procedure WriteDate(const Section, Name: string; Value: TDateTime); virtual;
procedure WriteDateTime(const Section, Name: string; Value: TDateTime); virtual;
procedure WriteFloat(const Section, Name: string; Value: Double); virtual;
procedure WriteTime(const Section, Name: string; Value: TDateTime); virtual;
procedure ReadSection(const Section: string; Strings: TStrings); virtual; abstract;
procedure ReadSections(Strings: TStrings); virtual; abstract;
procedure ReadSectionValues(const Section: string; Strings: TStrings); virtual; abstract;
procedure EraseSection(const Section: string); virtual; abstract;
procedure DeleteKey(const Section, Ident: String); virtual; abstract;
procedure UpdateFile; virtual; abstract;
function ValueExists(const Section, Ident: string): Boolean;
property FileName: string read FFileName;
end;
{ TIniFile - Encapsulates the Windows INI file interface
(Get/SetPrivateProfileXXX functions) }
TIniFile = class(TCustomIniFile)
public
function ReadString(const Section, Ident, Default: string): string; override;
procedure WriteString(const Section, Ident, Value: String); override;
procedure ReadSection(const Section: string; Strings: TStrings); override;
procedure ReadSections(Strings: TStrings); override;
procedure ReadSectionValues(const Section: string; Strings: TStrings); override;
procedure EraseSection(const Section: string); override;
procedure DeleteKey(const Section, Ident: String); override;
procedure UpdateFile; override;
end;
{ TMemIniFile - loads and entire ini file into memory and allows all
operations to be performed on the memory image. The image can then
be written out to the disk file }
TMemIniFile = class(TCustomIniFile)
private
FSections: TStringList;
function AddSection(const Section: string): TStrings;
procedure LoadValues;
public
constructor Create(const FileName: string);
destructor Destroy; override;
procedure Clear;
procedure DeleteKey(const Section, Ident: String); override;
procedure EraseSection(const Section: string); override;
procedure GetStrings(List: TStrings);
procedure ReadSection(const Section: string; Strings: TStrings); override;
procedure ReadSections(Strings: TStrings); override;
procedure ReadSectionValues(const Section: string; Strings: TStrings); override;
function ReadString(const Section, Ident, Default: string): string; override;
procedure Rename(const FileName: string; Reload: Boolean);
procedure SetStrings(List: TStrings);
procedure UpdateFile; override;
procedure WriteString(const Section, Ident, Value: String); override;
end;
implementation
uses Consts;
{ TCustomIniFile }
constructor TCustomIniFile.Create(const FileName: string);
begin
FFileName := FileName;
end;
function TCustomIniFile.SectionExists(const Section: string): Boolean;
var
S: TStrings;
begin
S := TStringList.Create;
try
ReadSection(Section, S);
Result := S.Count > 0;
finally
S.Free;
end;
end;
function TCustomIniFile.ReadInteger(const Section, Ident: string;
Default: Longint): Longint;
var
IntStr: string;
begin
IntStr := ReadString(Section, Ident, '');
if (Length(IntStr) > 2) and (IntStr[1] = '0') and
((IntStr[2] = 'X') or (IntStr[2] = 'x')) then
IntStr := '$' + Copy(IntStr, 3, Maxint);
Result := StrToIntDef(IntStr, Default);
end;
procedure TCustomIniFile.WriteInteger(const Section, Ident: string; Value: Longint);
begin
WriteString(Section, Ident, IntToStr(Value));
end;
function TCustomIniFile.ReadBool(const Section, Ident: string;
Default: Boolean): Boolean;
begin
Result := ReadInteger(Section, Ident, Ord(Default)) <> 0;
end;
function TCustomIniFile.ReadDate(const Section, Name: string; Default: TDateTime): TDateTime;
var
DateStr: string;
begin
DateStr := ReadString(Section, Name, '');
Result := Default;
if DateStr <> '' then
try
Result := StrToDate(DateStr);
except
on EConvertError do
else raise;
end;
end;
function TCustomIniFile.ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime;
var
DateStr: string;
begin
DateStr := ReadString(Section, Name, '');
Result := Default;
if DateStr <> '' then
try
Result := StrToDateTime(DateStr);
except
on EConvertError do
else raise;
end;
end;
function TCustomIniFile.ReadFloat(const Section, Name: string; Default: Double): Double;
var
FloatStr: string;
begin
FloatStr := ReadString(Section, Name, '');
Result := Default;
if FloatStr <> '' then
try
Result := StrToFloat(FloatStr);
except
on EConvertError do
else raise;
end;
end;
function TCustomIniFile.ReadTime(const Section, Name: string; Default: TDateTime): TDateTime;
var
TimeStr: string;
begin
TimeStr := ReadString(Section, Name, '');
Result := Default;
if TimeStr <> '' then
try
Result := StrToTime(TimeStr);
except
on EConvertError do
else raise;
end;
end;
procedure TCustomIniFile.WriteDate(const Section, Name: string; Value: TDateTime);
begin
WriteString(Section, Name, DateToStr(Value));
end;
procedure TCustomIniFile.WriteDateTime(const Section, Name: string; Value: TDateTime);
begin
WriteString(Section, Name, DateTimeToStr(Value));
end;
procedure TCustomIniFile.WriteFloat(const Section, Name: string; Value: Double);
begin
WriteString(Section, Name, FloatToStr(Value));
end;
procedure TCustomIniFile.WriteTime(const Section, Name: string; Value: TDateTime);
begin
WriteString(Section, Name, TimeToStr(Value));
end;
procedure TCustomIniFile.WriteBool(const Section, Ident: string; Value: Boolean);
const
Values: array[Boolean] of string = ('0', '1');
begin
WriteString(Section, Ident, Values[Value]);
end;
function TCustomIniFile.ValueExists(const Section, Ident: string): Boolean;
var
S: TStrings;
begin
S := TStringList.Create;
try
ReadSection(Section, S);
Result := S.IndexOf(Ident) > -1;
finally
S.Free;
end;
end;
{ TIniFile }
function TIniFile.ReadString(const Section, Ident, Default: string): string;
var
Buffer: array[0..2047] of Char;
begin
SetString(Result, Buffer, GetPrivateProfileString(PChar(Section),
PChar(Ident), PChar(Default), Buffer, SizeOf(Buffer), PChar(FFileName)));
end;
procedure TIniFile.WriteString(const Section, Ident, Value: string);
begin
if not WritePrivateProfileString(PChar(Section), PChar(Ident),
PChar(Value), PChar(FFileName)) then
raise Exception.CreateFmt(SIniFileWriteError, [FileName]);
end;
procedure TIniFile.ReadSections(Strings: TStrings);
const
BufSize = 16384;
var
Buffer, P: PChar;
begin
GetMem(Buffer, BufSize);
try
Strings.BeginUpdate;
try
Strings.Clear;
if GetPrivateProfileString(nil, nil, nil, Buffer, BufSize,
PChar(FFileName)) <> 0 then
begin
P := Buffer;
while P^ <> #0 do
begin
Strings.Add(P);
Inc(P, StrLen(P) + 1);
end;
end;
finally
Strings.EndUpdate;
end;
finally
FreeMem(Buffer, BufSize);
end;
end;
procedure TIniFile.ReadSection(const Section: string; Strings: TStrings);
const
BufSize = 16384;
var
Buffer, P: PChar;
begin
GetMem(Buffer, BufSize);
try
Strings.BeginUpdate;
try
Strings.Clear;
if GetPrivateProfileString(PChar(Section), nil, nil, Buffer, BufSize,
PChar(FFileName)) <> 0 then
begin
P := Buffer;
while P^ <> #0 do
begin
Strings.Add(P);
Inc(P, StrLen(P) + 1);
end;
end;
finally
Strings.EndUpdate;
end;
finally
FreeMem(Buffer, BufSize);
end;
end;
procedure TIniFile.ReadSectionValues(const Section: string; Strings: TStrings);
var
KeyList: TStringList;
I: Integer;
begin
KeyList := TStringList.Create;
try
ReadSection(Section, KeyList);
Strings.BeginUpdate;
try
for I := 0 to KeyList.Count - 1 do
Strings.Values[KeyList[I]] := ReadString(Section, KeyList[I], '');
finally
Strings.EndUpdate;
end;
finally
KeyList.Free;
end;
end;
procedure TIniFile.EraseSection(const Section: string);
begin
if not WritePrivateProfileString(PChar(Section), nil, nil,
PChar(FFileName)) then
raise Exception.CreateFmt(SIniFileWriteError, [FileName]);
end;
procedure TIniFile.DeleteKey(const Section, Ident: String);
begin
WritePrivateProfileString(PChar(Section), PChar(Ident), nil,
PChar(FFileName));
end;
procedure TIniFile.UpdateFile;
begin
WritePrivateProfileString(nil, nil, nil, PChar(FFileName));
end;
{ TMemIniFile }
constructor TMemIniFile.Create(const FileName: string);
begin
inherited Create(FileName);
FSections := TStringList.Create;
LoadValues;
end;
destructor TMemIniFile.Destroy;
begin
if FSections <> nil then Clear;
FSections.Free;
end;
function TMemIniFile.AddSection(const Section: string): TStrings;
begin
Result := TStringList.Create;
try
FSections.AddObject(Section, Result);
except
Result.Free;
end;
end;
procedure TMemIniFile.Clear;
var
I: Integer;
begin
for I := 0 to FSections.Count - 1 do
TStrings(FSections.Objects[I]).Free;
FSections.Clear;
end;
procedure TMemIniFile.DeleteKey(const Section, Ident: String);
var
I, J: Integer;
Strings: TStrings;
begin
I := FSections.IndexOf(Section);
if I >= 0 then
begin
Strings := TStrings(FSections.Objects[I]);
J := Strings.IndexOfName(Ident);
if J >= 0 then Strings.Delete(J);
end;
end;
procedure TMemIniFile.EraseSection(const Section: string);
var
I: Integer;
begin
I := FSections.IndexOf(Section);
if I >= 0 then
begin
TStrings(FSections.Objects[I]).Free;
FSections.Delete(I);
end;
end;
procedure TMemIniFile.GetStrings(List: TStrings);
var
I, J: Integer;
Strings: TStrings;
begin
List.BeginUpdate;
try
for I := 0 to FSections.Count - 1 do
begin
List.Add('[' + FSections[I] + ']');
Strings := TStrings(FSections.Objects[I]);
for J := 0 to Strings.Count - 1 do List.Add(Strings[J]);
List.Add('');
end;
finally
List.EndUpdate;
end;
end;
procedure TMemIniFile.LoadValues;
var
List: TStringList;
begin
if (FileName <> '') and FileExists(FileName) then
begin
List := TStringList.Create;
try
List.LoadFromFile(FileName);
SetStrings(List);
finally
List.Free;
end;
end else Clear;
end;
procedure TMemIniFile.ReadSection(const Section: string;
Strings: TStrings);
var
I, J: Integer;
SectionStrings: TStrings;
begin
Strings.BeginUpdate;
try
Strings.Clear;
I := FSections.IndexOf(Section);
if I >= 0 then
begin
SectionStrings := TStrings(FSections.Objects[I]);
for J := 0 to SectionStrings.Count - 1 do
Strings.Add(SectionStrings.Names[J]);
end;
finally
Strings.EndUpdate;
end;
end;
procedure TMemIniFile.ReadSections(Strings: TStrings);
begin
Strings.Assign(FSections);
end;
procedure TMemIniFile.ReadSectionValues(const Section: string;
Strings: TStrings);
var
I: Integer;
begin
Strings.BeginUpdate;
try
Strings.Clear;
I := FSections.IndexOf(Section);
if I >= 0 then Strings.Assign(TStrings(FSections.Objects[I]));
finally
Strings.EndUpdate;
end;
end;
function TMemIniFile.ReadString(const Section, Ident,
Default: string): string;
var
I: Integer;
Strings: TStrings;
begin
I := FSections.IndexOf(Section);
if I >= 0 then
begin
Strings := TStrings(FSections.Objects[I]);
I := Strings.IndexOfName(Ident);
if I >= 0 then
begin
Result := Copy(Strings[I], Length(Ident) + 2, Maxint);
Exit;
end;
end;
Result := Default;
end;
procedure TMemIniFile.Rename(const FileName: string; Reload: Boolean);
begin
FFileName := FileName;
if Reload then LoadValues;
end;
procedure TMemIniFile.SetStrings(List: TStrings);
var
I: Integer;
S: string;
Strings: TStrings;
begin
Clear;
Strings := nil;
for I := 0 to List.Count - 1 do
begin
S := List[I];
if (S <> '') and (S[1] <> ';') then
if (S[1] = '[') and (S[Length(S)] = ']') then
Strings := AddSection(Copy(S, 2, Length(S) - 2))
else
if Strings <> nil then Strings.Add(S);
end;
end;
procedure TMemIniFile.UpdateFile;
var
List: TStringList;
begin
List := TStringList.Create;
try
GetStrings(List);
List.SaveToFile(FFileName);
finally
List.Free;
end;
end;
procedure TMemIniFile.WriteString(const Section, Ident, Value: String);
var
I: Integer;
S: string;
Strings: TStrings;
begin
I := FSections.IndexOf(Section);
if I >= 0 then
Strings := TStrings(FSections.Objects[I]) else
Strings := AddSection(Section);
S := Ident + '=' + Value;
I := Strings.IndexOfName(Ident);
if I >= 0 then Strings[I] := S else Strings.Add(S);
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit MCIcodes;
interface
function mciProcess(S : String; Len : Byte) : String;
function mciProcessControlCode(C : String) : Boolean;
function mciProcessMCICode(C : String) : Boolean;
implementation
uses Crt,
Global, Output, Strings, Misc, DateTime, Input;
function mciProcessControlCode(C : String) : Boolean;
begin
mciProcessControlCode := False;
if (Length(C) <> 3) or (C[1] <> ctrHeader) then Exit;
Delete(C,1,1);
C := UpStr(C);
mciProcessControlCode := True;
case C[1] of
'0' : case C[2] of
'0' : oSetFore(0);
'1' : oSetFore(1);
'2' : oSetFore(2);
'3' : oSetFore(3);
'4' : oSetFore(4);
'5' : oSetFore(5);
'6' : oSetFore(6);
'7' : oSetFore(7);
'8' : oSetFore(8);
'9' : oSetFore(9);
end;
'1' : case C[2] of
'0' : oSetFore(10);
'1' : oSetFore(11);
'2' : oSetFore(12);
'3' : oSetFore(13);
'4' : oSetFore(14);
'5' : oSetFore(15);
'6' : oSetBack(0);
'7' : oSetBack(1);
'8' : oSetBack(2);
'9' : oSetBack(3);
end;
'2' : case C[2] of
'0' : oSetBack(4);
'1' : oSetBack(5);
'2' : oSetBack(6);
'3' : oSetBack(7);
end;
'A' : case C[2] of
'S' : saveCol := Col;
'L' : oSetColRec(saveCol);
end;
'B' : case C[2] of
'0' : oSetBack(0);
'1' : oSetBack(1);
'2' : oSetBack(2);
'3' : oSetBack(3);
'4' : oSetBack(4);
'5' : oSetBack(5);
'6' : oSetBack(6);
'7' : oSetBack(7);
end;
'C' : case C[2] of
'B' : oMoveDown(25);
'D' : oMoveDown(1);
'E' : oMoveRight(80);
'H' : oMoveLeft(80);
'L' : oMoveLeft(1);
'R' : oMoveRight(1);
'S' : oClrScr;
'T' : oMoveUp(25);
'U' : oMoveUp(1);
'Z' : oClrEol;
end;
'D' : case C[2] of
'E' : Delay(750);
'H' : Delay(500);
'M' : Delay(100);
'S' : Delay(1000);
end;
'H' : case C[2] of
'C' : oGotoXY(1,1);
end;
'L' : case C[2] of
'C' : oRestoreCursor;
'F' : oWrite(#13#10);
end;
'P' : case C[2] of
'A' : oPromptKey;
'K' : iReadKey;
'S' : oPause;
end;
'S' : case C[2] of
'C' : oSaveCursor;
end;
'U' : case C[2] of
'0' : oSetCol(colError);
'1' : oSetCol(colText);
'2' : oSetCol(colTextLo);
'3' : oSetCol(colTextHi);
'4' : oSetCol(colInfo);
'5' : oSetCol(colInfoLo);
'6' : oSetCol(colInfoHi);
'7' : oSetCol(colItem);
'8' : oSetCol(colItemSel);
'9' : oSetCol(colBorder);
end;
else mciProcessControlCode := False;
end;
end;
function mciProcessMCICode(C : String) : Boolean;
var S : String;
begin
mciProcessMCIcode := False;
S := '';
C := UpStr(C);
if (Length(C) <> 3) or (C[1] <> mciHeader) then Exit;
mciProcessMCIcode := True;
Delete(C,1,1);
case C[1] of
'A' : case C[2] of
'1'..'6' : if User^.AutoSigLns >= StrToInt(C[2]) then
S := User^.AutoSig[StrToInt(C[2])] else S := '';
'C' : S := mAreaCode;
'D' : S := User^.Address;
'L' : S := St(User^.AutoSigLns);
'Q' : S := B2St(acQuote in User^.acFlag);
end;
'B' : case C[2] of
'D' : S := User^.Birthdate;
'L' : S := Cfg^.bbsLocation;
'N' : S := Cfg^.BBSname;
'P' : S := Cfg^.BBSphone;
'R' : S := mBaudString(User^.BaudRate);
end;
'C' : case C[2] of
'F' : S := fConf^.Desc;
'M' : S := mConf^.Desc;
'T' : S := Stc(User^.CallsToday);
end;
'D' : case C[2] of
'C' : S := Stc(His^.Calls);
'D' : S := Stc(His^.Downloads);
'F' : S := dtDateFullString(dtDateString);
'K' : S := Stc(User^.DownloadKb)+'k';
'L' : S := Stc(User^.Downloads);
'P' : S := Stc(His^.Posts);
'S' : S := St(User^.DSL);
'T' : S := dtDateString;
'U' : S := Stc(His^.Uploads);
end;
'E' : case C[2] of
'M' : S := mEmulation(User^);
end;
'F' : case C[2] of
'A' : S := fArea^.Name;
'C' : S := User^.FirstCall;
'D' : S := User^.fileScan;
'P' : S := St(User^.filePts);
'I' : S := St(User^.curFileArea);
'S' : S := User^.fileScan;
end;
'H' : case C[2] of
'K' : S := B2St(acHotKey in User^.acFlag);
end;
'I' : case C[2] of
'D' : S := St(User^.Number);
'N' : S := bbsTitle;
'S' : S := inputString;
'V' : S := bbsVersion;
end;
'L' : case C[2] of
'A' : if tLibOpen then S := textLib^.Author else S := 'n/a';
'C' : S := User^.LastCall;
'D' : if tLibOpen then S := textLib^.Desc else S := 'n/a';
'O' : S := User^.Location;
end;
'M' : case C[2] of
'A' : S := mArea^.Name;
'I' : S := St(User^.curMsgArea);
'N' : S := St(curMsg);
'P' : S := Menu^.PromptName;
'T' : S := St(numMsg);
'W' : S := St(User^.EmailWaiting);
end;
'N' : case C[2] of
'D' : S := St(node);
end;
'P' : case C[2] of
'A' : S := B2St(acPause in User^.acFlag);
'L' : S := St(User^.PageLength);
'N' : S := User^.PhoneNum;
'W' : S := User^.Password;
end;
'R' : case C[2] of
'N' : S := User^.RealName;
'T' : S := ripTerm;
end;
'S' : case C[2] of
'L' : S := St(User^.SL);
'N' : S := Cfg^.SysOpAlias;
'O' : S := User^.SysopNote;
'R' : S := Cfg^.SysOpName;
'X' : S := mSexString(User^.Sex);
end;
'T' : case C[2] of
'C' : S := Stc(Stat^.Calls);
'D' : S := Stc(Stat^.Downloads);
'E' : S := Stc(Stat^.Email);
'I' : S := dtTimeStr12;
'L' : S := St(mTimeLeft('M'));
'M' : S := dtTimeStr24;
'P' : S := Stc(Stat^.Posts);
'T' : S := St(User^.TimePerDay);
'U' : S := Stc(numUsers);
'Z' : S := mRatio(Stat^.Posts,Stat^.Calls);
end;
'U' : case C[2] of
'A' : S := User^.Level;
'C' : S := Stc(User^.TotalCalls);
'E' : S := Stc(User^.Email);
'I' : S := mInitials(User^.Username);
'K' : S := Stc(User^.UploadKb)+'k';
'L' : S := Stc(User^.Uploads);
'N' : S := User^.UserName;
'O' : S := User^.UserNote;
'P' : S := Stc(User^.Posts);
'Z' : S := mRatio(User^.Posts,User^.TotalCalls);
end;
'V' : case C[2] of
'L' : S := bbsVerLong;
'N' : S := Stc(User^.voteNo);
'Y' : S := Stc(User^.voteYes);
end;
'X' : case C[2] of
'M' : S := B2St(acExpert in User^.acFlag);
end;
'Y' : case C[2] of
'N' : S := B2St(acYesNoBar in User^.acFlag);
end;
'@' : case C[2] of
'A'..'Z' : S := B2St(C[2] in User^.Flag);
end;
else begin mciProcessMCIcode := False; S := mciHeader+C; end;
end;
mciString := S;
end;
function mciProcess(S : String; Len : Byte) : String;
var Cd : String; N : Byte;
begin
mciProcess := '';
N := 0;
if S = '' then Exit;
while N < Length(S) do
begin
Inc(N);
if S[N] = mciHeader then
begin
if mciProcessMCICode(Copy(S,N,3)) then
begin
Delete(S,N,3);
if Len <> 0 then mciString := strSquish(mciString,Len);
Insert(mciString,S,N);
Dec(N);
end;
end;
end;
mciProcess := S;
end;
end. |
unit scanner;
interface
const
IdLen = 31; {number of significant characters in identifiers}
type
Symbol = (null, TableStartSym, TableEndSym, RowStartSym, RowEndSym, CellStartSym, CellEndSym, ContentsSym, UnknownSym, EofSym);
Contents = string[IdLen];
var
sym: Symbol; {next symbol}
val: integer; {value of number if sym = NumberSym}
cont: Contents; {string to hold contents of a cell}
tag: Contents; {string to hold a tag}
error: Boolean; {whether an error has occurred so far}
procedure Mark (msg: string);
procedure GetSym;
implementation
const
KW = 6; {number of keywords}
type
KeyTable = array [1..KW] of
record sym: Symbol; id: Contents end;
var
ch: char;
line, lastline, errline: integer;
pos, lastpos, errpos: integer;
keyTab: KeyTable;
fn: string[255]; {name of source file}
source: text; {source file}
procedure GetChar;
begin
lastpos := pos;
if eoln (source) then begin pos := 0; line := line + 1 end
else begin lastline:= line; pos := pos + 1 end;
read (source, ch)
end;
procedure getCell;
var len, k: integer;
begin len := 0;
repeat
if len < IdLen then begin len := len + 1; cont[len] := ch; end;
GetChar
until not (ch in ['A'..'Z', 'a'..'z', '0'..'9']);
setlength(cont, len); k := 1;
while (k <= KW) and (cont <> keyTab[k].id) do k := k + 1;
if k <= KW then sym := keyTab[k].sym else sym := ContentsSym;
end;
procedure getTag;
var len, k: integer;
begin len := 0;
repeat
if len < IdLen then begin len := len + 1; tag[len] := ch; end;
GetChar
until (ch = '>');
setlength(tag, len); k := 1;
while (k <= KW) and (tag <> keyTab[k].id) do k := k + 1;
if k <= KW then sym := keyTab[k].sym else sym := UnknownSym;
end;
procedure Mark (msg: string);
begin
if (lastline > errline) or (lastpos > errpos) then
writeln ('error: line ', lastline:1, ' pos ', lastpos:1, ' ', msg);
errline := lastline; errpos := lastpos; error := true
end;
procedure GetSym;
begin {first skip white space}
while not eof (source) and (ch <= ' ') do GetChar;
if eof (source) then sym := EofSym
else
case ch of
'<': begin GetChar; getTag; end;
'A' .. 'Z', 'a'..'z', '0'..'9': getCell;
otherwise
begin GetChar; sym := null end
end
end;
begin
line := 1; lastline := 1; errline := 1;
pos := 0; lastpos := 0; errpos := 0;
error := false;
keyTab[1].sym := TableStartSym; keyTab[1].id := 'TABLE';
keyTab[2].sym := TableEndSym; keyTab[2].id := '/TABLE';
keyTab[3].sym := RowStartSym; keyTab[3].id := 'TR';
keyTab[4].sym := RowEndSym; keyTab[4].id := '/TR';
keyTab[5].sym := CellStartSym; keyTab[5].id := 'TD';
keyTab[6].sym := CellEndSym; keyTab[6].id := '/TD';
if paramcount > 0 then
begin fn := paramstr (1); assign (source, fn); reset (source);
GetChar
end
else Mark ('name of source file expected')
end.
|
unit SpriteTimer;
interface
uses Classes, WinTypes, Controls, Forms, MmSystem;
type
PThreadControl = ^TThreadControl;
TThreadControl = record
Control: TControl;
Interval: dword;
Enabled: boolean;
OnTimer: TNotifyEvent;
TickRun: dword;
end;
TSpriteTimer = class(TThread)
private
Killed: boolean;
CurrentControl: PThreadControl;
ControlsList: TList;
procedure Execute; override;
procedure ExecuteControl;
public
procedure Kill;
constructor Create;
//destructor Destroy; override;
procedure RegisterControl(_Control: TControl; _Interval: dword; _Enabled: boolean; _OnTimer: TNotifyEvent);
procedure UnregisterControl(_Control: TControl);
protected
published
end;
var
AnimateTimer: TSpriteTimer = nil;
implementation
constructor TSpriteTimer.Create;
begin
Killed := False;
ControlsList := TList.Create;
FreeOnTerminate := True;
inherited Create(True);
end;
{destructor TSpriteTimer.Destroy;
var
i: integer;
begin
for i:=ControlsList.Count - 1 downto 0 do begin
dispose(PThreadControl(ControlsList[i]));
end;
ControlsList.Free;
inherited Destroy;
end;}
procedure TSpriteTimer.RegisterControl(_Control: TControl; _Interval: dword; _Enabled: boolean; _OnTimer: TNotifyEvent);
var
ThreadControl: PThreadControl;
begin
try
new(ThreadControl);
with ThreadControl^ do begin
Control := _Control;
Interval := _Interval;
Enabled := _Enabled;
OnTimer := _OnTimer;
TickRun := TimeGetTime;
end;
ControlsList.Add(ThreadControl);
Suspended := False;
except
end;
end;
procedure TSpriteTimer.UnregisterControl(_Control: TControl);
var
ThreadControl: PThreadControl;
i: integer;
begin
try
for i:=0 to ControlsList.Count - 1 do
if PThreadControl(ControlsList.Items[i])^.Control = _Control then begin
ThreadControl := PThreadControl(ControlsList.Items[i]);
ControlsList.Remove(ThreadControl);
dispose(ThreadControl);
if ControlsList.Count = 0 then Suspended:=True;
exit;
end;
except
end;
end;
procedure TSpriteTimer.ExecuteControl;
begin
try
CurrentControl^.OnTimer(Self);
CurrentControl^.TickRun := TimeGetTime;
except
end;
end;
procedure TSpriteTimer.Kill;
begin
Killed := True;
Suspended := False;
end;
procedure TSpriteTimer.Execute;
var
i: integer;
begin
while not Killed do begin
try
for i:=0 to ControlsList.Count - 1 do begin
CurrentControl:=PThreadControl(ControlsList.Items[i]);
if CurrentControl^.Enabled then
if (TimeGetTime - CurrentControl^.TickRun) > CurrentControl^.Interval then
Synchronize(ExecuteControl);
Application.ProcessMessages;
end;
except
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXMetaDataCommandFactory;
interface
uses
Data.DBXCommon,
Data.DBXPlatform,
Data.DBXSqlScanner,
Data.DBXCommonTable,
Data.DBXMetaDataReader
;
type
TDBXMetaDataCommandFactory = class(TDBXCommandFactory)
public
class procedure RegisterMetaDataCommandFactory(const ObjectClass: TClass); static;
class procedure UnRegisterMetaDataCommandFactory(const ObjectClass: TClass); static;
function CreateCommand(DbxContext: TDBXContext; Connection: TDBXConnection;
MorphicCommand: TDBXCommand): TDBXCommand; override;
function CreateMetaDataReader: TDBXMetaDataReader; virtual; abstract;
function GetProductName: UnicodeString; virtual;
end;
TDBXDataExpressProviderContext = class(TDBXProviderContext)
protected
FConnection: TDBXConnection;
FScanner: TDBXSqlScanner;
FParameterMarker: UnicodeString;
FMarkerIncludedInParameterName: Boolean;
FUseAnsiStrings: Boolean;
FRemoveIsNull: Boolean;
private
// procedure BindParametersByName(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray);
procedure BindParametersByOrdinal(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray);
function FindParameterByName(const ParameterName: UnicodeString; ParameterNames: TDBXStringArray): Integer;
public
constructor Create;
destructor Destroy; override;
function GetPlatformTypeName(const DataType: Integer;
const IsUnsigned: Boolean): UnicodeString; override;
function ExecuteQuery(const Sql: UnicodeString;
const ParameterNames: TDBXStringArray;
const ParameterValues: TDBXStringArray): TDBXTable; override;
function CreateTableStorage(const CollectionName: UnicodeString;
const Columns: TDBXValueTypeArray): TDBXTable; override;
function CreateRowStorage(const CollectionName: UnicodeString;
const Columns: TDBXValueTypeArray): TDBXTableRow; override;
procedure StartTransaction; override;
procedure StartSerializedTransaction; override;
procedure Commit; override;
procedure Rollback; override;
function GetVendorProperty(const name: UnicodeString): UnicodeString; override;
protected
function GetSqlParameterMarker: UnicodeString;
function GetMarkerIncludedInParameterName: Boolean;
public
property SqlParameterMarker: UnicodeString read FParameterMarker;
property IsMarkerIncludedInParameterName: Boolean read FMarkerIncludedInParameterName;
property Connection: TDBXConnection read FConnection write FConnection;
property UseAnsiStrings: Boolean read FUseAnsiStrings write FUseAnsiStrings;
property RemoveIsNull: Boolean read FRemoveIsNull write FRemoveIsNull;
end;
const
BlackfishSQLProduct = 'BlackfishSQL'; { Do not localize }
implementation
uses
Data.DBXClassRegistry,
System.SysUtils,
Data.DBXReaderTableStorage,
Data.DBXMetaDataCommand,
Data.DBXCommonResStrs
;
function TDBXMetaDataCommandFactory.GetProductName: UnicodeString;
begin
Result := '';
end;
class procedure TDBXMetaDataCommandFactory.RegisterMetaDataCommandFactory(const ObjectClass: TClass);
var
ClassRegistry: TClassRegistry;
ClassName: UnicodeString;
begin
ClassRegistry := TClassRegistry.GetClassRegistry;
ClassName := ObjectClass.ClassName;
if not ClassRegistry.HasClass(ClassName) then
ClassRegistry.RegisterClass(ClassName, ObjectClass, nil); { Do not resource }
end;
class procedure TDBXMetaDataCommandFactory.UnRegisterMetaDataCommandFactory(
const ObjectClass: TClass);
var
ClassName: UnicodeString;
begin
ClassName := ObjectClass.ClassName;
TClassRegistry.GetClassRegistry.UnRegisterClass(ClassName);
end;
function TDBXMetaDataCommandFactory.CreateCommand(DbxContext: TDBXContext;
Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand;
var
Reader: TDBXMetaDataReader;
ProviderContext: TDBXDataExpressProviderContext;
ProductName: UnicodeString;
begin
ProductName := GetProductName;
if (ProductName = '') or (ProductName = Connection.ProductName) then
begin
Reader := TDBXMetaDataReader(TDBXDriverHelp.GetMetaDataReader(Connection));
if Reader = nil then
begin
Reader := CreateMetaDataReader;
ProviderContext := TDBXDataExpressProviderContext.Create;
ProviderContext.Connection := Connection;
ProviderContext.UseAnsiStrings := TDBXProviderContext.UseAnsiString(Reader.ProductName);
if Reader.ProductName <> BlackfishSQLProduct then
ProviderContext.RemoveIsNull := True;
Reader.Context := ProviderContext;
Reader.Version := TDBXConnection(Connection).ProductVersion;
TDBXDriverHelp.SetMetaDataReader(Connection, Reader);
end;
Result := TDBXMetaDataCommand.Create(DBXContext, MorphicCommand, Reader);
end else
Result := nil;
end;
constructor TDBXDataExpressProviderContext.Create;
begin
inherited Create;
end;
destructor TDBXDataExpressProviderContext.Destroy;
begin
FreeAndNil(FScanner);
inherited Destroy;
end;
function TDBXDataExpressProviderContext.GetPlatformTypeName(const DataType: Integer; const IsUnsigned: Boolean): UnicodeString;
begin
case DataType of
TDBXDataTypes.Uint8Type:
Result := 'Byte';
TDBXDataTypes.Int8Type:
Result := 'ShortInt';
TDBXDataTypes.UInt16Type:
Result := 'Word';
TDBXDataTypes.Int16Type:
Result := 'SmallInt';
TDBXDataTypes.UInt32Type,
TDBXDataTypes.Int32Type:
Result := 'TInt32';
TDBXDataTypes.UInt64Type,
TDBXDataTypes.Int64Type:
Result := 'Int64';
TDBXDataTypes.BooleanType:
Result := 'Boolean';
TDBXDataTypes.DateType:
Result := 'TDBXDate';
TDBXDataTypes.TimeType:
Result := 'TDBXTime';
TDBXDataTypes.TimeStampType:
Result := 'TSQLTimeStamp';
TDBXDataTypes.IntervalType:
Result := 'TSQLTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Result := 'TSQLTimeStampOffset';
TDBXDataTypes.WideStringType:
Result := 'String';
TDBXDataTypes.AnsiStringType:
Result := 'AnsiString';
TDBXDataTypes.BcdType:
Result := 'TBcd';
TDBXDataTypes.SingleType:
Result := 'Single';
TDBXDataTypes.DoubleType:
Result := 'Double';
TDBXDataTypes.BlobType,
TDBXDataTypes.BytesType,
TDBXDataTypes.VarBytesType:
Result := 'TBytes';
TDBXDataTypes.ObjectType:
Result := 'TObject';
else
raise Exception.Create(SUnknownDataType);
end;
end;
function TDBXDataExpressProviderContext.GetSqlParameterMarker: UnicodeString;
begin
Result := FParameterMarker;
end;
function TDBXDataExpressProviderContext.GetMarkerIncludedInParameterName: Boolean;
begin
Result := FMarkerIncludedInParameterName;
end;
function TDBXDataExpressProviderContext.ExecuteQuery(const Sql: UnicodeString; const ParameterNames: TDBXStringArray; const ParameterValues: TDBXStringArray): TDBXTable;
var
Reader: TDBXReader;
Command: TDBXCommand;
begin
Command := FConnection.CreateCommand;
Command.Text := Sql;
try
if ParameterValues <> nil then
begin
BindParametersByOrdinal(Command, ParameterNames, ParameterValues);
end;
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Result := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command,Reader));
// When the Result is freed, this Command will be freed.
//
Command := nil;
end;
finally
FreeAndNil(Command);
end;
end;
function TDBXDataExpressProviderContext.CreateTableStorage(const CollectionName: UnicodeString; const Columns: TDBXValueTypeArray): TDBXTable;
begin
Result := nil;
end;
function TDBXDataExpressProviderContext.CreateRowStorage(const CollectionName: UnicodeString; const Columns: TDBXValueTypeArray): TDBXTableRow;
begin
Result := nil;
end;
procedure TDBXDataExpressProviderContext.StartTransaction;
begin
end;
procedure TDBXDataExpressProviderContext.StartSerializedTransaction;
begin
end;
procedure TDBXDataExpressProviderContext.Commit;
begin
end;
procedure TDBXDataExpressProviderContext.Rollback;
begin
end;
function TDBXDataExpressProviderContext.GetVendorProperty(const name: UnicodeString): UnicodeString;
begin
Result := FConnection.GetVendorProperty(name);
end;
{
procedure TDBXDataExpressProviderContext.BindParametersByName(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray);
var
Parameters: TDBXParameterList;
Parameter: TDBXParameter;
Index: Integer;
begin
Parameters := Command.Parameters;
for Index := Low(ParameterValues) to High(ParameterValues) do
begin
Parameter := Command.CreateParameter;
Parameter.DataType := TDBXDataTypes.WideStringType;
Parameter.Name := ParameterNames[Index];
if ParameterValues[Index] = NullString then
Parameter.Value.SetNull
else
Parameter.Value.SetWideString(ParameterValues[Index]);
Parameters.AddParameter(Parameter);
end;
end;
}
procedure TDBXDataExpressProviderContext.BindParametersByOrdinal(Command: TDBXCommand; ParameterNames: TDBXStringArray; ParameterValues: TDBXStringArray);
const
KeywordIS = 'IS'; { Do not localize }
KeywordNULL = 'NULL'; { Do not localize }
SqlTrueValue = '1=1'; { Do not localize }
SqlFalseValue = '1=2'; { Do not localize }
DummyValue = 'A'; { Do not localize }
TokenIS = 1;
TokenNULL = 2;
var
Token: Integer;
StartPos: Integer;
EndPos: Integer;
ParameterIndex: Integer;
Parameters: TDBXParameterList;
Parameter: TDBXParameter;
Buffer: TDBXStringBuffer;
Params: array of Integer;
Count: Integer;
Index: Integer;
NullWasRemoved: Boolean;
begin
Count := 0;
StartPos := 1;
Buffer := nil;
if FScanner = nil then
begin
FScanner := TDBXSqlScanner.Create('','','');
FScanner.RegisterId(KeywordIS, TokenIS);
FScanner.RegisterId(KeywordNULL, TokenNULL);
end;
FScanner.Init(Command.Text);
Token := FScanner.NextToken;
while Token <> TDBXSqlScanner.TokenEos do
begin
if (Token <> TDBXSqlScanner.TokenSymbol) or (FScanner.Symbol <> ':') then
Token := FScanner.NextToken
else
begin
EndPos := FScanner.NextIndex;
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenId then
begin
if Buffer = nil then
begin
Buffer := TDBXStringBuffer.Create(Length(Command.Text));
SetLength(Params,Length(ParameterNames)*3);
end;
Buffer.Append(Copy(Command.Text,StartPos,EndPos-StartPos));
StartPos := FScanner.NextIndex+1;
ParameterIndex := FindParameterByName(FScanner.Id, ParameterNames);
NullWasRemoved := false;
if RemoveIsNull then
begin
if (FScanner.LookAtNextToken = TokenIS) then
begin
FScanner.NextToken;
if FScanner.LookAtNextToken = TokenNull then
begin
FScanner.NextToken;
StartPos := FScanner.NextIndex+1;
NullWasRemoved := true;
if ParameterValues[ParameterIndex] = NullString then
Buffer.Append(SqlTrueValue)
else
Buffer.Append(SqlFalseValue)
end;
end;
end;
if not NullWasRemoved then
begin
Buffer.Append('?');
if Length(Params) <= Count then
SetLength(Params, Count+2);
Params[Count] := ParameterIndex;
Inc(Count);
end;
end;
end;
end;
if Buffer <> nil then
begin
Buffer.Append(Copy(Command.Text,StartPos,Length(Command.Text)-StartPos+1));
Command.Text := Buffer.ToString;
Parameters := Command.Parameters;
Parameters.ClearParameters;
for Index := 0 to Count - 1 do
begin
ParameterIndex := Params[Index];
Parameter := Command.CreateParameter;
if UseAnsiStrings then
Parameter.DataType := TDBXDataTypes.AnsiStringType
else
Parameter.DataType := TDBXDataTypes.WideStringType;
if RemoveIsNull and (ParameterValues[ParameterIndex] = NullString) then
ParameterValues[ParameterIndex] := DummyValue;
if (ParameterValues[ParameterIndex] = NullString) then
Parameter.Value.SetNull
else if UseAnsiStrings then
Parameter.Value.SetAnsiString(AnsiString(ParameterValues[ParameterIndex]))
else
Parameter.Value.SetString(ParameterValues[ParameterIndex]);
Parameters.AddParameter(Parameter);
end;
FreeAndNil(Buffer);
Params := nil;
end;
end;
function TDBXDataExpressProviderContext.FindParameterByName(const ParameterName: UnicodeString; ParameterNames: TDBXStringArray): Integer;
var
Index: Integer;
Found: Boolean;
begin
Index := High(ParameterNames);
Found := False;
while not Found and (Index >= Low(ParameterNames)) do
begin
if ParameterNames[Index] = ParameterName then
Found := True
else
Dec(Index);
end;
if not Found then
raise Exception.Create('ParameterName not found: '+ParameterName);
Result := Index;
end;
end.
|
unit uTranslateVclComStrs;
interface
uses
Windows,
Vcl.ComStrs,
uTranslate;
Type
TTranslateDataSqlConst = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateDataSqlConst.ChangeValues;
begin
SetResourceString(@sTabFailClear, 'Falha ao limpar controle de aba');
SetResourceString(@sTabFailDelete, 'Falha ao deletar índice "%d" da aba');
SetResourceString(@sTabFailRetrieve, 'Falha ao recuperar a aba no índice "%d"');
SetResourceString(@sTabFailGetObject, 'Falha ao inicializar objeto no índice "%d"');
SetResourceString(@sTabFailSet, 'Falha ao ajustar a aba "%s" no índice "%d"');
SetResourceString(@sTabFailSetObject, 'Falha ao ajustar o objeto no índice "%d"');
SetResourceString(@sTabMustBeMultiLine, 'O MultiLine deve ser verdadeiro quando TabPosition for tpLeft ou tpRight ');
SetResourceString(@sInvalidLevel, 'Nível de ítem atribuído inválido');
SetResourceString(@sInvalidLevelEx, 'Nível inválido (%d) para o item "%s"');
SetResourceString(@sInvalidIndex, 'Índice inválido');
SetResourceString(@sInsertError, 'Erro de inserção');
SetResourceString(@sInvalidOwner, 'Proprietário Inválido');
SetResourceString(@sUnableToCreateColumn, 'Não é possível criar uma nova coluna');
SetResourceString(@sUnableToCreateItem, 'Não é possível criar um novo item');
SetResourceString(@sRichEditInsertError, 'Erro inserindo linha no RichEdit');
SetResourceString(@sRichEditLoadFail, 'Falha ao tentar carregar Stream');
SetResourceString(@sRichEditSaveFail, 'Falha ao tentar salvar Stream');
SetResourceString(@sTooManyPanels, 'Barra de status não pode ter mais de 64 painéis');
SetResourceString(@sHKError, 'Erro ao atribuir Hot-Key à "%s". "%s"');
SetResourceString(@sHKInvalid, 'Hot-Key inválida');
SetResourceString(@sHKInvalidWindow, 'A janela é inválida ou é uma Janela filha');
SetResourceString(@sHKAssigned, 'Esta Hot-Key está atribuída a uma outra janela');
SetResourceString(@sUDAssociated, '"%s" já é associado para "%s"');
SetResourceString(@sPageIndexError, '"%d" é um valor de índice de página inválido. O índice de página deve estar entre 0 e %d');
SetResourceString(@sInvalidComCtl32, 'Este controle requer COMCTL32.DLL versão 4.70 ou superior');
SetResourceString(@sDateTimeMax, 'A data excede o valor máximo de "%s"');
SetResourceString(@sDateTimeMin, 'A data é menor que o valor mínimo de "%s"');
SetResourceString(@sNeedAllowNone, 'Você deve estar em modo de ShowCheckbox para fixar esta data');
SetResourceString(@sFailSetCalDateTime, 'Falha ao ajustar a data ou a hora do calendário');
SetResourceString(@sFailSetCalMaxSelRange, 'Falha ao ajustar a escala máxima de seleção');
SetResourceString(@sFailSetCalMinMaxRange, 'Falha ao ajustar a escala máxima do calendário');
SetResourceString(@sCalRangeNeedsMultiSelect, 'A escala da data somente pode ser usada no modo multiseleção');
SetResourceString(@sFailsetCalSelRange, 'Falha ao ajustar a escala selecionada do calendário');
end;
End. |
unit AnimalsClasses;
interface
type
TAnimal = class
public
constructor Create;
function GetKind: string;
private
FKind: string;
end;
TDog = class (TAnimal)
public
constructor Create;
end;
implementation
{ TAnimal }
constructor TAnimal.Create;
begin
FKind := 'Animal';
end;
function TAnimal.GetKind: string;
begin
Result := FKind;
end;
{ TDog }
constructor TDog.Create;
begin
inherited;
FKind := 'Dog';
end;
end.
|
unit frComments;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frComments.pas, released Nov 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ delphi }
StdCtrls, Classes, Controls, Forms,
{ local }
frmBaseSettingsFrame;
type
TfComments = class(TfrSettingsFrame)
cbRemoveEmptyDoubleSlashComments: TCheckBox;
cbRemoveEmptyCurlyBraceComments: TCheckBox;
private
public
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
end;
implementation
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
uses JcfHelp, JcfSettings, SetComments;
constructor TfComments.Create(AOwner: TComponent);
begin
inherited;
fiHelpContext := HELP_CLARIFY_COMMENTS;
end;
procedure TfComments.Read;
begin
with JcfFormatSettings.Comments do
begin
cbRemoveEmptyDoubleSlashComments.Checked := RemoveEmptyDoubleSlashComments;
cbRemoveEmptyCurlyBraceComments.Checked := RemoveEmptyCurlyBraceComments;
end;
end;
procedure TfComments.Write;
begin
with JcfFormatSettings.Comments do
begin
RemoveEmptyDoubleSlashComments := cbRemoveEmptyDoubleSlashComments.Checked;
RemoveEmptyCurlyBraceComments := cbRemoveEmptyCurlyBraceComments.Checked;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit REST.Backend.EMSServices;
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
REST.Client,
REST.Backend.Providers,
REST.Backend.PushTypes,
REST.Backend.ServiceTypes,
REST.Backend.MetaTypes,
REST.Backend.EMSApi,
REST.Backend.EMSProvider,
REST.Backend.ServiceFactory;
type
// Push service
TEMSPushAPI = class(TEMSServiceAPIAuth, IBackendPushApi, IBackendPushApi2, IBackendPushApi3)
protected
{ IBackendPushAPI }
procedure PushBroadcast(const AData: TPushData); overload;
{ IBackendPushApi2 }
procedure PushBroadcast(const AData: TJSONObject); overload;
function PushDataAsJSON(const AData: TPushData): TJSONObject;
{ IBackendPushApi3 }
procedure PushToTarget(const AData: TPushData; const ATarget: TJSONObject); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject); overload;
end;
TEMSPushService = class(TEMSBackendService<TEMSPushAPI>, IBackendService, IBackendPushService)
protected
{ IBackendPushService }
function CreatePushApi: IBackendPushApi;
function GetPushApi: IBackendPushApi;
end;
// Query service
TEMSQueryAPI = class(TEMSServiceAPIAuth, IBackendQueryApi)
protected
{ IBackendQueryAPI }
function GetMetaFactory: IBackendMetaFactory;
procedure GetServiceNames(out ANames: TArray<string>);
procedure Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AObjects: TArray<TBackendEntityValue>); overload;
end;
TEMSQueryService = class(TEMSBackendService<TEMSQueryAPI>, IBackendService,
IBackendQueryService)
protected
{ IBackendQueryService }
function CreateQueryApi: IBackendQueryApi;
function GetQueryApi: IBackendQueryApi;
end;
// Login service
TEMSLoginAPI = class(TEMSServiceAPIAuth, IBackendAuthApi)
private
protected
{ IBackendAuthApi }
function GetMetaFactory: IBackendMetaFactory;
procedure SignupUser(const AUserName, APassword: string;
const AUserData: TJSONObject; out ACreatedObject: TBackendEntityValue);
procedure LoginUser(const AUserName, APassword: string;
AProc: TFindObjectProc); overload;
procedure LoginUser(const AUserName, APassword: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray); overload;
function FindCurrentUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean; overload;
function FindCurrentUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray)
: Boolean; overload;
procedure UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
end;
TEMSLoginService = class(TEMSBackendService<TEMSLoginAPI>, IBackendService,
IBackendAuthService)
protected
{ IBackendAuthService }
function CreateAuthApi: IBackendAuthApi;
function GetAuthApi: IBackendAuthApi;
end;
TEMSLoginAPIHelper = class helper for TEMSLoginAPI
public
procedure LogoutUser;
end;
// Users service
TEMSUsersAPI = class(TEMSLoginAPI, IBackendUsersApi)
private
protected
{ IBackendUsersAPI }
function DeleteUser(const AObject: TBackendEntityValue): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray)
: Boolean; overload;
procedure UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
function QueryUserName(const AUserName: string; AProc: TFindObjectProc)
: Boolean; overload;
function QueryUserName(const AUserName: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray)
: Boolean; overload;
procedure QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>); overload;
end;
TEMSUsersService = class(TEMSBackendService<TEMSUsersAPI>, IBackendService,
IBackendUsersService)
protected
{ IBackendUsersService }
function CreateUsersApi: IBackendUsersApi;
function GetUsersApi: IBackendUsersApi;
end;
// Groups service
TEMSGroupsAPI = class(TEMSServiceAPIAuth, IBackendGroupsApi)
private
protected
{ IBackendGroupsAPI }
function GetMetaFactory: IBackendMetaFactory;
procedure AddUsers(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue);
function RemoveUsers(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue): Boolean;
procedure CreateGroup(const AGroup: string; AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteGroup(const AObject: TBackendEntityValue): Boolean; overload;
function FindGroup(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean;
procedure UpdateGroup(const AObject: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue);
end;
TEMSGroupsService = class(TEMSBackendService<TEMSGroupsAPI>, IBackendService,
IBackendGroupsService)
protected
{ IBackendUsersService }
function CreateGroupsApi: IBackendGroupsApi;
function GetGroupsApi: IBackendGroupsApi;
end;
TEMSCustomEndpointAPI = class(TEMSServiceAPIAuth, IBackendCustomEndpointApi)
protected
{ IBackendCustomEndpointApi }
procedure PrepareClient(const AClient: TCustomRESTClient);
procedure PrepareRequest(const ARequest: TCustomRESTRequest);
procedure CheckForResponseErrors(const AResponse: TCustomRESTResponse; AValidStatusCodes: array of Integer);
end;
TEMSCustomEndpointService = class(TEMSBackendService<TEMSCustomEndpointAPI>, IBackendService,
IBackendCustomEndpointService)
protected
{ IBackendCustomEndpointService }
function GetCustomEndpointAPI: IBackendCustomEndpointApi;
function CreateCustomEndpointApi: IBackendCustomEndpointApi;
end;
TEMSProviderServiceFactory<T: IBackendService> = class
(TProviderServiceFactory<T>)
var
FMethod: TFunc<IBackendProvider, IBackendService>;
protected
function CreateService(const AProvider: IBackendProvider; const IID: TGUID)
: IBackendService; override;
public
constructor Create(const AMethod: TFunc<IBackendProvider, IBackendService>);
end;
implementation
uses
System.TypInfo, System.Generics.Collections,
REST.Backend.Exception,
REST.Backend.EMSMetaTypes,
REST.Backend.Consts;
{ TEMSProviderServiceFactory<T> }
constructor TEMSProviderServiceFactory<T>.Create(const AMethod
: TFunc<IBackendProvider, IBackendService>);
begin
inherited Create(TCustomEMSProvider.ProviderID,
'REST.Backend.EMSServices');
FMethod := AMethod;
end;
function TEMSProviderServiceFactory<T>.CreateService(const AProvider
: IBackendProvider; const IID: TGUID): IBackendService;
begin
Result := FMethod(AProvider);
end;
{ TEMSPushAPI }
procedure TEMSPushAPI.PushBroadcast(
const AData: TPushData);
begin
PushToTarget(AData, nil);
end;
procedure TEMSPushAPI.PushBroadcast(
const AData: TJSONObject);
begin
PushToTarget(AData, nil);
end;
procedure TEMSPushAPI.PushToTarget(
const AData: TPushData; const ATarget: TJSONObject);
var
LJSON: TJSONObject;
begin
LJSON := PushDataAsJSON(AData);
try
PushToTarget(LJSON, ATarget);
finally
LJSON.Free;
end;
end;
procedure TEMSPushAPI.PushToTarget(
const AData: TJSONObject; const ATarget: TJSONObject);
var
LJSON: TJSONObject;
begin
if AData is TJSONObject then
LJSON := AData.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
EMSAPI.PushToTarget(LJSON, ATarget);
finally
LJSON.Free;
end;
end;
function TEMSPushAPI.PushDataAsJSON(
const AData: TPushData): TJSONObject;
const
sGCM = 'gcm';
sAPS = 'aps';
sExtras = 'extras';
var
LGCM: TJSONObject;
LAPS: TJSONObject;
begin
Result := TJSONObject.Create;
try
LGCM := TJSONObject.Create;
Result.AddPair(sGCM, LGCM);
LAPS := TJSONObject.Create;
Result.AddPair(sAps, LAPS);
if AData <> nil then
begin
AData.Extras.Save(Result, sExtras);
AData.GCM.Save(LGCM, '');
AData.APS.Save(LAPS, '');
if (AData.APS.Alert = '') and (AData.Message <> '') then
AData.SaveMessage(LAPS, TPushData.TAPS.TNames.Alert);
if (AData.GCM.Message = '') and (AData.GCM.Msg = '') and (AData.Message <> '') then
AData.SaveMessage(LGCM, TPushData.TGCM.TNames.Message);
end;
except
Result.Free;
raise;
end;
end;
{ TEMSPushService }
function TEMSPushService.CreatePushApi: IBackendPushApi;
begin
Result := CreateBackendApi;
end;
function TEMSPushService.GetPushApi: IBackendPushApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TEMSQueryAPI }
procedure TEMSQueryAPI.GetServiceNames(out ANames: TArray<string>);
begin
ANames := TArray<string>.Create(
TBackendQueryServiceNames.Users, TBackendQueryServiceNames.Groups, TBackendQueryServiceNames.Installations,
TBackendQueryServiceNames.Modules, TBackendQueryServiceNames.ModulesResources);
end;
function TEMSQueryAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
procedure TEMSQueryAPI.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Users) then
EMSAPI.QueryUsers(AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Groups) then
EMSAPI.QueryGroups(AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Installations) then
EMSAPI.QueryInstallations(
AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Modules) then
EMSAPI.QueryModules(
AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.ModulesResources) then
if AClass.BackendClassName <> '' then
EMSAPI.QueryModuleResources(AClass.BackendClassName,
AQuery, AJSONArray)
else
EMSAPI.QueryModuleResources('', // All
AQuery, AJSONArray)
else
raise EEMSClientAPIError.CreateFmt(sUnsupportedBackendQueryType,
[AClass.BackendDataType]);
end;
procedure TEMSQueryAPI.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AObjects: TArray<TBackendEntityValue>);
var
// LObjectIDArray: TArray<TEMSClientAPI.TObjectID>;
LUsersArray: TArray<TEMSClientAPI.TUser>;
LGroupsArray: TArray<TEMSClientAPI.TGroup>;
LInstallationsArray: TArray<TEMSClientAPI.TInstallation>;
LModulesArray: TArray<TEMSClientAPI.TModule>;
LModuleResourcesArray: TArray<TEMSClientAPI.TModuleResource>;
// LObjectID: TEMSClientAPI.TObjectID;
LList: TList<TBackendEntityValue>;
LUser: TEMSClientAPI.TUser;
LGroup: TEMSClientAPI.TGroup;
LInstallation: TEMSClientAPI.TInstallation;
LModule: TEMSClientAPI.TModule;
LModuleResource: TEMSClientAPI.TModuleResource;
begin
// if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Storage) then
// KinveyAPI.QueryAppData(
// AClass.BackendClassName, AQuery, AJSONArray, LObjectIDArray)
// else
if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Users) then
EMSAPI.QueryUsers(AQuery, AJSONArray, LUsersArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Groups) then
EMSAPI.QueryGroups(AQuery, AJSONArray, LGroupsArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Installations) then
EMSAPI.QueryInstallations(
AQuery, AJSONArray, LInstallationsArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Modules) then
EMSAPI.QueryModules(
AQuery, AJSONArray, LModulesArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.ModulesResources) then
if AClass.BackendClassName <> '' then
EMSAPI.QueryModuleResources(AClass.BackendClassName,
AQuery, AJSONArray, LModuleResourcesArray)
else
EMSAPI.QueryModuleResources('', // All
AQuery, AJSONArray, LModuleResourcesArray)
else
raise EEMSClientAPIError.CreateFmt(sUnsupportedBackendQueryType,
[AClass.BackendDataType]);
if Length(LUsersArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LUser in LUsersArray do
LList.Add(TEMSMetaFactory.CreateMetaFoundUser(LUser));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
if Length(LGroupsArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LGroup in LGroupsArray do
LList.Add(TEMSMetaFactory.CreateMetaFoundGroup(LGroup));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
if Length(LInstallationsArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LInstallation in LInstallationsArray do
LList.Add(TEMSMetaFactory.CreateMetaFoundInstallation(LInstallation));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
if Length(LModulesArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LModule in LModulesArray do
LList.Add(TEMSMetaFactory.CreateMetaFoundModule(LModule));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
if Length(LModuleResourcesArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LModuleResource in LModuleResourcesArray do
LList.Add(TEMSMetaFactory.CreateMetaFoundModuleResource(LModuleResource));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
end;
{ TKinveyQueryService }
function TEMSQueryService.CreateQueryApi: IBackendQueryApi;
begin
Result := CreateBackendApi;
end;
function TEMSQueryService.GetQueryApi: IBackendQueryApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TEMSUsersService }
function TEMSUsersService.CreateUsersApi: IBackendUsersApi;
begin
Result := CreateBackendApi;
end;
function TEMSUsersService.GetUsersApi: IBackendUsersApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TEMSGroupsService }
function TEMSGroupsService.CreateGroupsApi: IBackendGroupsApi;
begin
Result := CreateBackendApi;
end;
function TEMSGroupsService.GetGroupsApi: IBackendGroupsApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
var
FFactories: TList<TProviderServiceFactory>;
procedure RegisterServices;
var
LFactory: TProviderServiceFactory;
begin
FFactories := TObjectList<TProviderServiceFactory>.Create;
// Users
LFactory := TEMSProviderServiceFactory<IBackendUsersService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSUsersService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Groups
LFactory := TEMSProviderServiceFactory<IBackendGroupsService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSGroupsService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Query
LFactory := TEMSProviderServiceFactory<IBackendQueryService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSQueryService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Endpoint
LFactory := TEMSProviderServiceFactory<IBackendCustomEndpointService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSCustomEndpointService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Login
LFactory := TEMSProviderServiceFactory<IBackendAuthService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSLoginService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Push
LFactory := TEMSProviderServiceFactory<IBackendPushService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSPushService.Create(AProvider);
end);
FFactories.Add(LFactory);
for LFactory in FFactories do
LFactory.Register;
end;
procedure UnregisterServices;
var
LFactory: TProviderServiceFactory;
begin
for LFactory in FFactories do
LFactory.Unregister;
FreeAndNil(FFactories);
end;
{ TEMSUsersAPI }
function TEMSUsersAPI.DeleteUser(const AObject: TBackendEntityValue): Boolean;
begin
if AObject.Data is TMetaUser then
Result := EMSAPI.DeleteUser((AObject.Data as TMetaUser).User)
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSUsersAPI.FindUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
var
LMetaUser: TMetaUser;
begin
if AObject.Data is TMetaUser then
begin
LMetaUser := TMetaUser(AObject.Data);
Result := EMSAPI.RetrieveUser(LMetaUser.User,
procedure(const AUser: TEMSClientAPI.TUser; const AObj: TJSONObject)
begin
AProc(TEMSMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSUsersAPI.FindUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LMetaUser: TMetaUser;
LUser: TEMSClientAPI.TUser;
begin
if AObject.Data is TMetaUser then
begin
LMetaUser := TMetaUser(AObject.Data);
Result := EMSAPI.RetrieveUser(LMetaUser.User, LUser, AJSON);
AUser := TEMSMetaFactory.CreateMetaFoundUser(LUser);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSUsersAPI.QueryUserName(const AUserName: string;
AProc: TFindObjectProc): Boolean;
begin
Result := EMSAPI.QueryUserName(AUserName,
procedure(const AUser: TEMSClientAPI.TUser; const AObj: TJSONObject)
begin
AProc(TEMSMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
end;
function TEMSUsersAPI.QueryUserName(const AUserName: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LUser: TEMSClientAPI.TUser;
begin
Result := EMSAPI.QueryUserName(AUserName, LUser, AJSON);
AUser := TEMSMetaFactory.CreateMetaFoundUser(LUser);
end;
procedure TEMSUsersAPI.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray);
begin
EMSAPI.QueryUsers(AQuery, AJSONArray);
end;
procedure TEMSUsersAPI.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>);
var
LUserArray: TArray<TEMSClientAPI.TUser>;
LUser: TEMSClientAPI.TUser;
LList: TList<TBackendEntityValue>;
begin
EMSAPI.QueryUsers(AQuery, AJSONArray, LUserArray);
if Length(LUserArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LUser in LUserArray do
LList.Add(TEMSMetaFactory.CreateMetaUserObject(LUser));
AMetaArray := LList.ToArray;
finally
LList.Free;
end;
end;
end;
procedure TEMSUsersAPI.UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TEMSClientAPI.TUpdatedAt;
LMetaUser: TMetaUser;
begin
if AObject.Data is TMetaUser then
begin
LMetaUser := TMetaUser(AObject.Data);
EMSAPI.UpdateUser(LMetaUser.User, AUserData, LUpdated);
AUpdatedObject := TEMSMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
{ TEMSCustomEndpointService }
function TEMSCustomEndpointService.CreateCustomEndpointApi: IBackendCustomEndpointApi;
begin
Result := CreateBackendApi;
end;
function TEMSCustomEndpointService.GetCustomEndpointAPI: IBackendCustomEndpointApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TEMSCustomEndpointAPI }
procedure TEMSCustomEndpointAPI.CheckForResponseErrors(
const AResponse: TCustomRESTResponse; AValidStatusCodes: array of Integer);
begin
EMSAPI.CheckForResponseError(AResponse, AValidStatusCodes);
end;
procedure TEMSCustomEndpointAPI.PrepareClient(const AClient: TCustomRESTClient);
begin
EMSAPI.ApplyConnectionInfo(AClient);
end;
procedure TEMSCustomEndpointAPI.PrepareRequest(const ARequest: TCustomRESTRequest);
begin
ARequest.TransientParams.Clear;
EMSAPI.AddAuthParameters(ARequest);
end;
{ TEMSCustomLoginService }
function TEMSLoginService.CreateAuthApi: IBackendAuthApi;
begin
Result := CreateBackendApi;
end;
function TEMSLoginService.GetAuthApi: IBackendAuthApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TEMSLoginAPI }
function TEMSLoginAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
function TEMSLoginAPI.FindCurrentUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
var
LMetaLogin: TMetaLogin;
begin
if AObject.Data is TMetaLogin then
begin
LMetaLogin := TMetaLogin(AObject.Data);
EMSAPI.Login(LMetaLogin.Login);
try
Result := EMSAPI.RetrieveCurrentUser(
procedure(const AUser: TEMSClientAPI.TUser; const AObj: TJSONObject)
begin
AProc(TEMSMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
finally
EMSAPI.Logout;
end;
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSLoginAPI.FindCurrentUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LMetaLogin: TMetaLogin;
LUser: TEMSClientAPI.TUser;
begin
if AObject.Data is TMetaLogin then
begin
LMetaLogin := TMetaLogin(AObject.Data);
EMSAPI.Login(LMetaLogin.Login);
try
Result := EMSAPI.RetrieveCurrentUser(LUser, AJSON);
AUser := TEMSMetaFactory.CreateMetaFoundUser(LUser)
finally
EMSAPI.Logout;
end;
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
procedure TEMSLoginAPI.LoginUser(const AUserName, APassword: string;
AProc: TFindObjectProc);
begin
EMSAPI.LoginUser(AUserName, APassword,
procedure(const ALogin: TEMSClientAPI.TLogin;
const AUserObject: TJSONObject)
begin
if Assigned(Aproc) then
AProc(TEMSMetaFactory.CreateMetaLoginUser(ALogin), AUserObject);
end);
end;
procedure TEMSLoginAPI.LoginUser(const AUserName, APassword: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray);
var
LLogin: TEMSClientAPI.TLogin;
begin
EMSAPI.LoginUser(AUserName, APassword, LLogin, AJSON);
AUser := TEMSMetaFactory.CreateMetaLoginUser(LLogin);
end;
procedure TEMSLoginAPIHelper.LogoutUser;
begin
EMSAPI.LogoutUser;
end;
procedure TEMSLoginAPI.SignupUser(const AUserName, APassword: string;
const AUserData: TJSONObject; out ACreatedObject: TBackendEntityValue);
var
LLogin: TEMSClientAPI.TLogin;
begin
EMSAPI.SignupUser(AUserName, APassword, AUserData, LLogin);
ACreatedObject := TEMSMetaFactory.CreateMetaSignupUser(LLogin);
end;
procedure TEMSLoginAPI.UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TEMSClientAPI.TUpdatedAt;
LMetaUser: TMetaUser;
begin
if AObject.Data is TMetaUser then
begin
LMetaUser := TMetaUser(AObject.Data);
EMSAPI.UpdateUser(LMetaUser.User, AUserData, LUpdated);
AUpdatedObject := TEMSMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
{ TEMSGroupsAPI }
procedure TEMSGroupsAPI.AddUsers(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TEMSClientAPI.TUpdatedAt;
begin
EMSAPI.AddUsersToGroup(AGroupName, AUsers, LUpdated);
AUpdatedObject := TEMSMetaFactory.CreateMetaUpdatedGroup(LUpdated);
end;
function TEMSGroupsAPI.RemoveUsers(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue): Boolean;
var
LUpdated: TEMSClientAPI.TUpdatedAt;
begin
Result := EMSAPI.RemoveUsersFromGroup(AGroupName, AUsers, LUpdated);
AUpdatedObject := TEMSMetaFactory.CreateMetaUpdatedGroup(LUpdated);
end;
procedure TEMSGroupsAPI.CreateGroup(const AGroup: string; AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue);
var
LGroup: TEMSClientAPI.TGroup;
begin
EMSAPI.CreateGroup(AGroup, AJSON, LGroup);
ACreatedObject := TEMSMetaFactory.CreateMetaGroupObject(LGroup);
end;
function TEMSGroupsAPI.DeleteGroup(const AObject: TBackendEntityValue): Boolean;
begin
if AObject.Data is TMetaGroup then
Result := EMSAPI.DeleteGroup((AObject.Data as TMetaGroup).Group)
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSGroupsAPI.FindGroup(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
var
LMetaGroup: TMetaGroup;
begin
if AObject.Data is TMetaGroup then
begin
LMetaGroup := TMetaGroup(AObject.Data);
Result := EMSAPI.RetrieveGroup(LMetaGroup.Group,
procedure(const AGroup: TEMSClientAPI.TGroup; const AObj: TJSONObject)
begin
AProc(TEMSMetaFactory.CreateMetaFoundGroup(AGroup), AObj);
end);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
procedure TEMSGroupsAPI.UpdateGroup(const AObject: TBackendEntityValue;
const AJSONObject: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TEMSClientAPI.TUpdatedAt;
LMetaGroup: TMetaGroup;
begin
if AObject.Data is TMetaGroup then
begin
LMetaGroup := TMetaGroup(AObject.Data);
EMSAPI.UpdateGroup(LMetaGroup.Group, AJSONObject, LUpdated);
AUpdatedObject := TEMSMetaFactory.CreateMetaUpdatedGroup(LUpdated);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TEMSGroupsAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
initialization
RegisterLogoutProc(TEMSLoginAPI,
procedure (AServiceAPI: TObject)
begin
(AServiceAPI as TEMSLoginAPI).LogoutUser;
end);
RegisterServices;
finalization
UnregisterServices;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/block.h
// Bitcoin file: src/primitives/block.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TBlockHeader;
interface
type
{** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*}
TBlockHeader = class
public:
// header
nVersion: int32_t;
hashPrevBlock: uint256;
hashMerkleRoot: uint256;
nTime: uint32_t;
nBits: uint32_t;
nNonce: uint32_t;
SERIALIZE_METHODS(CBlockHeader, obj) { READWRITE(obj.nVersion, obj.hashPrevBlock, obj.hashMerkleRoot, obj.nTime, obj.nBits, obj.nNonce); }
procedure TBlockHeader.SetNull();
function TBlockHeader.IsNull() : boolean;
function TBlockHeader.GetHash() : uint256;
function TBlockHeader.GetBlockTime() : int64_t;
end;
implementation
// #include <hash.h>
// #include <tinyformat.h>
constructor TBlockHeader.Create;
begin
SetNull();
end;
procedure TBlockHeader.SetNull();
begin
nVersion := 0;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime := 0;
nBits := 0;
nNonce := 0;
end;
function TBlockHeader.IsNull() : boolean;
begin
result := (nBits == 0);
end;
function TBlockHeader.GetHash() : uint256;
begin
return SerializeHash( *this);
end;
function TBlockHeader.GetBlockTime() : int64_t;
begin
result := (int64_t) nTime;
end;
end.
|
unit PushSupplierMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, CORBA, CosEvent, PushSupplier_Impl;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
PushSupplier_Skeleton : PushSupplier;
Event_Channel : EventChannel;
Supplier_Admin : SupplierAdmin;
Push_Consumer : ProxyPushConsumer;
procedure CorbaInit;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CorbaInit;
begin
CorbaInitialize;
// Create the skeleton and register it with the boa
PushSupplier_Skeleton := TPushSupplierSkeleton.Create('Jack B Quick', TPushSupplier.Create);
BOA.SetScope( RegistrationScope(1) );
BOA.ObjIsReady(PushSupplier_Skeleton as _Object);
//bind to the event channel and get a Supplier Admin object
Event_Channel := TEventChannelHelper.bind;
Supplier_Admin := Event_Channel.for_suppliers;
//get a push consumer and register the supplier object
Push_Consumer := Supplier_Admin.obtain_push_consumer;
Push_Consumer.connect_push_supplier(PushSupplier_Skeleton);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CorbaInit;
Memo1.Lines.Add('Account object created...');
Memo1.Lines.Add('Server is ready');
end;
procedure TForm1.Button1Click(Sender: TObject);
var myAny : Any;
begin
myAny := Edit1.text;
try
Push_Consumer.Push(myAny);
except
on EDisconnected do ShowMessage('Client Disconnected');
end;
end;
end.
|
unit Generics.Collections;
interface
{$MODE DELPHIUNICODE}
uses fgl;
type
TArray<T> = array of T;
TList<T> = class(TFPGList<T>)
end;
{ TDictionary }
TDictionary<TKey, TData> = class(TFPGMap<TKey, TData>)
public
function TryGetValue(const Key: TKey; out Value: TData): Boolean;
end;
{ TObjectList }
TObjectList<T: class> = class(TFPGList<T>)
private
FOwnsObjects: Boolean;
public
constructor Create(AOwnsObjects: Boolean = True); overload;
destructor Destroy; override;
procedure Clear;
end;
implementation
{ TObjectList<T> }
constructor TObjectList<T>.Create(AOwnsObjects: Boolean);
begin
inherited Create;
FOwnsObjects := AOwnsObjects;
end;
destructor TObjectList<T>.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TObjectList<T>.Clear;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].Free;
inherited Clear;
end;
{ TDictionary }
function TDictionary<TKey, TData>.TryGetValue(const Key: TKey; out Value: TData): Boolean;
var
Idx: Integer;
begin
Result := Find(Key, Idx);
if Result then
Value := Data[Idx];
end;
end.
|
unit Security.Login.Interfaces;
interface
uses Vcl.Forms, Vcl.ExtCtrls;
Type
// TAuthNotifyEvent = reference to procedure(const aEmail: string; const aPassword: string; var aAuthenticated: boolean; var aEmailError: string; var aPasswordError: string);
// TResultNotifyEvent = reference to procedure(const aResult: boolean = false);
TAuthNotifyEvent = procedure(const aEmail: string; const aPassword: string; var aAuthenticated: boolean; var aEmailError: string; var aPasswordError: string) of Object;
TResultNotifyEvent = procedure(const aResult: boolean = false) of Object;
Type
iPrivateLoginEvents = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ Strict private declarations }
function getOnAuth: TAuthNotifyEvent;
function getOnResult: TResultNotifyEvent;
procedure setOnAuth(const Value: TAuthNotifyEvent);
procedure setOnResult(const Value: TResultNotifyEvent);
end;
iLoginViewEvents = interface(iPrivateLoginEvents)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ Public declarations }
property OnAuth: TAuthNotifyEvent read getOnAuth write setOnAuth;
property OnResult: TResultNotifyEvent read getOnResult write setOnResult;
end;
iPrivateLoginViewProperties = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ Private declarations }
function getComputerIP: string;
function getServerIP: string;
function getSigla: string;
function getUpdatedAt: string;
function getVersion: string;
procedure setComputerIP(const Value: string);
procedure setServerIP(const Value: string);
procedure setSigla(const Value: string);
procedure setUpdatedAt(const Value: string);
procedure setVersion(const Value: string);
end;
iLoginViewProperties = interface(iPrivateLoginViewProperties)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ Public declarations }
property ComputerIP: string read getComputerIP write setComputerIP;
property ServerIP: string read getServerIP write setServerIP;
property Sigla: string read getSigla write setSigla;
property Version: string read getVersion write setVersion;
property UpdatedAt: string read getUpdatedAt write setUpdatedAt;
end;
iLoginView = interface
['{87FEC43E-4C47-47D7-92F6-E0B6A532E49D}']
function Properties: iLoginViewProperties;
function Events: iLoginViewEvents;
end;
implementation
end.
|
unit FontStuffTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SBPro, Vcl.StdCtrls;
type
TForm1 = class(TForm)
StatusBarPro1: TStatusBarPro;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
fForeColor: TColor;
fBackColor: TColor;
ffFontStyles: TFontStyles;
public
{ Public declarations }
property fFontStyles: TFontStyles read ffFontStyles write ffFontStyles;
property ForeColor: TColor read fForeColor write fForeColor;
property BackColor: TColor read fBackColor write fBackColor;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
StatusBarPro1.Panels[0].Color := fBackColor;
StatusBarPro1.Panels[0].Font.Style := ffFontStyles;
StatusBarPro1.Panels[0].Font.Color := fForeColor;
StatusBarPro1.Panels[0].Text := 'Back Color';
StatusBarPro1.Panels[1].Color := fBackColor;
StatusBarPro1.Panels[1].Font.Color := fForeColor;
StatusBarPro1.Panels[1].Font.Style := ffFontStyles;
StatusBarPro1.Panels[1].Text := 'Fore Color';
end;
end.
|
unit bDB;
interface
uses Firedac.comp.client, Firedac.Phys.MySQL, Firedac.UI.Intf,
Firedac.comp.dataset, Firedac.comp.UI,
types, winapi.windows,
Firedac.stan.Option, Firedac.dapt, Firedac.stan.def,
Data.DB, vEnv, system.sysutils, Firedac.stan.async, strutils;
type
TDB = class
private
class var
connection: TFDConnection;
waitCursor: TFDGUIxWaitCursor;
public
class function execute(pSql: string): tfdquery; overload;
class function execute(pSql: string; arr_params: array of variant): tfdquery; overload;
class function genWhere(const FieldNames: array of string): string;
class function listTables: TStringDynArray;
class function getConnection: TFDConnection;
end;
implementation
uses bSpartan;
{ TDB }
class function TDB.execute(pSql: string): tfdquery;
begin
TDB.execute(pSql, []);
end;
class function TDB.execute(pSql: string; arr_params: array of variant): tfdquery;
var
i: integer;
begin
result := tfdquery.Create(nil);
with result do
begin
connection := getConnection;
active := false;
close;
sql.Clear;
sql.Add(pSql);
for i := Low(arr_params) to High(arr_params) do
params[i].value := arr_params[i];
if lowercase(copy(pSql, 1, 6)) = 'select' then
begin
open;
active := True;
FetchAll;
if recordcount = 0 then
result := nil;
end
else
ExecSQL;
end;
end;
class function TDB.genWhere(const FieldNames: array of string): string;
var
filter: string;
i: integer;
begin
filter := ' WHERE ';
for i := Low(FieldNames) to High(FieldNames) do
begin
filter := concat(filter, ' ', FieldNames[i], '=?');
if i <> High(FieldNames) then
filter := concat(filter, ' AND');
end;
result := filter;
end;
class function TDB.getConnection: TFDConnection;
begin
if connection = nil then
begin
connection := TFDConnection.Create(nil);
with connection do
begin
Connected := false;
params.BeginUpdate;
params.Clear;
params.endUpdate;
ResourceOptions.AutoReconnect := false;
params.BeginUpdate;
LoginPrompt := false;
params.Values['Server'] := tenv.DB.Server;
params.Values['Port'] := tenv.DB.Port;
params.Values['Database'] := tenv.DB.Database;
params.Values['User_name'] := tenv.DB.User;
params.Values['Password'] := tenv.DB.Password;
params.Values['DriverID'] := tenv.DB.Driver;
params.Values['LoginTimeout'] := '5000';
params.endUpdate;
end;
end;
connection.ResourceOptions.AutoReconnect := True;
connection.ConnectedStoredUsage := [auDesignTime, auRunTime];
connection.Connected := True;
result := connection;
end;
class function TDB.listTables: TStringDynArray;
var
qry: tfdquery;
begin
result := nil;
case ansiindexstr(tenv.DB.Driver, ['mysql', 'postgres', 'firebird']) of
0:
begin
qry := TDB.execute('select table_name from information_schema.tables where table_schema = ?', [tenv.DB.Database]);
end
else
TSpartan.spartError(Format('Drive "%s" not supported yet.', [tenv.DB.Driver]));
end;
if qry <> nil then
begin
with qry do
begin
FetchAll;
setlength(result, recordcount);
first;
while not eof do
begin
result[qry.RecNo - 1] := Fields[0].AsString;
next;
end;
end;
end;
end;
end.
|
UNIT XYSTACK;
TYPE
nodetype = RECORD
a,b : WORD;
lastnode : POINTER;
END;
VAR
noderec : nodetype;
nodeptr : ^noderec;
{ ---------------------------------------------------------------}
PROCEDURE Push(VAR stack : POINTER; x,y : WORD);
BEGIN
new(node);
node^.a := x;
node^.b := y
node^.lastnode := stack;
stack := node;
END;
|
unit caTransparentWnd;
{$INCLUDE ca.inc}
interface
uses
Windows, Messages, Classes, Controls, Forms;
type
TcaTransparentWnd = class(TComponent)
private
{ Private declarations }
protected
_percent : shortint;
{ Protected declarations }
public
procedure SetTransparent(percent : shortint); overload;
procedure SetTransparentHWND(hwnd: longint; percent : shortint);
procedure SetTransparent; overload;
procedure SetOpaqueHWND(hwnd : longint);
procedure SetOpaque;
{ Public declarations }
published
property Percent: shortint read _percent write _percent default 0;
{ Published declarations }
end;
implementation
const LWA_ALPHA = $2;
const GWL_EXSTYLE = (-20);
const WS_EX_LAYERED = $80000;
const WS_EX_TRANSPARENT = $20;
procedure TcaTransparentWnd.SetOpaqueHWND(hwnd: longint);
var
old: longint;
begin
old := GetWindowLongA(hwnd,GWL_EXSTYLE);
SetWindowLongA(hwnd, GWL_EXSTYLE, old and ((not 0)-WS_EX_LAYERED) );
end;
procedure TcaTransparentWnd.SetOpaque;
begin
Self.SetOpaqueHWND((Self.Owner as TForm).Handle);
end;
procedure TcaTransparentWnd.SetTransparent;
begin
Self.SetTransparentHWND((Self.Owner as TForm).Handle,100-Self._percent);
end;
procedure TcaTransparentWnd.SetTransparentHWND(hwnd: longint; percent : shortint);
var
SetLayeredWindowAttributes: function (hwnd: LongInt; crKey: byte; bAlpha: byte; dwFlags: LongInt): LongInt; stdcall;
old: longint;
User32: Cardinal;
begin
User32 := LoadLibrary('USER32');
if User32 <> 0 then
try
SetLayeredWindowAttributes := GetProcAddress(User32, 'SetLayeredWindowAttributes');
if @SetLayeredWindowAttributes <> nil then
begin
old := GetWindowLongA(hwnd,GWL_EXSTYLE);
SetWindowLongA(hwnd,GWL_EXSTYLE,old or WS_EX_LAYERED);
SetLayeredWindowAttributes(hwnd, 0, (255 * percent) DIV 100, LWA_ALPHA);
end;
finally
FreeLibrary(User32);
end;
end;
procedure TcaTransparentWnd.SetTransparent(percent: shortint);
begin
Self.SetTransparentHWND((Self.Owner as TForm).Handle,100 - percent);
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ ZeosLib Database data import and export }
{ Copyright (c) 2015-2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.DB.ZeosLib;
(*
ZeosLib, database drivers for Delphi
https://sourceforge.net/projects/zeoslib
http://zeoslib.sourceforge.net/index.php
*)
interface
uses
System.Classes, System.Types, Data.DB, BI.DataItem, BI.DB, BI.DataSource,
BI.Persist, ZClasses, ZDbcIntfs, ZCompatibility, ZDbcConnection,
ZAbstractConnection;
type
TDbcConnection=ZDbcConnection.TZAbstractConnection;
TZAbstractConnectionClass=class of TDbcConnection;
TBIZeosLib=class(TBIItemsSource)
private
class procedure Append(const AStrings:TStrings;
const AResultSet:IZResultSet;
const AName:String); static;
class function ConnectionClass(const ADriver:String):TZAbstractConnectionClass; static;
class function CreateConnection(const Definition:TDataDefinition):TDbcConnection; static;
class function CreateQuery(const AConnection:TZAbstractConnection; const SQL:String):TDataSet; static;
class function GetConnectionName(const AConnection:TDbcConnection):String; static;
class function GetKeyFieldNames(const AConnection:TDbcConnection;
const ATable:String):TStrings; static;
class function GetSchemas(const AConnection: TDbcConnection): TStrings; static;
class function GetItemNames(const AConnection:TDbcConnection;
const IncludeSystem,IncludeViews:Boolean):TStrings;
class function GetTable(const AConnection:TZAbstractConnection; const AName:String):TDataSet; static;
class function QueryTable(const AConnection:TDbcConnection; const ATable:String):IZResultSet; static;
public
class function DriverNames: TStringDynArray; static;
class function FileFilter: TFileFilters; static;
class function Import(const AConnection:TDbcConnection;
const IncludeViews:Boolean=False):TDataItem; overload; static;
class function Import(const AFileName,AProtocol:String;
const IncludeViews:Boolean=False):TDataItem; overload; static;
class function Import(const AResultSet:IZResultSet):TDataItem; overload; static;
class function Supports(const Extension:String):Boolean; static;
end;
implementation
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 3.0 for Delphi 3.0/4.0/5.0 ::
:: ::
:: Demonstration on how to use the TQRExprMemo control ::
:: ::
:: Copyright (c) 1995-1999 QuSoft AS ::
:: All Rights Reserved ::
:: ::
:: web: http://www.qusoft.com fax: +47 22 41 74 91 ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
unit exprmemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
QuickRpt, Qrctrls, Db, DBTables, ExtCtrls;
type
TfrmExprmemo = class(TForm)
QuickRep1: TQuickRep;
tbCustomer: TTable;
DetailBand1: TQRBand;
tbCustomerCustNo: TFloatField;
tbCustomerCompany: TStringField;
tbCustomerAddr1: TStringField;
tbCustomerAddr2: TStringField;
tbCustomerCity: TStringField;
tbCustomerState: TStringField;
tbCustomerZip: TStringField;
tbCustomerCountry: TStringField;
tbCustomerPhone: TStringField;
tbCustomerFAX: TStringField;
tbCustomerTaxRate: TFloatField;
tbCustomerContact: TStringField;
tbCustomerLastInvoiceDate: TDateTimeField;
QRExprMemo1: TQRExprMemo;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmExprmemo: TfrmExprmemo;
implementation
{$R *.dfm}
end.
|
///////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUITitleBar.pas
// Creater : Shen Min
// Date : 2001-10-15 V1-V3
// 2003-06-15 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////////
unit SUITitleBar;
interface
{$I SUIPack.inc}
uses Windows, Controls, Classes, Forms, Messages, Graphics, Menus, ExtCtrls,
Dialogs, SysUtils,
SUIThemes, SUIMgr, SUIPopupMenu;
type
TsuiTitleBarSections = class;
TsuiTitleBarButtons = class;
TsuiTitleBar = class;
TsuiTitleBarButtonClickEvent = procedure (Sender : TObject; ButtonIndex : Integer) of object;
TsuiTitleBarPopupMenu = class(TsuiPopupMenu)
private
m_TitleBar : TsuiTitleBar;
procedure OnMin(Sender: TObject);
procedure OnMax(Sender: TObject);
procedure OnClose(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Popup(X, Y: Integer); override;
property TitleBar : TsuiTitleBar read m_TitleBar write m_TitleBar;
end;
TsuiTitleBar = class(TCustomPanel)
private
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
m_Sections : TsuiTitleBarSections;
m_Buttons : TsuiTitleBarButtons;
m_AutoSize : Boolean;
m_ButtonInterval : Integer;
m_Caption : TCaption;
m_Active : Boolean;
m_LeftBtnXOffset : Integer;
m_RightBtnXOffset : Integer;
m_RoundCorner : Integer;
m_RoundCornerBottom : Integer;
m_DrawAppIcon : Boolean;
m_SelfChanging : Boolean;
m_DefPopupMenu : TsuiTitleBarPopupMenu;
m_BorderColor : TColor;
m_Custom : Boolean;
m_MouseDown : Boolean;
m_InButtons : Integer;
m_BtnHeight : Integer;
m_BtnTop : Integer;
m_OnBtnClick : TsuiTitleBarButtonClickEvent;
m_OnHelpBtnClick : TsuiTitleBarButtonClickEvent;
procedure SetButtons(const Value : TsuiTitleBarButtons);
procedure SetSections(const Value : TsuiTitleBarSections);
procedure SetUIStyle(const Value : TsuiUIStyle);
procedure SetButtonInterval(const Value : Integer);
procedure SetCaption(const Value : TCaption);
procedure SetActive(const Value : Boolean);
procedure SetAutoSize2(Value : Boolean);
procedure SetLeftBtnXOffset(const Value: Integer);
procedure SetRightBtnXOffset(const Value: Integer);
procedure SetDrawAppIcon(const Value: Boolean);
procedure SetRoundCorner(const Value: Integer);
procedure SetRoundCornerBottom(const Value: Integer);
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure UpdateInsideTheme(UIStyle : TsuiUIStyle);
procedure UpdateFileTheme();
procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
procedure CMFONTCHANGED(var Msg : TMessage); message CM_FONTCHANGED;
procedure WMNCLBUTTONDOWN(var Msg: TMessage); message WM_NCLBUTTONDOWN;
procedure WMNCLBUTTONUP(var Msg: TMessage); message WM_NCLBUTTONUP;
procedure WMNCMOUSEMOVE(var Msg: TMessage); message WM_NCMOUSEMOVE;
procedure CMDesignHitTest(var Msg: TCMDesignHitTest); message CM_DESIGNHITTEST;
protected
procedure Paint(); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure DblClick(); override;
procedure MouseOut(var Msg : TMessage); message CM_MOUSELEAVE;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DrawSectionsTo(Buf : TBitmap); virtual;
procedure DrawButtons(Buf : TBitmap); virtual;
function InForm() : Boolean;
function InMDIForm() : Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure ProcessMaxBtn();
procedure GetLeftImage(out Bmp : TBitmap);
procedure GetRightImage(out Bmp : TBitmap);
procedure GetCenterImage(out Bmp : TBitmap);
function CanPaint() : Boolean;
property DefPopupMenu : TsuiTitleBarPopupMenu read m_DefPopupMenu;
published
property Custom : Boolean read m_Custom write m_Custom;
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property AutoSize read m_AutoSize write SetAutoSize2;
property BiDiMode;
property Height;
property Sections : TsuiTitleBarSections read m_Sections write SetSections;
property Buttons : TsuiTitleBarButtons read m_Buttons write SetButtons;
property ButtonInterval : Integer read m_ButtonInterval write SetButtonInterval;
property Caption read m_Caption write SetCaption;
property Font;
property FormActive : Boolean read m_Active write SetActive;
property LeftBtnXOffset : Integer read m_LeftBtnXOffset write SetLeftBtnXOffset;
property RightBtnXOffset : Integer read m_RightBtnXOffset write SetRightBtnXOffset;
property DrawAppIcon : Boolean read m_DrawAppIcon write SetDrawAppIcon;
property RoundCorner : Integer read m_RoundCorner write SetRoundCorner;
property RoundCornerBottom : Integer read m_RoundCornerBottom write SetRoundCornerBottom;
property OnCustomBtnsClick : TsuiTitleBarButtonClickEvent read m_OnBtnClick write m_OnBtnClick;
property OnHelpBtnClick : TsuiTitleBarButtonClickEvent read m_OnHelpBtnClick write m_OnHelpBtnClick;
property OnResize;
end;
// ---------------- Buttons ------------------------------------
TsuiTitleBarBtnType = (suiMax, suiMin, suiClose, suiHelp, suiControlBox, suiCustom);
TsuiTitleBarButton = class(TCollectionItem)
private
m_Visible : Boolean;
m_ButtonType : TsuiTitleBarBtnType;
m_Transparent : Boolean;
m_Top : Integer;
m_UIStyle : TsuiUIStyle;
m_PicNormal : TPicture;
m_PicMouseOn : TPicture;
m_PicMouseDown : TPicture;
m_ControlBoxMenu : TPopupMenu;
procedure SetButtonType(const Value : TsuiTitleBarBtnType);
procedure SetTransparent(const Value : Boolean);
procedure SetTop(const Value : Integer);
procedure SetUIStyle(const Value : TsuiUIStyle);
procedure SetPicNormal(const Value : TPicture);
procedure SetPicMouseOn(const Value : TPicture);
procedure SetPicMouseDown(const Value : TPicture);
procedure UpdateUIStyle();
procedure UpdateInsideTheme(UIStyle : TsuiUIStyle);
procedure UpdateFileTheme();
procedure ProcessMaxBtn();
procedure SetVisible(const Value: Boolean);
public
procedure DoClick();
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property ButtonType : TsuiTitleBarBtnType read m_ButtonType write SetButtonType;
property Transparent : Boolean read m_Transparent write SetTransparent;
property Top : Integer read m_Top write SetTop;
property ControlBoxMenu : TPopupMenu read m_ControlBoxMenu write m_ControlBoxMenu;
property Visible :Boolean read m_Visible write SetVisible;
property PicNormal : TPicture read m_PicNormal write SetPicNormal;
property PicMouseOn : TPicture read m_PicMouseOn write SetPicMouseOn;
property PicMouseDown : TPicture read m_PicMouseDown write SetPicMouseDown;
end;
TsuiTitleBarButtons = class(TCollection)
private
m_TitleBar : TsuiTitleBar;
protected
function GetItem(Index: Integer): TsuiTitleBarButton;
procedure SetItem(Index: Integer; Value: TsuiTitleBarButton);
procedure Update(Item: TCollectionItem); override;
function GetOwner : TPersistent; override;
public
function Add() : TsuiTitleBarButton;
constructor Create(TitleBar: TsuiTitleBar);
property Items[Index: Integer]: TsuiTitleBarButton read GetItem write SetItem;
end;
// ---------------- Sections ------------------------------------
TsuiTitleBarAlign = (suiLeft, suiRight, suiClient);
TsuiTitleBarSection = class(TCollectionItem)
private
m_Width : Integer;
m_Align : TsuiTitleBarAlign;
m_Picture : TPicture;
m_Stretch : Boolean;
m_AutoSize : Boolean;
procedure SetPicture(const Value : TPicture);
procedure SetAutoSize(const Value : Boolean);
procedure SetWidth(const Value : Integer);
procedure SetAlign(const Value : TsuiTitleBarAlign);
procedure SetStretch(const Value : Boolean);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property AutoSize : Boolean read m_AutoSize write SetAutoSize;
property Width : Integer read m_Width write SetWidth;
property Align : TsuiTitleBarAlign read m_Align write SetAlign;
property Picture : TPicture read m_Picture write SetPicture;
property Stretch : Boolean read m_Stretch write SetStretch;
end;
TsuiTitleBarSections = class(TCollection)
private
m_TitleBar : TsuiTitleBar;
protected
function GetItem(Index: Integer): TsuiTitleBarSection;
procedure SetItem(Index: Integer; Value: TsuiTitleBarSection);
procedure Update(Item: TCollectionItem); override;
function GetOwner : TPersistent; override;
public
constructor Create(TitleBar: TsuiTitleBar);
destructor Destroy(); override;
function Add() : TsuiTitleBarSection;
property Items[Index: Integer]: TsuiTitleBarSection read GetItem write SetItem;
end;
const
SUIM_GETBORDERWIDTH = WM_USER + 8899;
implementation
uses SUIResDef, SUIPublic, SUIForm;
{ TsuiTitleBarPopupMenu }
constructor TsuiTitleBarPopupMenu.Create(AOwner: TComponent);
var
MenuItem : TMenuItem;
begin
inherited;
Self.AutoHotkeys := maManual;
MenuItem := TMenuItem.Create(nil);
MenuItem.Caption := SUI_TITLE_MENUITEM_MINIMIZE;
MenuItem.OnClick := OnMin;
Items.Add(MenuItem);
MenuItem := TMenuItem.Create(nil);
MenuItem.Caption := SUI_TITLE_MENUITEM_MAXIMIZE;
MenuItem.OnClick := OnMax;
Items.Add(MenuItem);
MenuItem := TMenuItem.Create(nil);
MenuItem.Caption := '-';
Items.Add(MenuItem);
MenuItem := TMenuItem.Create(nil);
MenuItem.Caption := SUI_TITLE_MENUITEM_CLOSE;
MenuItem.OnClick := OnClose;
Items.Add(MenuItem);
MenuAdded();
end;
destructor TsuiTitleBarPopupMenu.Destroy;
begin
inherited;
end;
procedure TsuiTitleBarPopupMenu.OnClose(Sender: TObject);
var
ParentForm : TCustomForm;
begin
ParentForm := GetParentForm(m_TitleBar);
if ParentForm <> nil then
ParentForm.Close();
end;
procedure TsuiTitleBarPopupMenu.OnMax(Sender: TObject);
var
i : Integer;
begin
for i := 0 to m_TitleBar.m_Buttons.Count - 1 do
begin
if (m_TitleBar.m_Buttons.Items[i].ButtonType = suiMax) and
m_TitleBar.m_Buttons.Items[i].Visible then
m_TitleBar.m_Buttons.Items[i].DoClick();
end;
end;
procedure TsuiTitleBarPopupMenu.OnMin(Sender: TObject);
var
ParentForm : TCustomForm;
begin
ParentForm := GetParentForm(m_TitleBar);
if (ParentForm = nil) or (Application = nil) then
Exit;
if ParentForm = Application.MainForm then
SendMessage(Application.MainForm.Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0)
else
// ShowWindow(ParentForm.Handle, SW_SHOWMINIMIZED);
ParentForm.WindowState := wsMinimized;
end;
procedure TsuiTitleBarPopupMenu.Popup(X, Y: Integer);
var
i : Integer;
MinItem, MaxItem, CloseItem : Boolean;
begin
MinItem := false;
MaxItem := false;
CloseItem := false;
if (m_TitleBar.BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
Inc(X, 176);
for i := 0 to m_TitleBar.m_Buttons.Count - 1 do
begin
if (m_TitleBar.m_Buttons.Items[i].ButtonType = suiMin) and
m_TitleBar.m_Buttons.Items[i].Visible then
MinItem := true;
if (m_TitleBar.m_Buttons.Items[i].ButtonType = suiMax) and
m_TitleBar.m_Buttons.Items[i].Visible then
MaxItem := true;
if (m_TitleBar.m_Buttons.Items[i].ButtonType = suiClose) and
m_TitleBar.m_Buttons.Items[i].Visible then
CloseItem := true;
end;
Items[0].Enabled := MinItem;
Items[1].Enabled := MaxItem;
Items[3].Enabled := CloseItem;
inherited;
end;
{ TsuiTitleBar }
constructor TsuiTitleBar.Create(AOwner: TComponent);
var
Btn : TsuiTitleBarButton;
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls];
ParentBidiMode := true;
m_Custom := false;
m_DefPopupMenu := TsuiTitleBarPopupMenu.Create(self);
m_DefPopupMenu.TitleBar := self;
m_Sections := TsuiTitleBarSections.Create(self);
m_Buttons := TsuiTitleBarButtons.Create(self);
Btn := m_Buttons.Add();
Btn.ButtonType := suiControlBox;
Btn := m_Buttons.Add();
Btn.ButtonType := suiClose;
Btn := m_Buttons.Add();
Btn.ButtonType := suiMax;
Btn := m_Buttons.Add();
Btn.ButtonType := suiMin;
Align := alTop;
ButtonInterval := 0;
FormActive := true;
m_MouseDown := false;
m_InButtons := -1;
m_LeftBtnXOffset := 0;
m_RightBtnXOffset := 0;
m_DrawAppIcon := false;
m_SelfChanging := false;
Font.Color := clWhite;
Font.Name := 'Tahoma';
Font.Style := [fsBold];
UIStyle := GetSUIFormStyle(AOwner)
end;
procedure TsuiTitleBar.SetLeftBtnXOffset(const Value: Integer);
begin
m_LeftBtnXOffset := Value;
Repaint();
end;
procedure TsuiTitleBar.SetRightBtnXOffset(const Value: Integer);
begin
m_RightBtnXOffset := Value;
Repaint();
end;
procedure TsuiTitleBar.DblClick;
var
i : Integer;
ParentForm : TCustomForm;
begin
inherited;
if csDesigning in ComponentState then
Exit;
if m_InButtons <> -1 then
begin
if m_Buttons.Items[m_InButtons].ButtonType = suiControlBox then
begin
ParentForm := GetParentForm(self);
if ParentForm <> nil then
ParentForm.Close();
end;
Exit;
end;
for i := 0 to m_Buttons.Count - 1 do
begin
if (m_Buttons.Items[i].ButtonType = suiMax) and
m_Buttons.Items[i].Visible then
begin
m_Buttons.Items[i].DoClick();
Exit;
end;
end;
end;
destructor TsuiTitleBar.Destroy();
begin
m_Buttons.Free();
m_Buttons := nil;
m_Sections.Free();
m_Sections := nil;
m_DefPopupMenu.Free();
m_DefPopupMenu := nil;
inherited Destroy();
end;
procedure TsuiTitleBar.DrawButtons(Buf: TBitmap);
var
i : Integer;
Btn : TsuiTitleBarButton;
nControlBox : Integer;
BtnRect : TRect;
nLeft : Integer;
nLeft2 : Integer;
MousePoint : TPoint;
BtnBuf : TBitmap;
Cap : String;
Icon : TIcon;
CaptionHeight : Integer;
FormBorderWidth : Integer;
begin
nLeft := Buf.Width + 1 + m_RightBtnXOffset;
FormBorderWidth := SendMessage(GetParentForm(self).Handle, SUIM_GETBORDERWIDTH, 0, 0) - 1;
Inc(nLeft, FormBorderWidth);
nControlBox := -1;
BtnBuf := TBitmap.Create();
GetCursorPos(MousePoint);
MousePoint := ScreenToClient(MousePoint);
m_InButtons := -1;
for i := 0 to m_Buttons.Count - 1 do
begin
Btn := m_Buttons.Items[i];
if not Btn.Visible then
continue;
BtnBuf.Width := Btn.PicNormal.Width;
BtnBuf.Height := Btn.PicNormal.Height;
BtnBuf.Transparent := Btn.Transparent;
if Btn.ButtonType = suiControlBox then
begin
nControlBox := i;
continue;
end;
Dec(nLeft, Btn.PicNormal.Width + 1 + m_ButtonInterval);
if nLeft + Btn.PicNormal.Width + 1 > Buf.Width then
nLeft := Buf.Width - Btn.PicNormal.Width - 1;
BtnRect := Rect(nLeft, m_BtnTop, nLeft + Btn.PicNormal.Width, m_BtnTop + Btn.PicNormal.Height);
if InRect(MousePoint, BtnRect) then
begin
m_InButtons := i;
if m_MouseDown then
begin
if Btn.PicMouseDown <> nil then
BtnBuf.Canvas.Draw(0, 0, Btn.PicMouseDown.Graphic);
{$IFNDEF SUIPACK_D9UP}
if (csDesigning in ComponentState) and InForm() then
begin
if Btn.ButtonType = suiClose then
ShowWindow(GetParentForm(self).Handle, SW_HIDE);
end;
{$ENDIF}
end
else
begin
if Btn.PicMouseOn <> nil then
BtnBuf.Canvas.Draw(0, 0, Btn.PicMouseOn.Graphic);
end;
end
else
BtnBuf.Canvas.Draw(0, 0, Btn.PicNormal.Graphic);
Buf.Canvas.Draw(nLeft, m_BtnTop, BtnBuf);
end;
nLeft2 := m_LeftBtnXOffset;
Dec(nLeft2, FormBorderWidth);
if nLeft2 < 0 then
nLeft2 := 0;
if nControlBox <> -1 then
begin
Btn := m_Buttons.Items[nControlBox];
BtnRect := Rect(nLeft2, m_BtnTop, nLeft2 + Btn.PicNormal.Width, m_BtnTop + Btn.PicNormal.Height);
if not m_DrawAppIcon then
begin
BtnBuf.Width := Btn.PicNormal.Width;
BtnBuf.Height := Btn.PicNormal.Height;
BtnBuf.Transparent := Btn.Transparent;
if InRect(MousePoint, BtnRect) then
begin
m_InButtons := nControlBox;
if m_MouseDown then
BtnBuf.Canvas.Draw(0, 0, Btn.PicMouseDown.Graphic)
else
BtnBuf.Canvas.Draw(0, 0, Btn.PicMouseOn.Graphic);
end
else
BtnBuf.Canvas.Draw(0, 0, Btn.PicNormal.Graphic);
Buf.Canvas.Draw(nLeft2, m_BtnTop - 1, BtnBuf);
Inc(nLeft2, Btn.PicNormal.Width + 5);
end
else
begin
if InRect(MousePoint, BtnRect) then
m_InButtons := nControlBox;
BtnBuf.Height := 16;
BtnBuf.Width := 16;
Icon := TIcon.Create();
if Application <> nil then
Icon.Handle := CopyImage(Application.Icon.Handle, IMAGE_ICON, 16, 16, LR_COPYFROMRESOURCE)
else
Icon.Handle := LoadImage(hInstance, 'MAINICON', IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
Buf.Canvas.Draw(nLeft2 + 3, m_BtnTop, Icon);
Icon.Free();
Inc(nLeft2, 21);
end;
end;
if nLeft2 = 0 then
Inc(nLeft2, 6);
if not m_Active then
Buf.Canvas.Font.Color := clInactiveCaption;
if Buf.Canvas.TextWidth(Caption) > nLeft - nLeft2 then
begin
Cap := Caption;
while Buf.Canvas.TextWidth(Cap + '...') > nLeft - nLeft2 do
SetLength(Cap, Length(Cap) - 1);
Cap := Cap + '...'
end
else
Cap := Caption;
CaptionHeight := Buf.Canvas.TextHeight(Cap);
if (BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
Buf.Canvas.TextOut(nLeft - Buf.Canvas.TextWidth(Cap) - 10, m_BtnTop + (m_BtnHeight - CaptionHeight) div 2, Cap)
else
Buf.Canvas.TextOut(nLeft2, m_BtnTop + (m_BtnHeight - CaptionHeight) div 2, Cap);
BtnBuf.Free();
end;
function TsuiTitleBar.InForm: Boolean;
begin
if (
(Parent <> nil) and
((Parent is TsuiForm) or (Owner is TsuiMDIForm))
) then
Result := true
else
Result := false;
end;
procedure TsuiTitleBar.SetDrawAppIcon(const Value: Boolean);
begin
m_DrawAppIcon := Value;
Repaint();
end;
procedure TsuiTitleBar.DrawSectionsTo(Buf: TBitmap);
var
nLeft, nRight : Integer;
TopOffset : Integer;
Offset : Integer;
Bmp : TBitmap;
begin
nRight := 0;
nLefT := 0;
if InForm() then
begin
Offset := -1 * SendMessage(GetParentForm(self).Handle, SUIM_GETBORDERWIDTH, 0, 0);
if Offset = 0 then
begin
if InMDIForm() then
Offset := -4
else
Offset := -3;
end;
TopOffset := -3
end
else
begin
Offset := 0;
TopOffset := 0;
end;
if (m_Sections.Count > 0) and (m_Sections.Items[0].Picture <> nil) then
begin
GetLeftImage(Bmp);
Buf.Canvas.Draw(Offset, TopOffset, Bmp);
nLeft := Bmp.Width + Offset;
end;
if (m_Sections.Count > 1) and (m_Sections.Items[1].Picture <> nil) then
begin
GetRightImage(Bmp);
nRight := Buf.Width - Bmp.Width - Offset;
Buf.Canvas.Draw(nRight, TopOffset, Bmp);
end;
if (m_Sections.Count > 2) and (m_Sections.Items[2].Picture <> nil) then
begin
GetCenterImage(bmp);
Buf.Canvas.StretchDraw(Rect(nLeft, TopOffset, nRight, Bmp.Height + TopOffset), Bmp);
end;
end;
procedure TsuiTitleBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Form : TCustomForm;
begin
inherited;
if Button = mbLeft then
begin
m_MouseDown := true;
Repaint();
Form := GetParentForm(self);
if Form = nil then
Exit;
if (
((m_InButtons = -1) and
(Form.WindowState <> wsMaximized))
{$IFDEF SUIPACK_D9UP}
and not (csDesigning in ComponentState)
{$ELSE}
or (csDesigning in ComponentState)
{$ENDIF}
) then
begin
ReleaseCapture();
SendMessage(Form.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
m_MouseDown := false;
end
end
end;
procedure TsuiTitleBar.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
Repaint();
end;
procedure TsuiTitleBar.MouseOut(var Msg: TMessage);
begin
inherited;
Repaint();
end;
procedure TsuiTitleBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
Point : TPoint;
InButtons : Integer;
begin
inherited;
if Button <> mbLeft then
Exit;
InButtons := m_InButtons;
if InButtons <> -1 then
begin
if (
(m_Buttons.Items[InButtons].ButtonType = suiControlBox) and
(m_Buttons.Items[InButtons].ControlBoxMenu = nil)
) then
begin
Point.X := 0;
Point.Y := Height;
Point := ClientToScreen(Point);
m_DefPopupMenu.Popup(Point.X, Point.Y);
end
else
begin
m_Buttons.Items[InButtons].DoClick();
if (
Assigned(m_OnBtnClick) and
(m_Buttons.Items[InButtons].ButtonType = suiCustom)
) then
m_OnBtnClick(self, InButtons)
else if(
Assigned(m_OnHelpBtnClick) and
(m_Buttons.Items[InButtons].ButtonType = suiHelp)
) then
m_OnHelpBtnClick(self, InButtons);
end;
end;
m_MouseDown := false;
Repaint();
end;
procedure TsuiTitleBar.WMERASEBKGND(var Msg: TMessage);
begin
// do nothing
end;
procedure TsuiTitleBar.Paint;
var
Buf : TBitmap;
begin
Buf := TBitmap.Create();
Buf.Canvas.Brush.Style := bsClear;
Buf.Canvas.Font := Font;
try
Buf.Width := Width;
Buf.Height := Height;
DrawSectionsTo(Buf);
DrawButtons(Buf);
BitBlt(Canvas.Handle, 0, 0, Buf.Width, Buf.Height, Buf.Canvas.Handle, 0, 0, SRCCOPY);
finally
Buf.Free();
end;
end;
procedure TsuiTitleBar.SetActive(const Value: Boolean);
begin
m_Active := Value;
Repaint();
end;
procedure TsuiTitleBar.SetAutoSize2(Value: Boolean);
begin
m_AutoSize := Value;
if Sections.Count > 0 then
begin
if InForm() then
Height := Sections.Items[0].Picture.Height - 3
else
Height := Sections.Items[0].Picture.Height;
end
else
m_AutoSize := false;
end;
procedure TsuiTitleBar.SetButtonInterval(const Value: Integer);
begin
m_ButtonInterval := Value;
Repaint();
end;
procedure TsuiTitleBar.SetButtons(const Value: TsuiTitleBarButtons);
begin
m_Buttons.Assign(Value);
end;
procedure TsuiTitleBar.SetCaption(const Value: TCaption);
begin
m_Caption := Value;
Repaint();
end;
procedure TsuiTitleBar.SetSections(const Value: TsuiTitleBarSections);
begin
m_Sections.Assign(Value);
end;
procedure TsuiTitleBar.SetUIStyle(const Value: TsuiUIStyle);
var
i : Integer;
OutUIStyle : TsuiUIStyle;
bUsingFileTheme : Boolean;
Tmp : TColor;
begin
m_UIStyle := Value;
if m_Custom then
Exit;
Sections.Clear();
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
UpdateFileTheme();
bUsingFileTheme := true;
end
else
begin
UpdateInsideTheme(OutUIStyle);
bUsingFileTheme := false;
end;
for i := 0 to m_Buttons.Count - 1 do
m_Buttons.Items[i].UIStyle := OutUIStyle;
m_DefPopupMenu.UIStyle := OutUIStyle;
m_DefPopupMenu.FileTheme := m_FileTheme;
if not m_SelfChanging then
begin
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Font.Color := clBlack
else
{$ENDIF}
begin
if bUsingFileTheme then
begin
Tmp := m_FileTheme.GetColor(SUI_THEME_TITLEBAR_FONT_COLOR);
if Tmp = -1 then
begin
Tmp := m_FileTheme.GetColor(SUI_THEME_CONTROL_FONT_COLOR);
if (Tmp = 65536) or (Tmp = 262144) or (Tmp = 196608) or (Tmp = 327680) then
Font.Color := clBlack
else
Font.Color := clWhite;
end
else
Font.Color := Tmp;
end
else
Font.Color := clWhite;
end;
end;
AutoSize := true;
Repaint();
end;
procedure TsuiTitleBar.ProcessMaxBtn;
var
i : Integer;
begin
for i := 0 to m_Buttons.Count - 1 do
if m_Buttons.Items[i].ButtonType = suiMax then
m_Buttons.Items[i].ProcessMaxBtn();
end;
procedure TsuiTitleBar.GetCenterImage(out Bmp: TBitmap);
begin
if Sections.Count > 2 then
Bmp := Sections.Items[2].Picture.Bitmap;
end;
procedure TsuiTitleBar.GetLeftImage(out Bmp: TBitmap);
begin
if Sections.Count > 0 then
Bmp := Sections.Items[0].Picture.Bitmap;
end;
procedure TsuiTitleBar.GetRightImage(out Bmp: TBitmap);
begin
if Sections.Count > 1 then
Bmp := Sections.Items[1].Picture.Bitmap;
end;
procedure TsuiTitleBar.CMDesignHitTest(var Msg: TCMDesignHitTest);
var
HitPos : TPoint;
begin
if Msg.Keys = MK_LBUTTON then
begin
HitPos := SmallPointToPoint(Msg.Pos);
MouseDown(mbLeft, [], HitPos.X, HitPos.Y);
{$IFDEF SUIPACK_D6UP}
Msg.Result := 1;
{$ENDIF}
{$IFDEF SUIPACK_D5}
if not InMDIForm() then
Msg.Result := 1
{$ENDIF}
end;
end;
function TsuiTitleBar.CanPaint: Boolean;
begin
Result := false;
if Sections = nil then
Exit;
if Sections.Count = 3 then
begin
Result := (Sections.Items[0].Picture <> nil) and
(Sections.Items[1].Picture <> nil) and
(Sections.Items[2].Picture <> nil);
end;
end;
function TsuiTitleBar.InMDIForm: Boolean;
begin
if (
(Owner is TsuiMDIForm) and
(Parent <> nil)
) then
Result := true
else
Result := false;
end;
procedure TsuiTitleBar.SetRoundCornerBottom(const Value: Integer);
begin
m_RoundCornerBottom := Value;
end;
{ TsuiTitleBarSection }
procedure TsuiTitleBarSection.Assign(Source: TPersistent);
begin
if Source is TsuiTitleBarSection then
begin
Width := TsuiTitleBarSection(Source).m_Width;
Align := TsuiTitleBarSection(Source).m_Align;
Picture.Assign(TsuiTitleBarSection(Source).m_Picture);
Stretch := TsuiTitleBarSection(Source).m_Stretch;
AutoSize := TsuiTitleBarSection(Source).m_AutoSize;
end
else
inherited Assign(Source);
end;
constructor TsuiTitleBarSection.Create(Collection: TCollection);
begin
inherited;
m_Picture := TPicture.Create();
m_Width := 10;
m_Align := suiLeft;
m_Stretch := false;
m_AutoSize := false;
end;
destructor TsuiTitleBarSection.Destroy;
begin
m_Picture.Free();
m_Picture := nil;
inherited;
end;
procedure TsuiTitleBarSection.SetAlign(const Value: TsuiTitleBarAlign);
var
i : Integer;
begin
if Value = suiClient then
begin
for i := 0 to (Collection as TsuiTitleBarSections).Count - 1 do
begin
if (Collection as TsuiTitleBarSections).Items[i].Align = suiClient then
begin
MessageDlg('Sorry, only one section''s Align property can be "suiClient"', mtError, [mbOK], 0);
Exit;
end;
end;
m_Stretch := true;
end;
m_Align := Value;
(Collection as TsuiTitleBarSections).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarSection.SetAutoSize(const Value: Boolean);
begin
m_AutoSize := Value;
if m_Picture.Graphic <> nil then
m_Width := m_Picture.Width;
(Collection as TsuiTitleBarSections).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarSection.SetPicture(const Value: TPicture);
begin
m_Picture.Assign(Value);
if Value <> nil then
if m_AutoSize then
m_Width := m_Picture.Width;
(Collection as TsuiTitleBarSections).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarSection.SetStretch(const Value: Boolean);
begin
m_Stretch := Value;
if m_Align = suiClient then
m_Stretch := true;
(Collection as TsuiTitleBarSections).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarSection.SetWidth(const Value: Integer);
begin
m_Width := Value;
(Collection as TsuiTitleBarSections).m_TitleBar.Repaint();
end;
{ TsuiTitleBarSections }
function TsuiTitleBarSections.Add: TsuiTitleBarSection;
begin
Result := inherited Add() as TsuiTitleBarSection;
end;
constructor TsuiTitleBarSections.Create(TitleBar: TsuiTitleBar);
begin
Inherited Create(TsuiTitleBarSection);
m_TitleBar := TitleBar;
end;
destructor TsuiTitleBarSections.Destroy;
begin
m_TitleBar := nil;
inherited;
end;
function TsuiTitleBarSections.GetItem(Index: Integer): TsuiTitleBarSection;
begin
Result := inherited GetItem(Index) as TsuiTitleBarSection;
end;
function TsuiTitleBarSections.GetOwner: TPersistent;
begin
Result := m_TitleBar;
end;
procedure TsuiTitleBarSections.SetItem(Index: Integer;
Value: TsuiTitleBarSection);
begin
inherited SetItem(Index, Value);
end;
procedure TsuiTitleBarSections.Update(Item: TCollectionItem);
begin
inherited;
m_TitleBar.Repaint();
end;
{ TsuiTitleBarButtons }
function TsuiTitleBarButtons.Add: TsuiTitleBarButton;
begin
Result := inherited Add() as TsuiTitleBarButton;
end;
constructor TsuiTitleBarButtons.Create(TitleBar: TsuiTitleBar);
begin
Inherited Create(TsuiTitleBarButton);
m_TitleBar := TitleBar;
end;
function TsuiTitleBarButtons.GetItem(Index: Integer): TsuiTitleBarButton;
begin
Result := inherited GetItem(Index) as TsuiTitleBarButton;
end;
function TsuiTitleBarButtons.GetOwner: TPersistent;
begin
Result := m_TitleBar;
end;
procedure TsuiTitleBarButtons.SetItem(Index: Integer;
Value: TsuiTitleBarButton);
begin
inherited SetItem(Index, Value);
end;
procedure TsuiTitleBarButtons.Update(Item: TCollectionItem);
begin
inherited;
m_TitleBar.Repaint()
end;
{ TsuiTitleBarButton }
procedure TsuiTitleBarButton.Assign(Source: TPersistent);
begin
if Source is TsuiTitleBarButton then
begin
Visible := TsuiTitleBarButton(Source).m_Visible;
ButtonType := TsuiTitleBarButton(Source).m_ButtonType;
Transparent := TsuiTitleBarButton(Source).m_Transparent;
Top := TsuiTitleBarButton(Source).m_Top;
UIStyle := TsuiTitleBarButton(Source).m_UIStyle;
PicNormal.Assign(TsuiTitleBarButton(Source).m_PicNormal);
PicMouseOn.Assign(TsuiTitleBarButton(Source).m_PicMouseOn);
PicMouseDown.Assign(TsuiTitleBarButton(Source).m_PicMouseDown);
ControlBoxMenu := TsuiTitleBarButton(Source).m_ControlBoxMenu;
end
else
inherited Assign(Source);
end;
constructor TsuiTitleBarButton.Create(Collection: TCollection);
begin
inherited;
m_Visible := true;
m_ButtonType := suiCustom;
m_Transparent := false;
m_Top := 2;
m_PicNormal := TPicture.Create();
m_PicMouseOn := TPicture.Create();
m_PicMouseDown := TPicture.Create();
UIStyle := SUI_THEME_DEFAULT;
ControlBoxMenu := nil;
end;
destructor TsuiTitleBarButton.Destroy;
begin
m_PicMouseDown.Free();
m_PicMouseDown := nil;
m_PicMouseOn.Free();
m_PicMouseOn := nil;
m_PicNormal.Free();
m_PicNormal := nil;
inherited;
end;
procedure TsuiTitleBarButton.DoClick;
var
ParentForm : TCustomForm;
Point : TPoint;
WorkAreaRect : TRect;
begin
if (Collection as TsuiTitleBarButtons).m_TitleBar = nil then
Exit;
ParentForm := GetParentForm((Collection as TsuiTitleBarButtons).m_TitleBar);
if ParentForm = nil then
Exit;
case m_ButtonType of
suiMax :
begin
if ParentForm.WindowState = wsMaximized then
ParentForm.WindowState := wsNormal
else
begin
ParentForm.WindowState := wsMaximized;
if not (Collection as TsuiTitleBarButtons).m_TitleBar.InForm() then
begin
WorkAreaRect := GetWorkAreaRect();
Dec(WorkAreaRect.Bottom);
Dec(WorkAreaRect.Top, 2);
Dec(WorkAreaRect.Left, 2);
Inc(WorkAreaRect.Right, 2);
PlaceControl(ParentForm, WorkAreaRect);
end;
end;
ProcessMaxBtn();
end;
suiMin :
begin
if (Application <> nil) and (ParentForm = Application.MainForm) then
SendMessage(Application.MainForm.Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0)
else
begin
//ShowWindow(ParentForm.Handle, SW_SHOWMINIMIZED);
ParentForm.WindowState := wsMinimized;
end;
end;
suiClose :
begin
ParentForm.Close();
end;
suiControlBox :
begin
if Assigned(m_ControlBoxMenu) then
begin
if ((Collection as TsuiTitleBarButtons).m_TitleBar.BidiMode = bdRightToLeft) and SysLocale.MiddleEast then
Point.X := 176
else
Point.X := 0;
Point.Y := (Collection as TsuiTitleBarButtons).m_TitleBar.Height;
Point := (Collection as TsuiTitleBarButtons).m_TitleBar.ClientToScreen(Point);
if Point.X < 0 then
Point.X := 0;
m_ControlBoxMenu.Popup(Point.X, Point.Y);
end;
end;
suiCustom :
begin
end;
end; // case
end;
procedure TsuiTitleBarButton.ProcessMaxBtn;
procedure InMAX(FileTheme : TsuiFileTheme);
var
OutUIStyle : TsuiUIStyle;
begin
if UsingFileTheme(FileTheme, m_UIStyle, OutUIStyle) then
begin
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, 10);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, 11);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, 12);
end
else
begin
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, 10);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, 11);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, 12);
end;
end;
procedure InNormal(FileTheme : TsuiFileTheme);
var
OutUIStyle : TsuiUIStyle;
begin
if UsingFileTheme(FileTheme, m_UIStyle, OutUIStyle) then
begin
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, 7);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, 8);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, 9);
end
else
begin
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, 7);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, 8);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, 9);
end;
end;
var
ParentForm : TCustomForm;
begin
if ButtonType <> suiMax then
Exit;
if (Collection as TsuiTitleBarButtons).m_TitleBar.Custom then
Exit;
ParentForm := GetParentForm((Collection as TsuiTitleBarButtons).m_TitleBar);
if ParentForm = nil then
begin
InNormal((Collection as TsuiTitleBarButtons).m_TitleBar.FileTheme);
Exit;
end;
if ParentForm.WindowState = wsMaximized then
InMax((Collection as TsuiTitleBarButtons).m_TitleBar.FileTheme)
else
InNormal((Collection as TsuiTitleBarButtons).m_TitleBar.FileTheme);
end;
procedure TsuiTitleBarButton.SetButtonType(const Value: TsuiTitleBarBtnType);
var
i : Integer;
begin
if Value = suiControlBox then
begin
for i := 0 to (Collection as TsuiTitleBarButtons).Count - 1 do
begin
if (Collection as TsuiTitleBarButtons).Items[i].ButtonType = suiControlBox then
begin
MessageDlg('Sorry, only one button''s ButtonType property can be "suiControlBox"', mtError, [mbOK], 0);
Exit;
end;
end;
end;
m_ButtonType := Value;
UpdateUIStyle();
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetPicMouseDown(const Value: TPicture);
begin
m_PicMouseDown.Assign(Value);
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetPicMouseOn(const Value: TPicture);
begin
m_PicMouseOn.Assign(Value);
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetPicNormal(const Value: TPicture);
begin
m_PicNormal.Assign(Value);
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetTop(const Value: Integer);
begin
m_Top := Value;
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetTransparent(const Value: Boolean);
begin
m_Transparent := Value;
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.SetUIStyle(const Value: TsuiUIStyle);
begin
m_UIStyle := Value;
UpdateUIStyle();
end;
procedure TsuiTitleBarButton.SetVisible(const Value: Boolean);
begin
m_Visible := Value;
(Collection as TsuiTitleBarButtons).m_TitleBar.Repaint();
end;
procedure TsuiTitleBarButton.UpdateFileTheme;
var
nNormal : Integer;
nMouseOn : Integer;
nMouseDown : Integer;
FileTheme : TsuiFileTheme;
begin
FileTheme := (Collection as TsuiTitleBarButtons).m_TitleBar.FileTheme;
Transparent := FileTheme.GetBool(SUI_THEME_TITLEBAR_BUTTON_TRANSPARENT_BOOL);
case m_ButtonType of
suiMax :
begin
nNormal := 7;
nMouseOn := 8;
nMouseDown := 9;
end;
suiMin :
begin
nNormal := 13;
nMouseOn := 14;
nMouseDown := 15;
end;
suiClose :
begin
nNormal := 16;
nMouseOn := 17;
nMouseDown := 18;
end;
suiHelp :
begin
nNormal := 4;
nMouseOn := 5;
nMouseDown := 6;
end;
suiControlBox :
begin
nNormal := 1;
nMouseOn := 2;
nMouseDown := 3;
end;
else Exit;
end; // case
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, nNormal);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, nMouseOn);
FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, nMouseDown);
Top := FileTheme.GetInt(SUI_THEME_TITLEBAR_BUTTON_TOP_INT);
end;
procedure TsuiTitleBarButton.UpdateInsideTheme(UIStyle : TsuiUIStyle);
var
nNormal : Integer;
nMouseOn : Integer;
nMouseDown : Integer;
begin
Transparent := GetInsideThemeBool(UIStyle, SUI_THEME_TITLEBAR_BUTTON_TRANSPARENT_BOOL);
case m_ButtonType of
suiMax :
begin
nNormal := 7;
nMouseOn := 8;
nMouseDown := 9;
end;
suiMin :
begin
nNormal := 13;
nMouseOn := 14;
nMouseDown := 15;
end;
suiClose :
begin
nNormal := 16;
nMouseOn := 17;
nMouseDown := 18;
end;
suiHelp :
begin
nNormal := 4;
nMouseOn := 5;
nMouseDown := 6;
end;
suiControlBox :
begin
nNormal := 1;
nMouseOn := 2;
nMouseDown := 3;
end;
else Exit;
end; // case
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicNormal.Bitmap, 18, nNormal);
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseOn.Bitmap, 18, nMouseOn);
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, PicMouseDown.Bitmap, 18, nMouseDown);
Top := GetInsideThemeInt(UIStyle, SUI_THEME_TITLEBAR_BUTTON_TOP_INT);
end;
procedure TsuiTitleBarButton.UpdateUIStyle;
var
OutUIStyle : TsuiUIStyle;
begin
if UsingFileTheme((Collection as TsuiTitleBarButtons).m_TitleBar.FileTheme, m_UIStyle, OutUIStyle) then
UpdateFileTheme()
else
UpdateInsideTheme(OutUIStyle);
if m_ButtonType = suiMax then
ProcessMaxBtn();
end;
procedure TsuiTitleBar.CMFONTCHANGED(var Msg: TMessage);
begin
Repaint();
end;
procedure TsuiTitleBar.SetRoundCorner(const Value: Integer);
begin
m_RoundCorner := Value;
end;
procedure TsuiTitleBar.WMNCLBUTTONDOWN(var Msg: TMessage);
begin
Msg.Result := SendMessage(GetParentForm(Self).Handle, Msg.Msg, Msg.WParam, Msg.LParam);
end;
procedure TsuiTitleBar.WMNCLBUTTONUP(var Msg: TMessage);
begin
Msg.Result := SendMessage(GetParentForm(Self).Handle, Msg.Msg, Msg.WParam, Msg.LParam);
end;
procedure TsuiTitleBar.WMNCMOUSEMOVE(var Msg: TMessage);
begin
Msg.Result := SendMessage(GetParentForm(Self).Handle, Msg.Msg, Msg.WParam, Msg.LParam);
end;
procedure TsuiTitleBar.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
m_SelfChanging := true;
SetUIStyle(m_UIStyle);
m_SelfChanging := false;
end;
procedure TsuiTitleBar.UpdateFileTheme;
var
Sec : TsuiTitleBarSection;
Form : TCustomForm;
TempBmp : TBitmap;
begin
Sec := Sections.Add();
m_FileTheme.GetBitmap(SUI_THEME_TITLEBAR_LEFT_IMAGE, Sec.Picture.Bitmap);
Sec.AutoSize := true;
Sec := Sections.Add();
m_FileTheme.GetBitmap(SUI_THEME_TITLEBAR_RIGHT_IMAGE, Sec.Picture.Bitmap);
Sec.AutoSize := true;
Sec.Align := suiRight;
Sec := Sections.Add();
m_FileTheme.GetBitmap(SUI_THEME_TITLEBAR_CLIENT_IMAGE, Sec.Picture.Bitmap);
Sec.Align := suiClient;
LeftBtnXOffset := m_FileTheme.GetInt(SUI_THEME_TITLEBAR_BUTTON_LEFTOFFSET_INT);
RightBtnXOffset := m_FileTheme.GetInt(SUI_THEME_TITLEBAR_BUTTON_RIGHTOFFSET_INT);
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_FORM_BORDER_COLOR);
TempBmp := TBitmap.Create();
m_FileTheme.GetBitmap(SUI_THEME_TITLEBAR_BUTTON_IMAGE, TempBmp);
m_BtnHeight := TempBmp.Height;
TempBmp.Free();
m_BtnTop := m_FileTheme.GetInt(SUI_THEME_TITLEBAR_BUTTON_TOP_INT);
if Inform() then
Dec(m_BtnTop, 3);
Form := GetParentForm(self);
if Form <> nil then
Form.Constraints.MinWidth := m_FileTheme.GetInt(SUI_THEME_FORM_MINWIDTH_INT);
m_RoundCorner := m_FileTheme.GetInt(SUI_THEME_FORM_ROUNDCORNER_INT);
m_RoundCornerBottom := m_FileTheme.GetInt(SUI_THEME_FORM_BOTTOMROUNDCORNOR_INT);
end;
procedure TsuiTitleBar.UpdateInsideTheme(UIStyle : TsuiUIStyle);
var
Sec : TsuiTitleBarSection;
Form : TCustomForm;
TempBmp : TBitmap;
begin
Sec := Sections.Add();
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_LEFT_IMAGE, Sec.Picture.Bitmap);
Sec.AutoSize := true;
Sec := Sections.Add();
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_RIGHT_IMAGE, Sec.Picture.Bitmap);
Sec.AutoSize := true;
Sec.Align := suiRight;
Sec := Sections.Add();
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_CLIENT_IMAGE, Sec.Picture.Bitmap);
Sec.Align := suiClient;
LeftBtnXOffset := GetInsideThemeInt(UIStyle, SUI_THEME_TITLEBAR_BUTTON_LEFTOFFSET_INT);
RightBtnXOffset := GetInsideThemeInt(UIStyle, SUI_THEME_TITLEBAR_BUTTON_RIGHTOFFSET_INT);
m_BorderColor := GetInsideThemeColor(UIStyle, SUI_THEME_FORM_BORDER_COLOR);
TempBmp := TBitmap.Create();
GetInsideThemeBitmap(UIStyle, SUI_THEME_TITLEBAR_BUTTON_IMAGE, TempBmp);
m_BtnHeight := TempBmp.Height;
TempBmp.Free();
m_BtnTop := GetInsideThemeInt(UIStyle, SUI_THEME_TITLEBAR_BUTTON_TOP_INT);
if Inform() then
Dec(m_BtnTop, 3);
Form := GetParentForm(self);
if Form <> nil then
Form.Constraints.MinWidth := GetInsideThemeInt(UIStyle, SUI_THEME_FORM_MINWIDTH_INT);
m_RoundCorner := GetInsideThemeInt(UIStyle, SUI_THEME_FORM_ROUNDCORNER_INT);
m_RoundCornerBottom := 0;
end;
procedure TsuiTitleBar.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
end.
|
unit uKamObjektiv;
{$MODE Delphi}
//Bisher etwas mager, da nur Objektive für perspektivische Sicht vorgesehen sind.
//Eine Minimalauswahl aus "Standardobjektiven wäre vorstellbar (Weitwinkelobjektiv ...).
interface
TYPE TObjektiv= (Perspektive, Orthogonal);
VAR aktObjektiv: TObjektiv;
procedure KamProjFlaecheInit
(Breite,Hoehe:CARDINAL);
(*Die Kamera besitzt ein Display von Breite * Hoehe Pixeln.*)
procedure KamObjektivInit (Sichtwinkel:Real; //in y-Richtung
nah,fern:Real); //Clippingbereich
(*Vor: 0<SichtWinkel<180 und 0<nah<fern
Eff: Initialisiert die Kamera mit dem Objektiv so, dass das
Kameradisplay ProjFlaechenBreite*ProjFlaechenHoehe Pixel besitzt.
Das Objektiv hat die Einstellung, dass es in der ProjFlaechenHoehe
den Sichtwinkel abbildet.
Nah und Fern sind der darstellbare Tiefenbereich des Objektivs.*)
procedure KamObjektivZoom (deltaSichtWinkel:Real);
//Ändert den SichtWinkel um deltaSichtWinkel, wobei deltaSichtwinkel>0 ein
//heranzoomen bedeutet.
//Würde hierdurch der Sichtwinkel<=0 oder SichtWinkel>=180, so ist nichts
//verändert.
implementation
uses dglOpenGL, Math;
VAR phi:Real;
Pbreite,Phoehe:CARDINAL; //Pixelanzahl
Cnah,Cfern:Real;
procedure KamProjFlaecheInit(Breite,Hoehe:CARDINAL);
begin
PBreite:=breite;
PHoehe:=Hoehe;
end;
procedure KamObjektivInit (Sichtwinkel:Real; //in y-Richtung
nah,fern:Real); //Clippingbereich
VAR d:REAL;
begin
Cnah:=nah;
CFern:=fern;
phi:=Sichtwinkel;
glMatrixMode(GL_Projection);
glLoadIdentity;
IF aktObjektiv=Perspektive THEN
gluPerspective(phi,Pbreite/Phoehe, CNah, CFern)
ELSE
begin
d:=3*tan(phi/180*pi);
glOrtho (-Pbreite/PHoehe*d,PBreite/PHoehe*d,-d,d,Cnah,Cfern);
end;
end;
procedure KamObjektivZoom (deltaSichtWinkel:Real);
var temp:Real;
d:Real;
begin
temp:=phi-deltaSichtWinkel;
IF (temp>0) and (temp<180) then
begin
phi:=temp;
glMatrixMode(GL_Projection);
glLoadIdentity;
IF aktObjektiv=Perspektive THEN
gluPerspective(phi,Pbreite/Phoehe, CNah, CFern)
Else
begin
d:=3*tan(phi/180*pi);
glOrtho (-Pbreite/PHoehe*d,PBreite/PHoehe*d,-d,d,Cnah,Cfern);
end;
end;
end;
begin
aktObjektiv:=Perspektive
end.
|
unit ORCtrlsVA508Compatibility;
interface
uses
Forms, Controls, StdCtrls, SysUtils, Windows, VA508AccessibilityManager;
type
TORCheckBox508Manager = class(TVA508ManagedComponentClass)
public
constructor Create; override;
function GetComponentName(Component: TWinControl): string; override;
function GetInstructions(Component: TWinControl): string; override;
function GetState(Component: TWinControl): string; override;
end;
TLBMgr = class
private
function GetIdx(Component: TWinControl): integer;
public
function GetComponentName(Component: TWinControl): string; virtual; abstract;
function GetState(Component: TWinControl): string; virtual; abstract;
function GetItemInstructions(Component: TWinControl): string; virtual; abstract;
end;
TORListBox508Manager = class(TVA508ManagedComponentClass)
var
FCheckBoxes: TLBMgr;
FMultiSelect: TLBMgr;
FStandard: TLBMgr;
FCurrent: TLBMgr;
function GetCurrent(Component: TWinControl): TLBMgr;
public
constructor Create; override;
destructor Destroy; override;
function GetComponentName(Component: TWinControl): string; override;
function GetState(Component: TWinControl): string; override;
function GetItem(Component: TWinControl): TObject; override;
function GetItemInstructions(Component: TWinControl): string; override;
function GetValue(Component: TWinControl): string; override;
end;
TVA508TORDateComboComplexManager = class(TVA508ComplexComponentManager)
public
constructor Create;
procedure Refresh(Component: TWinControl;
AccessibilityManager: TVA508AccessibilityManager); override;
end;
// TVA508TORComboBoxComplexManager = class(TVA508ComplexComponentManager)
// public
// constructor Create;
// procedure Refresh(Component: TWinControl;
// AccessibilityManager: TVA508AccessibilityManager); override;
// end;
{ TVA508TORDateBoxComplexManager = class(TVA508ComplexComponentManager)
public
constructor Create;
procedure Refresh(Component: TWinControl;
AccessibilityManager: TVA508AccessibilityManager); override;
end;}
TORComboBox508Manager = class(TVA508ManagedComponentClass)
public
constructor Create; override;
function GetValue(Component: TWinControl): string; override;
end;
TORDayCombo508Manager = class(TORComboBox508Manager)
public
constructor Create; override;
function GetCaption(Component: TWinControl): string; override;
end;
TORMonthCombo508Manager = class(TORComboBox508Manager)
public
constructor Create; override;
function GetCaption(Component: TWinControl): string; override;
end;
TORYearEdit508Manager = class(TVA508ManagedComponentClass)
public
constructor Create; override;
function GetCaption(Component: TWinControl): string; override;
end;
TORDateButton508Manager = class(TVA508ManagedComponentClass)
public
constructor Create; override;
function GetCaption(Component: TWinControl): string; override;
end;
// TORComboEdit508Manager = class(TVA508ManagedComponentClass)
// public
// constructor Create; override;
// function Redirect(Component: TWinControl; var ManagedType: TManagedType): TWinControl; override;
// end;
implementation
uses VA508DelphiCompatibility, ORCtrls, ORDtTm, VA508AccessibilityRouter,
VA508AccessibilityConst, ORDtTmRng;
function GetEditBox(ComboBox: TORComboBox): TORComboEdit;
var
i: integer;
begin
Result := nil;
for i := 0 to ComboBox.ControlCount - 1 do
begin
if ComboBox.Controls[i] is TORComboEdit then
begin
Result := TORComboEdit(ComboBox.Controls[i]);
exit;
end;
end;
end;
function ORComboBoxAlternateHandle(Component: TWinControl): HWnd;
var
eBox: TORComboEdit;
cBox: TORComboBox;
begin
cBox := TORComboBox(Component);
eBox := GetEditBox(cBox);
if assigned(eBox) then
Result := eBox.Handle
else
Result := cBox.Handle;
end;
type
TVA508RegistrationScreenReader = class(TVA508ScreenReader);
{ Registration }
procedure RegisterORComponents;
begin
RegisterAlternateHandleComponent(TORComboBox, ORComboBoxAlternateHandle);
RegisterManagedComponentClass(TORCheckBox508Manager.Create);
RegisterManagedComponentClass(TORComboBox508Manager.Create);
RegisterManagedComponentClass(TORListBox508Manager.Create);
RegisterManagedComponentClass(TORDayCombo508Manager.Create);
RegisterManagedComponentClass(TORMonthCombo508Manager.Create);
RegisterManagedComponentClass(TORYearEdit508Manager.Create);
RegisterManagedComponentClass(TORDateButton508Manager.Create);
// RegisterManagedComponentClass(TORComboEdit508Manager.Create);
RegisterComplexComponentManager(TVA508TORDateComboComplexManager.Create);
// RegisterComplexComponentManager(TVA508TORComboBoxComplexManager.Create);
// RegisterComplexComponentManager(TVA508TORDateBoxComplexManager.Create);
with TVA508RegistrationScreenReader(GetScreenReader) do
begin
//---TORCalendar ???
//---TORPopupMenu ???
//---TORMenuItem ???
RegisterCustomClassBehavior(TORTreeView.ClassName, CLASS_BEHAVIOR_TREE_VIEW);
RegisterCustomClassBehavior(TORAlignEdit.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TORAlignButton.ClassName, CLASS_BEHAVIOR_BUTTON);
RegisterCustomClassBehavior(TORAlignSpeedButton.ClassName, CLASS_BEHAVIOR_BUTTON);
RegisterCustomClassBehavior(TORCheckBox.ClassName, CLASS_BEHAVIOR_CHECK_BOX);
RegisterCustomClassBehavior(TKeyClickPanel.ClassName, CLASS_BEHAVIOR_BUTTON);
RegisterCustomClassBehavior(TKeyClickRadioGroup.ClassName, CLASS_BEHAVIOR_GROUP_BOX);
RegisterCustomClassBehavior(TCaptionTreeView.ClassName, CLASS_BEHAVIOR_TREE_VIEW);
RegisterCustomClassBehavior(TCaptionMemo.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TCaptionEdit.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TCaptionRichEdit.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TOROffsetLabel.ClassName, CLASS_BEHAVIOR_STATIC_TEXT);
RegisterCustomClassBehavior(TCaptionComboBox.ClassName, CLASS_BEHAVIOR_COMBO_BOX);
RegisterCustomClassBehavior(TORComboEdit.ClassName, CLASS_BEHAVIOR_EDIT_COMBO);
RegisterCustomClassBehavior(TORComboBox.ClassName, CLASS_BEHAVIOR_COMBO_BOX);
RegisterCustomClassBehavior(TORListBox.ClassName, CLASS_BEHAVIOR_LIST_BOX);
RegisterCustomClassBehavior(TCaptionCheckListBox.ClassName, CLASS_BEHAVIOR_LIST_BOX);
RegisterCustomClassBehavior(TCaptionStringGrid.ClassName, CLASS_BEHAVIOR_LIST_BOX);
RegisterCustomClassBehavior(TORDateEdit.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TORDayCombo.ClassName, CLASS_BEHAVIOR_COMBO_BOX);
RegisterCustomClassBehavior(TORMonthCombo.ClassName, CLASS_BEHAVIOR_COMBO_BOX);
RegisterCustomClassBehavior(TORYearEdit.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TORDateBox.ClassName, CLASS_BEHAVIOR_EDIT);
RegisterCustomClassBehavior(TORDateCombo.ClassName, CLASS_BEHAVIOR_GROUP_BOX);
RegisterCustomClassBehavior(TORListView.ClassName, CLASS_BEHAVIOR_LIST_VIEW);
RegisterCustomClassBehavior(TCaptionListView.ClassName, CLASS_BEHAVIOR_LIST_VIEW);
RegisterCustomClassBehavior(TCaptionListBox.ClassName, CLASS_BEHAVIOR_LIST_BOX);
RegisterCustomClassBehavior(TORDateRangeDlg.ClassName, CLASS_BEHAVIOR_DIALOG);
RegisterCustomClassBehavior(TORfrmDtTm.ClassName, CLASS_BEHAVIOR_DIALOG);//called by TORDateTimeDlg
end;
end;
{ TORCheckBox508Manager }
constructor TORCheckBox508Manager.Create;
begin
inherited Create(TORCheckBox, [mtComponentName, mtInstructions, mtState, mtStateChange], TRUE);
end;
function TORCheckBox508Manager.GetComponentName(Component: TWinControl): string;
begin
with TORCheckBox(Component) do
begin
if RadioStyle then
Result := 'radio button'
else
Result := VA508DelphiCompatibility.GetCheckBoxComponentName(AllowGrayed);
end;
end;
function TORCheckBox508Manager.GetInstructions(Component: TWinControl): string;
begin
Result := VA508DelphiCompatibility.GetCheckBoxInstructionMessage(TORCheckBox(Component).Checked);
end;
function TORCheckBox508Manager.GetState(Component: TWinControl): string;
var
cb: TORCheckBox;
begin
Application.ProcessMessages; // <<< needed to allow messages that set state to process
Result := '';
cb := TORCheckBox(Component);
if (cb.State = cbGrayed) and (cb.GrayedStyle in [gsQuestionMark, gsBlueQuestionMark]) then
Result := 'Question Mark'
else
Result := VA508DelphiCompatibility.GetCheckBoxStateText(cb.State);
end;
{ TORListBox508Manager }
type
TORListBoxCheckBoxes508Manager = class(TLBMgr)
public
function GetComponentName(Component: TWinControl): string; override;
function GetState(Component: TWinControl): string; override;
function GetItemInstructions(Component: TWinControl): string; override;
end;
TORListBoxMultiSelect508Manager = class(TLBMgr)
public
function GetComponentName(Component: TWinControl): string; override;
function GetState(Component: TWinControl): string; override;
function GetItemInstructions(Component: TWinControl): string; override;
end;
TORListBoxStandard508Manager = class(TLBMgr)
public
function GetComponentName(Component: TWinControl): string; override;
function GetState(Component: TWinControl): string; override;
function GetItemInstructions(Component: TWinControl): string; override;
end;
constructor TORListBox508Manager.Create;
begin
inherited Create(TORListBox, [mtComponentName, mtValue, mtState, mtStateChange,
mtItemChange, mtItemInstructions]);
end;
destructor TORListBox508Manager.Destroy;
begin
FCurrent := nil;
if assigned(FCheckBoxes) then
FreeAndNil(FCheckBoxes);
if assigned(FMultiSelect) then
FreeAndNil(FMultiSelect);
if assigned(FStandard) then
FreeAndNil(FStandard);
inherited;
end;
function TORListBox508Manager.GetComponentName(Component: TWinControl): string;
begin
Result := GetCurrent(Component).GetComponentName(Component);
end;
function TORListBox508Manager.GetItem(Component: TWinControl): TObject;
var
lb : TORListBox;
max, id: integer;
begin
GetCurrent(Component);
lb := TORListBox(Component);
max := lb.items.Count + 2;
if max < 10000 then
max := 10000;
id := (lb.items.Count * max) + (lb.FocusIndex + 2);
if lb.FocusIndex < 0 then dec(id);
Result := TObject(id);
end;
function TORListBox508Manager.GetItemInstructions(
Component: TWinControl): string;
begin
Result := GetCurrent(Component).GetItemInstructions(Component);
end;
function TORListBox508Manager.GetState(Component: TWinControl): string;
begin
Result := GetCurrent(Component).GetState(Component);
end;
function TORListBox508Manager.GetValue(Component: TWinControl): string;
var idx: integer;
lb: TORListBox;
begin
lb := TORListBox(Component);
idx := lb.FocusIndex;
if idx < 0 then
idx := 0;
Result := lb.DisplayText[idx];
end;
function TORListBox508Manager.GetCurrent(Component: TWinControl): TLBMgr;
var
lb : TORListBox;
begin
lb := TORListBox(Component);
if lb.CheckBoxes then
begin
if not assigned(FCheckBoxes) then
FCheckBoxes := TORListBoxCheckBoxes508Manager.Create;
FCurrent := FCheckBoxes;
end
else if lb.MultiSelect then
begin
if not assigned(FMultiSelect) then
FMultiSelect := TORListBoxMultiSelect508Manager.Create;
FCurrent := FMultiSelect;
end
else
begin
if not assigned(FStandard) then
FStandard := TORListBoxStandard508Manager.Create;
FCurrent := FStandard;
end;
Result := FCurrent;
end;
{ TORListBoxCheckBoxes508Manager }
function TORListBoxCheckBoxes508Manager.GetComponentName(
Component: TWinControl): string;
begin
Result := 'Check List Box'
end;
function TORListBoxCheckBoxes508Manager.GetItemInstructions(
Component: TWinControl): string;
var
lb: TORListBox;
idx: integer;
begin
Result := '';
lb := TORListBox(Component);
idx := GetIdx(Component);
if (idx >= 0) then
Result := VA508DelphiCompatibility.GetCheckBoxInstructionMessage(lb.Checked[idx])
else
Result := '';
end;
function TORListBoxCheckBoxes508Manager.GetState(
Component: TWinControl): string;
var
lb: TORListBox;
idx: integer;
begin
lb := TORListBox(Component);
idx := GetIdx(Component);
if (idx >= 0) then
begin
Result := GetCheckBoxStateText(lb.CheckedState[idx]);
if lb.FocusIndex < 0 then
Result := 'not selected ' + Result;
end
else
Result := '';
end;
{ TORListBoxMultiSelect508Manager }
function TORListBoxMultiSelect508Manager.GetComponentName(
Component: TWinControl): string;
begin
Result := 'Multi Select List Box'
end;
function TORListBoxMultiSelect508Manager.GetItemInstructions(
Component: TWinControl): string;
var
lb: TORListBox;
idx: integer;
begin
Result := '';
lb := TORListBox(Component);
idx := GetIdx(Component);
if (idx >= 0) then
begin
if not lb.Selected[idx] then
Result := 'to select press space bar'
else
Result := 'to un select press space bar';
end;
end;
function TORListBoxMultiSelect508Manager.GetState(
Component: TWinControl): string;
var
lb: TORListBox;
idx: Integer;
begin
lb := TORListBox(Component);
idx := GetIdx(Component);
if (idx >= 0) then
begin
if lb.Selected[idx] then
Result := 'Selected'
else
Result := 'Not Selected';
end
else
Result := '';
end;
{ TORListBoxStandard508Manager }
function TORListBoxStandard508Manager.GetComponentName(
Component: TWinControl): string;
begin
Result := 'List Box';
end;
function TORListBoxStandard508Manager.GetItemInstructions(
Component: TWinControl): string;
begin
Result := '';
end;
function TORListBoxStandard508Manager.GetState(Component: TWinControl): string;
var
lb: TORListBox;
begin
lb := TORListBox(Component);
if (lb.FocusIndex < 0) then
Result := 'Not Selected'
else
Result := '';
end;
{ TLBMgr }
function TLBMgr.GetIdx(Component: TWinControl): integer;
begin
Result := TORListBox(Component).FocusIndex;
if (Result < 0) and (TORListBox(Component).Count > 0) then
Result := 0;
end;
{ TVA508TORDateComboComplexManager }
constructor TVA508TORDateComboComplexManager.Create;
begin
inherited Create(TORDateCombo);
end;
type
TORDateComboFriend = class(TORDateCombo);
procedure TVA508TORDateComboComplexManager.Refresh(Component: TWinControl;
AccessibilityManager: TVA508AccessibilityManager);
begin
with TORDateComboFriend(Component) do
begin
ClearSubControls(Component);
// if assigned(CalBtn) then
// CalBtn.TabStop := TRUE;
// if IncludeBtn then
// AddSubControl(CalBtn, AccessibilityManager);
AddSubControl(Component, YearEdit, AccessibilityManager);
// AddSubControl(YearUD, AccessibilityManager);
if IncludeMonth then
AddSubControl(Component, MonthCombo, AccessibilityManager);
if IncludeDay then
AddSubControl(Component, DayCombo, AccessibilityManager);
end;
end;
{ TORDayCombo508Manager }
constructor TORDayCombo508Manager.Create;
begin
inherited Create(TORDayCombo, [mtCaption, mtValue]);
end;
function TORDayCombo508Manager.GetCaption(Component: TWinControl): string;
begin
Result := 'Day';
end;
{ TORMonthCombo508Manager }
constructor TORMonthCombo508Manager.Create;
begin
inherited Create(TORMonthCombo, [mtCaption, mtValue]);
end;
function TORMonthCombo508Manager.GetCaption(Component: TWinControl): string;
begin
Result := 'Month';
end;
{ TORYearEdit508Manager }
constructor TORYearEdit508Manager.Create;
begin
inherited Create(TORYearEdit, [mtCaption]);
end;
function TORYearEdit508Manager.GetCaption(Component: TWinControl): string;
begin
Result := 'Year';
end;
{ TORDateButton508Manager }
constructor TORDateButton508Manager.Create;
begin
inherited Create(TORDateButton, [mtCaption]);
end;
function TORDateButton508Manager.GetCaption(Component: TWinControl): string;
begin
Result := 'Date';
end;
(*
{ TVA508TORDateBoxComplexManager }
constructor TVA508TORDateBoxComplexManager.Create;
begin
inherited Create(TORDateBox);
end;
type
TORDateBoxFriend = class(TORDateBox);
procedure TVA508TORDateBoxComplexManager.Refresh(Component: TWinControl;
AccessibilityManager: TVA508AccessibilityManager);
begin
with TORDateBoxFriend(Component) do
begin
ClearSubControls;
if assigned(DateButton) then
begin
DateButton.TabStop := TRUE;
AddSubControl(DateButton, AccessibilityManager);
end;
end;
end;
*)
{ TVA508ORComboManager }
constructor TORComboBox508Manager.Create;
begin
inherited Create(TORComboBox, [mtValue], TRUE);
end;
function TORComboBox508Manager.GetValue(Component: TWinControl): string;
begin
Result := TORComboBox(Component).Text;
end;
{ TORComboEdit508Manager }
//constructor TORComboEdit508Manager.Create;
//begin
// inherited Create(TORComboEdit, [mtComponentRedirect]);
//end;
//
//function TORComboEdit508Manager.Redirect(Component: TWinControl;
// var ManagedType: TManagedType): TWinControl;
//begin
// ManagedType := mtCaption;
// Result := TWinControl(Component.Owner);
//end;
{ TVA508TORComboBoxComplexManager }
//constructor TVA508TORComboBoxComplexManager.Create;
//begin
// inherited Create(TORComboBox);
//end;
//
//procedure TVA508TORComboBoxComplexManager.Refresh(Component: TWinControl;
// AccessibilityManager: TVA508AccessibilityManager);
//var
// eBox: TORComboEdit;
//begin
// begin
// ClearSubControls;
// eBox := GetEditBox(TORComboBox(Component));
// if assigned(eBox) then
// AddSubControl(eBox, AccessibilityManager);
// end;
//end;
initialization
RegisterORComponents;
end.
|
{ Copyright (C) 2004 Vincent Snijders
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Abstract:
This unit adds a new project type and a new unit type to the IDE.
New Project Type:
FPTest Application - A Free Pascal program for FPTest tests.
New Unit Type:
FPTest test - A unit with a unit test.
Adapted from FPCUnit package.
}
unit FPTestLazIDEIntf;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazIDEIntf, ProjectIntf, Controls, Forms, FPTestTestCaseOpts;
type
{ TFPTestApplicationDescriptor }
TFPTestApplicationDescriptor = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles({%H-}AProject: TLazProject): TModalResult; override;
end;
{ TFPTestConsoleApplicationDescriptor }
TFPTestConsoleApplicationDescriptor = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles({%H-}AProject: TLazProject): TModalResult; override;
end;
{ TFileDescPascalUnitFPTestTestCase }
TFileDescPascalUnitFPTestTestCase = class(TFileDescPascalUnit)
private
FTestCaseName: string;
FCreateSetup: boolean;
FCreateTearDown: boolean;
public
constructor Create; override;
function CreateSource(const Filename, SourceName,
ResourceName: string): string; override;
function GetInterfaceUsesSection: string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function GetInterfaceSource(const {%H-}Filename, {%H-}SourceName,
{%H-}ResourceName: string): string;override;
function GetImplementationSource(const {%H-}Filename, {%H-}SourceName,
{%H-}ResourceName: string): string; override;
property TestCaseName: string read FTestCaseName write FTestCaseName;
property CreateSetup: boolean read FCreateSetup write FCreateSetup;
property CreateTeardown: boolean read FCreateTeardown write FCreateTeardown;
end;
var
ProjectDescriptorFPTestApplication: TFPTestApplicationDescriptor;
ProjectDescriptorFPTestConsoleApp: TFPTestConsoleApplicationDescriptor;
FileDescriptorFPTestTestCase: TFileDescPascalUnitFPTestTestCase;
procedure Register;
implementation
uses
strutils;
resourcestring
sFPTestTestApp = 'FPTest Test Application';
sFPTestTestAppDesc = 'FPTest Test Application%sAn application to run '
+'FPTest test cases.%sThe application source is automatically maintained by '
+'Lazarus.';
sFPTestTestCase = 'FPTest Test Case';
sFPTestTestCaseDesc = 'FPTest Test Case%sA unit containing a FPTest Test '
+'Case.';
sWriteYourOwnTest = 'Write your own test';
sFPTestConsoleTestApp = 'FPTest Console Test Application';
sFPTestConsoleTestDesc = 'FPTest Console Test Application%sAn application '
+'to run FPTest test cases in console mode.%sThe application source is '
+'automatically maintained by Lazarus.';
procedure Register;
begin
FileDescriptorFPTestTestCase:=TFileDescPascalUnitFPTestTestCase.Create;
RegisterProjectFileDescriptor(FileDescriptorFPTestTestCase);
ProjectDescriptorFPTestConsoleApp := TFPTestConsoleApplicationDescriptor.Create;
RegisterProjectDescriptor(ProjectDescriptorFPTestConsoleApp);
ProjectDescriptorFPTestApplication:=TFPTestApplicationDescriptor.Create;
RegisterProjectDescriptor(ProjectDescriptorFPTestApplication);
end;
{ TFPTestApplicationDescriptor }
constructor TFPTestApplicationDescriptor.Create;
begin
inherited Create;
Name:='FPTest Application';
end;
function TFPTestApplicationDescriptor.GetLocalizedName: string;
begin
Result:=sFPTestTestApp;
end;
function TFPTestApplicationDescriptor.GetLocalizedDescription: string;
var
le: string;
begin
le := System.LineEnding;
Result:=Format(sFPTestTestAppDesc,[le+le,le]);
end;
function TFPTestApplicationDescriptor.InitProject(AProject: TLazProject): TModalResult;
var
le: string;
NewSource: String;
MainFile: TLazProjectFile;
begin
inherited InitProject(AProject);
MainFile:=AProject.CreateProjectFile('fptestproject1.lpr');
MainFile.IsPartOfProject:=true;
AProject.AddFile(MainFile,false);
AProject.MainFileID:=0;
AProject.UseAppBundle:=true;
AProject.UseManifest:=true;
AProject.LoadDefaultIcon;
// create program source
le:=LineEnding;
NewSource:='program FPTestProject1;'+le
+le
+'{$mode objfpc}{$H+}'+le
+le
+'uses'+le
+' Interfaces, Forms, GUITestRunner;'+le
+le
+'begin'+le
+' Application.Initialize;'+le
+' RunRegisteredTests;'+le
+'end.'+le
+le;
AProject.MainFile.SetSourceText(NewSource);
// add
AProject.AddPackageDependency('FCL');
AProject.AddPackageDependency('LCL');
AProject.AddPackageDependency('fptest_lcl');
// compiler options
AProject.LazCompilerOptions.UseLineInfoUnit:=true;
AProject.LazCompilerOptions.Win32GraphicApp:=true;
AProject.LazCompilerOptions.TargetFilename:='fptestproject1';
AProject.LazCompilerOptions.UnitOutputDirectory:='lib'+PathDelim+'$(TargetCPU)-$(TargetOS)';
Result:=mrOK;
end;
function TFPTestApplicationDescriptor.CreateStartFiles(AProject: TLazProject): TModalResult;
begin
LazarusIDE.DoNewEditorFile(FileDescriptorFPTestTestCase,'','',
[nfIsPartOfProject,nfOpenInEditor,nfCreateDefaultSrc]);
Result:=mrOK;
end;
{ TFileDescPascalUnitFPTestTestCase }
constructor TFileDescPascalUnitFPTestTestCase.Create;
begin
inherited Create;
Name:='FPTest TestCase';
DefaultFilename:='testcase.pas';
DefaultSourceName:='TestCase1';
end;
function TFileDescPascalUnitFPTestTestCase.CreateSource(const Filename,
SourceName, ResourceName: string): string;
var
LE: string;
begin
CreateSetup := false;
CreateTeardown := false;
LE:=LineEnding;
with TFPTestTestCaseOptionsForm.Create(nil) do
try
edDefaultName.Text := 'T' + SourceName;
ShowModal;
if edDefaultName.Text <> '' then
TestCaseName := edDefaultName.Text
else
TestCaseName:= 'T' + SourceName;
if cbSetup.Checked then
CreateSetup := True
else
CreateSetup := False;
if cbTeardown.Checked then
CreateTeardown := True
else
CreateTeardown := False;
finally
Free;
end;
Result:=
'unit '+SourceName+';'+LE
+LE
+'{$mode objfpc}{$H+}'+LE
+LE
+'interface'+LE
+LE
+'uses'+LE
+' '+GetInterfaceUsesSection+';'+LE
+LE
+GetInterfaceSource(Filename,SourceName,ResourceName)
+'implementation'+LE
+LE
+GetImplementationSource(Filename,SourceName,ResourceName)
+'end.'+LE
+LE;
end;
function TFileDescPascalUnitFPTestTestCase.GetInterfaceUsesSection: string;
begin
Result:=inherited GetInterfaceUsesSection;
Result:=Result+', TestFramework';
end;
function TFileDescPascalUnitFPTestTestCase.GetLocalizedName: string;
begin
Result:=sFPTestTestCase;
end;
function TFileDescPascalUnitFPTestTestCase.GetLocalizedDescription: string;
begin
Result:=Format(sFPTestTestCaseDesc,[#13]);
end;
function TFileDescPascalUnitFPTestTestCase.GetInterfaceSource(const Filename,
SourceName, ResourceName: string): string;
var
le: string;
setupMethod: string;
teardownMethod: string;
protectedSection: string;
begin
le:=System.LineEnding;
if CreateSetup or CreateTeardown then
protectedSection := ' protected' + le;
if CreateSetup then
setupMethod := ' procedure SetUp; override;' + le;
if CreateTeardown then
teardownMethod := ' procedure TearDown; override;' + le;
Result := 'type' + le
+ le
+' '+TestCaseName+'= class(TTestCase)'+le
+ protectedSection
+ setupMethod
+ teardownMethod
+' published'+le
+' procedure TestHookUp;'+le
+' end;'+le+le;
end;
function TFileDescPascalUnitFPTestTestCase.GetImplementationSource(
const Filename, SourceName, ResourceName: string): string;
var
le: string;
setupMethod: string;
teardownMethod: string;
begin
le:=System.LineEnding;
if CreateSetup then
setupMethod := 'procedure '+TestCaseName+'.SetUp;'+le
+'begin'+le
+le
+'end;'+le;
if CreateTeardown then
teardownMethod := 'procedure '+TestCaseName+'.TearDown;'+le
+'begin'+le
+le
+'end;'+le;
Result:='procedure '+TestCaseName+'.TestHookUp;'+le
+'begin'+le
+' Fail('+QuotedStr(sWriteYourOwnTest)+');'+le
+'end;'+le
+le
+ IfThen(CreateSetup, setupMethod + le)
+ IfThen(CreateTeardown, teardownMethod + le)
+'initialization'+le
+' RegisterTest('+TestCaseName+'.Suite);'
+le;
end;
{ TFPTestConsoleApplicationDescriptor }
constructor TFPTestConsoleApplicationDescriptor.Create;
begin
inherited Create;
Name:='FPTest Console Application';
end;
function TFPTestConsoleApplicationDescriptor.GetLocalizedName: string;
begin
Result:=sFPTestConsoleTestApp;
end;
function TFPTestConsoleApplicationDescriptor.GetLocalizedDescription: string;
var
le: string;
begin
le := System.LineEnding;
Result:=Format(sFPTestConsoleTestDesc,[le+le,le]);
end;
function TFPTestConsoleApplicationDescriptor.InitProject(
AProject: TLazProject): TModalResult;
var
NewSource: string;
MainFile: TLazProjectFile;
begin
inherited InitProject(AProject);
MainFile:=AProject.CreateProjectFile('fptestproject1.lpr');
MainFile.IsPartOfProject:=true;
AProject.AddFile(MainFile,false);
AProject.MainFileID:=0;
// create program source
NewSource := 'program FPTestProject1;' + LineEnding
+ LineEnding
+ '{$mode objfpc}{$H+}' + LineEnding
+ LineEnding
+ 'uses' + LineEnding
+ ' Classes, TextTestRunner;' + LineEnding
+ LineEnding
+ 'begin' + LineEnding
+ ' if not RunRegisteredTests.WasSuccessful then' + LineEnding
+ ' ExitCode:= 1;' + LineEnding
+ 'end.' + LineEnding
;
AProject.MainFile.SetSourceText(NewSource);
// add FCL dependency
AProject.AddPackageDependency('FCL');
AProject.AddPackageDependency('fptest');
// compiler options
AProject.LazCompilerOptions.UseLineInfoUnit:=true;
AProject.LazCompilerOptions.Win32GraphicApp:=False;
AProject.LazCompilerOptions.TargetFilename:='fptestproject1';
AProject.LazCompilerOptions.UnitOutputDirectory:='lib'+PathDelim+'$(TargetCPU)-$(TargetOS)';
Result:=mrOK;
end;
function TFPTestConsoleApplicationDescriptor.CreateStartFiles(
AProject: TLazProject): TModalResult;
begin
LazarusIDE.DoNewEditorFile(FileDescriptorFPTestTestCase,'','',
[nfIsPartOfProject,nfOpenInEditor,nfCreateDefaultSrc]);
Result:=mrOK;
end;
end.
|
unit ExtraChargeQuery2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, NotifyEvents, ExtraChargeSimpleQuery,
System.Generics.Collections, DSWrap, BaseEventsQuery;
type
TExtraChargeW = class(TDSWrap)
private
FIDExtraChargeType: TFieldWrap;
FID: TFieldWrap;
FRange: TFieldWrap;
FWholeSale: TFieldWrap;
protected
public
constructor Create(AOwner: TComponent); override;
procedure FilterByType(AIDExtraRangeType: Integer);
function GetWholeSaleList: TArray<String>;
function LocateByRange(AIDExtraRangeType: Integer; ARange: string): Boolean;
function LookupByRange(AIDExtraRangeType: Integer;
const ARange: string): Variant;
property IDExtraChargeType: TFieldWrap read FIDExtraChargeType;
property ID: TFieldWrap read FID;
property Range: TFieldWrap read FRange;
property WholeSale: TFieldWrap read FWholeSale;
end;
TQueryExtraCharge2 = class(TQueryBaseEvents)
private
FqExtraChargeSimple: TQueryExtraChargeSimple;
FW: TExtraChargeW;
function GetqExtraChargeSimple: TQueryExtraChargeSimple;
{ Private declarations }
protected
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
function CreateDSWrap: TDSWrap; override;
procedure DoBeforeOpen(Sender: TObject);
property qExtraChargeSimple: TQueryExtraChargeSimple
read GetqExtraChargeSimple;
public
constructor Create(AOwner: TComponent); override;
property W: TExtraChargeW read FW;
{ Public declarations }
end;
implementation
uses
ExceptionHelper;
{$R *.dfm}
constructor TQueryExtraCharge2.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TExtraChargeW;
AutoTransaction := False;
FDQuery.OnUpdateRecord := DoOnQueryUpdateRecord;
TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList);
end;
procedure TQueryExtraCharge2.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
// Ищем удаляемую запись
qExtraChargeSimple.SearchByID(W.PK.AsInteger, 1);
// Удаляем эту запись
qExtraChargeSimple.FDQuery.Delete;
end;
procedure TQueryExtraCharge2.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
AHight: Integer;
ALow: Integer;
begin
MyExceptionMessage := qExtraChargeSimple.CheckBounds(W.PK.AsInteger,
W.IDExtraChargeType.F.Value, W.Range.F.AsString, ALow, AHight);
if not MyExceptionMessage.IsEmpty then
begin
// Потом будет создана исключительная ситуация
AAction := eaFail;
raise Exception.Create(MyExceptionMessage);
// Exit;
end;
if not qExtraChargeSimple.FDQuery.Active then
qExtraChargeSimple.SearchByID(0);
// Добавляем запись
qExtraChargeSimple.W.TryAppend;
qExtraChargeSimple.W.L.F.AsInteger := ALow;
qExtraChargeSimple.W.H.F.AsInteger := AHight;
qExtraChargeSimple.W.WholeSale.F.Value := W.WholeSale.F.Value;
qExtraChargeSimple.W.IDExtraChargeType.F.Value := W.IDExtraChargeType.F.Value;
qExtraChargeSimple.W.TryPost;
Assert(qExtraChargeSimple.W.ID.F.AsInteger > 0);
FetchFields([W.PKFieldName], [qExtraChargeSimple.W.ID.F.Value], ARequest, AAction,
AOptions);
end;
procedure TQueryExtraCharge2.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
AHight: Integer;
ALow: Integer;
begin
Assert(ASender = FDQuery);
MyExceptionMessage := qExtraChargeSimple.CheckBounds(W.PK.AsInteger,
W.IDExtraChargeType.F.AsInteger, W.Range.F.AsString, ALow, AHight);
if not MyExceptionMessage.IsEmpty then
begin
AAction := eaFail;
// Потом будет создана исключительная ситуация
raise Exception.Create(MyExceptionMessage);
// Exit;
end;
// Ищем обновляемую запись
qExtraChargeSimple.SearchByID(W.PK.AsInteger, 1);
qExtraChargeSimple.W.TryEdit;
qExtraChargeSimple.W.L.F.Value := ALow;
qExtraChargeSimple.W.H.F.Value := AHight;
qExtraChargeSimple.W.WholeSale.F.Value := W.WholeSale.F.Value;
qExtraChargeSimple.W.IDExtraChargeType.F.Value := W.IDExtraChargeType.F.Value;
qExtraChargeSimple.W.TryPost;
end;
function TQueryExtraCharge2.CreateDSWrap: TDSWrap;
begin
Result := TExtraChargeW.Create(FDQuery);
end;
procedure TQueryExtraCharge2.DoBeforeOpen(Sender: TObject);
begin
if FDQuery.FieldDefs.Count > 0 then
begin
FDQuery.FieldDefs.Clear;
FDQuery.Fields.Clear;
end;
FDQuery.FieldDefs.Update;
FDQuery.FieldDefs.Find(W.Range.FieldName).Size := 30;
W.CreateDefaultFields(False);
end;
function TQueryExtraCharge2.GetqExtraChargeSimple: TQueryExtraChargeSimple;
begin
if FqExtraChargeSimple = nil then
FqExtraChargeSimple := TQueryExtraChargeSimple.Create(Self);
Result := FqExtraChargeSimple;
end;
constructor TExtraChargeW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FIDExtraChargeType := TFieldWrap.Create(Self, 'IDExtraChargeType');
FRange := TFieldWrap.Create(Self, 'Range', 'Количество (шт.)');
FWholeSale := TFieldWrap.Create(Self, 'WholeSale', 'Оптовая наценка (%)');
end;
procedure TExtraChargeW.FilterByType(AIDExtraRangeType: Integer);
begin
DataSet.Filter := Format('%s = %d', [IDExtraChargeType.FieldName,
AIDExtraRangeType]);
DataSet.Filtered := True;
end;
function TExtraChargeW.GetWholeSaleList: TArray<String>;
var
L: TList<String>;
begin
L := TList<String>.Create();
try
DataSet.DisableControls;
try
DataSet.First;
while not DataSet.Eof do
begin
L.Add(WholeSale.F.AsString);
DataSet.Next;
end;
finally
DataSet.EnableControls;
end;
DataSet.First;
Result := L.ToArray;
finally
FreeAndNil(L);
end;
end;
function TExtraChargeW.LocateByRange(AIDExtraRangeType: Integer;
ARange: string): Boolean;
var
AFieldNames: string;
begin
AFieldNames := Format('%s;%s', [IDExtraChargeType.FieldName,
Range.FieldName]);
Result := FDDataSet.LocateEx(AFieldNames,
VarArrayOf([AIDExtraRangeType, ARange]), []);
end;
function TExtraChargeW.LookupByRange(AIDExtraRangeType: Integer;
const ARange: string): Variant;
var
AFieldNames: string;
begin
AFieldNames := Format('%s;%s', [IDExtraChargeType.FieldName,
Range.FieldName]);
Result := FDDataSet.LookupEx(AFieldNames,
VarArrayOf([AIDExtraRangeType, ARange]), [lxoCaseInsensitive]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ ISAPI/NSAPI Web server application components }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$DENYPACKAGEUNIT}
unit Web.Win.ISAPIApp;
interface
uses Winapi.Windows, System.SyncObjs, System.Classes, Web.HTTPApp, Web.WebBroker, Web.Win.IsapiHTTP, Winapi.Isapi2;
type
TISAPIFactory = class;
TISAPITerminateProc = procedure;
TISAPIApplication = class(TWebApplication)
private
FFactory: TISAPIFactory;
FTerminateProc: TISAPITerminateProc;
function NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest;
function NewResponse(ISAPIRequest: TISAPIRequest): TISAPIResponse;
procedure ISAPIHandleException(Sender: TObject);
public
// These are the entry points relayed from the ISAPI DLL imports
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
function TerminateExtension(dwFlags: DWORD): BOOL;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnTerminate: TISAPITerminateProc read FTerminateProc write FTerminateProc;
end;
TISAPIFactory = class(TObject)
protected
function NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest; virtual;
function NewResponse(ISAPIRequest: TISAPIRequest): TISAPIResponse; virtual;
public
constructor Create;
end;
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL; stdcall;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD; stdcall;
function TerminateExtension(dwFlags: DWORD): BOOL; stdcall;
var
DispatchThread: function (AECB: PEXTENSION_CONTROL_BLOCK): Boolean of object;
implementation
uses System.SysUtils, Web.BrkrConst;
{ TISAPIApplication }
procedure HandleServerException(E: TObject; var ECB: TEXTENSION_CONTROL_BLOCK);
var
ResultText, ResultHeaders: string;
Size: DWORD;
EMsg: string;
begin
ECB.dwHTTPStatusCode := 500;
if E is Exception then
EMsg := Exception(E).Message
else
EMsg := '';
ResultText := Format(sInternalServerError, [E.ClassName, EMsg]);
ResultHeaders := Format(
'Content-Type: text/html'#13#10 + { do not localize }
'Content-Length: %d'#13#10#13#10, { do not localize }
[Length(ResultText)]);
ECB.ServerSupportFunction(ECB.ConnID, HSE_REQ_SEND_RESPONSE_HEADER,
PChar('500 ' + EMsg), @Size, LPDWORD(ResultHeaders));
Size := Length(ResultText);
ECB.WriteClient(ECB.ConnID, Pointer(ResultText), Size, 0);
end;
function TISAPIApplication.GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
begin
try
Ver.dwExtensionVersion := MakeLong(HSE_VERSION_MINOR, HSE_VERSION_MAJOR);
StrLCopy(Ver.lpszExtensionDesc, PAnsiChar(AnsiString(Title)), HSE_MAX_EXT_DLL_NAME_LEN);
Integer(Result) := 1; // This is so that the Apache web server will know what "True" really is
except
Result := False;
end;
end;
function TISAPIApplication.HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
var
HTTPRequest: TISAPIRequest;
HTTPResponse: TISAPIResponse;
begin
try
HTTPRequest := NewRequest(ECB);
try
HTTPResponse := NewResponse(HTTPRequest);
try
if HandleRequest(HTTPRequest, HTTPResponse) then
Result := HSE_STATUS_SUCCESS
else Result := HSE_STATUS_ERROR;
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
except
HandleServerException(ExceptObject, ECB);
Result := HSE_STATUS_ERROR;
end;
end;
function TISAPIApplication.NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest;
begin
Result := FFactory.NewRequest(AECB);
end;
function TISAPIApplication.NewResponse(ISAPIRequest: TISAPIRequest): TISAPIResponse;
begin
Result := FFactory.NewResponse(ISAPIRequest);
end;
function TISAPIApplication.TerminateExtension(dwFlags: DWORD): BOOL;
begin
if Assigned(FTerminateProc) then
FTerminateProc;
Integer(Result) := 1; // This is so that the Apache web server will know what "True" really is
end;
// ISAPI interface
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
begin
Result := (Application as TISAPIApplication).GetExtensionVersion(Ver);
end;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
begin
if Assigned(DispatchThread) then
begin
if DispatchThread(@ECB) then
Result := HSE_STATUS_PENDING
else
Result := HSE_STATUS_ERROR;
end
else
Result := (Application as TISAPIApplication).HttpExtensionProc(ECB);
end;
function TerminateExtension(dwFlags: DWORD): BOOL;
begin
Result := (Application as TISAPIApplication).TerminateExtension(dwFlags);
end;
procedure InitApplication;
begin
Application := TISAPIApplication.Create(nil);
end;
procedure TISAPIApplication.ISAPIHandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
E: TObject;
begin
Handled := False;
if (ExceptObject is Exception) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
begin
E := ExceptObject;
AcquireExceptionObject;
raise E;
end;
end;
function GetISAPIFileName: string;
begin
Result := GetModuleName(hInstance);
// UNC issue in Vista.
if Pos('\\?\', Result) = 1 then
Delete(Result, 1, 4);
end;
constructor TISAPIApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// Must set application name to the ISAPI dll, otherwise exe name will be used (w3wp.exe)
Web.HTTPApp.FWebApplicationFileName := GetISAPIFileName;
FFactory := TISAPIFactory.Create;
System.Classes.ApplicationHandleException := ISAPIHandleException;
end;
destructor TISAPIApplication.Destroy;
begin
if Assigned(FFactory) then
FreeAndNil(FFactory);
inherited Destroy;
end;
{ TISAPIFactory }
constructor TISAPIFactory.Create;
begin
inherited;
end;
function TISAPIFactory.NewRequest(var AECB: TEXTENSION_CONTROL_BLOCK): TISAPIRequest;
begin
Result := TISAPIRequest.Create(@AECB);
end;
function TISAPIFactory.NewResponse(ISAPIRequest: TISAPIRequest): TISAPIResponse;
begin
Result := TISAPIResponse.Create(ISAPIRequest);
end;
initialization
InitApplication;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* (c) Copyright 1993, Silicon Graphics, Inc.
* 1993-1995 Microsoft Corporation
* ALL RIGHTS RESERVED
*/}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
Dialogs, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
Closed : Boolean = False;
implementation
uses DGLUT;
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
ambient : Array [0..3] of GLfloat = (0.0, 0.0, 0.0, 1.0);
diffuse : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
position : Array [0..3] of GLfloat = (0.0, 3.0, 3.0, 0.0);
begin
glLightfv(GL_LIGHT0, GL_AMBIENT, @ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, @position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
end;
procedure renderTeapot (x, y, ambr, ambg, ambb,
difr, difg, difb, specr, specg, specb, shine : GLfloat);
var
mat : Array [0..2] of GLfloat;
begin
glPushMatrix;
glTranslatef (x, y, 0.0);
mat[0] := ambr; mat[1] := ambg; mat[2] := ambb;
glMaterialfv (GL_FRONT, GL_AMBIENT, @mat);
mat[0] := difr; mat[1] := difg; mat[2] := difb;
glMaterialfv (GL_FRONT, GL_DIFFUSE, @mat);
mat[0] := specr; mat[1] := specg; mat[2] := specb;
glMaterialfv (GL_FRONT, GL_SPECULAR, @mat);
glMaterialf (GL_FRONT, GL_SHININESS, shine*128.0);
glutSolidTeapot (1.0);
glPopMatrix;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT );
glPushMatrix;
renderTeapot (2.0, 17.0, 0.0215, 0.1745, 0.0215,
0.07568, 0.61424, 0.07568, 0.633, 0.727811, 0.633, 0.6);
renderTeapot (2.0, 14.0, 0.135, 0.2225, 0.1575,
0.54, 0.89, 0.63, 0.316228, 0.316228, 0.316228, 0.1);
renderTeapot (2.0, 11.0, 0.05375, 0.05, 0.06625,
0.18275, 0.17, 0.22525, 0.332741, 0.328634, 0.346435, 0.3);
renderTeapot (2.0, 8.0, 0.25, 0.20725, 0.20725,
1, 0.829, 0.829, 0.296648, 0.296648, 0.296648, 0.088);
renderTeapot (2.0, 5.0, 0.1745, 0.01175, 0.01175,
0.61424, 0.04136, 0.04136, 0.727811, 0.626959, 0.626959, 0.6);
renderTeapot (2.0, 2.0, 0.1, 0.18725, 0.1745,
0.396, 0.74151, 0.69102, 0.297254, 0.30829, 0.306678, 0.1);
renderTeapot (6.0, 17.0, 0.329412, 0.223529, 0.027451,
0.780392, 0.568627, 0.113725, 0.992157, 0.941176, 0.807843,
0.21794872);
renderTeapot (6.0, 14.0, 0.2125, 0.1275, 0.054,
0.714, 0.4284, 0.18144, 0.393548, 0.271906, 0.166721, 0.2);
renderTeapot (6.0, 11.0, 0.25, 0.25, 0.25,
0.4, 0.4, 0.4, 0.774597, 0.774597, 0.774597, 0.6);
renderTeapot (6.0, 8.0, 0.19125, 0.0735, 0.0225,
0.7038, 0.27048, 0.0828, 0.256777, 0.137622, 0.086014, 0.1);
renderTeapot (6.0, 5.0, 0.24725, 0.1995, 0.0745,
0.75164, 0.60648, 0.22648, 0.628281, 0.555802, 0.366065, 0.4);
renderTeapot (6.0, 2.0, 0.19225, 0.19225, 0.19225,
0.50754, 0.50754, 0.50754, 0.508273, 0.508273, 0.508273, 0.4);
renderTeapot (10.0, 17.0, 0.0, 0.0, 0.0, 0.01, 0.01, 0.01,
0.50, 0.50, 0.50, 0.25);
renderTeapot (10.0, 14.0, 0.0, 0.1, 0.06, 0.0, 0.50980392, 0.50980392,
0.50196078, 0.50196078, 0.50196078, 0.25);
renderTeapot (10.0, 11.0, 0.0, 0.0, 0.0,
0.1, 0.35, 0.1, 0.45, 0.55, 0.45, 0.25);
renderTeapot (10.0, 8.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0,
0.7, 0.6, 0.6, 0.25);
renderTeapot (10.0, 5.0, 0.0, 0.0, 0.0, 0.55, 0.55, 0.55,
0.70, 0.70, 0.70, 0.25);
renderTeapot (10.0, 2.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0,
0.60, 0.60, 0.50, 0.25);
renderTeapot (14.0, 17.0, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01,
0.4, 0.4, 0.4, 0.078125);
renderTeapot (14.0, 14.0, 0.0, 0.05, 0.05, 0.4, 0.5, 0.5,
0.04, 0.7, 0.7, 0.078125);
renderTeapot (14.0, 11.0, 0.0, 0.05, 0.0, 0.4, 0.5, 0.4,
0.04, 0.7, 0.04, 0.078125);
renderTeapot (14.0, 8.0, 0.05, 0.0, 0.0, 0.5, 0.4, 0.4,
0.7, 0.04, 0.04, 0.078125);
renderTeapot (14.0, 5.0, 0.05, 0.05, 0.05, 0.5, 0.5, 0.5,
0.7, 0.7, 0.7, 0.078125);
renderTeapot (14.0, 2.0, 0.05, 0.05, 0.0, 0.5, 0.5, 0.4,
0.7, 0.7, 0.04, 0.078125);
glPopMatrix;
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight );
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
If ClientWidth <= ClientHeight
then glOrtho (0.0, 16.0, 0.0, 16.0*ClientHeight / ClientWidth, -10.0, 10.0)
else glOrtho (0.0, 16.0*ClientWidth / ClientHeight, 0.0, 16.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
end.
|
{*****************************************************************}
{ SimpleTimer is a timer class. It has the same timer resolution }
{ as TTimer, but it is more lightweight because it's derived from }
{ TObject in stead of TComponent. Furthermore, the same handle is }
{ shared between multiple instances of SimpleTimer. }
{ This makes it ideal for developers who need a timer in their }
{ own components or applications, but want to keep the resource }
{ usage minimal. }
{ }
{ The unit is freeware. Feel free to use and improve it. }
{ I would be pleased to hear what you think. }
{ }
{ Troels Jakobsen - delphiuser@get2net.dk }
{ Copyright (c) 2002 }
{*****************************************************************}
unit SimpleTimer;
{ Some methods have moved to the Classes unit in D6 and are thus deprecated.
Using the following compiler directives we handle that situation. }
{$IFDEF VER140} {$DEFINE DELPHI_6} {$ENDIF}
{$IFDEF VER150} {$DEFINE DELPHI_7} {$ENDIF}
{$IFDEF DELPHI_6} {$DEFINE DELPHI_6_UP} {$ENDIF}
{$IFDEF DELPHI_7} {$DEFINE DELPHI_6_UP} {$ENDIF}
interface
uses
Windows, Classes;
type
TSimpleTimer = class(TObject)
private
FId: UINT;
FEnabled: Boolean;
FInterval: Cardinal;
FAutoDisable: Boolean;
FOnTimer: TNotifyEvent;
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: Cardinal);
procedure SetOnTimer(Value: TNotifyEvent);
procedure Initialize(AInterval: Cardinal; AOnTimer: TNotifyEvent);
protected
function Start: Boolean;
function Stop(Disable: Boolean): Boolean;
public
constructor Create;
constructor CreateEx(AInterval: Cardinal; AOnTimer: TNotifyEvent);
destructor Destroy; override;
property Enabled: Boolean read FEnabled write SetEnabled;
property Interval: Cardinal read FInterval write SetInterval default 1000;
property AutoDisable: Boolean read FAutoDisable write FAutoDisable;
property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer;
end;
function GetSimpleTimerCount: Cardinal;
function GetSimpleTimerActiveCount: Cardinal;
implementation
uses
Messages{$IFNDEF DELPHI_6_UP}, Forms {$ENDIF};
type
TSimpleTimerHandler = class(TObject)
private
RefCount: Cardinal;
ActiveCount: Cardinal;
FWindowHandle: HWND;
procedure WndProc(var Msg: TMessage);
public
constructor Create;
destructor Destroy; override;
procedure AddTimer;
procedure RemoveTimer;
end;
var
SimpleTimerHandler: TSimpleTimerHandler = nil;
function GetSimpleTimerCount: Cardinal;
begin
if Assigned(SimpleTimerHandler) then
Result := SimpleTimerHandler.RefCount
else
Result := 0;
end;
function GetSimpleTimerActiveCount: Cardinal;
begin
if Assigned(SimpleTimerHandler) then
Result := SimpleTimerHandler.ActiveCount
else
Result := 0;
end;
{--------------- TSimpleTimerHandler ------------------}
constructor TSimpleTimerHandler.Create;
begin
inherited Create;
{$IFDEF DELPHI_6_UP}
FWindowHandle := Classes.AllocateHWnd(WndProc);
{$ELSE}
FWindowHandle := AllocateHWnd(WndProc);
{$ENDIF}
end;
destructor TSimpleTimerHandler.Destroy;
begin
{$IFDEF DELPHI_6_UP}
Classes.DeallocateHWnd(FWindowHandle);
{$ELSE}
DeallocateHWnd(FWindowHandle);
{$ENDIF}
inherited Destroy;
end;
procedure TSimpleTimerHandler.AddTimer;
begin
Inc(RefCount);
end;
procedure TSimpleTimerHandler.RemoveTimer;
begin
if RefCount > 0 then
Dec(RefCount);
end;
procedure TSimpleTimerHandler.WndProc(var Msg: TMessage);
var
Timer: TSimpleTimer;
begin
if Msg.Msg = WM_TIMER then
begin
{$WARNINGS OFF}
Timer := TSimpleTimer(Msg.wParam);
{$WARNINGS ON}
if Timer.FAutoDisable then
Timer.Stop(True);
// Call OnTimer event method if assigned
if Assigned(Timer.FOnTimer) then
Timer.FOnTimer(Timer);
end
else
Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
{---------------- Container management ----------------}
procedure AddTimer;
begin
if not Assigned(SimpleTimerHandler) then
// Create new handler
SimpleTimerHandler := TSimpleTimerHandler.Create;
SimpleTimerHandler.AddTimer;
end;
procedure RemoveTimer;
begin
if Assigned(SimpleTimerHandler) then
begin
SimpleTimerHandler.RemoveTimer;
if SimpleTimerHandler.RefCount = 0 then
begin
// Destroy handler
SimpleTimerHandler.Free;
SimpleTimerHandler := nil;
end;
end;
end;
{------------------ Callback method -------------------}
{
procedure TimerProc(hWnd: HWND; uMsg: UINT; idEvent: UINT; dwTime: DWORD); stdcall;
var
Timer: TSimpleTimer;
begin
// if uMsg = WM_TIMER then // It's always WM_TIMER
begin
try
Timer := TSimpleTimer(idEvent);
if Assigned(Timer.FCallBackProc) then
Timer.FCallBackProc(Timer.FOwner);
except
// ???
end;
end;
end;
}
{------------------- TSimpleTimer ---------------------}
constructor TSimpleTimer.Create;
begin
inherited Create;
Initialize(1000, nil);
end;
constructor TSimpleTimer.CreateEx(AInterval: Cardinal; AOnTimer: TNotifyEvent);
begin
inherited Create;
Initialize(AInterval, AOnTimer);
end;
destructor TSimpleTimer.Destroy;
begin
if FEnabled then
Stop(True);
RemoveTimer; // Container management
inherited Destroy;
end;
procedure TSimpleTimer.Initialize(AInterval: Cardinal; AOnTimer: TNotifyEvent);
begin
{$WARNINGS OFF}
FId := UINT(Self); // Use Self as id in call to SetTimer and callback method
{$WARNINGS ON}
FAutoDisable := False;
FEnabled := False;
FInterval := AInterval;
SetOnTimer(AOnTimer);
AddTimer; // Container management
end;
procedure TSimpleTimer.SetEnabled(Value: Boolean);
begin
if Value then
Start
else
Stop(True);
end;
procedure TSimpleTimer.SetInterval(Value: Cardinal);
begin
if Value <> FInterval then
begin
FInterval := Value;
if FEnabled then
if FInterval <> 0 then
Start
else
Stop(False);
end;
end;
procedure TSimpleTimer.SetOnTimer(Value: TNotifyEvent);
begin
FOnTimer := Value;
if (not Assigned(Value)) and (FEnabled) then
Stop(False);
end;
function TSimpleTimer.Start: Boolean;
begin
if FInterval = 0 then
begin
Result := False;
Exit;
end;
if FEnabled then
Stop(True);
// Result := (SetTimer(SimpleTimerHandler.FWindowHandle, FId, FInterval, @TimerProc) <> 0);
Result := (SetTimer(SimpleTimerHandler.FWindowHandle, FId, FInterval, nil) <> 0);
if Result then
begin
FEnabled := True;
Inc(SimpleTimerHandler.ActiveCount);
end
{ else
raise EOutOfResources.Create(SNoTimers); }
end;
function TSimpleTimer.Stop(Disable: Boolean): Boolean;
begin
if Disable then
FEnabled := False;
Result := KillTimer(SimpleTimerHandler.FWindowHandle, FId);
if Result and (SimpleTimerHandler.ActiveCount > 0) then
Dec(SimpleTimerHandler.ActiveCount);
end;
initialization
finalization
if Assigned(SimpleTimerHandler) then
begin
SimpleTimerHandler.Free;
SimpleTimerHandler := nil;
end;
end.
|
{ Turbo Reference }
{ Copyright (c) 1985, 1989 by Borland International, Inc. }
program Circular;
{ Simple program that demonstrates circular unit references via
a USES clause in the implementation section.
Note that it is NOT possible for the two units to "USE" each
other in their interface sections. It is possible for AA's
interface to use BB, and BB's implementation to use AA, but
this is tricky and depends on compilation order. We don't
document or recommend it.
}
uses
Crt, Display, Error;
begin
ClrScr;
WriteXY(1, 1, 'Upper left');
WriteXY(100, 100, 'Off the screen');
WriteXY(81 - Length('Back to reality'), 15, 'Back to reality');
end.
|
{*!
* Fano Web Framework (https://fano.juhara.id)
*
* @link https://github.com/zamronypj/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/zamronypj/fano/blob/master/LICENSE (GPL 3.0)
*}
unit MySqlDbImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
DependencyIntf,
RdbmsIntf,
RdbmsResultSetIntf,
RdbmsFieldsIntf,
RdbmsFieldIntf,
db,
sqldb,
mysql56conn,
mysql57conn;
type
(*!------------------------------------------------
* basic class having capability to
* handle mysql relational database operation
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-------------------------------------------------*)
TMySQLDb = class(TInterfacedObject, IRdbms, IRdbmsResultSet, IRdbmsFields, IRdbmsField, IDependency)
private
dbInstance : TSQLConnector;
query : TSQLQuery;
currentField : TField;
version : string;
public
constructor create(const mysqlVersion : string);
destructor destroy(); override;
(*!------------------------------------------------
* create connection to database server
*-------------------------------------------------
* @param host hostname/ip where MySQl server run
* @param dbname database name to use
* @param username user name credential to login
* @param password password credential to login
* @param port TCP port where MySQL listen
* @return current instance
*-------------------------------------------------*)
function connect(
const host : string;
const dbname : string;
const username : string;
const password : string;
const port : word
) : IRdbms;
(*!------------------------------------------------
* initiate a transaction
*-------------------------------------------------
* @param connectionString
* @return database connection instance
*-------------------------------------------------*)
function beginTransaction() : IRdbms;
(*!------------------------------------------------
* end a transaction
*-------------------------------------------------
* @return database connection instance
*-------------------------------------------------
* This is provided to make it easy to auto commit or
* rollback
*-------------------------------------------------*)
function endTransaction() : IRdbms;
(*!------------------------------------------------
* execute query
*-------------------------------------------------
* @return result set
*-------------------------------------------------*)
function exec(const sql : string) : IRdbmsResultSet;
(*!------------------------------------------------
* total data in result set
*-------------------------------------------------
* @return total data in current result set
*-------------------------------------------------*)
function resultCount() : largeInt;
(*!------------------------------------------------
* test if we in end of result set
*-------------------------------------------------
* @return true if at end of file and no more record
*-------------------------------------------------*)
function eof() : boolean;
(*!------------------------------------------------
* advanced cursor position to next record
*-------------------------------------------------
* @return true if at end of file and no more record
*-------------------------------------------------*)
function next() : IRdbmsResultSet;
(*!------------------------------------------------
* get list of fields
*-------------------------------------------------
* @return current fields
*-------------------------------------------------*)
function fields() : IRdbmsFields;
(*!------------------------------------------------
* number of fields
*-------------------------------------------------
* @return integer number of fields
*-------------------------------------------------*)
function fieldCount() : integer;
(*!------------------------------------------------
* get field by name
*-------------------------------------------------
* @return field
*-------------------------------------------------*)
function fieldByName(const name : shortstring) : IRdbmsField;
(*!------------------------------------------------
* get field by name
*-------------------------------------------------
* @return field
*-------------------------------------------------*)
function fieldByIndex(const indx : integer) : IRdbmsField;
(*!------------------------------------------------
* return field data as boolean
*-------------------------------------------------
* @return boolean value of field
*-------------------------------------------------*)
function asBoolean() : boolean;
(*!------------------------------------------------
* return field data as integer value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function asInteger() : integer;
(*!------------------------------------------------
* return field data as string value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function asString() : string;
(*!------------------------------------------------
* return field data as double value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function asFloat() : double;
(*!------------------------------------------------
* return field data as datetime value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function asDateTime() : TDateTime;
end;
implementation
uses
EInvalidDbConnectionImpl,
EInvalidDbFieldImpl;
resourcestring
sErrInvalidConnection = 'Invalid connection';
sErrInvalidField = 'Invalid field.';
constructor TMySQLDb.create(const mysqlVersion : string);
begin
dbInstance := nil;
query := nil;
currentField := nil;
version := mysqlVersion;
end;
destructor TMySQLDb.destroy();
begin
inherited destroy();
query.free();
dbInstance.free();
currentField := nil;
end;
(*!------------------------------------------------
* create connection to database server
*-------------------------------------------------
* @param host hostname/ip where MySQl server run
* @param dbname database name to use
* @param username user name credential to login
* @param password password credential to login
* @param port TCP port where MySQL listen
* @return current instance
*-------------------------------------------------*)
function TMySQLDb.connect(
const host : string;
const dbname : string;
const username : string;
const password : string;
const port : word
) : IRdbms;
begin
if (dbInstance = nil) then
begin
dbInstance := TSQLConnector.create(nil);
dbInstance.transaction := TSQLTransaction.create(dbInstance);
query := TSQLQuery.create(nil);
query.database := dbInstance;
end;
dbInstance.ConnectorType := version;
dbInstance.HostName := host;
dbInstance.DatabaseName := dbname;
dbInstance.UserName := username;
dbInstance.Password := password;
result := self;
end;
(*!------------------------------------------------
* initiate a transaction
*-------------------------------------------------
* @param connectionString
* @return database connection instance
*-------------------------------------------------*)
function TMySQLDb.beginTransaction() : IRdbms;
begin
if (dbInstance = nil) then
begin
raise EInvalidDbConnection.create(sErrInvalidConnection);
end;
dbInstance.startTransaction();
result := self;
end;
(*!------------------------------------------------
* commit or rollback and end a transaction
*-------------------------------------------------
* @return database connection instance
*-------------------------------------------------*)
function TMySQLDb.endTransaction() : IRdbms;
begin
if (dbInstance = nil) then
begin
raise EInvalidDbConnection.create(sErrInvalidConnection);
end;
dbInstance.endTransaction();
result := self;
end;
(*!------------------------------------------------
* execute query
*-------------------------------------------------
* @return result set
*-------------------------------------------------*)
function TMySQLDb.exec(const sql : string) : IRdbmsResultSet;
begin
query.sql.text := sql;
query.open();
result := self;
end;
(*!------------------------------------------------
* number of record in result set
*-------------------------------------------------
* @return largeInt number of records
*-------------------------------------------------*)
function TMySQLDb.resultCount() : largeInt;
begin
result := query.RecordCount;
end;
(*!------------------------------------------------
* test if we in end of result set
*-------------------------------------------------
* @return true if at end of file and no more record
*-------------------------------------------------*)
function TMySQLDb.eof() : boolean;
begin
result := query.eof;
end;
(*!------------------------------------------------
* advanced cursor position to next record
*-------------------------------------------------
* @return true if at end of file and no more record
*-------------------------------------------------*)
function TMySQLDb.next() : IRdbmsResultSet;
begin
query.next();
result := self;
end;
(*!------------------------------------------------
* advanced cursor position to next record
*-------------------------------------------------
* @return true if at end of file and no more record
*-------------------------------------------------*)
function TMySQLDb.fields() : IRdbmsFields;
begin
result := self;
end;
(*!------------------------------------------------
* number of fields
*-------------------------------------------------
* @return integer number of fields
*-------------------------------------------------*)
function TMySQLDb.fieldCount() : integer;
begin
result := query.fields.count;
end;
(*!------------------------------------------------
* get field by name
*-------------------------------------------------
* @return field
*-------------------------------------------------*)
function TMySQLDb.fieldByName(const name : shortstring) : IRdbmsField;
begin
currentField := query.fields.fieldByName(name);
result := self;
end;
(*!------------------------------------------------
* get field by name
*-------------------------------------------------
* @return field
*-------------------------------------------------*)
function TMySQLDb.fieldByIndex(const indx : integer) : IRdbmsField;
begin
currentField := query.fields.fieldByNumber(indx);
result := self;
end;
(*!------------------------------------------------
* return field data as boolean
*-------------------------------------------------
* @return boolean value of field
*-------------------------------------------------*)
function TMySQLDb.asBoolean() : boolean;
begin
if (currentField = nil) then
begin
raise EInvalidDbField.create(sErrInvalidField);
end;
result := currentField.asBoolean;
end;
(*!------------------------------------------------
* return field data as integer value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function TMySQLDb.asInteger() : integer;
begin
if (currentField = nil) then
begin
raise EInvalidDbField.create(sErrInvalidField);
end;
result := currentField.asInteger;
end;
(*!------------------------------------------------
* return field data as string value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function TMySQLDb.asString() : string;
begin
if (currentField = nil) then
begin
raise EInvalidDbField.create(sErrInvalidField);
end;
result := currentField.asString;
end;
(*!------------------------------------------------
* return field data as double value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function TMySQLDb.asFloat() : double;
begin
if (currentField = nil) then
begin
raise EInvalidDbField.create(sErrInvalidField);
end;
result := currentField.asFloat;
end;
(*!------------------------------------------------
* return field data as datetime value
*-------------------------------------------------
* @return value of field
*-------------------------------------------------*)
function TMySQLDb.asDateTime() : TDateTime;
begin
if (currentField = nil) then
begin
raise EInvalidDbField.create(sErrInvalidField);
end;
result := currentField.asDateTime;
end;
end.
|
{*********************************************}
{ TeeChart Pro OpenGL Component }
{ Copyright (c) 1998-2004 by David Berneda }
{ All Rights Reserved }
{*********************************************}
unit TeeOpenGL;
{$I TeeDefs.inc}
interface
uses Classes,
{$IFDEF CLX}
QGraphics, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, StdCtrls, ExtCtrls,
{$ENDIF}
TeeProcs, TeCanvas, TeeGLCanvas;
type
TTeeOpenGL=class;
TGLPosition=class(TPersistent)
private
FX : Double;
FY : Double;
FZ : Double;
FOwner : TTeeOpenGL;
protected
Procedure SetX(Const Value:Double);
Procedure SetY(Const Value:Double);
Procedure SetZ(Const Value:Double);
public
Procedure Assign(Source:TPersistent); override;
published
property X:Double read FX write SetX;
property Y:Double read FY write SetY;
property Z:Double read FZ write SetZ;
end;
TGLLight=class(TPersistent)
private
FColor : TColor;
FVisible : Boolean;
IOwner : TTeeOpenGL;
protected
Procedure SetColor(Value:TColor);
procedure SetVisible(Value:Boolean);
public
Constructor Create(AOwner:TTeeOpenGL);
Procedure Assign(Source:TPersistent); override;
Function GLColor:GLMat;
published
property Color:TColor read FColor write SetColor default clSilver;
property Visible:Boolean read FVisible write SetVisible;
end;
TGLLightSource=class(TGLLight)
private
FPosition : TGLPosition;
FFixed: Boolean;
procedure SetFixed(const Value: Boolean);
protected
Procedure SetPosition(Value:TGLPosition);
public
Constructor Create(AOwner:TTeeOpenGL);
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
published
property FixedPosition:Boolean read FFixed write SetFixed default False;
property Position:TGLPosition read FPosition write SetPosition;
end;
TTeeOpenGL = class(TComponent)
private
{ Private declarations }
FActive : Boolean;
FAmbientLight : Integer;
FFontExtrusion: Integer;
FFontOutlines : Boolean;
FLight0 : TGLLightSource;
FLight1 : TGLLightSource;
FLight2 : TGLLightSource;
FShadeQuality : Boolean;
FShininess : Double;
FTeePanel : TCustomTeePanel;
FDrawStyle : TTeeCanvasSurfaceStyle;
FOnInit : TNotifyEvent;
Function GetCanvas:TGLCanvas;
Procedure SetActive(Value:Boolean);
Procedure SetAmbientLight(Value:Integer);
Procedure SetFontExtrusion(Value:Integer);
Procedure SetFontOutlines(Value:Boolean);
Procedure SetLightSource0(Value:TGLLightSource);
Procedure SetLightSource1(Value:TGLLightSource);
Procedure SetLightSource2(Value:TGLLightSource);
Procedure SetShadeQuality(Value:Boolean);
Procedure SetShininess(Const Value:Double);
Procedure SetTeePanel(Value:TCustomTeePanel);
procedure SetDrawStyle(const Value: TTeeCanvasSurfaceStyle);
Procedure Activate;
Procedure OnCanvasInit(Sender:TObject);
Procedure SetDoubleProperty(Var Variable:Double; Const Value:Double);
protected
{ Protected declarations }
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
Procedure Repaint;
public
{ Public declarations }
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
property Canvas:TGLCanvas read GetCanvas;
property Light0:TGLLightSource read FLight0;
published
{ Published declarations }
property Active:Boolean read FActive write SetActive default False;
property AmbientLight:Integer read FAmbientLight write SetAmbientLight;
property FontExtrusion:Integer read FFontExtrusion write SetFontExtrusion default 0;
property FontOutlines:Boolean read FFontOutlines write SetFontOutlines default False;
property Light:TGLLightSource read FLight0 write SetLightSource0;
property Light1:TGLLightSource read FLight1 write SetLightSource1;
property Light2:TGLLightSource read FLight2 write SetLightSource2;
property ShadeQuality:Boolean read FShadeQuality write SetShadeQuality default True;
property Shininess:Double read FShininess write SetShininess;
property TeePanel:TCustomTeePanel read FTeePanel write SetTeePanel;
property DrawStyle:TTeeCanvasSurfaceStyle read FDrawStyle
write SetDrawStyle default tcsSolid;
property OnInit:TNotifyEvent read FOnInit write FOnInit;
end;
implementation
{$IFDEF CLR}
{$R 'TTeeOpenGL.bmp'}
{$ELSE}
{$R TeeGLIcon.res}
{$ENDIF}
Uses {$IFDEF CLX}
QControls,
{$ELSE}
Controls,
{$ENDIF}
{$IFDEF LINUX}
OpenGLLinux,
{$ELSE}
Windows,
OpenGL2,
{$ENDIF}
TeeConst;
{ TGLPosition }
Procedure TGLPosition.SetX(Const Value:Double);
begin
FOwner.SetDoubleProperty(FX,Value);
end;
Procedure TGLPosition.SetY(Const Value:Double);
begin
FOwner.SetDoubleProperty(FY,Value);
end;
Procedure TGLPosition.SetZ(Const Value:Double);
begin
FOwner.SetDoubleProperty(FZ,Value);
end;
Procedure TGLPosition.Assign(Source:TPersistent);
begin
if Source is TGLPosition then
With TGLPosition(Source) do
begin
Self.FX:=X;
Self.FY:=Y;
Self.FZ:=Z;
end
else inherited;
end;
{ TGLLightSource }
Constructor TGLLightSource.Create(AOwner:TTeeOpenGL);
begin
inherited;
FPosition:=TGLPosition.Create;
With FPosition do
begin
FOwner:=Self.IOwner;
FX:=-100;
FY:=-100;
FZ:=-100;
end;
end;
Destructor TGLLightSource.Destroy;
begin
FPosition.Free;
inherited;
end;
Procedure TGLLightSource.SetPosition(Value:TGLPosition);
begin
FPosition.Assign(Value);
end;
Procedure TGLLightSource.Assign(Source:TPersistent);
begin
if Source is TGLLightSource then
With TGLLightSource(Source) do
begin
Self.Position:=Position;
end;
inherited;
end;
procedure TGLLightSource.SetFixed(const Value: Boolean);
begin
if FFixed<>Value then
begin
FFixed:=Value;
IOwner.Repaint;
end;
end;
{ TGLLight }
Constructor TGLLight.Create(AOwner:TTeeOpenGL);
begin
inherited Create;
IOwner:=AOwner;
FColor:=clGray;
end;
Procedure TGLLight.SetColor(Value:TColor);
begin
if FColor<>Value then
begin
FColor:=Value;
IOwner.Repaint;
end;
end;
procedure TGLLight.SetVisible(Value:Boolean);
begin
if FVisible<>Value then
begin
FVisible:=Value;
IOwner.Repaint;
end;
end;
Function TGLLight.GLColor:GLMat;
const tmpInv=1/255.0;
var AColor : TColor;
begin
AColor:=ColorToRGB(FColor);
result[0]:=GetRValue(AColor)*tmpInv;
result[1]:=GetGValue(AColor)*tmpInv;
result[2]:=GetBValue(AColor)*tmpInv;
result[3]:=1;
end;
Procedure TGLLight.Assign(Source:TPersistent);
begin
if Source is TGLLight then
With TGLLight(Source) do
begin
Self.FColor:=Color;
Self.FVisible:=Visible;
end
else inherited;
end;
{ TTeeOpenGL }
Constructor TTeeOpenGL.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FLight0:=TGLLightSource.Create(Self);
FLight0.Visible:=True;
FLight1:=TGLLightSource.Create(Self);
FLight2:=TGLLightSource.Create(Self);
FAmbientLight:=8; {%}
FShininess:=0.5;
FShadeQuality:=True;
end;
{$IFNDEF CLR}
type
TTeePanelAccess=class(TCustomTeePanel);
{$ENDIF}
Destructor TTeeOpenGL.Destroy;
begin
FLight2.Free;
FLight1.Free;
FLight0.Free;
if Assigned(FTeePanel) then
begin
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FTeePanel).GLComponent:=nil;
if FActive then
FTeePanel.Canvas:=TTeeCanvas3D.Create;
end;
inherited;
end;
Function TTeeOpenGL.GetCanvas:TGLCanvas;
begin
if Assigned(FTeePanel) and (FTeePanel.Canvas is TGLCanvas) then
result:=TGLCanvas(FTeePanel.Canvas)
else
result:=nil;
end;
type TPrivateGLCanvas=class(TGLCanvas);
Procedure TTeeOpenGL.OnCanvasInit(Sender:TObject);
Procedure SetLight(ALight:TGLLightSource; Num:Integer);
begin
With ALight do
if Visible then
begin
if FixedPosition then Canvas.DisableRotation;
With Position do
TPrivateGLCanvas(Canvas).InitLight(Num,GLColor,X,Y,Z);
if FixedPosition then Canvas.EnableRotation;
end
else
glDisable(Num);
end;
begin
TPrivateGLCanvas(Canvas).InitAmbientLight(FAmbientLight);
SetLight(FLight0,GL_LIGHT0);
SetLight(FLight1,GL_LIGHT1);
SetLight(FLight2,GL_LIGHT2);
TPrivateGLCanvas(Canvas).SetShininess(FShininess);
if Assigned(FOnInit) then FOnInit(Self);
end;
Procedure TTeeOpenGL.SetShininess(Const Value:Double);
begin
SetDoubleProperty(FShininess,Value);
if Assigned(FTeePanel) then FTeePanel.Repaint;
end;
Procedure TTeeOpenGL.SetShadeQuality(Value:Boolean);
begin
if FShadeQuality<>Value then
begin
FShadeQuality:=Value;
if FActive and Assigned(FTeePanel) then
With Canvas do
begin
ShadeQuality:=Value;
Repaint;
end;
end;
end;
procedure TTeeOpenGL.Notification( AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and Assigned(FTeePanel) and (AComponent=FTeePanel) then
TeePanel:=nil;
end;
Procedure TTeeOpenGL.Activate;
var tmpCanvas : TGLCanvas;
begin
if Assigned(FTeePanel) then
if FActive then
begin
tmpCanvas:=TGLCanvas.Create;
With tmpCanvas do
begin
FontOutlines:=Self.FFontOutlines;
DrawStyle:=Self.DrawStyle;
ShadeQuality:=Self.FShadeQuality;
OnInit:=OnCanvasInit;
UseBuffer:=FTeePanel.Canvas.UseBuffer;
end;
FTeePanel.Canvas:=tmpCanvas;
end
else FTeePanel.Canvas:=TTeeCanvas3D.Create;
end;
Procedure TTeeOpenGL.SetAmbientLight(Value:Integer);
begin
if FAmbientLight<>Value then
begin
FAmbientLight:=Value;
Repaint;
end;
end;
Procedure TTeeOpenGL.SetFontExtrusion(Value:Integer);
begin
FFontExtrusion:=Value;
if FActive and Assigned(FTeePanel) then
With Canvas do
begin
DeleteFont;
FontExtrusion:=Value;
Repaint;
end;
end;
Procedure TTeeOpenGL.SetFontOutlines(Value:Boolean);
begin
FFontOutlines:=Value;
if FActive and Assigned(FTeePanel) then
With Canvas do
begin
DeleteFont;
FontOutlines:=Value;
Repaint;
end;
end;
Procedure TTeeOpenGL.SetLightSource0(Value:TGLLightSource);
begin
FLight0.Assign(Value);
end;
Procedure TTeeOpenGL.SetLightSource1(Value:TGLLightSource);
begin
FLight1.Assign(Value);
end;
Procedure TTeeOpenGL.SetLightSource2(Value:TGLLightSource);
begin
FLight2.Assign(Value);
end;
Procedure TTeeOpenGL.SetActive(Value:Boolean);
begin
if FActive<>Value then
begin
FActive:=Value;
Activate;
end;
end;
Procedure TTeeOpenGL.Repaint;
begin
if Assigned(FTeePanel) then FTeePanel.Repaint;
end;
Procedure TTeeOpenGL.SetTeePanel(Value:TCustomTeePanel);
begin
FTeePanel:=Value;
if Assigned(FTeePanel) then
begin
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FTeePanel).GLComponent:=Self;
FTeePanel.FreeNotification(Self);
Activate;
end
else FActive:=False;
end;
Procedure TTeeOpenGL.SetDoubleProperty(Var Variable:Double; Const Value:Double);
begin
if Variable<>Value then
begin
Variable:=Value;
Repaint;
end;
end;
procedure TTeeOpenGL.SetDrawStyle(const Value: TTeeCanvasSurfaceStyle);
begin
FDrawStyle:=Value;
if FActive and Assigned(FTeePanel) then
begin
Canvas.DrawStyle:=FDrawStyle;
Repaint;
end;
end;
end.
|
unit uDownloads.Controller.DownloaderControler;
interface
uses
uDownloads.Controller.Interfaces, System.Net.HttpClient,
System.SysUtils, System.Classes, uDownloads.Service.HTTPDownload,
uDownloads.View.Log, uDownloads.Model.Entidades.LogDowload,
uDownloads.Model.Interfaces, System.IOUtils, Vcl.Dialogs;
type
TDownloadsController = class(TInterfacedObject, IDownloadsController)
private
FIdLogAtual: Integer;
procedure SalvarLog(AcUrl: String);
procedure SalvarArquivo(AResponse: IHTTPResponse);
procedure oRequestRequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
procedure AtualzarDataFimLog;
function GetEntidadeLog: IEntidadeLogDowload;
public
destructor Destroy; override;
class function New(): IDownloadsController;
function IniciarDownload(cUrl: String; OnReceiveData: TReceiveDataEvent): IDownloadsController;
function ExibirMensagem: IDownloadsController;
function PararDownload: IDownloadsController;
function HistoricoDownloads: IDownloadsController;
function AbrirDiretorioDownload: IDownloadsController;
end;
implementation
class function TDownloadsController.New: IDownloadsController;
begin
Result := Self.Create();
end;
function TDownloadsController.IniciarDownload(cUrl: String; OnReceiveData: TReceiveDataEvent): IDownloadsController;
var
oThreadHTTPDownload: TThreadHTTPDownload;
begin
Result := Self;
SalvarLog(cUrl);
oThreadHTTPDownload := TThreadHTTPDownload.Create(True);
oThreadHTTPDownload.OnReceiveData := OnReceiveData;
oThreadHTTPDownload.OnRequestCompleted := oRequestRequestCompleted;
oThreadHTTPDownload.Url := cUrl;
oThreadHTTPDownload.Start;
end;
function TDownloadsController.ExibirMensagem: IDownloadsController;
begin
Result := Self;
end;
function TDownloadsController.PararDownload: IDownloadsController;
begin
Result := Self;
end;
function TDownloadsController.HistoricoDownloads: IDownloadsController;
var
oForm: TFrmLog;
begin
Result := Self;
oForm := TFrmLog.New(
GetEntidadeLog);
try
oForm.ShowModal;
finally
if Assigned(oForm) then
FreeAndNil(oForm);
end;
end;
function TDownloadsController.AbrirDiretorioDownload: IDownloadsController;
begin
Result := Self;
end;
procedure TDownloadsController.SalvarLog(AcUrl: String);
begin
FIdLogAtual := GetEntidadeLog.Inserir(AcUrl);
end;
procedure TDownloadsController.oRequestRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
begin
try
SalvarArquivo(AResponse);
AtualzarDataFimLog;
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOK], 0);
Abort;
end;
end;
end;
procedure TDownloadsController.AtualzarDataFimLog;
begin
GetEntidadeLog.AtualizarHoraFinal(FIdLogAtual);
end;
function TDownloadsController.GetEntidadeLog: IEntidadeLogDowload;
begin
try
Result := TModelEntidadesLogDowload.New;
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOK], 0);
Abort;
end;
end;
end;
procedure TDownloadsController.SalvarArquivo(AResponse: IHTTPResponse);
var
oMemoryStream: TMemoryStream;
cFileName: String;
begin
try
cFileName := TDirectory.GetCurrentDirectory + TPath.DirectorySeparatorChar +
TPath.GetRandomFileName + '.' + AResponse.MimeType.Split(['/'])[1];
oMemoryStream := TMemoryStream.Create();
oMemoryStream.LoadFromStream(AResponse.ContentStream);
oMemoryStream.SaveToFile(cFileName);
finally
if Assigned(oMemoryStream) then
FreeAndNil(oMemoryStream);
end;
end;
destructor TDownloadsController.Destroy;
begin
inherited;
end;
end.
|
Unit IdIMAP4Server;
Interface
{
2002-Apr-21 - J. Berg
-use fetch()
2000-May-18 - J. Peter Mugaas
-Ported to Indy
2000-Jan-13 - MTL
-Moved to new Palette Scheme (Winshoes Servers)
1999-Aug-26 - Ray Malone
-Started unit
}
Uses
Classes,
IdAssignedNumbers,
IdTCPServer;
Const
IMAPCommands : Array [1..25] Of String =
({ Client Commands - Any State}
'CAPABILITY', {Do not Localize}
'NOOP', {Do not Localize}
'LOGOUT', {Do not Localize}
{ Client Commands - Non Authenticated State}
'AUTHENTICATE', {Do not Localize}
'LOGIN', {Do not Localize}
{ Client Commands - Authenticated State}
'SELECT', {Do not Localize}
'EXAMINE', {Do not Localize}
'CREATE', {Do not Localize}
'DELETE', {Do not Localize}
'RENAME', {Do not Localize}
'SUBSCRIBE', {Do not Localize}
'UNSUBSCRIBE', {Do not Localize}
'LIST', {Do not Localize}
'LSUB', {Do not Localize}
'STATUS', {Do not Localize}
'APPEND', {Do not Localize}
{ Client Commands - Selected State}
'CHECK', {Do not Localize}
'CLOSE', {Do not Localize}
'EXPUNGE', {Do not Localize}
'SEARCH', {Do not Localize}
'FETCH', {Do not Localize}
'STORE', {Do not Localize}
'COPY', {Do not Localize}
'UID', {Do not Localize}
{ Client Commands - Experimental/ Expansion}
'X'); {Do not Localize}
Type
TCommandEvent = procedure (Thread : TIdPeerThread; const Tag, CmdStr: String;
var Handled: Boolean) of Object;
TIdIMAP4Server = class ( TIdTCPServer )
Protected
fOnCommandCAPABILITY : TCommandEvent;
fONCommandNOOP: TCommandEvent;
fONCommandLOGOUT: TCommandEvent;
fONCommandAUTHENTICATE: TCommandEvent;
fONCommandLOGIN: TCommandEvent;
fONCommandSELECT : TCommandEvent;
fONCommandEXAMINE : TCommandEvent;
fONCommandCREATE : TCommandEvent;
fONCommandDELETE : TCommandEvent;
fONCommandRENAME : TCommandEvent;
fONCommandSUBSCRIBE : TCommandEvent;
fONCommandUNSUBSCRIBE : TCommandEvent;
fONCommandLIST : TCommandEvent;
fONCommandLSUB : TCommandEvent;
fONCommandSTATUS : TCommandEvent;
fONCommandAPPEND : TCommandEvent;
fONCommandCHECK : TCommandEvent;
fONCommandCLOSE : TCommandEvent;
fONCommandEXPUNGE : TCommandEvent;
fONCommandSEARCH : TCommandEvent;
fONCommandFETCH : TCommandEvent;
fONCommandSTORE : TCommandEvent;
fONCommandCOPY : TCommandEvent;
fONCommandUID : TCommandEvent;
fONCommandX : TCommandEvent;
fOnCommandError : TCommandEvent;
procedure DoCommandCAPABILITY ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
procedure DoCommandNOOP(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
procedure DoCommandLOGOUT ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandAUTHENTICATE ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandLOGIN ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandSELECT ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandEXAMINE ( Thread : TIdPeerThread; const Tag, CmdStr :String; var Handled : Boolean );
Procedure DoCommandCREATE ( Thread : TIdPeerThread; const Tag, CmdStr :String; var Handled : Boolean );
Procedure DoCommandDELETE ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandRENAME ( Thread : TIdPeerThread; const Tag, CmdStr :String; var Handled : Boolean);
Procedure DoCommandSUBSCRIBE ( Thread : TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandUNSUBSCRIBE ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandLIST(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandLSUB(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandSTATUS(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandAPPEND(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandCHECK(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandCLOSE(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandEXPUNGE ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandSEARCH ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandFETCH ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandSTORE ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandCOPY ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandUID ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandX ( Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Procedure DoCommandError(Thread: TIdPeerThread; const Tag, CmdStr : String; var Handled : Boolean );
Function DoExecute(Thread: TIdPeerThread): Boolean; override;
public
Constructor Create(AOwner: TComponent); Override;
published
Property ONCommandCAPABILITY : TCommandEvent Read fOnCommandCAPABILITY write fOnCommandCAPABILITY;
Property ONCommandNOOP : TCommandEvent Read fONCommandNOOP write fONCommandNOOP;
Property ONCommandLOGOUT : TCommandEvent Read fONCommandLOGOUT write fONCommandLOGOUT;
Property ONCommandAUTHENTICATE : TCommandEvent Read fONCommandAUTHENTICATE write fONCommandAUTHENTICATE;
Property ONCommandLOGIN : TCommandEvent Read fONCommandLOGIN write fONCommandLOGIN;
Property ONCommandSELECT : TCommandEvent Read fONCommandSELECT write fONCommandSELECT;
Property OnCommandEXAMINE :TCommandEvent Read fOnCommandEXAMINE write fOnCommandEXAMINE;
property ONCommandCREATE : TCommandEvent Read fONCommandCREATE write fONCommandCREATE;
property ONCommandDELETE : TCommandEvent Read fONCommandDELETE write fONCommandDELETE;
property OnCommandRENAME : TCommandEvent Read fOnCommandRENAME write fOnCommandRENAME;
property ONCommandSUBSCRIBE : TCommandEvent read fONCommandSUBSCRIBE write fONCommandSUBSCRIBE;
property ONCommandUNSUBSCRIBE : TCommandEvent read fONCommandUNSUBSCRIBE write fONCommandUNSUBSCRIBE;
property ONCommandLIST : TCommandEvent read fONCommandLIST write fONCommandLIST;
property OnCommandLSUB : TCommandEvent read fOnCommandLSUB write fOnCommandLSUB;
property ONCommandSTATUS : TCommandEvent read fONCommandSTATUS write fONCommandSTATUS;
property OnCommandAPPEND : TCommandEvent read fOnCommandAPPEND write fOnCommandAPPEND;
property ONCommandCHECK : TCommandEvent read fONCommandCHECK write fONCommandCHECK;
property OnCommandCLOSE : TCommandEvent read fOnCommandCLOSE write fOnCommandCLOSE;
property ONCommandEXPUNGE : TCommandEvent read fONCommandEXPUNGE write fONCommandEXPUNGE;
property OnCommandSEARCH : TCommandEvent read fOnCommandSEARCH write fOnCommandSEARCH;
property ONCommandFETCH : TCommandEvent read fONCommandFETCH write fONCommandFETCH;
property OnCommandSTORE : TCommandEvent read fOnCommandSTORE write fOnCommandSTORE;
property OnCommandCOPY : TCommandEvent read fOnCommandCOPY write fOnCommandCOPY;
property ONCommandUID : TCommandEvent read fONCommandUID write fONCommandUID;
property OnCommandX : TCommandEvent read fOnCommandX write fOnCommandX;
property OnCommandError : TCommandEvent read fOnCommandError write fOnCommandError;
end;
Implementation
Uses
IdGlobal,
SysUtils;
//--------------------Start of TIdIMAP4Server Code ---------------------
// Started August 26, 1999
//------------------------------------------------------------------------------
Const
cCAPABILITY = 1;
cNOOP = 2;
cLOGOUT = 3;
cAUTHENTICATE = 4;
cLOGIN = 5;
cSELECT = 6;
cEXAMINE = 7;
cCREATE = 8;
cDELETE = 9;
cRENAME = 10;
cSUBSCRIBE = 11;
cUNSUBSCRIBE = 12;
cLIST = 13;
cLSUB = 14;
cSTATUS = 15;
cAPPEND = 16;
cCHECK = 17;
cCLOSE = 18;
cEXPUNGE = 19;
cSEARCH = 20;
cFETCH = 21;
cSTORE = 22;
cCOPY = 23;
cUID = 24;
cXCmd = 25;
constructor TIdIMAP4Server.Create(AOwner: TComponent);
begin
Inherited;
DefaultPort := IdPORT_IMAP4;
end;
function TIdIMAP4Server.DoExecute(Thread: TIdPeerThread): Boolean;
var
RcvdStr,
ArgStr,
sTag,
sCmd : String;
cmdNum : Integer;
Handled : Boolean;
begin
result := true;
while Thread.Connection.Connected Do
begin
Handled := False;
RcvdStr := Thread.Connection.ReadLn;
ArgStr := RcvdStr;
sTag := UpperCase ( Fetch ( ArgStr, CHAR32 ) );
sCmd := UpperCase ( Fetch ( ArgStr, CHAR32 ) );
CmdNum := Succ ( PosInStrArray ( Uppercase ( sCmd ), IMAPCommands ) );
case CmdNum Of
cCAPABILITY : DoCommandCAPABILITY ( Thread, sTag, ArgStr, Handled );
cNOOP : DoCommandNOOP ( Thread, sTag, ArgStr, Handled );
cLOGOUT : DoCommandLOGOUT ( Thread, sTag, ArgStr, Handled );
cAUTHENTICATE : DoCommandAUTHENTICATE ( Thread, sTag, ArgStr, Handled );
cLOGIN : DoCommandLOGIN ( Thread, sTag, ArgStr, Handled );
cSELECT : DoCommandSELECT ( Thread, sTag, ArgStr, Handled );
cEXAMINE : DoCommandEXAMINE ( Thread, sTag, ArgStr, Handled );
cCREATE : DoCommandCREATE ( Thread, sTag, ArgStr, Handled );
cDELETE : DoCommandDELETE ( Thread, sTag, ArgStr, Handled );
cRENAME : DoCommandRENAME ( Thread, sTag, ArgStr, Handled );
cSUBSCRIBE : DoCommandSUBSCRIBE ( Thread, sTag, ArgStr, Handled );
cUNSUBSCRIBE : DoCommandUNSUBSCRIBE ( Thread, sTag, ArgStr, Handled );
cLIST : DoCommandLIST ( Thread, sTag, ArgStr, Handled );
cLSUB : DoCommandLSUB ( Thread, sTag, ArgStr, Handled );
cSTATUS : DoCommandSTATUS ( Thread, sTag, ArgStr, Handled );
cAPPEND : DoCommandAPPEND ( Thread, sTag, ArgStr, Handled );
cCHECK : DoCommandCHECK ( Thread, sTag, ArgStr, Handled );
cCLOSE : DoCommandCLOSE ( Thread, sTag, ArgStr, Handled );
cEXPUNGE : DoCommandEXPUNGE ( Thread, sTag, ArgStr, Handled);
cSEARCH : DoCommandSEARCH ( Thread, sTag, ArgStr, Handled );
cFETCH : DoCommandFETCH ( Thread, sTag, ArgStr, Handled );
cSTORE : DoCommandSTORE ( Thread, sTag, ArgStr, Handled );
cCOPY : DoCommandCOPY ( Thread, sTag, ArgStr, Handled );
cUID : DoCommandUID ( Thread, sTag, ArgStr, Handled );
else
begin
if ( Length ( SCmd ) > 0 ) and ( UpCase ( SCmd[1] ) = 'X' ) then {Do not Localize}
begin
DoCommandX ( Thread, sTag, ArgStr, Handled );
end //if ( Length ( SCmd ) > 0) and ( UpCase ( SCmd[1] ) = 'X' ) then {Do not Localize}
else
begin
DoCommandError ( Thread, sTag, ArgStr, Handled );
end; // else ..if ( Length ( SCmd ) > 0) and ( UpCase ( SCmd[1] ) = 'X' ) then {Do not Localize}
end; // else .. case
end; {Case}
end; {while}
end; { doExecute }
procedure TIdIMAP4Server.DoCommandCapability(Thread: TIdPeerThread; Const Tag, CmdStr :String;
Var Handled :Boolean);
begin
if Assigned ( fOnCommandCAPABILITY ) then
begin
OnCommandCAPABILITY ( Thread, Tag, CmdStr, Handled );
end; //if Assigned ( fOnCommandCAPABILITY ) then
end;
procedure TIdIMAP4Server.DoCommandNOOP ( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandNOOP ) then
begin
OnCommandNOOP ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandNOOP ) then
end;
procedure TIdIMAP4Server.DoCommandLOGOUT( Thread : TIdPeerThread;
const Tag,CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandLOGOUT ) then
begin
OnCommandLOGOUT ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandLOGOUT ) then
end;
procedure TIdIMAP4Server.DoCommandAUTHENTICATE ( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandAUTHENTICATE ) then
begin
OnCommandAUTHENTICATE(Thread,Tag, CmdStr,Handled);
end; // if Assigned ( fONCommandAUTHENTICATE ) then
end;
procedure TIdIMAP4Server.DoCommandLOGIN ( Thread : TIdPeerThread;
const Tag,CmdStr :String; var Handled :Boolean );
begin
if Assigned ( fONCommandLOGIN ) then
begin
OnCommandLOGIN ( Thread,Tag, CmdStr, Handled );
end; //if Assigned ( fONCommandLOGIN ) then
end;
procedure TIdIMAP4Server.DoCommandSELECT(Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandSELECT ) then
begin
OnCommandSELECT ( Thread, Tag, CmdStr, Handled );
end; //if Assigned ( fONCommandSELECT ) then
end;
procedure TIdIMAP4Server.DoCommandEXAMINE(Thread : TIdPeerThread;
const Tag, CmdStr :String; var Handled : Boolean);
begin
if Assigned ( fONCommandEXAMINE ) then
begin
OnCommandEXAMINE ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandEXAMINE ) then
end;
procedure TIdIMAP4Server.DoCommandCREATE ( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandCREATE ) then
begin
OnCommandCREATE( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandCREATE ) then
end;
procedure TIdIMAP4Server.DoCommandDELETE ( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean );
begin
if Assigned ( fONCommandDELETE ) then
begin
OnCommandDELETE ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandDELETE ) then
end;
procedure TIdIMAP4Server.DoCommandRENAME ( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandRENAME ) then
begin
OnCommandRENAME( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandRENAME ) then
end;
procedure TIdIMAP4Server.DoCommandSUBSCRIBE( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandSUBSCRIBE ) then
begin
OnCommandSUBSCRIBE ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandSUBSCRIBE ) then
end;
procedure TIdIMAP4Server.DoCommandUNSUBSCRIBE( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandUNSUBSCRIBE ) then
begin
OnCommandUNSUBSCRIBE(Thread,Tag,CmdStr,Handled);
end; // if Assigned ( fONCommandUNSUBSCRIBE ) then
end;
procedure TIdIMAP4Server.DoCommandLIST(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean);
begin
if Assigned ( fONCommandLIST ) then
begin
OnCommandLIST(Thread,Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandLIST ) then
end;
procedure TIdIMAP4Server.DoCommandLSUB ( Thread: TIdPeerThread;
const Tag, CmdStr :String; var Handled : Boolean );
begin
if Assigned ( fONCommandLSUB ) then
begin
OnCommandLSUB ( Thread, Tag, CmdStr, Handled );
end; //if Assigned ( fONCommandLSUB ) then
end;
procedure TIdIMAP4Server.DoCommandSTATUS( Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean);
begin
if Assigned ( fONCommandSTATUS ) then
begin
OnCommandSTATUS ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandSTATUS ) then
end;
procedure TIdIMAP4Server.DoCommandAPPEND( Thread : TIdPeerThread;
const Tag, CmdStr : String; var Handled : Boolean );
begin
if Assigned ( fONCommandAPPEND ) then
begin
OnCommandAPPEND ( Thread, Tag, CmdStr, Handled );
end; // if Assigned(fONCommandAPPEND) then
end;
procedure TIdIMAP4Server.DoCommandCHECK(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandCHECK ) then
begin
OnCommandCHECK ( Thread, Tag, CmdStr, Handled );
end; // if Assigned(fONCommandCHECK) then
end;
procedure TIdIMAP4Server.DoCommandCLOSE(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean );
begin
if Assigned ( fONCommandCLOSE ) then
begin
OnCommandCLOSE ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandCLOSE ) then
end;
procedure TIdIMAP4Server.DoCommandEXPUNGE(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandEXPUNGE ) then
begin
OnCommandEXPUNGE ( Thread, Tag, CmdStr, Handled );
end; //if Assigned ( fONCommandEXPUNGE ) then
end;
procedure TIdIMAP4Server.DoCommandSEARCH(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean );
begin
if Assigned ( fONCommandSEARCH ) then
begin
OnCommandSEARCH ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandSEARCH ) then
end;
procedure TIdIMAP4Server.DoCommandFETCH(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandFETCH ) then
begin
OnCommandFETCH ( Thread,Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandFETCH ) then
end;
procedure TIdIMAP4Server.DoCommandSTORE(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandSTORE ) then
begin
OnCommandSTORE ( Thread, Tag, CmdStr, Handled );
end; //if Assigned ( fONCommandSTORE ) then
end;
procedure TIdIMAP4Server.DoCommandCOPY(Thread: TIdPeerThread;
const Tag, CmdStr : String; var Handled :Boolean);
begin
if Assigned ( fONCommandCOPY ) then
begin
OnCommandCOPY ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandCOPY ) then
end;
procedure TIdIMAP4Server.DoCommandUID(Thread: TIdPeerThread; const Tag, CmdStr :String;
var Handled : Boolean );
begin
if Assigned ( fONCommandUID ) then
begin
OnCommandUID ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandUID ) then
end;
procedure TIdIMAP4Server.DoCommandX(Thread: TIdPeerThread; const Tag, CmdStr :String;
var Handled : Boolean);
begin
if Assigned ( fONCommandX ) then
begin
OnCommandX ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandX ) then
end;
procedure TIdIMAP4Server.DoCommandError(Thread: TIdPeerThread; const Tag, CmdStr :String;
var Handled : Boolean );
begin
if Assigned ( fONCommandError ) then
begin
OnCommandError ( Thread, Tag, CmdStr, Handled );
end; // if Assigned ( fONCommandError ) then
end;
//------------------------------------------------------------------------------
// End of TIdIMAP4Server Code
// Started August 26, 1999
//------------------------------------------------------------------------------
End.
|
unit Classe_Acesso;
interface
uses Classes, Dialogs, SysUtils, IniFiles,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
FireDAC.Stan.Intf, FireDAC.Stan.Option,
Classe_Empresa;
type
TAcesso = class
private
FNomeDaConexao,
vNomeDoArquivoINI: String;
FConectado : Boolean;
function conexaoExiste:Boolean;
function carregarConfiguracaoDeAcesso:Boolean;
function acessarBaseDeDados:Boolean;
function getNomeDaConexao: String;
procedure setNomeDaConexao(const Value: String);
procedure AtualizaBaseDeDados;
public
procedure Conectar;
procedure Desconectar;
function Conectado:Boolean;
property nomeDaConexao: String read getNomeDaConexao
write setNomeDaConexao;
end;
implementation
{ TAcesso }
uses Dados, Funcoes;
function TAcesso.acessarBaseDeDados: Boolean;
begin
result := false;
if not conexaoExiste then exit;
if not carregarConfiguracaoDeAcesso then exit;
AtualizaBaseDeDados;
Empresa := TEmpresa.Create;
Empresa.Abrir;
result := true;
end;
procedure TAcesso.AtualizaBaseDeDados;
begin
if globalFuncoes_Atualizado = 'S' then
EXIT;
//Aumenta o tamanho da coluna ATU_FUNCAO de 100 para 255 caracteres
{
Executar_Script('ALTER TABLE ATUALIZADO_ATU ADD ATU_FUNCAOOLD VARCHAR(100) NULL');
Executar_Script('UPDATE ATUALIZADO_ATU SET ATU_FUNCAOOLD = ATU_FUNCAO');
Executar_Script('ALTER TABLE ATUALIZADO_ATU DROP COLUMN ATU_FUNCAO');
Executar_Script('ALTER TABLE ATUALIZADO_ATU ADD ATU_FUNCAO VARCHAR(255) NULL');
Executar_Script('UPDATE ATUALIZADO_ATU SET ATU_FUNCAO = ATU_FUNCAOOLD');
Executar_Script('ALTER TABLE ATUALIZADO_ATU DROP COLUMN ATU_FUNCAOOLD');
}
// Outras Atualizações
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CODIGO_UNISYSTEM VARCHAR(10) NULL');
Executar_Script('TRUNCATE TABLE CORPOEMAIL_CEMAIL');
Executar_Script('TRUNCATE TABLE EMAIL_EMAIL ');
Executar_Script('TRUNCATE TABLE FUSADA_FUS ');
Executar_Script('TRUNCATE TABLE FUNCOES_FUN ');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_DESCRICAO');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_INICIOATIVIDADES DATETIME NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_SUFRAMA VARCHAR(10) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_INSCRICAO_ESTADUAL VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_INSCRICAO_MUNICIPAL VARCHAR(20) NULL');
Executar_Script('UPDATE EMPRESA_EMP SET EMP_INSCRICAO_ESTADUAL = EMP_IE');
Executar_Script('UPDATE EMPRESA_EMP SET EMP_INSCRICAO_MUNICIPAL = EMP_INSCRICAOMUNICIPAL');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_IE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_INSCRICAOMUNICIPAL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_NIRE VARCHAR(11) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_INSCRICAO_ESTADUAL_ST varchar(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTRIBUINTE_IPI INTEGER NULL DEFAULT 0');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_APURACAO_MENSAL INTEGER NULL DEFAULT 0');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CELULAR VARCHAR(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_WHATSAPP VARCHAR(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_RESPONSAVEL_NOME varchar(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_RESPONSAVEL_TELEFONE varchar(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_RESPONSAVEL_CELULAR varchar(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_RESPONSAVEL_EMAIL varchar(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_EMPRESA VARCHAR(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_RESPONSAVEL VARCHAR(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_CNPJ VARCHAR(14) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_CPF VARCHAR(11) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_TEL1 VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_TEL2 VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_CRC VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_CEL1 VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_CEL2 VARCHAR(20) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_CONTADOR_EMAIL VARCHAR(40) NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_DT DATETIME NULL');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CNPJCPF');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CORTELA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CORLETRA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_DISCIPLINAS');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_QTDMESAS');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_FONTEMAPAMESAS');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CODIGOINTERFACE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_FAX');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_GERENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_FONESGERENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_FAXGERENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_EMAILGERENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_ALMOXARIFADOPARADIESEL');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CIDADENOME');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_EMPRESA_SIMPLES_NACIONAL');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CERTIFICADOVENCE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_BOLETO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_BANCO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CDBANCO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_NMBANCO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CDCEDENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_DGCEDENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CARTEIRA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_AGENCIA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_DGAGENCIA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_CONTACORRENTE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_DIGITOCC');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_ESPECIE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_MULTAATRASO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_JUROSDIA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_ACRESCIMOBOLETO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_PRINTER_COMANDA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_PRINTER_COZINHA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_PRINTER_NFCE');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_LINHASAPOSCUPOM');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_TEMPOSEMCOMANDARMESA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_MSGRODAPECOMANDA');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_MSGRODAPERECIBO');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_TAXAGARCOM');
Executar_Script('ALTER TABLE EMPRESA_EMP DROP COLUMN EMP_COUVERT');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_PIS_CUMULATIVO INTEGER NULL DEFAULT 0');
Executar_Script('ALTER TABLE EMPRESA_EMP ADD EMP_PIS_ALIQUOTA NUMERIC(12,2) NULL DEFAULT 0');
globalFuncoes_Atualizado:='S';
end;
function TAcesso.carregarConfiguracaoDeAcesso: Boolean;
var ArquivoIni: TIniFile;
CONEXAO,
HOSTNAME,
USERNAME,
PASSWORD,
PORTA,
BANCO,
DRIVER : String;
begin
result := false;
ArquivoIni := TIniFile.Create(vNomeDoArquivoINI);
HOSTNAME := Descriptografar(ArquivoIni.ReadString('CONEXAO','SERVER' ,''));
PORTA := Descriptografar(ArquivoIni.ReadString('CONEXAO','PORT' ,''));
BANCO := Descriptografar(ArquivoIni.ReadString('CONEXAO','DATABASE',''));
USERNAME := Descriptografar(ArquivoIni.ReadString('CONEXAO','USERNAME',''));
PASSWORD := Descriptografar(ArquivoIni.ReadString('CONEXAO','PASSWORD',''));
ArquivoIni.Free;
try
with dm.DataBase1 do
begin
Connected := False;
Params.Clear;
Params.Values['DriverID'] := 'MSSQL';
Params.Values['Server'] := HOSTNAME;
Params.Values['Database'] := BANCO;
Params.Values['User_name'] := USERNAME;
Params.Values['Password'] := password;
Connected := True;
with FormatOptions do
begin
OwnMapRules := True;
with MapRules.Add do
begin
ScaleMin := 4;
ScaleMax := 4;
PrecMin := 18;
PrecMax := 18;
SourceDataType := dtBcd;
TargetDataType := dtDouble;
end;
with MapRules.Add do
begin
ScaleMin := 4;
ScaleMax := 4;
PrecMin := 18;
PrecMax := 18;
SourceDataType := dtDateTimeStamp;
TargetDataType := dtDateTime;
end;
end;
end;
FConectado:=True;
Result := True;
except
FConectado:=False;
exit;
end;
end;
function TAcesso.Conectado: Boolean;
begin
Result := FConectado;
end;
procedure TAcesso.Conectar;
begin
FConectado := AcessarBaseDeDados;
end;
function TAcesso.conexaoExiste: Boolean;
begin
result := false;
if FNomeDaConexao = '' then
begin
ShowMessage('Informe a Empresa (Banco de Dados) desejado.');
exit;
end;
vNomeDoArquivoINI := 'Arquivos\Conexoes\'+FNomeDaConexao+'.INI';
if not FileExists(vNomeDoArquivoINI) then
begin
ShowMessage('Execute o aplicativo ConfiguraBases para '+FNomedaConexao);
exit;
end;
result := true;
end;
procedure TAcesso.Desconectar;
begin
dm.Database1.Close;
end;
function TAcesso.getNomeDaConexao: String;
begin
result := self.FNomeDaConexao;
end;
procedure TAcesso.setNomeDaConexao(const Value: String);
begin
self.FNomeDaConexao := Value;
end;
end.
UPDATE EMPRESA_EMP SET EMP_INICIOATIVIDADES = '01/10/2019'
UPDATE EMPRESA_EMP SET EMP_SUFRAMA = 'EXSUFRAMA'
UPDATE EMPRESA_EMP SET EMP_INSCRICAO_ESTADUAL = 'EX IE'
UPDATE EMPRESA_EMP SET EMP_INSCRICAO_MUNICIPAL = 'EX IM'
UPDATE EMPRESA_EMP SET EMP_NIRE = 'EX NIRE'
UPDATE EMPRESA_EMP SET EMP_INSCRICAO_ESTADUAL_ST = 'EX IEST'
UPDATE EMPRESA_EMP SET EMP_CONTRIBUINTE_IPI = 1
UPDATE EMPRESA_EMP SET EMP_CELULAR = 'EX CEL'
UPDATE EMPRESA_EMP SET EMP_WHATSAPP = 'EX WHATS UP'
UPDATE EMPRESA_EMP SET EMP_RESPONSAVEL_NOME = 'EX RESP NOME'
UPDATE EMPRESA_EMP SET EMP_RESPONSAVEL_TELEFONE = 'EX RESP TEL'
UPDATE EMPRESA_EMP SET EMP_RESPONSAVEL_CELULAR = 'EX RESP CEL'
UPDATE EMPRESA_EMP SET EMP_RESPONSAVEL_EMAIL = 'EX RESP EMAIL'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_EMPRESA = 'EX EMPRESA'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_RESPONSAVEL = 'EX CONT RESP'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_CNPJ = 'EX CONT CNPJ'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_CPF = 'EX CONT CPF'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_TEL1 = 'EX CONT TEL1'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_TEL2 = 'EX CONT TEL2'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_CRC = 'EX CONT CRC'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_CEL1 = 'EX CONT CEL1'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_CEL2 = 'EX CONT CEL2'
UPDATE EMPRESA_EMP SET EMP_CONTADOR_EMAIL = 'EX CONT EMAIL'
UPDATE EMPRESA_EMP SET EMP_DT = '20/10/2020'
UPDATE EMPRESA_EMP SET EMP_CONTRIBUINTE_IPI = 1
UPDATE EMPRESA_EMP SET EMP_CELULAR = 'CEL TEST'
UPDATE EMPRESA_EMP SET EMP_WHATSAPP = 'ZAP TEST'
UPDATE EMPRESA_EMP SET EMP_PIS_ALIQUOTA = 1.65
|
unit Restaurantes.Constantes;
interface
const
//Mensagens de retorno
Info200 = 200;
DescInfo200 = 'Requisição bem sucedida.';
Erro400 = 400;
DescErro400 = 'Requisição inválida: o pedido não pode ser entregue devido a sintaxe incrorreta';
Erro500 = 500;
DescErro500 = 'Erro interno';
implementation
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* (c) Copyright 1993, Silicon Graphics, Inc.
* 1993-1995 Microsoft Corporation
* ALL RIGHTS RESERVED
*/}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
Dialogs, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
Quadric : GLUquadricObj;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
diffuseMaterial : Array [0..3] of GLfloat = ( 0.5, 0.5, 0.5, 1.0 );
implementation
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
mat_specular : Array [0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 );
light_position : Array [0..3] of GLfloat = ( 1.0, 1.0, 1.0, 0.0 );
begin
glMaterialfv(GL_FRONT, GL_DIFFUSE, @diffuseMaterial);
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular);
glMaterialf(GL_FRONT, GL_SHININESS, 25.0);
glLightfv(GL_LIGHT0, GL_POSITION, @light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
end;
procedure changeRedDiffuse;
begin
diffuseMaterial[0] := diffuseMaterial[0] + 0.1;
If diffuseMaterial[0] > 1.0
then diffuseMaterial[0] := 0.0;
glColor4fv(@diffuseMaterial);
end;
procedure changeGreenDiffuse;
begin
diffuseMaterial[1] := diffuseMaterial[1] + 0.1;
If diffuseMaterial[1] > 1.0
then diffuseMaterial[1] := 0.0;
glColor4fv(@diffuseMaterial);
end;
procedure changeBlueDiffuse;
begin
diffuseMaterial[2] := diffuseMaterial[2] + 0.1;
If diffuseMaterial[2] > 1.0
then diffuseMaterial[2] := 0.0;
glColor4fv(@diffuseMaterial);
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT );
gluSphere (Quadric, 1.0, 20, 20);
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Quadric := GLUNewQuadric;
Init;
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight );
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
If ClientWidth < ClientHeight
then glOrtho (-1.5, 1.5, -1.5*ClientHeight/ClientWidth,
1.5*ClientHeight/ClientWidth, -10.0, 10.0)
else glOrtho (-1.5*ClientWidth/ClientHeight,
1.5*ClientWidth/ClientHeight, -1.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
gluDeleteQuadric (Quadric);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
Case Key of
ord ('R') : changeRedDiffuse;
ord ('G') : changeGreenDiffuse;
ord ('B') : changeBlueDiffuse;
end;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
end.
|
{***************************************************************
*
* Project : Resolver
* Unit Name: ResolverTest
* Purpose :
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:14:19
* Author : Ray Malone / Vladimir Vassiliev <ray@mbssoftware.com voldemarv@hotpop.com>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit ResolverTest;
//------------------------------------------------------------------------------
// The setup data for the Resolver is stored in the regsistry
// It stores the port and primary, secondary and tertiany dns servers.
//------------------------------------------------------------------------------
// The TDNResolver is us just a UPD Client containing a TDnsMessage.
// Its sole funciton is to connect disconect send and receive DNS messages.
// The DnsMessage ecodes and decodes DNS messages
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// A DNS Resolver sends a Dns Header and a DnsQuestion to a DNS server.
// Type DNS Header (tDNSHeader) is a component to store the header of
// a DNSResolver Query and Header DNS Server Response
// The ReEsolver sends the Server a header and the Sever returns it with various
// bits or values set.
// The DNS Header Contains the following
// The Most significant are the Rcodes (Return Codes) if the Rcode is 0 the
// the server was able to complete the requested task. Otherwise it contains
// an error code for what when wrong. The RCodes are listed in the
// WinshoeDnsResolver.pas file.
//
// fQdCount is the number of entries in the request from a resolver to a server.
// fQdCount would normally be set to 1.
//
// fAnCount is set by the server to the number of answers to the query.
//
// fNsCount is the number of entries in the Name Server list
//
// fArCount is the number of additional records.
//
// TDNSHeader exposes all the fields of a header... even those only set by
// the server so it can be used to build a DNS server
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// TDNS Question
// A DNS Question contains three pieces of data
// They are:
// QName : ShortString;
// QType : Word;
// QClass : Word;
//
// QName is either a domain name or an IP address.
// The QType is the type of question
// They are requests for
// A a Host Address
// NS Authoritative name server
// MD A mail destination obsolete use MX (OBSOLETE)
// MF A mail forwarder obsolete use MX (OBSOLETE)
// Name The canonical name for an alias
// SOA Marks the start of a zone of authority
// MB A mail box domain name (Experimental)
// MG A mail group member (Experimental)
// MR A mail Rename Domain Name (Experimental)
// NULL RR (Experimental)
// WKS A well known service description
// PTR A Domain Name Pointer (IP Addr) is question Answer is Domain name
// HINFO Host Information;
// MINFO Mailbox or Mail List Information;
// MX Mail Exchange
// TXT Text String;
// AXFR A Request for the Transfer of an entire zone;
// MAILB A request for mailbox related records (MB MG OR MR}
// MAILA A request for mail agent RRs (Obsolete see MX)
// Star A Request for all Records '*'
//
// Indy implements these requests by defining constant values.
// The identifier is preceeded by the letter c to show its a constant value
// ca = 1;
// cns =2 etc.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// TDNS Response
//-----------------------------------------------------------------------------
// The total Data returned by server in response to a query is stored the
// following Record structure.
// The Name, Type, and Class were defines as Qname, Qtype, and QClass above
// TTL is a dateTime Dword to tell when the information expires. This is uses
// By resolvers to cache data to hold network traffic to a mimimum.
// The Winshoe DNS Resolvers does not implement a cache.
// RData if defined above
// StarData is of indefinate length. the '*' Query type is send me everything
// It is Defined as an RData Type but a pascal variant record can not store
// a type String so we made a Star data string;
//------------------------------------------------------------------------------
// DNS Servers return data in various forms. the TDnsMessage parses this data
// and puts it in structures depending on its aType as shown in the Const
// QType definitions above.
// Data Structures for the Responses to the various Qtypes are defined next.
// The data structures are named for the types of questions and responses (QType)
//
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
//Type
// ptDNSResource = ^TDNSresource;
// tDNSResource = Record
// Name : ShortString;
// aType : Word;
// aClass : Word;
// TTL : DWord;
// RdLength : Word;
// RData : TRData;
// StarData: String;
// end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// The Returnd Data (RData) from a server in response to a query can be in
// several formats the following variant record is used to hold the returned
// data.
//-----------------------------------------------------------------------------
// TRdata = Record
// case Byte of
// 1 : (DomainName : ShortString);
// 2 : (HInfo : tHInfo);
// 3 : (MInfo : tMInfo);
// 4 : (MX : TMx);
// 5 : (SOA : TSOA);
// 6 : (A : DWord);
// 7 : (WKS : TWks);
// 8 : (Data : Array[0..4096] of Char);
// 9 : (HostAddrStr : ShortString);
// end;
//
//
// Type
// tHInfo = Record
// CPUStr : ShortString;
// OsStr : ShortString;
// end;
//
//
// tMInfo = Record
// RMailBox : ShortString;
// EMailBox : ShortString;
// end;
//
//
// tMX = Record
// Preference : Word; { This is the priority of this server }
// Exchange : ShortString; {this is the Domain name of the Mail Server }
// end;
//
//
// TSOA = Record
// MName : ShortString;
// RName : ShortString;
// Serial : DWord;
// Refresh : DWord;
// ReTry : Dword;
// Expire : Dword;
// Minimum : DWord;
// end;
//
//
// TWKS = Record
// Address : Dword;
// Protocol : Byte;
// Bits : Array[0..7] of Byte;
// end;
//------------------------------------------------------------------------------
// Header, question, and response objects make up the DNS Message object.
// the TDNSQuestionList is used to hold both the send and received queries
// in easy to handle pascal data structures
// A Question Consists of a Name, Atype and aClass.
// Name can be a domain name or an IP address depending on the type of
// question. Question and answer types and Classes are given constant names
// as defined in WinshoeDnsResolver.pas
//------------------------------------------------------------------------------
//
// The procedure CreateQueryPacket takes the Mesage header and questions and
// formats them in to a query packet for sending. When the Server responds
// with a reply packet the procedure DecodeReplyPacket formats the reply into
// the proper response data structures depending on the type of reponse.
//------------------------------------------------------------------------------
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls,
QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls,
{$ENDIF}
windows, messages, SysUtils, Classes, IdBaseComponent, IdComponent, IdUDPBase,
IdUDPClient, IdDNSResolver, IniFiles;
type
TResolverForm = class(TForm)
ConnectBtn: TBitBtn;
Memo: TMemo;
Edit1: TEdit;
QueryTypeListBox: TListBox;
Panel1: TPanel;
SelectedQueryLabel: TPanel;
DNSLabel: TPanel;
StatusBar: TStatusBar;
IdDNSResolver: TIdDNSResolver;
EdDNS: TEdit;
Label1: TLabel;
Label2: TLabel;
EdTimeOut: TEdit;
Label3: TLabel;
procedure ConnectBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure QueryTypeListBoxClick(Sender: TObject);
procedure EdTimeOutKeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
InProgress: Boolean;
aQueryType: Integer;
procedure ShowQueryType;
procedure DisplayResults;
public
{ Public declarations }
end;
var
ResolverForm: TResolverForm;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TResolverForm.FormCreate(Sender: TObject);
var
IniFile: TIniFile;
begin { FormCreate }
IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Resolve.ini');
with IniFile do
try
EdDNS.Text := ReadString('Resolver', 'DNS', '');
EdTimeOut.Text := IntToStr(ReadInteger('Resolver', 'TimeOut', 30000));
finally
Free;
end;
aQueryType := 1;
QueryTypeListBox.ItemIndex := 0;
ShowQueryType;
StatusBar.SimpleText := 'Current Domain Name Server is : ' +
IdDnsResolver.Host;
end; { FormCreate }
procedure TResolverForm.ShowQueryType;
begin { ShowQueryType }
with SelectedQueryLabel do
begin
Alignment := taCenter;
Caption := 'Selected Query Type is ' + GetQTypeStr(aQueryType);
Alignment := taCenter;
end;
if aQueryType = cPTR then
DnsLabel.Caption := 'Enter IP Address'
else
DnsLabel.Caption := 'Enter Domain Name';
end; { ShowQueryType }
procedure TResolverForm.QueryTypeListBoxClick(Sender: TObject);
begin { QueryTypeListBoxClick }
with QueryTypelistBox do
begin
if ItemIndex > -1 then
aQueryType := Succ(ItemIndex);
if aQueryType > 16 then
aQueryType := aQueryType + 235;
ShowQueryType;
end;
end; { QueryTypeListBoxClick }
procedure TResolverForm.DisplayResults;
var
DnsResource: TIdDNSResourceItem;
Idx: Integer;
procedure ShowaList;
procedure ShowSoa;
begin { ShowSoa }
with DnsResource.Rdata.SOA do
begin
Memo.Lines.Add('Primary Data Src : ' + MName);
Memo.Lines.Add('Responsible Mailbox : ' + Rname);
Memo.Lines.Add('Serial : ' + IntToStr(Serial) + ' Refresh : ' +
IntTostr(REfresh)
+ ' Retry : ' + IntTosTr(Retry));
Memo.Lines.Add('Expire : ' + IntTosTr(Expire) + ' Minimum : ' +
IntToStr(Minimum));
end;
end; { ShowSoa }
begin { ShowAList }
Memo.Lines.Add('Resource name is : ' + DnsResource.Name);
Memo.Lines.Add('Type is : ' + GetQTypeStr(DnsResource.aType) +
' Class is : ' + GetQClassStr(DnsResource.AClass));
case DnsResource.aType of
cA: Memo.Lines.Add('IP Address is : ' + DnsResource.Rdata.HostAddrStr
{DomainName});
cSoa: ShowSoa;
cPtr: Memo.Lines.Add('Domain name is : ' + DnsResource.Rdata.DomainName);
cMx: Memo.Lines.Add('MX Priority : ' +
IntToStr(DnsResource.Rdata.MX.Preference)
+ ' MX Server : ' + DNsResource.Rdata.MX.Exchange);
else
Memo.Lines.Add('Domain name is : ' + DnsResource.Rdata.DomainName);
end;
Memo.Lines.Add('');
end; { ShowAList }
begin { DisplayResults }
Memo.Lines.Clear;
with IdDNSResolver do
begin
if DnsAnList.Count > 0 then
begin
Memo.Lines.Add('Answer List' + #13 + #10);
for Idx := 0 to DnsAnList.Count - 1 do
begin
DnsResource := DnsAnList[Idx];
ShowAList;
end;
end;
Memo.Lines.Add('');
if DnsNsList.Count > 0 then
begin
Memo.Lines.Add('Authority List' + #13 + #10);
for Idx := 0 to DnsNsList.Count - 1 do
begin
DnsResource := DnsNsList[Idx];
ShowAList;
end;
end;
Memo.Lines.Add('');
if DnsArList.Count > 0 then
begin
Memo.Lines.Add('Additional Response List' + #13 + #10);
for Idx := 0 to DnsArList.Count - 1 do
begin
DnsResource := DnsArList[Idx];
ShowAList;
end;
end;
end;
end; { DisplayResults }
procedure TResolverForm.ConnectBtnClick(Sender: TObject);
begin { ConnectBtnClick }
if InProgress then
Exit;
InProgress := True;
try
Memo.Clear;
IdDnsResolver.Host := EdDNS.Text;
IdDnsResolver.ReceiveTimeout := StrToInt(EdTimeOut.Text);
StatusBar.SimpleText := 'Current Domain Name Server is : ' +
IdDnsResolver.Host;
IdDnsResolver.ClearVars;
with IdDnsREsolver.DNSHeader do
begin
// InitVars; { It's not neccessary because this call is in ClearVars}
// ID := Id +1; { Resolver/Server coordination Set to Random num on Create then inc'd }
Qr := False; { False is a query; True is a response}
Opcode := 0;
{ 0 is Query 1 is Iquery Iquery is send IP return <domainname>}
RD := True; { Request Recursive search}
QDCount := 1; { Just one Question }
end;
IdDnsREsolver.DNSQDList.Clear;
with IdDnsREsolver.DNSQDList.Add do {And the Question is ?}
begin
if Length(Edit1.Text) = 0 then
begin
if aQueryType = cPTR then
Qname := '209.239.140.2'
else
QName := 'mbssoftware.com';
end
else
QName := Edit1.Text;
QType := aQueryType;
QClass := cIN;
end;
IdDNSResolver.ResolveDNS;
DisplayResults;
finally
InProgress := False;
end;
end; { ConnectBtnClick }
procedure TResolverForm.EdTimeOutKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', '-', #8]) then
begin
Key := #0;
Beep;
end;
end;
procedure TResolverForm.FormDestroy(Sender: TObject);
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Resolve.ini');
with IniFile do
try
WriteString('Resolver', 'DNS', EdDNS.Text);
WriteInteger('Resolver', 'TimeOut', StrToInt(EdTimeOut.Text));
finally
Free;
end;
end;
end.
|
unit fOptionsReportsDefault;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Spin, fOptions, ComCtrls, ORFn, ORNet, ORCtrls,
ORDtTm, rCore, fBase508Form, VA508AccessibilityManager;
type
TfrmOptionsReportsDefault = class(TfrmBase508Form)
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edtDefaultMax: TCaptionEdit;
Bevel1: TBevel;
Bevel2: TBevel;
Panel1: TPanel;
btnOK: TButton;
btnReset: TButton;
lblDefaultText: TMemo;
btnCancel: TButton;
odcDfStart: TORDateBox;
odcDfStop: TORDateBox;
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure edtDefaultMaxExit(Sender: TObject);
procedure edtDefaultStartKeyPress(Sender: TObject; var Key: Char);
procedure edtDefaultEndKeyPress(Sender: TObject; var Key: Char);
procedure edtDefaultMaxKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure odcDfStartExit(Sender: TObject);
procedure odcDfStopExit(Sender: TObject);
procedure odcDfStartKeyPress(Sender: TObject; var Key: Char);
procedure odcDfStopKeyPress(Sender: TObject; var Key: Char);
procedure odcDfStartClick(Sender: TObject);
procedure odcDfStopClick(Sender: TObject);
procedure edtDefaultMaxClick(Sender: TObject);
private
{ Private declarations }
startDate, endDate, maxOcurs: integer;
sDate,eDate: String;
public
{ Public declarations }
procedure fillLabelText;
end;
var
frmOptionsReportsDefault: TfrmOptionsReportsDefault;
procedure DialogOptionsHSDefault(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
implementation
uses rOptions, uOptions, fReports, uCore, VAUtils;
{$R *.DFM}
procedure DialogOptionsHSDefault(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
var
frmOptionsReportsDefault: TfrmOptionsReportsDefault;
begin
frmOptionsReportsDefault := TfrmOptionsReportsDefault.Create(Application);
actiontype := 0;
try
with frmOptionsReportsDefault do
begin
if (topvalue < 0) or (leftvalue < 0) then
Position := poScreenCenter
else
begin
Position := poDesigned;
Top := topvalue;
Left := leftvalue;
end;
ResizeAnchoredFormToFont(frmOptionsReportsDefault);
ShowModal;
actiontype := btnOK.Tag;
end;
finally
frmOptionsReportsDefault.Release;
end;
end;
procedure TfrmOptionsReportsDefault.btnOKClick(Sender: TObject);
var
valueStartdate, valueEnddate, valueMax, values: string;
begin
if (odcDfStart.Text = sDate) and (odcDfStop.Text = eDate) and (not edtDefaultMax.Modified ) then
begin
Close;
Exit;
end;
if (odcDfStart.Text='') or (odcDfStop.Text='') or (edtDefaultMax.Text='') then
begin
InfoBox('You have to fill out each box, don''t leave blank!', 'Warning', MB_OK or MB_ICONWARNING);
Exit;
end;
valueStartdate := odcDfStart.RelativeTime;
valueEnddate := odcDfStop.RelativeTime;
valueMax := edtDefaultMax.Text;
values := valueStartdate + ';' + valueEnddate + ';' + valueMax;
if InfoBox('Do you really want to change all of the reports settings to the specified values as following?'
+#13#13' Start date: ' + odcDfStart.Text
+#13' End date: ' + odcDfStop.Text
+#13' Max occurences: ' + edtDefaultMax.Text
+#13#13' Click Yes, all of the CPRS reports except for health summary reports will have these same settings.',
'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
begin
rpcSetDefaultReportsSetting(values);
rpcActiveDefaultSetting;
frmReports.LoadTreeView;
with frmReports.tvReports do
begin
if Items.Count > 0 then
Selected := Items.GetFirstNode;
frmReports.tvReportsClick(Selected);
end;
Close;
end
else
begin
odcDfStart.Text := sDate;
odcDfStop.Text := eDate;
edtDefaultMax.Text := IntToStr(maxOcurs);
end;
end;
procedure TfrmOptionsReportsDefault.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmOptionsReportsDefault.btnResetClick(Sender: TObject);
var
startD,endD,maxOc: integer;
values,msg,stdate,endate: string;
today: TFMDateTime;
begin
rpcRetrieveDefaultSetting(startD,endD,maxOc,msg);
today := FMToday;
if msg = 'NODEFAULT' then
begin
InfoBox('No default report settings are available', 'Warning', MB_OK or MB_ICONWARNING);
Exit;
end;
//if (startD=startDate) and (endD=endDate) and (maxOc=maxOcurs) then
// Exit;
stdate := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, startD)));
endate := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, endD)));
if InfoBox('Do you really want to change all of the reports settings to the default values as following?'
+#13#13' Start date: ' + stdate
+#13' End date: ' + endate
+#13' Max occurences: ' + IntToStr(maxOc)
+#13#13' Click Yes, all of the CPRS reports except for health summary reports will have these same settings.',
'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
begin
rpcDeleteUserLevelReportsSetting;
odcDfStart.Text := stdate;
odcDfStop.Text := endate;
edtDefaultMax.Text := inttostr(maxOc);
values := odcDfStart.RelativeTime + ';' + odcDfStop.RelativeTime + ';' + edtDefaultMax.Text;
rpcSetDefaultReportsSetting(values);
rpcActiveDefaultSetting;
sDate := odcDfStart.Text;
eDate := odcDfStop.Text;
startDate := startD;
endDate := endD;
maxOcurs := maxOc;
fillLabelText;
frmReports.LoadTreeView;
with frmReports.tvReports do
begin
if Items.Count > 0 then
Selected := Items.GetFirstNode;
frmReports.tvReportsClick(Selected);
end;
end;
end;
procedure TfrmOptionsReportsDefault.edtDefaultMaxExit(Sender: TObject);
var
newValue: string;
I, code: integer;
begin
if edtDefaultMax.Modified then
begin
newValue := edtDefaultMax.Text;
if length(newValue) = 0 then
begin
InfoBox('Invalid value of max occurences', 'Warning', MB_OK or MB_ICONWARNING);
edtDefaultMax.Text := '100';
end;
if length(newValue) > 0 then
begin
Val(newValue, I, code);
if I = 0 then begin end; //added to keep compiler from generating a hint
if code <> 0 then
begin
InfoBox('Invalid value of max occurences', 'Warning', MB_OK or MB_ICONWARNING);
edtDefaultMax.Text := inttostr(maxOcurs);
end;
if code = 0 then
if strtoint(edtDefaultMax.Text) <= 0 then
begin
InfoBox('Invalid value of max occurences', 'Warning', MB_OK or MB_ICONWARNING);
edtDefaultMax.Text := inttostr(maxOcurs);
end;
end;
fillLabelText;
end;
end;
procedure TfrmOptionsReportsDefault.fillLabelText;
var
fromday,dayto: string;
begin
fromday := DateToStr(FMDateTimeToDateTime(odcDfStart.FMDateTime));
dayto := DateToStr(FMDateTimeToDateTime(odcDfStop.FMDateTime));
lblDefaultText.Text := 'All of the CPRS reports except for Health Summary reports will be displayed on the CPRS Reports tab from start date: '
+ fromday + ' to end date: ' + dayto + '.';
end;
procedure TfrmOptionsReportsDefault.edtDefaultStartKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsDefault.edtDefaultEndKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsDefault.edtDefaultMaxKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsDefault.FormCreate(Sender: TObject);
var
today : TFMDateTime;
begin
today := FMToday;
rpcGetDefaultReportsSetting(startDate,endDate,maxOcurs);
odcDfStart.text := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, startDate)));
sDate := odcDfStart.Text;
odcDfStop.text := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, endDate)));
eDate := odcDfStop.Text;
if maxOcurs <> 0 then
begin
edtDefaultMax.Text := inttostr(maxOcurs);
fillLabelText;
end;
lblDefaultText.Text := 'Click dots in boxes to set start and end dates. You can also input values directly.';
btnCancel.caption := 'Cancel';
if (not User.ToolsRptEdit) then // For users with Reports settings edit parameter not set.
begin
lblDefaultText.Text := 'Settings can only be viewed (no editing provided).';
btnReset.visible := false;
btnOK.visible := false;
btnCancel.caption := 'Close';
odcDfStart.readOnly := true;
odcDfStart.enabled := false;
odcDfStart.onExit := nil;
odcDfStart.onKeyPress := nil;
odcDfStop.readOnly := true;
odcDfStop.enabled := false;
odcDfStop.onExit := nil;
odcDfStop.onKeyPress := nil;
edtDefaultMax.readOnly := true;
end;
end;
procedure TfrmOptionsReportsDefault.odcDfStartExit(Sender: TObject);
const
TX_BAD_START = 'The start date is not valid.';
TX_STOPSTART = 'The start date must not be after the stop date.';
var
x,ErrMsg,datestart,datestop: String;
begin
if odcDfStart.text = '' then
begin
InfoBox(TX_BAD_START, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStart.Text := sDate;
odcDfStart.Setfocus;
odcDfStart.SelectAll;
exit;
end;
ErrMsg := '';
odcDfStart.Validate(x);
if Length(x) > 0 then
begin
ErrMsg := TX_BAD_START;
InfoBox(TX_BAD_START, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStart.Text := sDate;
odcDfStart.Setfocus;
odcDfStart.SelectAll;
exit;
end;
datestart := odcDfStart.RelativeTime;
datestop := odcDfStop.RelativeTime;
delete(datestart,1,1);
delete(datestop,1,1);
if StrToIntDef(datestop,0) < StrToIntDef(datestart,0) then
begin
InfoBox(TX_STOPSTART, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStart.Text := odcDfStop.Text;
odcDfStart.SetFocus;
odcDfStart.SelectAll;
exit;
end;
odcDfStart.Text := DateToStr(FMDateTimeToDateTime(odcDfStart.FMDateTime));
fillLabelText;
end;
procedure TfrmOptionsReportsDefault.odcDfStopExit(Sender: TObject);
const
TX_BAD_STOP = 'The stop date is not valid.';
TX_BAD_ORDER = 'The stop date must not be earlier than start date.';
var
x, ErrMsg,datestart,datestop: string;
begin
if odcDfStop.text = '' then
begin
InfoBox(TX_BAD_STOP, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStop.Text := eDate;
odcDfStop.Setfocus;
odcDfStop.SelectAll;
exit;
end;
ErrMsg := '';
odcDfStop.Validate(x);
if Length(x) > 0 then
begin
ErrMsg := TX_BAD_STOP;
InfoBox(TX_BAD_STOP, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStop.Visible := True;
odcDfStop.Text := eDate;
odcDfStop.Setfocus;
odcDfStop.SelectAll;
exit;
end;
datestart := odcDfStart.RelativeTime;
datestop := odcDfStop.RelativeTime;
delete(datestart,1,1);
delete(datestop,1,1);
if StrToIntDef(datestop,0) < StrToIntDef(datestart,0) then
begin
InfoBox(TX_BAD_ORDER, 'Warning', MB_OK or MB_ICONWARNING);
odcDfStop.Text := odcDfStart.Text;
odcDfStop.SetFocus;
odcDfStop.SelectAll;
exit;
end;
odcDfStop.Text := DateToStr(FMDateTimeToDateTime(odcDfStop.FMDateTime));
fillLabelText;
end;
procedure TfrmOptionsReportsDefault.odcDfStartKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
if Key = #27 then //Escape
begin
Key := #0;
btnCancel.Click;
end;
end;
procedure TfrmOptionsReportsDefault.odcDfStopKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
if Key = #27 then //Escape
begin
Key := #0;
btnCancel.Click;
end;
end;
procedure TfrmOptionsReportsDefault.odcDfStartClick(Sender: TObject);
begin
odcDfStart.SelectAll;
end;
procedure TfrmOptionsReportsDefault.odcDfStopClick(Sender: TObject);
begin
odcDfStop.SelectAll;
end;
procedure TfrmOptionsReportsDefault.edtDefaultMaxClick(Sender: TObject);
begin
edtDefaultMax.SelectAll;
end;
end.
|
unit RelatorioLookupDataUn;
interface
uses
SysUtils, Classes, DB, DBClient, osClientDataset, osLookupDataUn, FMTBcd,
Provider, osCustomDataSetProvider, osSQLDataSetProvider, SqlExpr,
osSQLDataSet;
type
TRelatorioLookupData = class(TosLookupData)
TipoRelatorioClientDataSet: TosClientDataset;
TipoRelatorioLookupDataSet: TosSQLDataSet;
TipoRelatorioLookupProvider: TosSQLDataSetProvider;
TipoRelatorioClientDataSetNOME: TStringField;
TemplateClientDataset: TosClientDataset;
TemplateLookupDataSet: TosSQLDataSet;
TemplateLookupProvider: TosSQLDataSetProvider;
TemplateLookupDataSetNOME: TStringField;
TemplateLookupDataSetITEM_ID: TIntegerField;
TemplateClientDatasetNOME: TStringField;
TemplateClientDatasetITEM_ID: TIntegerField;
FilterDefClientDataSet: TosClientDataset;
FilterDefLookupDataSet: TosSQLDataSet;
FilterDefLookupProvider: TosSQLDataSetProvider;
FilterDefLookupDataSetNAME: TStringField;
FilterDefClientDataSetNAME: TStringField;
FilterDefLookupDataSetIDXFILTERDEF: TIntegerField;
FilterDefClientDataSetIDXFILTERDEF: TIntegerField;
TipoRelatorioClientDataSetIDTIPORELATORIO: TIntegerField;
RelatorioClientDataset: TosClientDataset;
RelatorioDataSet: TosSQLDataSet;
RelatorioDataSetProvider: TosSQLDataSetProvider;
RelatorioClientDatasetIDRELATORIO: TIntegerField;
RelatorioClientDatasetTITULO: TStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
procedure GetData; override;
end;
var
RelatorioLookupData: TRelatorioLookupData;
implementation
uses acCustomSQLMainDataUn;
{$R *.dfm}
procedure TRelatorioLookupData.GetData;
begin
acCustomSQLMainData.RegisterRefreshTable(tnTipoRelatorio, TipoRelatorioClientDataSet);
end;
procedure TRelatorioLookupData.DataModuleCreate(Sender: TObject);
begin
inherited;
TipoRelatorioLookupDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
TemplateLookupDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
FilterDefLookupDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
RelatorioDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
end;
end.
|
unit CommonDataProvider.ADO;
interface
uses
CommonConnection.Intf, DB, ADODB, DBClient, SysUtils, classes, Variants,
Spring.Container, Spring.Services, UIRestore, NCADOConnection, DMBase,
DataSetHelper, uGlobal, CommonConnectionClass, Provider, CommonResourceStrings;
type
TNG_ADOConnection = class(TInterfacedObject, ICommonConnection)
private
FConnectionProperties : ICommonConnectionProperties;
FServerType : TDatabaseTypeOption;
FADOConnection, FDefaultConnection : TNCADOConnection;
// IDBConnection
function GetConnectionProperties : ICommonConnectionProperties;
function GetServerType: TDatabaseTypeOption;
procedure SetServerType(Value: TDatabaseTypeOption);
// Connection
function GetConnection : TObject;
procedure SetConnection(Value: TObject);
// Connected
function GetConnected: Boolean;
procedure SetConnected(Value: Boolean);
procedure SetConnectionString;
//Events
function GetAfterConnect: TNotifyEvent;
procedure SetAfterConnect(Value: TNotifyEvent);
function GetAfterDisconnect: TNotifyEvent;
procedure SetAfterDisconnect(Value: TNotifyEvent);
// Private
procedure CreateDefaultConnection;
procedure ReleaseDefaultConnection;
procedure CreateConnectionProperties;
procedure ReleaseConnectionProperties;
public
property Connection : TObject read GetConnection write SetConnection;
property Connected : Boolean read GetConnected write SetConnected;
constructor Create;
destructor Destroy; override;
end;
TNG_ADODataProvider = class(TInterfacedObject, IClientDataSetProvider)
private
FDBConnection : ICommonConnection;
FUseCloneDataProvider : Boolean;
procedure CreateDBConnection;
procedure ReleaseDBConnection;
function GetDBConnection : ICommonConnection;
// Private
procedure CreateFieldInfoCDS(ds : TDataSet; cdsMapping: TClientDataSet);
procedure AssignParamValues(qry : TADOQuery; cds, cdsMapping : TClientDataSet);
procedure AssignFieldValues(qry : TADOQuery; cds : TClientDataSet);
procedure AssignAutoIDValues(qry : TADOQuery; cds, cdsDelta : TClientDataSet);
// ICommonDataProvider
procedure SetConnectionString(const ServerType : TDatabaseTypeOption;
const HostName, DatabaseName, PortNumber,
LoginName, LoginPassword: string; OSAuthentication: Boolean);
function GetConnected: Boolean;
procedure SetConnected(Value: Boolean);
procedure GetExcelSheetNames(Sheets: TStringList);
procedure CheckCDS(cds : TClientDataSet; cdsName: string; CheckActive : Boolean);
function GetKeyFieldValue(cds: TClientDataSet; KeyFieldName: string) : Variant;
function LocateKeyField(cds: TClientDataSet; KeyFieldName: string; KeyValue: Variant) : Boolean;
function CanEditCDS(cds : TClientDataSet) : Boolean;
function CanInsertCDS(cds: TClientDataSet): Boolean;
function CanCancelCDS(cds: TClientDataSet): Boolean;
function CanSaveCDS(cds: TClientDataSet): Boolean;
function CanDeleteCDS(cds: TClientDataSet): Boolean;
procedure PostCDS(cds : TClientDataSet);
function GetServerDateTimeNow : TDateTime;
function TextToListText(s : string) : string;
function KeyFieldsToWhereAnd(TableAlias, KeyFields : string): string;
function FieldToParam(FieldName: string): string;
function AddFieldBrackets(FieldName: string): string;
function GetQueryText(QryIndex: Integer; WhereAnd: string): string;
function GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy : string) : string;
procedure CreateParam(cds : TClientDataSet; ParamName: string;
DataType : TFieldType; ParamValue : Variant);
procedure CreateBlobParam(cds : TClientDataSet; ParamName: string;
BlobType: TBlobType; Stream: TStream);
procedure CreateDefaultParams(cds: TClientDataSet; PageSize, PageNum: Integer);
procedure cdsOpenQryTextExt(QryText: string;
cds : TClientDataSet; ExecQry, CreateFieldDefs : Boolean;
LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsExecQryText(QryText: string; cds : TClientDataSet);
procedure cdsOpenQryText(QryText: string;
cds : TClientDataSet; CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsExecQryIndex(QryIndex : Integer; WhereAnd: string;
cds : TClientDataSet);
procedure cdsOpenQryIndex(QryIndex : Integer; WhereAnd: string;
cds : TClientDataSet; CreateFieldDefs : Boolean);
procedure cdsOpenTable(const TableName, TableAlias, WhereAnd, OrderBy: string;
cds : TClientDataSet; CreateFieldDefs : Boolean);
procedure cdsOpenTableExt(const TableName, TableAlias, WhereAnd, OrderBy : string;
cds : TClientDataSet; CreateFieldDefs : Boolean;
var DataSetState : TomControlState);
procedure cdsApplyUpdatesTable(cds : TClientDataSet;
TableName, TableAlias, WhereAnd, KeyFields : string);
procedure cdsApplyUpdates(cds : TClientDataSet);
function DataSetQryOpen(cds: TClientDataSet): TDataSet;
procedure cdsOpen(cds: TClientDataSet; CreateFieldDefs: Boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsOpenExt(cds: TClientDataSet; CreateFieldDefs: Boolean;
var DataSetState : TomControlState);
procedure cdsExec(cds: TClientDataSet);
procedure ExecSQL(SQL : string);
function ExecSQLInt(SQL : string): Integer;
function ExecSQLStr(SQL : string): String;
procedure BeginTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
procedure ResetQuery(cds : TClientDataSet);
procedure cdsParamGenerate(cds : TClientDataSet);
function CloneDataProvider: ICommonDataProvider<TClientDataSet>;
function GetUseCloneDataProvider: Boolean;
procedure SetUseCloneDataProvider(Value : Boolean);
function CheckTableAndField(const s: String): Boolean;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TNG_ADODataProvider }
function TNG_ADODataProvider.AddFieldBrackets(FieldName: string): string;
begin
Result := FieldName;
if FieldName <= ' ' then
exit;
if Result[1] <> '[' then
Result := '[' + Result;
if Result[length(Result)] <> ']' then
Result := Result + ']';
end;
procedure TNG_ADODataProvider.AssignAutoIDValues(qry: TADOQuery; cds, cdsDelta: TClientDataSet);
begin
qry.ForEachField(
function (Field: TField) : Boolean
begin
Result := (Field.DataType = ftAutoInc)
and (cds.FindField(Field.FieldName) <> nil)
and (not cdsDelta.FieldByName(Field.FieldName).IsNull);
end,
procedure (Field: TField)
begin
if cds.Locate(Field.FieldName, cdsDelta.FieldByName(Field.FieldName).Value, []) then
begin
cds.Edit;
cds.FieldByName(Field.FieldName).Value := Field.Value;
cds.Post;
end;
end,
nil
);
end;
procedure TNG_ADODataProvider.AssignFieldValues(qry: TADOQuery; cds: TClientDataSet);
begin
CheckFalseFmt(Assigned(qry) and qry.Active, uGlobal.Err_InvalidPointerInCodeRef,
['qry', 'TNG_ADODataProvider.AssignFieldValues']);
CheckFalseFmt(Assigned(cds), uGlobal.Err_InvalidPointerInCodeRef,
['cds', 'TNG_ADODataProvider.AssignFieldValues']);
cds.ForEachField(
function (Field: TField) : Boolean
begin
Result := (qry.FindField(Field.FieldName) <> nil)
and ((not Field.IsNull) or (Field.NewValue <> Unassigned));
end,
procedure (Field: TField)
begin
if Field.IsBlob then
TBlobField(qry.FieldByName(Field.FieldName)).Assign(Field)
else if (Field.DataType <> ftAutoInc) and
(qry.FieldByName(Field.FieldName).DataType <> ftAutoInc) then
qry.FieldByName(Field.FieldName).Value := Field.Value;
end,
nil
);
end;
procedure TNG_ADODataProvider.AssignParamValues(qry: TADOQuery; cds, cdsMapping: TClientDataSet);
var
i : Integer;
QryParam : TParameter;
begin
for i := 0 to qry.Parameters.Count - 1 do
begin
QryParam := qry.Parameters[i];
if cdsMapping.Locate('ParamName', QryParam.Name, [loCaseInsensitive]) then
QryParam.Value := cds.Fields[cdsMapping.FieldByName('FieldIndex').AsInteger].Value;
end;
end;
procedure TNG_ADODataProvider.BeginTransaction;
begin
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
TNCADOConnection(FDBConnection.Connection).BeginTrans;
end;
function TNG_ADODataProvider.CanCancelCDS(cds: TClientDataSet): Boolean;
begin
Result := TDataSet.CanCancelDataSet(cds);
end;
function TNG_ADODataProvider.CanDeleteCDS(cds: TClientDataSet): Boolean;
begin
Result := TDataSet.CanDeleteDataSet(cds);
end;
function TNG_ADODataProvider.CanEditCDS(cds: TClientDataSet): Boolean;
begin
Result := TDataSet.CanEditDataSet(cds);
end;
function TNG_ADODataProvider.CanInsertCDS(cds: TClientDataSet): Boolean;
begin
Result := TDataSet.CanInsertDataSet(cds);
end;
function TNG_ADODataProvider.CanSaveCDS(cds: TClientDataSet): Boolean;
begin
Result := TDataSet.CanSaveDataSet(cds);
end;
procedure TNG_ADODataProvider.cdsApplyUpdates(cds: TClientDataSet);
begin
//
end;
procedure TNG_ADODataProvider.cdsApplyUpdatesTable(cds: TClientDataSet;
TableName, TableAlias, WhereAnd, KeyFields: string);
var
qry : TADOQuery; iqry : IObjCleaner;
cdsDelta, cdsDelta2 : TClientDataSet;
icdsDelta, icdsDelta2 : IObjCleaner;
cdsMapping : TClientDataSet; icdsMapping : IObjCleaner;
begin
PostCDS(cds);
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
if not (assigned(cds) and cds.Active and (cds.ChangeCount > 0)) then
exit;
// Create vars
qry := TNCADOConnection(FDBConnection.Connection).CreateQuery; iqry := CreateObjCleaner(qry);
cdsDelta := TClientDataSet.Create(nil); icdsDelta := CreateObjCleaner(cdsDelta);
cdsDelta2 := TClientDataSet.Create(nil); icdsDelta2 := CreateObjCleaner(cdsDelta2);
cdsMapping := TClientDataSet.Create(nil); icdsMapping := CreateObjCleaner(cdsMapping);
// Initialize vars
cdsDelta.Data := cds.Delta;
cdsDelta2.Data := cds.Delta;
qry.SQL.Text := GetQueryTextTable(TableName, TableAlias, WhereAnd, KeyFields, '');
CreateFieldInfoCDS(cds, cdsMapping);
cdsDelta.ForEachRecord(nil,
procedure (ds : TDataSet)
begin
qry.Close;
if cdsDelta.UpdateStatus = TUpdateStatus.usModified then
begin
cdsDelta2.RecNo := cdsDelta.RecNo - 1;
AssignParamValues(qry, cdsDelta2, cdsMapping);
qry.Open;
if not qry.EOF then
begin
qry.Edit;
AssignFieldValues(qry, cdsDelta);
qry.Post;
end;
end
else if cdsDelta.UpdateStatus = TUpdateStatus.usInserted then
begin
AssignParamValues(qry, cdsDelta, cdsMapping);
qry.Open;
qry.Append;
AssignFieldValues(qry, cdsDelta);
qry.Post;
AssignAutoIDValues(qry, cds, cdsDelta);
end
else if cdsDelta.UpdateStatus = TUpdateStatus.usDeleted then
begin
AssignParamValues(qry, cdsDelta, cdsMapping);
qry.Open;
while not qry.EOF do
qry.Delete;
end
end
);
cds.MergeChangeLog;
end;
procedure TNG_ADODataProvider.cdsExec(cds: TClientDataSet);
begin
try
cdsExecQryText(cds.CommandText, cds);
except
on E:Exception do
raise EGlobalException.Create(E.Message);
end;
end;
procedure TNG_ADODataProvider.cdsExecQryIndex(QryIndex: Integer;
WhereAnd: string; cds: TClientDataSet);
begin
cdsExecQryText(GetQueryText(QryIndex, WhereAnd), cds);
end;
procedure TNG_ADODataProvider.cdsExecQryText(QryText: string;
cds: TClientDataSet);
begin
cdsOpenQryTextExt(QryText, cds, True, False);
end;
function TNG_ADODataProvider.DataSetQryOpen(cds: TClientDataSet) : TDataSet;
var
qry : TADOQuery; //iqry : IObjCleaner;
QryText: string;
i : Integer;
qryParam : TParameter;
cdsParam : TParam;
begin
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
QryText := Trim(cds.CommandText);
uGlobal.CheckFalseFmt(QryText > ' ', uGlobal.Err_InvalidPointerInCodeRef,
['QryText', 'TNG_ADODataProvider.DataSetQryOpen']);
qry := (FDBConnection as TNG_ADOConnection).FADOConnection.CreateQuery; //iqry := CreateObjCleaner(qry);
qry.SQL.Text := QryText;
for i := 0 to qry.Parameters.Count - 1 do
begin
qryParam := qry.Parameters[i];
cdsParam := cds.Params.FindParam(qryParam.Name);
if Assigned(cdsParam) then
begin
if cdsParam.DataType = ftBlob then
qryParam.Assign(cdsParam)
else
qryParam.Value := cdsParam.Value;
end;
end;
qry.SQL.Text := StringReplace(qry.SQL.Text, '--WHERE--', ' ', [rfIgnoreCase]);
qry.Open;
Result := qry;
end;
procedure TNG_ADODataProvider.cdsOpen(cds: TClientDataSet; CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
begin
cdsOpenQryText(cds.CommandText, cds, CreateFieldDefs, LAppend, LUseDP);
end;
procedure TNG_ADODataProvider.cdsOpenExt(cds: TClientDataSet;
CreateFieldDefs: Boolean; var DataSetState: TomControlState);
begin
DataSetState := ocsLoading;
try
cdsOpen(cds, CreateFieldDefs);
finally
DataSetState := ocsIdle;
end;
end;
procedure TNG_ADODataProvider.cdsOpenQryIndex(QryIndex: Integer; WhereAnd: string;
cds : TClientDataSet; CreateFieldDefs : Boolean);
begin
cdsOpenQryText(GetQueryText(QryIndex, WhereAnd), cds, CreateFieldDefs);
end;
procedure TNG_ADODataProvider.cdsOpenQryText(QryText: string;
cds: TClientDataSet; CreateFieldDefs : boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
begin
cdsOpenQryTextExt(QryText, cds, False, CreateFieldDefs, LAppend, LUseDP);
end;
procedure TNG_ADODataProvider.cdsOpenQryTextExt(QryText: string;
cds: TClientDataSet; ExecQry, CreateFieldDefs: Boolean;
LAppend: Boolean = False; LUseDP: Boolean = False);
procedure CopyQryToCDS(q: TADOQuery; c: TClientDataSet);
var
DP: TDataSetProvider; iDP: IObjCleaner;
begin
DP := TDataSetProvider.Create(nil); iDP := CreateObjCleaner(DP);
DP.DataSet := q;
c.Data := DP.Data;
end;
var
qry : TADOQuery; iqry : IObjCleaner;
cdsStructure : TClientDataSet; icdsStructure : IObjCleaner;
i : Integer;
qryParam : TParameter;
cdsParam : TParam;
cdsEvents : TClientDataSet; icdsEvents : IObjCleaner;
sRowXml, str: string;
begin
if CreateFieldDefs then
LAppend := False;
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
uGlobal.CheckFalseFmt(Assigned(cds), uGlobal.Err_InvalidPointerInCodeRef,
['cds', 'TNG_ADODataProvider.cdsOpenQryTextExt']);
QryText := Trim(QryText);
uGlobal.CheckFalseFmt(QryText > ' ', uGlobal.Err_InvalidPointerInCodeRef,
['QryText', 'TNG_ADODataProvider.cdsOpenQryTextExt']);
cdsStructure := TClientDataSet.Create(nil); icdsStructure := CreateObjCleaner(cdsStructure);
qry := (FDBConnection as TNG_ADOConnection).FADOConnection.CreateQuery; iqry := CreateObjCleaner(qry);
qry.SQL.Text := QryText;
for i := 0 to qry.Parameters.Count - 1 do
begin
qryParam := qry.Parameters[i];
cdsParam := cds.Params.FindParam(qryParam.Name);
if Assigned(cdsParam) then
begin
if cdsParam.DataType = ftBlob then
qryParam.Assign(cdsParam)
else
qryParam.Value := cdsParam.Value;
end;
end;
qry.SQL.Text := StringReplace(qry.SQL.Text, '--WHERE--', ' ', [rfIgnoreCase]);
if ExecQry then
begin
qry.ExecSQL;
exit;
end;
qry.Open;
// if qry.RecordCount > 10000 then
// begin
// str := 'SQL statement:' + #13#10 + #13#10 + qry.SQL.Text;
// if Length(str) > 200 then
// str := Copy(str, 1, 200) + #13#10 + '...';
// raise EGlobalException.Create(RS_LargeSizeDataSetErr + #13#10 + #13#10 + Trim(str));
// end;
cdsEvents := TClientDataSet.Create(nil); icdsEvents := CreateObjCleaner(cdsEvents);
try
cdsEvents.CopyDataSetEvents(cds, True);
if not LAppend then
begin
cds.Close;
if CreateFieldDefs then
cds.CopyFieldDefs(qry)
else
cds.CreateDataSet;
end;
cdsStructure.CloneCursor(cds, True, False);
// Backup ReadOnly property
cds.ForEachField(
function (Field: TField) : Boolean
begin
Result := Field.ReadOnly;
end,
procedure (Field: TField)
begin
Field.ReadOnly := False;
end,
nil
);
if LUseDP then
CopyQryToCDS(qry, cds)
else
cds.CopyDataSet(qry);
cds.MergeChangeLog;
// Restore ReadOnly property
cdsStructure.ForEachField(
function (Field : TField): Boolean
begin
Result := Field.ReadOnly;
end,
procedure (Field: TField)
begin
cds.FieldByName(Field.FieldName).ReadOnly := True;
end,
nil
);
finally
cds.CopyDataSetEvents(cdsEvents);
end;
if cds.RecNo > 1 then
cds.First;
end;
procedure TNG_ADODataProvider.cdsOpenTable(const TableName, TableAlias, WhereAnd, OrderBy: string;
cds: TClientDataSet; CreateFieldDefs : Boolean);
begin
cdsOpenQryText(GetQueryTextTable(TableName, TableAlias, WhereAnd, '', OrderBy), cds, CreateFieldDefs);
end;
procedure TNG_ADODataProvider.cdsOpenTableExt(const TableName, TableAlias,
WhereAnd, OrderBy: string; cds: TClientDataSet; CreateFieldDefs: Boolean;
var DataSetState: TomControlState);
begin
DataSetState := ocsLoading;
try
cdsOpenTable(TableName, TableAlias, WhereAnd, OrderBy,
cds, CreateFieldDefs);
finally
DataSetState := ocsIdle;
end;
end;
procedure TNG_ADODataProvider.cdsParamGenerate(cds: TClientDataSet);
var
qry : TADOQuery; iqry : IObjCleaner;
i : Integer;
qryParam : TParameter;
cdsParam : TParam;
begin
if cds.CommandText = '' then
Exit;
cds.Params.Clear;
qry := (FDBConnection as TNG_ADOConnection).FADOConnection.CreateQuery; iqry := CreateObjCleaner(qry);
qry.SQL.Text := cds.CommandText;
for i := 0 to qry.Parameters.Count - 1 do
begin
qryParam := qry.Parameters[i];
cdsParam := cds.Params.FindParam(qryParam.Name);
if not Assigned(cdsParam) then
begin
cdsParam := cds.Params.AddParameter;
cdsParam.Name := qryParam.Name;
end;
cdsParam.DataType := qryParam.DataType;
end;
end;
procedure TNG_ADODataProvider.ReleaseDBConnection;
begin
GlobalContainer.Release(FDBConnection);
FDBConnection := nil;
end;
procedure TNG_ADODataProvider.ResetQuery(cds: TClientDataSet);
begin
if not Assigned(cds) then
exit;
cds.Close;
cds.Params.Clear;
end;
procedure TNG_ADODataProvider.CheckCDS(cds: TClientDataSet; cdsName: string; CheckActive: Boolean);
begin
TDataSet.CheckDataSet(cds, cdsName, CheckActive);
end;
function TNG_ADODataProvider.CheckTableAndField(const s: String): Boolean;
begin
Result := TNCADOConnection(FDBConnection.Connection).CheckTableAndField(s);
end;
function TNG_ADODataProvider.CloneDataProvider: ICommonDataProvider<TClientDataSet>;
begin
Result := ServiceLocator.GetService<ICommonDataProvider<TClientDataSet>>('ADOConnection');
Result.DBConnection.ConnectionProperties.Assign(FDBConnection.ConnectionProperties);
Result.DBConnection.SetConnectionString;
Result.Connected := GetConnected;
end;
procedure TNG_ADODataProvider.CommitTransaction;
begin
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
if TNCADOConnection(FDBConnection.Connection).InTransaction then
TNCADOConnection(FDBConnection.Connection).CommitTrans;
end;
procedure TNG_ADODataProvider.CreateFieldInfoCDS(ds: TDataSet; cdsMapping: TClientDataSet);
begin
CheckFalseFmt(Assigned(ds) and ds.Active, uGlobal.Err_InvalidPointerInCodeRef,
['ds', 'TNG_ADODataProvider.CreateFieldInfoCDS']);
CheckFalseFmt(Assigned(cdsMapping), uGlobal.Err_InvalidPointerInCodeRef,
['cdsMapping', 'TNG_ADODataProvider.CreateFieldInfoCDS']);
cdsMapping.Close;
cdsMapping.FieldDefs.Clear;
cdsMapping.FieldDefs.Add('FieldName', ftWideString, 50, False);
cdsMapping.FieldDefs.Add('DisplayName', ftWideString, 50, True);
cdsMapping.FieldDefs.Add('ParamName', ftWideString, 50, True);
cdsMapping.FieldDefs.Add('FieldIndex', ftInteger, 0, True);
cdsMapping.CreateDataSet;
// FieldName
ds.ForEachField(nil,
procedure (Field : TField)
begin
cdsMapping.Append;
cdsMapping.FieldByName('FieldName').Value := Field.FieldName;
cdsMapping.FieldByName('DisplayName').Value := Field.DisplayName;
cdsMapping.FieldByName('ParamName').Value := FieldToParam(Field.FieldName);
cdsMapping.FieldByName('FieldIndex').Value := Field.Index;
cdsMapping.Post;
end,
nil
);
end;
procedure TNG_ADODataProvider.CreateParam(cds: TClientDataSet;
ParamName: string; DataType: TFieldType; ParamValue: Variant);
var
p : TParam;
begin
CheckFalseFmt(Assigned(cds), uGlobal.Err_FalseConditionInCodeRef, ['cds', 'TNG_ADODataProvider.CreateParam']);
if cds.Params.FindParam(ParamName) <> nil then
p := cds.Params.FindParam(ParamName)
else
begin
p := cds.Params.AddParameter;
p.Name := ParamName;
end;
p.DataType := DataType;
p.Value := ParamValue;
end;
destructor TNG_ADODataProvider.Destroy;
begin
ReleaseDBConnection;
inherited;
end;
constructor TNG_ADODataProvider.Create;
begin
inherited;
CreateDBConnection;
end;
procedure TNG_ADODataProvider.CreateBlobParam(cds : TClientDataSet;
ParamName: string; BlobType: TBlobType; Stream: TStream);
var
p : TParam;
begin
CheckFalseFmt(Assigned(cds), uGlobal.Err_FalseConditionInCodeRef, ['cds', 'TNG_ADODataProvider.CreateBlobParam']);
if cds.Params.FindParam(ParamName) <> nil then
p := cds.Params.FindParam(ParamName)
else
begin
p := cds.Params.AddParameter;
p.Name := ParamName;
end;
p.DataType := BlobType;
P.LoadFromStream(Stream, BlobType);
end;
procedure TNG_ADODataProvider.CreateDBConnection;
begin
FDBConnection := TNG_ADOConnection.Create;
end;
procedure TNG_ADODataProvider.CreateDefaultParams(cds: TClientDataSet; PageSize,
PageNum: Integer);
begin
CheckCDS(cds, '', False);
CreateParam(cds, 'PageSize', ftInteger, PageSize);
CreateParam(cds, 'PageNum', ftInteger, PageNum);
end;
procedure TNG_ADODataProvider.ExecSQL(SQL: string);
var
cds : TClientDataSet; icds : IObjCleaner;
begin
cds := TClientDataSet.Create(nil); icds := CreateObjCleaner(cds);
cds.CommandText := SQL;
cdsExec(cds);
end;
function TNG_ADODataProvider.ExecSQLInt(SQL: string): Integer;
var
qry : TADOQuery; iqry : IObjCleaner;
begin
Result := -1;
try
qry := (FDBConnection as TNG_ADOConnection).FADOConnection.CreateQuery; iqry := CreateObjCleaner(qry);
qry.SQL.Text := SQL;
qry.Open;
Result := qry.Fields[0].AsInteger;
except
on E:Exception do
raise EGlobalException.Create(E.Message);
end;
end;
function TNG_ADODataProvider.ExecSQLStr(SQL: string): String;
var
qry : TADOQuery; iqry : IObjCleaner;
begin
Result := '';
try
qry := (FDBConnection as TNG_ADOConnection).FADOConnection.CreateQuery; iqry := CreateObjCleaner(qry);
qry.SQL.Text := SQL;
qry.Open;
Result := qry.Fields[0].AsWideString;
except
on E:Exception do
raise EGlobalException.Create(E.Message);
end;
end;
function TNG_ADODataProvider.FieldToParam(FieldName: string): string;
begin
Result := StringReplace(FieldName, ' ', '_', [rfReplaceAll]);
Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
Result := StringReplace(Result, '?', '_', [rfReplaceAll]);
Result := StringReplace(Result, '-', '_', [rfReplaceAll]);
end;
function TNG_ADODataProvider.GetConnected: Boolean;
begin
Result := FDBConnection.Connected;
end;
function TNG_ADODataProvider.GetDBConnection: ICommonConnection;
begin
Result := FDBConnection;
end;
procedure TNG_ADODataProvider.GetExcelSheetNames(Sheets: TStringList);
begin
CheckFalseFmt(Assigned(Sheets), uGlobal.Err_InvalidPointerInCodeRef, ['Sheets', 'TNG_ADODataProvider.GetExcelSheetNames']);
NCADOConnection.GetExcelSheetNames((FDBConnection as TNG_ADOConnection).FADOConnection, Sheets);
end;
function TNG_ADODataProvider.GetKeyFieldValue(cds: TClientDataSet; KeyFieldName: string): Variant;
begin
Result := TDataSet(cds).GetKeyFieldValue(cds, KeyFieldName);
end;
function TNG_ADODataProvider.GetQueryText(QryIndex: Integer; WhereAnd: string): string;
begin
Result := StringReplace(DataModuleBase.GetQueryText(QryIndex),
'--WHEREAND--', WhereAnd, [rfIgnoreCase, rfReplaceAll]);
end;
function TNG_ADODataProvider.GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy: string): string;
begin
CheckFalseFmt(TableName > ' ', uGlobal.Err_InvalidPointerInCodeRef, ['TableName', 'TNG_ADODataProvider.GetQueryTextTable']);
// select * from
Result := Format('select * from [%s] ', [TableName]);
if TableAlias > ' ' then
Result := Result + ' ' + TableAlias;
Result := Result + #13#10' where 1 = 1';
if KeyFields > ' ' then
Result := Result + #13#10 + KeyFieldsToWhereAnd(TableAlias, KeyFields);
// WhereAnd
if WhereAnd > ' ' then
begin
if LowerCase(copy(WhereAnd, 1, 3)) <> 'and' then
Result := Result + #13#10'and ' + WhereAnd + ' '
else
Result := Result + #13#10 + WhereAnd + ' ';
end;
// OrderBy
if OrderBy > ' ' then
Result := Result + #13#10' order by ' + OrderBy;
end;
function TNG_ADODataProvider.GetServerDateTimeNow: TDateTime;
var
cds : TClientDataSet; icds : IObjCleaner;
begin
cds := TClientDataSet.Create(nil); icds := CreateObjCleaner(cds);
cds.CommandText := 'select getDate()';
cdsOpen(cds, True);
Result := cds.Fields[0].AsDateTime;
end;
function TNG_ADODataProvider.GetUseCloneDataProvider: Boolean;
begin
Result := FUseCloneDataProvider;
end;
function TNG_ADODataProvider.KeyFieldsToWhereAnd(TableAlias, KeyFields: string): string;
var
lstKeyFields : TStringList; ilstKeyFields : IObjCleaner;
i : Integer;
Alias : string;
begin
Result := '';
if KeyFields <= ' ' then
exit;
lstKeyFields := TStringList.Create; ilstKeyFields := CreateObjCleaner(lstKeyFields);
lstKeyFields.Text := TextToListText(KeyFields);
if TableAlias > ' ' then
Alias := TableAlias + '.'
else
Alias := '';
for i := 0 to lstKeyFields.Count - 1 do
Result := Result + #13#10' and ' + Alias + AddFieldBrackets(lstKeyFields[i]) +
' = :' + FieldToParam(lstKeyFields[i]);
end;
function TNG_ADODataProvider.LocateKeyField(cds: TClientDataSet;
KeyFieldName: string; KeyValue: Variant): Boolean;
begin
Result := TDataSet.LocateKeyField(cds, KeyFieldName, KeyValue);
end;
procedure TNG_ADODataProvider.PostCDS(cds: TClientDataSet);
begin
TDataSet.PostDataSet(cds);
end;
procedure TNG_ADODataProvider.RollbackTransaction;
begin
uGlobal.CheckFalse(GetConnected, RS_DatabaseNotConnected);
if TNCADOConnection(FDBConnection.Connection).InTransaction then
TNCADOConnection(FDBConnection.Connection).RollbackTrans;
end;
procedure TNG_ADODataProvider.SetConnected(Value: Boolean);
begin
FDBConnection.Connected := Value;
end;
procedure TNG_ADODataProvider.SetConnectionString(
const ServerType: TDatabaseTypeOption; const HostName, DatabaseName,
PortNumber, LoginName, LoginPassword: string; OSAuthentication: Boolean);
begin
FDBConnection.ServerType := ServerType;
FDBConnection.ConnectionProperties.ServerName := HostName;
FDBConnection.ConnectionProperties.DatabaseName := DatabaseName;
FDBConnection.ConnectionProperties.PortNumber := PortNumber;
FDBConnection.ConnectionProperties.ServerLogin := LoginName;
FDBConnection.ConnectionProperties.ServerPassword := LoginPassword;
FDBConnection.ConnectionProperties.OSAuthentication := OSAuthentication;
FDBConnection.SetConnectionString;
end;
procedure TNG_ADODataProvider.SetUseCloneDataProvider(Value: Boolean);
begin
FUseCloneDataProvider := Value;
end;
function TNG_ADODataProvider.TextToListText(s: string): string;
begin
Result := StringReplace(StringReplace(s, ', ', '', [rfReplaceAll]),
',', #13#10, [rfReplaceAll]);
end;
{ TNG_ADOConnection }
constructor TNG_ADOConnection.Create;
begin
inherited;
CreateDefaultConnection;
CreateConnectionProperties;
end;
procedure TNG_ADOConnection.CreateConnectionProperties;
begin
FConnectionProperties := ServiceLocator.GetService<ICommonConnectionProperties>;
end;
procedure TNG_ADOConnection.CreateDefaultConnection;
begin
FDefaultConnection := TNCADOConnection.Create(nil);
FDefaultConnection.LoginPrompt := False;
FADOConnection := FDefaultConnection;
end;
destructor TNG_ADOConnection.Destroy;
begin
ReleaseConnectionProperties;
ReleaseDefaultConnection;
inherited;
end;
function TNG_ADOConnection.GetAfterConnect: TNotifyEvent;
begin
Result := FADOConnection.AfterConnect;
end;
function TNG_ADOConnection.GetAfterDisconnect: TNotifyEvent;
begin
Result := FADOConnection.AfterDisconnect;
end;
function TNG_ADOConnection.GetConnected: Boolean;
begin
Result := FADOConnection.Connected;
end;
function TNG_ADOConnection.GetConnection: TObject;
begin
Result := FADOConnection;
end;
function TNG_ADOConnection.GetConnectionProperties: ICommonConnectionProperties;
begin
Result := FConnectionProperties;
end;
function TNG_ADOConnection.GetServerType: TDatabaseTypeOption;
begin
Result := FServerType
end;
procedure TNG_ADOConnection.ReleaseConnectionProperties;
begin
if Assigned(FConnectionProperties) then
begin
{$IFNDEF AUTOREFCOUNT}
GlobalContainer.Release(FConnectionProperties);
{$ENDIF}
FConnectionProperties := nil;
end;
end;
procedure TNG_ADOConnection.ReleaseDefaultConnection;
begin
FreeAndNil(FDefaultConnection);
end;
procedure TNG_ADOConnection.SetAfterConnect(Value: TNotifyEvent);
begin
FADOConnection.AfterConnect := Value;
end;
procedure TNG_ADOConnection.SetAfterDisconnect(Value: TNotifyEvent);
begin
FADOConnection.AfterDisconnect := Value;
end;
procedure TNG_ADOConnection.SetConnected(Value: Boolean);
begin
if Value then
FADOConnection.Open
else
begin
if FADOConnection.Connected then
FADOConnection.CloseConnection;
end;
end;
procedure TNG_ADOConnection.SetConnection(Value: TObject);
begin
CheckFalseFmt(Assigned(Value) and (Value is TNCADOConnection),
Err_InvalidPointerInCodeRef, ['Value', 'TNG_ADOConnection.SetConnection']);
ReleaseDefaultConnection;
FADOConnection := TNCADOConnection(Value);
end;
procedure TNG_ADOConnection.SetConnectionString;
begin
if FServerType = dtoSQLServer then
(FADOConnection as ISQLServerConnection).SetSQLServerConnectionString(
FConnectionProperties.ServerName,
FConnectionProperties.DatabaseName,
FConnectionProperties.ServerLogin,
FConnectionProperties.ServerPassword,
FConnectionProperties.OSAuthentication)
else if FServerType = dtoExcel then
(FADOConnection as IExcelConnection).SetExcelConnectionString(FConnectionProperties.DatabaseName);
FConnectionProperties.ConnectionString := FADOConnection.ConnectionString;
end;
procedure TNG_ADOConnection.SetServerType(Value: TDatabaseTypeOption);
begin
FServerType := Value;
end;
initialization
GlobalContainer.RegisterType<TNG_ADODataProvider>.Implements<IClientDataSetProvider>(CDP_IDENT_ADO);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FileX<p>
Simple X format support for Delphi (Microsoft's favorite format)<p>
<b>History : </b><font size=-1><ul>
<li>17/04/13 - YP - Warn user if file content unparsable (http://paulbourke.net/dataformats/directx/)
<li>04/10/10 - Yar - Fixed TDXFileHeader type (thanks JironBach)
<li>07/11/09 - DaStr - Initial version (Added from the GLScene-Lazarus SVN)
</ul></font>
}
unit FileX;
interface
{$i GLScene.inc}
uses
Classes, SysUtils,
// GLScene
GLVectorTypes, GLVectorGeometry, GLVectorLists, GLPersistentClasses, GLUtils;
type
TDXNode = class;
TDXFileHeader = record
Magic : array[0..3] of AnsiChar;
Major : array[0..1] of AnsiChar;
Minor : array[0..1] of AnsiChar;
FileType : array[0..3] of AnsiChar;
FloatType : array[0..3] of AnsiChar;
end;
TDXNode = class (TList)
private
FName,
FTypeName : String;
FOwner : TDXNode;
function GetItem(index : Integer) : TDXNode;
public
constructor CreateOwned(AOwner : TDXNode);
constructor Create; virtual;
procedure Clear; override;
property Name : String read FName write FName;
property TypeName : String read FTypeName write FTypeName;
property Owner : TDXNode read FOwner;
property Items[index : Integer] : TDXNode read GetItem;
end;
TDXMaterialList = class;
TDXMaterial = class (TPersistentObject)
private
FDiffuse : TVector4f;
FSpecPower : Single;
FSpecular,
FEmissive : TVector3f;
FTexture : String;
public
constructor CreateOwned(AOwner : TDXMaterialList);
property Diffuse : TVector4f read FDiffuse write FDiffuse;
property SpecPower : Single read FSpecPower write FSpecPower;
property Specular : TVector3f read FSpecular write FSpecular;
property Emissive : TVector3f read FEmissive write FEmissive;
property Texture : String read FTexture write FTexture;
end;
TDXMaterialList = class (TDXNode)
private
function GetMaterial(index : Integer) : TDXMaterial;
public
property Items[index : Integer] : TDXMaterial read GetMaterial;
end;
TDXFrame = class (TDXNode)
private
FMatrix : TMatrix;
public
constructor Create; override;
function GlobalMatrix : TMatrix;
property Matrix : TMatrix read FMatrix write FMatrix;
end;
TDXMesh = class (TDXNode)
private
FVertices,
FNormals,
FTexCoords : TAffineVectorList;
FVertexIndices,
FNormalIndices,
FMaterialIndices,
FVertCountIndices : TIntegerList;
FMaterialList : TDXMaterialList;
public
constructor Create; override;
destructor Destroy; override;
property Vertices : TAffineVectorList read FVertices;
property Normals : TAffineVectorList read FNormals;
property TexCoords : TAffineVectorList read FTexCoords;
property VertexIndices : TIntegerList read FVertexIndices;
property NormalIndices : TIntegerList read FNormalIndices;
property MaterialIndices : TIntegerList read FMaterialIndices;
property VertCountIndices : TIntegerList read FVertCountIndices;
property MaterialList : TDXMaterialList read FMaterialList;
end;
TDXFile = class
private
FRootNode : TDXNode;
FHeader : TDXFileHeader;
protected
procedure ParseText(Stream : TStream);
procedure ParseBinary(Stream : TStream);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromStream(Stream : TStream);
//procedure SaveToStream(Stream : TStream);
property Header : TDXFileHeader read FHeader;
property RootNode : TDXNode read FRootNode;
end;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
implementation
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Text parsing functions
// ----------------------------------------------------------------------
// RemoveComments
//
procedure RemoveComments(Text : TStringList);
var
i, comment : Integer;
begin
for i:=0 to Text.Count-1 do begin
comment:=Pos('//',Text[i]);
if comment>0 then
Text[i]:=Copy(Text[i], 0, comment-1);
comment:=Pos('#',Text[i]);
if comment>0 then
Text[i]:=Copy(Text[i], 0, comment-1);
end;
end;
// ----------------------------------------------------------------------
// TDXFile
// ----------------------------------------------------------------------
// Create
//
constructor TDXFile.Create;
begin
FRootNode:=TDXNode.Create;
end;
// Destroy
//
destructor TDXFile.Destroy;
begin
FRootNode.Free;
inherited;
end;
// LoadFromStream
//
procedure TDXFile.LoadFromStream(Stream : TStream);
begin
Stream.Read(FHeader, SizeOf(TDXFileHeader));
Assert(Header.Magic = 'xof ', 'Invalid DirectX file');
if Header.FileType = 'txt ' then
ParseText(Stream)
else
if Header.FileType = 'bin ' then
raise Exception.Create('FileX error, "bin" filetype not supported')
else
if Header.FileType = 'tzip' then
raise Exception.Create('FileX error, "tzip" filetype not supported')
else
if Header.FileType = 'bzip' then
raise Exception.Create('FileX error, "bzip" filetype not supported');
end;
procedure TDXFile.ParseBinary(Stream: TStream);
begin
// To-do
end;
procedure TDXFile.ParseText(Stream: TStream);
var
XText,
TempBuffer : TStringList;
Cursor : Integer;
Buffer : String;
function ContainsColon(Buffer : String) : Boolean;
begin
Result:=Pos(';', Buffer)>0;
end;
function ContainsBegin(Buffer : String) : Boolean;
begin
Result:=Pos('{', Buffer)>0;
end;
function ContainsEnd(Buffer : String) : Boolean;
begin
Result:=Pos('}', Buffer)>0;
end;
function ReadString : String;
begin
if Cursor<XText.Count then
Result:=XText[Cursor]
else
Result:='';
Inc(Cursor);
end;
function GetNodeData(var NodeType, NodeName : String) : Boolean;
begin
NodeType:='';
NodeName:='';
Result:=False;
if Cursor<3 then exit;
NodeType:=XText[Cursor-3];
NodeName:=XText[Cursor-2];
if ContainsBegin(NodeType)
or ContainsEnd(NodeType)
or ContainsColon(NodeType) then begin
NodeType:=NodeName;
NodeName:='';
end;
NodeType:=LowerCase(NodeType);
end;
function ReadInteger : Integer;
var
str : String;
begin
str:=ReadString;
if ContainsColon(str) then str:=StringReplace(str, ';', '', [rfReplaceAll]);
if ContainsBegin(str) then str:=StringReplace(str, '{', '', [rfReplaceAll]);
if ContainsEnd(str) then str:=StringReplace(str, '}', '', [rfReplaceAll]);
Result:=StrToInt(str);
end;
function ReadSingle : Single;
var
str : String;
begin
str:=ReadString;
if ContainsColon(str) then str:=StringReplace(str, ';', '', [rfReplaceAll]);
if ContainsBegin(str) then str:=StringReplace(str, '{', '', [rfReplaceAll]);
if ContainsEnd(str) then str:=StringReplace(str, '}', '', [rfReplaceAll]);
Result:=StrToFloatDef(str);
end;
function ReadMatrix : TMatrix;
var
i, j : Integer;
begin
try
for j:=0 to 3 do
for i:=0 to 3 do
Result.V[i].V[j]:=ReadSingle;
except
on E:Exception do begin
Result:=IdentityHMGMatrix;
end;
end;
end;
function ReadVector3f : TAffineVector;
var
str : String;
begin
str:=ReadString;
str:=StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText:=str;
if TempBuffer.Count > 1 then begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=StrToFloatDef(TempBuffer[1]);
Result.Z:=StrToFloatDef(TempBuffer[2]);
end else begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=ReadSingle;
Result.Z:=ReadSingle;
end;
end;
function ReadVector4f : TVector;
var
str : String;
begin
str:=ReadString;
str:=StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText:=str;
if TempBuffer.Count > 1 then begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=StrToFloatDef(TempBuffer[1]);
Result.Z:=StrToFloatDef(TempBuffer[2]);
Result.W:=StrToFloatDef(TempBuffer[3]);
end else begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=ReadSingle;
Result.Z:=ReadSingle;
Result.W:=ReadSingle;
end;
end;
function ReadTexCoord : TAffineVector;
var
str : String;
begin
str:=ReadString;
str:=StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText:=str;
if TempBuffer.Count > 1 then begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=StrToFloatDef(TempBuffer[1]);
end else begin
Result.X:=StrToFloatDef(TempBuffer[0]);
Result.Y:=ReadSingle;
end;
Result.Z:=0;
end;
procedure ReadMeshVectors(VectorList : TAffineVectorList);
var
i, NumVectors : Integer;
begin
NumVectors:=ReadInteger;
for i:=0 to NumVectors-1 do
VectorList.Add(ReadVector3f);
end;
procedure ReadMeshIndices(IndexList : TIntegerList; VertCountIndices : TIntegerList = nil);
var
str : String;
i, j, NumFaces, NumIndices, jStart : Integer;
Indices : array of Integer;
begin
NumFaces:=ReadInteger;
for i:=0 to NumFaces-1 do begin
str:=ReadString;
str:=StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText:=str;
NumIndices:=StrToInt(TempBuffer[0]);
SetLength(Indices, NumIndices);
jStart:=0;
if TempBuffer.Count>1 then begin
Indices[0]:=StrToInt(TempBuffer[1]);
jStart:=1;
end;
for j:=jStart to NumIndices-1 do
Indices[j]:=ReadInteger;
case NumIndices of
3 : begin
IndexList.Add(Indices[0], Indices[1], Indices[2]);
if Assigned(VertCountIndices) then VertCountIndices.Add(3);
end;
4 : begin
IndexList.Add(Indices[0], Indices[1], Indices[2]);
IndexList.Add(Indices[0], Indices[2], Indices[3]);
if Assigned(VertCountIndices) then VertCountIndices.Add(6);
end;
end;
SetLength(Indices, 0);
end;
end;
procedure ReadTexCoords(VectorList : TAffineVectorList);
var
i, NumVectors : Integer;
begin
NumVectors:=ReadInteger;
for i:=0 to NumVectors-1 do
VectorList.Add(ReadTexCoord);
end;
procedure ReadMeshVertices(Mesh : TDXMesh);
begin
ReadMeshVectors(Mesh.Vertices);
ReadMeshIndices(Mesh.VertexIndices, Mesh.VertCountIndices);
end;
procedure ReadMeshNormals(Mesh : TDXMesh);
begin
ReadMeshVectors(Mesh.Normals);
ReadMeshIndices(Mesh.NormalIndices);
end;
procedure ReadMeshTexCoords(Mesh : TDXMesh);
begin
ReadTexCoords(Mesh.TexCoords);
end;
procedure ReadMeshMaterialList(Mesh : TDXMesh);
var
i, {NumMaterials,} NumIndices : Integer;
begin
{NumMaterials:=}ReadInteger;
NumIndices:=ReadInteger;
for i:=0 to NumIndices-1 do
Mesh.MaterialIndices.Add(ReadInteger);
end;
procedure ReadMeshMaterial(Mesh : TDXMesh);
begin
with TDXMaterial.CreateOwned(Mesh.MaterialList) do begin
Diffuse:=ReadVector4f;
SpecPower:=ReadSingle;
Specular:=ReadVector3f;
Emissive:=ReadVector3f;
end;
end;
procedure ReadTextureFilename(Mesh : TDXMesh);
var
Str : String;
begin
if Mesh.MaterialList.Count>0 then begin
Str:=ReadString;
Str:=StringReplace(Str, '"', '', [rfReplaceAll]);
Str:=StringReplace(Str, ';', '', [rfReplaceAll]);
Str:=Trim(Str);
Mesh.MaterialList.Items[Mesh.MaterialList.Count-1].Texture:=Str;
end;
end;
procedure ReadStruct(ParentNode : TDXNode);
var
Buffer,
NodeType,
NodeName : String;
Loop : Boolean;
NewNode : TDXNode;
begin
Loop:=True;
while Loop do begin
Buffer:=ReadString;
if Cursor>XText.Count-1 then break;
if ContainsEnd(Buffer) then
Loop:=False
else if ContainsBegin(Buffer) then begin
GetNodeData(NodeType, NodeName);
NewNode:=nil;
// Frame
if NodeType = 'frame' then begin
NewNode:=TDXFrame.CreateOwned(ParentNode);
ReadStruct(NewNode);
// Frame transform matrix
end else if NodeType = 'frametransformmatrix' then begin
if ParentNode is TDXFrame then
TDXFrame(ParentNode).Matrix:=ReadMatrix;
ReadStruct(ParentNode);
// Mesh
end else if NodeType = 'mesh' then begin
NewNode:=TDXMesh.CreateOwned(ParentNode);
ReadMeshVertices(TDXMesh(NewNode));
ReadStruct(NewNode);
// Mesh normals
end else if NodeType = 'meshnormals' then begin
if ParentNode is TDXMesh then
ReadMeshNormals(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh texture coords
end else if NodeType = 'meshtexturecoords' then begin
if ParentNode is TDXMesh then
ReadMeshTexCoords(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh material list
end else if NodeType = 'meshmateriallist' then begin
if ParentNode is TDXMesh then
ReadMeshMaterialList(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh material
end else if NodeType = 'material' then begin
if ParentNode is TDXMesh then
ReadMeshMaterial(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Material texture filename
end else if NodeType = 'texturefilename' then begin
if ParentNode is TDXMesh then
ReadTextureFilename(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Unknown type
end else begin
//NewNode:=TDXNode.CreateOwned(ParentNode);
//NodeType:='*'+NodeType;
//ReadStruct(NewNode);
ReadStruct(ParentNode);
end;
if Assigned(NewNode) then begin
NewNode.TypeName:=NodeType;
NewNode.Name:=NodeName;
end;
end;
end;
end;
begin
XText:=TStringList.Create;
TempBuffer:=TStringList.Create;
XText.LoadFromStream(Stream);
// Remove comments and white spaces
RemoveComments(XText);
XText.CommaText:=XText.Text;
// Fix embedded open braces
Cursor:=0;
while Cursor<XText.Count-1 do begin
Buffer:=ReadString;
if Pos('{',Buffer)>1 then begin
XText[Cursor-1]:=Copy(Buffer,0,Pos('{',Buffer)-1);
XText.Insert(Cursor,'{');
end;
end;
XText.SaveToFile('XText_dump.txt');
// Start parsing
Cursor:=0;
while Cursor<XText.Count-1 do
ReadStruct(RootNode);
TempBuffer.Free;
XText.Free;
end;
// ----------------------------------------------------------------------
// TDXMaterialList
// ----------------------------------------------------------------------
// GetMaterial
//
function TDXMaterialList.GetMaterial(index: Integer): TDXMaterial;
begin
Result:=TDXMaterial(Get(index));
end;
// ----------------------------------------------------------------------
// TDXMesh
// ----------------------------------------------------------------------
// Create
//
constructor TDXMesh.Create;
begin
inherited;
FVertices:=TAffineVectorList.Create;
FNormals:=TAffineVectorList.Create;
FTexCoords:=TAffineVectorList.Create;
FVertexIndices:=TIntegerList.Create;
FNormalIndices:=TIntegerList.Create;
FMaterialIndices:=TIntegerList.Create;
FVertCountIndices:=TIntegerList.Create;
FMaterialList:=TDXMaterialList.Create;
end;
// Destroy
//
destructor TDXMesh.Destroy;
begin
FVertices.Free;
FNormals.Free;
FTexCoords.Free;
FVertexIndices.Free;
FNormalIndices.Free;
FMaterialIndices.Free;
FVertCountIndices.Free;
FMaterialList.Free;
inherited;
end;
// ----------------------------------------------------------------------
// TDXNode
// ----------------------------------------------------------------------
// Create
//
constructor TDXNode.Create;
begin
// Virtual
end;
// CreateOwned
//
constructor TDXNode.CreateOwned(AOwner: TDXNode);
begin
FOwner:=AOwner;
Create;
if Assigned(FOwner) then
FOwner.Add(Self);
end;
// GetItem
//
function TDXNode.GetItem(index: Integer): TDXNode;
begin
Result:=TDXNode(Get(index));
end;
// Clear
//
procedure TDXNode.Clear;
var
i : integer;
begin
for i:=0 to Count-1 do
Items[i].Free;
inherited;
end;
// ----------------------------------------------------------------------
// TDXFrame
// ----------------------------------------------------------------------
// Create
//
constructor TDXFrame.Create;
begin
inherited;
FMatrix:=IdentityHMGMatrix;
end;
// GlobalMatrix
//
function TDXFrame.GlobalMatrix: TMatrix;
begin
if Owner is TDXFrame then
Result:=MatrixMultiply(TDXFrame(Owner).GlobalMatrix, FMatrix)
else
Result:=FMatrix;
end;
// ----------------------------------------------------------------------
// TDXMaterial
// ----------------------------------------------------------------------
// CreateOwned
constructor TDXMaterial.CreateOwned(AOwner: TDXMaterialList);
begin
Create;
if Assigned(AOwner) then
AOwner.Add(Self);
end;
end.
|
Program arboles;
Type
// Lista de enteros
lista = ^nodoL;
nodoL = record
dato: integer;
sig: lista;
end;
// Arbol de enteros
arbol= ^nodoA;
nodoA = Record
dato: integer;
HI: arbol;
HD: arbol;
End;
// Lista de Arboles
{-----------------------------------------------------------------------------
AgregarAdelante - Agrega nro adelante de l}
procedure agregarAdelante(var l: Lista; nro: integer);
var
aux: lista;
begin
new(aux);
aux^.dato := nro;
aux^.sig := l;
l:= aux;
end;
{-----------------------------------------------------------------------------
CREARLISTA - Genera una lista con números aleatorios }
procedure crearLista(var l: Lista);
var
n: integer;
begin
l:= nil;
n := random (20);
While (n <> 0) do Begin
agregarAdelante(L, n);
n := random (20);
End;
end;
{-----------------------------------------------------------------------------
IMPRIMIRLISTA - Muestra en pantalla la lista l }
procedure imprimirLista(l: Lista);
begin
While (l <> nil) do begin
write(l^.dato, ' - ');
l:= l^.sig;
End;
end;
{-----------------------------------------------------------------------------
CONTARELEMENTOS - Devuelve la cantidad de elementos de una lista l }
{-----------------------------------------------------------------------------
AGREGARATRAS - Agrega un elemento atrás en l}
{-----------------------------------------------------------------------------
IMPRIMIRPORNIVEL - Muestra los datos del árbol a por niveles }
{Actividad}
procedure Insertar(num:integer; var a:arbol);
begin
if (a=nil) then begin
new(a);
a^.dato:=num;
a^.HI:=nil;
a^.HD:=nil;
end
else
if (a^.dato>num) then
Insertar(num,a^.HI)
else
if (a^.dato<num) then
Insertar(num,a^.HD)
end;
procedure InsertarElementos (L:lista; var a:arbol);
begin
if (L<>nil) then begin
Insertar(L^.dato,a);
InsertarElementos(L^.sig,a);
end;
end;
Procedure enOrden( a: arbol );
begin
if ( a <> nil ) then begin
enOrden (a^.HI);
write (a^.dato, ' ');
enOrden (a^.HD)
end;
end;
procedure VerValoresEnRango ( a:arbol; inf:integer; sup:integer);
begin
if (a<>nil) then
if(a^.dato>=inf)then
if(a^.dato<=sup)then begin
write(a^.dato,' - ');
VerValoresEnRango(a^.HI,inf,sup);
VerValoresEnRango(a^.HD,inf,sup);
end
else
VerValoresEnRango(a^.HI,inf,sup)
else
VerValoresEnRango(a^.HD,inf,sup)
end;
procedure borrarElemento (var a:arbol; num:integer; var resultado:boolean);
procedure buscoMinimo (a: arbol; var minimo: integer);
begin
if (a^.HI=nil) then
minimo:=a^.dato
else
buscoMinimo(a^.HI,minimo);
end;
var minimo:integer; aux:arbol;
begin
if (a<>nil) then begin
if (a^.dato>num) then
borrarElemento(a^.HI, num, resultado)
else
if (a^.dato<num) then
borrarElemento(a^.HD, num, resultado)
else begin
resultado:=true;
if (a^.HD=nil) then begin
aux:=a;
a:=a^.HI;
dispose(aux);
end
else begin
if (a^.HI=nil) then begin
aux:=a;
a:=a^.HD;
dispose(aux);
end
else begin
minimo:=9999;
buscoMinimo(a^.HD,minimo);
a^.dato:=minimo;
borrarElemento(a^.HD,a^.dato,resultado);
end;
end;
end;
end;
end;
Var
l: lista;
a:arbol;
num:integer;
resultado:boolean;
begin
Randomize;
crearLista(l);
writeln ('Lista generada: ');
imprimirLista(l);
insertarElementos(l,a);
imprimirpornivel(a);
readln(num);
resultado:=false;
borrarElemento(a,num,resultado);
writeln(resultado);
imprimirpornivel(a);
readln;
end.
|
unit gExpressionEvaluator;
{ Author: Steve Kramer, goog@goog.com }
interface
Uses
classes
, contnrs
, Variants
, gParse
, SysUtils
;
Type
TgExpressionEvaluatorClass = Class of TgExpressionEvaluator;
TgExpressionEvaluator = class(TgSymbolString)
strict private
FInFixTokenList : TObjectList;
FPostFixTokenList : TList;
Function EvaluateTokenList : Variant;
procedure ParseNextToken;
Procedure PostFixTokenList;
procedure TokenizeExpression;
strict protected
function GetValue(const AVariableName: String): Variant; virtual;
function UnknownTokenClass: TgTokenClass;
public
constructor Create; override;
Destructor Destroy;Override;
function Evaluate(const AExpression: String): Variant;
function OverrideTokenClass(ATokenClass: TgTokenClass; const ASymbol: String): TgTokenClass; virtual;
property Value[const AVariableName: String]: Variant read GetValue;
End;
TgVariantStack = class(TObject)
strict private
fStack : Array[0..99] of Variant;
fStackIndex : Integer;
public
Constructor Create;
Procedure Clear;
Function Pop : Variant;
Procedure Push(AValue : Variant);
End;
TgExpressionTokenClass = Class of TgExpressionToken;
TgExpressionToken = class(TgToken)
strict private
function GetExpressionEvaluator: TgExpressionEvaluator;
strict protected
class function TokenRegistry: TgTokenRegistry; override;
property ExpressionEvaluator: TgExpressionEvaluator read GetExpressionEvaluator;
public
constructor Create(AExpressionEvaluator : TgExpressionEvaluator); reintroduce; virtual;
Class Function CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList) : TgExpressionToken;Virtual;
procedure Evaluate(AStack : TgVariantStack); virtual;
Procedure PostFix(ATokenList : TList; AStack : TStack);Virtual;
End;
TgWhitespace = class(TgExpressionToken)
Public
class var
Chars: String;
procedure Parse(ASymbolLength: Integer); override;
class procedure Register(const ASymbol: String); override;
End;
TVariableClass = Class Of TgVariable;
TgVariable = class(TgExpressionToken)
strict private
Name: String;
class function IsValidFirstChar(const ASymbol: Char): Boolean;
class function IsValidOtherChar(const ASymbol: Char): Boolean;
public
procedure Evaluate(AStack : TgVariantStack); override;
procedure Parse(ASymbolLength: Integer); override;
Class Procedure Register;ReIntroduce;
class function ValidSymbol(const ASymbolName: String): Boolean; override;
End;
EgExpressionEvaluator = class(Exception)
end;
function Eval(const AExpression: String; AExpressionEvaluatorClass: TgExpressionEvaluatorClass = Nil): Variant;
implementation
Uses
Math
, Character
;
function Eval(const AExpression: String; AExpressionEvaluatorClass: TgExpressionEvaluatorClass = Nil): Variant;
var
ExpressionEvaluator: TgExpressionEvaluator;
begin
if Not Assigned(AExpressionEvaluatorClass) then
AExpressionEvaluatorClass := TgExpressionEvaluator;
ExpressionEvaluator := AExpressionEvaluatorClass.Create;
try
Result := ExpressionEvaluator.Evaluate(AExpression);
finally
ExpressionEvaluator.Free;
end;
end;
Var
ExpressionTokenRegistry : TgTokenRegistry;
VariableClass : TVariableClass;
{ TgExpressionEvaluator }
constructor TgExpressionEvaluator.Create;
Begin
Inherited;
FInFixTokenList := TObjectList.Create;
FPostFixTokenList := TList.Create;
End;
Destructor TgExpressionEvaluator.Destroy;
Begin
FPostFixTokenList.Free;
FInfixTokenList.Free;
Inherited Destroy;
End;
function TgExpressionEvaluator.Evaluate(const AExpression: String): Variant;
begin
Initialize( AExpression );
TokenizeExpression;
PostFixTokenList;
Result := EvaluateTokenList;
end;
function TgExpressionEvaluator.EvaluateTokenList: Variant;
Var
Counter : Integer;
Stack : TgVariantStack;
begin
Stack := TgVariantStack.Create;
Try
For Counter := 0 to FPostFixTokenList.Count - 1 Do
TgExpressionToken(FPostFixTokenList[Counter]).Evaluate(Stack);
Result := Stack.Pop;
Finally
Stack.Free;
End;
end;
function TgExpressionEvaluator.GetValue(const AVariableName: String): Variant;
begin
Result := Unassigned;
end;
function TgExpressionEvaluator.OverrideTokenClass(ATokenClass: TgTokenClass; const ASymbol: String): TgTokenClass;
begin
Result := ATokenClass;
end;
procedure TgExpressionEvaluator.ParseNextToken;
Var
TokenClass : TgTokenClass;
Token : TgExpressionToken;
Symbol: String;
Begin
TokenClass := ExpressionTokenRegistry.ClassifyNextSymbol(SourceString, SourceStringIndex, Symbol);
TokenClass := OverrideTokenClass( TokenClass, Symbol );
Token := TgExpressionTokenClass(TokenClass).CreateToken(Self, FInFixTokenList);
Token.Parse( Length( Symbol ) );
If Token.InheritsFrom(TgWhitespace) Then
Token.Free
Else
FInfixTokenList.Add(Token);
End;
procedure TgExpressionEvaluator.PostFixTokenList;
Var
Stack : TStack;
Counter : Integer;
begin
FPostFixTokenList.Clear;
Stack := TStack.Create;
Try
For Counter := 0 to FInFixTokenList.Count - 1 Do
TgExpressionToken(FInFixTokenList[Counter]).PostFix(FPostFixTokenList, Stack);
While Stack.Count > 0 Do
FPostFixTokenList.Add(Stack.Pop);
Finally
Stack.Free;
End;
end;
procedure TgExpressionEvaluator.TokenizeExpression;
Begin
FInfixTokenList.Clear;
While SourceStringIndex <= SourceStringLength Do
ParseNextToken;
End;
function TgExpressionEvaluator.UnknownTokenClass: TgTokenClass;
begin
Result := ExpressionTokenRegistry.UnknownTokenClass;
end;
constructor TgExpressionToken.Create(AExpressionEvaluator : TgExpressionEvaluator);
begin
Inherited Create(AExpressionEvaluator);
end;
class function TgExpressionToken.CreateToken(AExpressionEvaluator : TgExpressionEvaluator; AInFixTokenList : TObjectList): TgExpressionToken;
begin
Result := Create(AExpressionEvaluator);
end;
procedure TgExpressionToken.Evaluate(AStack : TgVariantStack);
begin
end;
function TgExpressionToken.GetExpressionEvaluator: TgExpressionEvaluator;
begin
Result := TgExpressionEvaluator(Owner);
end;
procedure TgExpressionToken.PostFix(ATokenList : TList; AStack: TStack);
begin
ATokenList.Add(Self);
end;
class function TgExpressionToken.TokenRegistry: TgTokenRegistry;
begin
Result := ExpressionTokenRegistry;
end;
{ TgVariable }
procedure TgVariable.Evaluate(AStack : TgVariantStack);
Begin
AStack.Push(ExpressionEvaluator.Value[Name]);
End;
class function TgVariable.IsValidFirstChar(const ASymbol: Char): Boolean;
begin
Result := TCharacter.IsLetter(ASymbol);
end;
class function TgVariable.IsValidOtherChar(const ASymbol: Char): Boolean;
begin
Result := (TCharacter.IsLetter(ASymbol) or TCharacter.IsNumber(ASymbol) or (Pos(ASymbol, '.[]') > 0));
end;
procedure TgVariable.Parse(ASymbolLength: Integer);
Var
TokenLength : Integer;
begin
If IsValidFirstChar(SourceString[SourceStringIndex]) Then
Begin
TokenLength := 1;
While ( ( SourceStringIndex + TokenLength ) <= ( SourceStringLength + 1 ) ) And IsValidOtherChar( SourceString[SourceStringIndex + TokenLength - 1] ) Do
Inc(TokenLength);
Dec(TokenLength);
Name := Copy( SourceString, SourceStringIndex, TokenLength);
SourceStringIndex := SourceStringIndex + TokenLength;
End
Else
Owner.RaiseException( 'Invalid variable first character ''%s''.', [SourceString[SourceStringIndex]] );
end;
class procedure TgVariable.Register;
begin
VariableClass := Self;
end;
class function TgVariable.ValidSymbol(const ASymbolName: String): Boolean;
const
StartPosition = 2;
Var
Counter : Integer;
VariableNameLength : Integer;
begin
Result := False;
VariableNameLength := Length(ASymbolName);
If (ASymbolName > '') And IsValidFirstChar(ASymbolName[1]) Then
Begin
For Counter := StartPosition to VariableNameLength Do
If Not IsValidOtherChar(ASymbolName[Counter]) Then
Exit;
Result := True;
End;
end;
{ TgVariantStack }
Constructor TgVariantStack.Create;
Begin
Inherited;
fStackIndex := -1;
End;
Procedure TgVariantStack.Clear;
Begin
fStackIndex := -1;
End;
Function TgVariantStack.Pop : Variant;
Begin
Result := fStack[fStackIndex];
Dec(fStackIndex);
End;
Procedure TgVariantStack.Push(AValue : Variant);
Begin
Inc(fStackIndex);
fStack[fStackIndex] := AValue;
End;
{ TgWhitespace }
procedure TgWhitespace.Parse(ASymbolLength: Integer);
begin
While (SourceStringIndex <= SourceStringLength) And ( Pos( SourceString[SourceStringIndex], Chars ) > 0 ) Do
SourceStringIndex := SourceStringIndex + 1;
end;
{ TgToken }
class procedure TgWhitespace.Register(const ASymbol: String);
begin
inherited Register( ASymbol );
Chars := Chars + ASymbol;
end;
Initialization
ExpressionTokenRegistry := TgTokenRegistry.Create;
TgVariable.Register;
TgWhitespace.Register(' ');
TgWhitespace.Register(#0009);
TgWhitespace.Register(#0013);
TgWhitespace.Register(#0010);
ExpressionTokenRegistry.UnknownTokenClass := TgVariable;
Finalization
ExpressionTokenRegistry.Free;
end.
|
unit PascalCoin.RawOp.Classes;
interface
uses System.SysUtils, System.Generics.Collections, PascalCoin.Wallet.Interfaces,
PascalCoin.Utils.Interfaces, PascalCoin.RawOp.Interfaces;
type
TRawOperations = class(TInterfacedObject, IRawOperations)
private
FList: TList<IRawOperation>;
protected
function GetRawOperation(const Index: integer): IRawOperation;
function GetRawData: string;
function AddRawOperation(Value: IRawOperation): integer;
public
constructor Create;
destructor Destroy; override;
end;
TBaseRawOp = class(TInterfacedObject, IRawOperation)
private
protected
FKeyTools: IKeyTools;
function AsHex(const Value: Cardinal): String; overload;
function AsHex(const Value: Integer): String; overload;
function AsHex(const Value: Currency): String; overload;
function AsHex(const Value: String; var lLen: integer): String; overload;
function GetRawData: String; virtual; abstract;
public
constructor Create(AKeyTools: IKeyTools);
end;
TRawTransactionOp = class(TBaseRawOp, IRawTransactionOp)
private
FSendFrom: Cardinal;
FNOp: Integer;
FSendTo: Cardinal;
FAmount: Currency;
FFee: Currency;
FPayload: String;
FKey: IPrivateKey;
FPayloadLength: integer;
{$IFDEF UNITTEST}
FKRandom: string;
FDelim: string;
{$ENDIF UNITTEST}
function ValueToHash: String;
function HashValue(const Value: string): String;
function Signature: TECDSA_Signature;
function LenAs2ByteHex(const Value: Integer): string;
protected
function GetRawData: String; override;
function GetSendFrom: Cardinal;
function GetNOp: integer;
function GetSendTo: Cardinal;
function GetAmount: Currency;
function GetFee: Currency;
function GetPayload: string;
procedure SetSendFrom(const Value: Cardinal);
procedure SetNOp(const Value: integer);
procedure SetSendTo(const Value: Cardinal);
procedure SetAmount(const Value: Currency);
procedure SetFee(const Value: Currency);
procedure SetPayload(const Value: String);
procedure SetKey(Value: IPrivateKey);
{$IFDEF UNITTEST}
function GetKRandom: string;
procedure SetKRandom(const Value: string);
function TestValue(const AKey: string): string;
{$ENDIF}
public
end;
implementation
uses clpConverters, clpEncoders;
const
Op_Transaction = 1;
{ TRawOperations }
function TRawOperations.AddRawOperation(Value: IRawOperation): integer;
begin
Result := FList.Add(Value);
end;
constructor TRawOperations.Create;
begin
inherited Create;
FList := TList<IRawOperation>.Create;
end;
destructor TRawOperations.Destroy;
begin
FList.Free;
inherited;
end;
function TRawOperations.GetRawData: string;
var
I: integer;
begin
Result := THEX.Encode(TConverters.ReadUInt32AsBytesLE(FList.Count));
for I := 0 to FList.Count - 1 do
Result := Result + FList[I].RawData;
end;
function TRawOperations.GetRawOperation(const Index: integer): IRawOperation;
begin
Result := FList[Index];
end;
{ TBaseRawOp }
function TBaseRawOp.AsHex(const Value: Cardinal): String;
begin
Result := THEX.Encode(TConverters.ReadUInt32AsBytesLE(Value), True);
end;
function TBaseRawOp.AsHex(const Value: Currency): String;
var
lVal: Int64;
begin
lVal := Trunc(Value * 10000);
Result := THEX.Encode(TConverters.ReadUInt64AsBytesLE(lVal), True);
end;
function TBaseRawOp.AsHex(const Value: String; var lLen: integer): String;
var
lVal: TBytes;
begin
lVal := TConverters.ConvertStringToBytes(Value, TEncoding.ANSI);
lLen := Length(lVal);
Result := THEX.Encode(lVal, True);
end;
function TBaseRawOp.AsHex(const Value: Integer): String;
begin
Result := THEX.Encode(TConverters.ReadUInt32AsBytesLE(Value), True);
end;
constructor TBaseRawOp.Create(AKeyTools: IKeyTools);
begin
inherited Create;
FKeyTools := AKeyTools;
end;
{ TTransactionOp }
function TRawTransactionOp.GetAmount: Currency;
begin
result := FAmount;
end;
function TRawTransactionOp.GetFee: Currency;
begin
result := FFee;
end;
function TRawTransactionOp.GetNOp: integer;
begin
result := FNOp;
end;
function TRawTransactionOp.GetPayload: string;
begin
result := FPayload;
end;
function TRawTransactionOp.GetRawData: String;
var
lSig: TECDSA_Signature;
begin
lSig := Signature;
Result := THEX.Encode(TConverters.ReadUInt32AsBytesLE(Op_Transaction)) +
AsHex(FSendFrom) + AsHex(FNOp) + AsHex(FSendTo) +
AsHex(FAmount) + AsHex(FFee) +
LenAs2ByteHex(FPayloadLength) + FPayload +
'000000000000' +
LenAs2ByteHex(lSig.RLen) + lSig.R +
LenAs2ByteHex(lSig.SLen) + lSig.S;
end;
function TRawTransactionOp.ValueToHash: String;
const
NullBytes = '0000';
OpType = '01';
begin
Result := AsHex(FSendFrom) + AsHex(FNOp) + AsHex(FSendTo) + AsHex(FAmount) +
AsHex(FFee) + FPayload +
NullBytes + OpType;
end;
function TRawTransactionOp.GetSendFrom: Cardinal;
begin
result := FSendFrom;
end;
function TRawTransactionOp.GetSendTo: Cardinal;
begin
result := FSendTo;
end;
function TRawTransactionOp.HashValue(const Value: string): String;
begin
Result := THEX.Encode(FKeyTools.ComputeSHA2_256_ToBytes(THEX.Decode(Value)));
end;
procedure TRawTransactionOp.SetAmount(const Value: Currency);
begin
FAmount := Value;
end;
procedure TRawTransactionOp.SetFee(const Value: Currency);
begin
FFee := Value;
end;
procedure TRawTransactionOp.SetKey(Value: IPrivateKey);
begin
FKey := Value;
end;
{$IFDEF UNITTEST}
function TRawTransactionOp.GetKRandom: string;
begin
result := FKRandom;
end;
procedure TRawTransactionOp.SetKRandom(const Value: string);
begin
FKRandom := Value;
end;
function TRawTransactionOp.TestValue(const AKey: string): string;
var lKey: String;
begin
lKey := AKey.ToUpper;
if lKey.Equals('SENDFROM') then Result := AsHex(FSendFrom)
else if lKey.Equals('NOP') then Result := AsHex(FNOp)
else if lKey.Equals('SENDTO') then Result := AsHex(FSendTo)
else if lKey.Equals('AMOUNT') then Result := AsHex(FAmount)
else if lKey.Equals('FEE') then Result := AsHex(FFee)
else if lKey.Equals('PAYLOADLEN') then Result := LenAs2ByteHex(FPayloadLength)
else if lKey.Equals('VALUETOHASH') then Result := ValueToHash
else if lKey.Equals('HASH') then Result := HashValue(ValueToHash)
else if lKey.Equals('SIG.R') then Result := Signature.R
else if lKey.Equals('SIG.S') then Result := Signature.S
else if lKey.Equals('SIG.R.LEN') then Result := LenAs2ByteHex(Signature.RLen)
else if lKey.Equals('SIG.S.LEN') then Result := LenAs2ByteHex(Signature.SLen)
else if lKey.Equals('KEY.HEX') then Result := FKey.AsHexStr
else if lKey.Equals('SIGNEDTX') then Result := GetRawData
{$IFDEF UNITTEST}
else if lKey.Equals('KRANDOM') then Result := FKRandom
{$ENDIF}
else result := 'N/A';
end;
{$ENDIF}
procedure TRawTransactionOp.SetNOp(const Value: integer);
begin
FNOp := Value;
end;
procedure TRawTransactionOp.SetPayload(const Value: String);
begin
FPayload := Value;
FPayloadLength := Length(THEX.Decode(FPayLoad));
end;
procedure TRawTransactionOp.SetSendFrom(const Value: Cardinal);
begin
FSendFrom := Value;
end;
procedure TRawTransactionOp.SetSendTo(const Value: Cardinal);
begin
FSendTo := Value;
end;
function TRawTransactionOp.LenAs2ByteHex(const Value: Integer): string;
var lSLE: TBytes;
begin
lSLE := FKeyTools.UInt32ToLittleEndianByteArrayTwoBytes(Value);
Result := THEX.EnCode(lSLE);
end;
function TRawTransactionOp.Signature: TECDSA_Signature;
var lHash: string;
begin
lhash := HashValue(ValueToHash);
{$IFDEF UNITTEST}
FKeyTools.SignOperation(FKey.AsHexStr, FKey.KeyType, lHash, Result, FKRandom);
{$ELSE}
FKeyTools.SignOperation(FKey, FKey.KeyType, HashValue(ValueToHash), Result);
{$ENDIF UNITTEST}
end;
end.
|
unit TestWarnings;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestWarnings, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork, BaseTestProcess;
type
TTestWarnings = class(TBaseTestProcess)
private
public
fStoreWarningsOn: Boolean;
fStoreWarnUnusedParamsOn: Boolean;
procedure SetUp; override;
procedure TearDown; override;
published
// no warnings in basic units
procedure TestNoWarningsBasic;
// warnings on empty stuff
procedure TestEmptyProcedure;
procedure TestEmptyProcedureOff;
procedure TestEmptyBlock;
procedure TestEmptyTryExcept;
procedure TestEmptyTryFinally;
// assign to fn name
procedure TestAssignToFunctionName;
// real and real84 types
procedure TestRealType1;
procedure TestRealType2;
procedure TestRealType3;
procedure TestRealType4;
// calls to destroy
procedure TestDestroy;
procedure TestDestroy2;
// case without else block
procedure TestCaseNoElse1;
procedure TestCaseNoElse2;
procedure TestWarnUnusedParam1;
procedure TestWarnUnusedParam2;
procedure TestWarnUnusedParam3;
procedure TestWarnUnusedParam4;
procedure TestWarnUnusedParam5;
procedure TestWarnUnusedParam6;
procedure TestWarnUnusedParam7;
procedure TestWarnUnusedParamClass;
procedure TestWarnUnusedParamConstructor;
procedure TestWarnUnusedParamClassFn;
procedure TestWarnUnusedParamOpOverload;
procedure TestUnusedParamClassConstructor;
procedure TestUnusedInnerClass;
procedure TestWarnUnusedParamOff;
end;
implementation
uses
{ local }
JcfStringUtils,
JcfSettings;
const
EMPTY_BEGIN_END = 'Empty begin..end block';
EMPTY_TRY = 'Empty try block';
EMPTY_EXCEPT_END = 'Empty except..end';
EMPTY_FINALLY_END = 'Empty finally..end';
REAL_TYPE_USED = 'Real type used';
REAL48_TYPE_USED = 'Real48 type used';
procedure TTestWarnings.Setup;
begin
inherited;
fStoreWarningsOn := JcfFormatSettings.Clarify.Warnings;
fStoreWarnUnusedParamsOn := JcfFormatSettings.Clarify.WarnUnusedParams;
JcfFormatSettings.Clarify.Warnings := True;
JcfFormatSettings.Clarify.WarnUnusedParams := True;
end;
procedure TTestWarnings.TearDown;
begin
JcfFormatSettings.Clarify.Warnings := fStoreWarningsOn;
JcfFormatSettings.Clarify.WarnUnusedParams := fStoreWarnUnusedParamsOn;
inherited;
end;
procedure TTestWarnings.TestNoWarningsBasic;
const
UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
begin
TestNoWarnings(UNIT_TEXT);
end;
procedure TTestWarnings.TestEmptyProcedure;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, EMPTY_BEGIN_END);
end;
// no warning if the setting is turned off
procedure TTestWarnings.TestEmptyProcedureOff;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin end; ' + UNIT_FOOTER;
begin
JcfFormatSettings.Clarify.Warnings := False;
TestNoWarnings(UNIT_TEXT);
end;
procedure TTestWarnings.TestEmptyBlock;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin begin end; end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, EMPTY_BEGIN_END);
end;
procedure TTestWarnings.TestEmptyTryExcept;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin try except end; end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, [EMPTY_TRY, EMPTY_EXCEPT_END]);
end;
procedure TTestWarnings.TestEmptyTryFinally;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin try finally end; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, [EMPTY_TRY, EMPTY_FINALLY_END]);
end;
procedure TTestWarnings.TestAssignToFunctionName;
const
UNIT_TEXT = UNIT_HEADER + ' function fred: integer; begin fred := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'Assignment to the function name');
end;
procedure TTestWarnings.TestRealType1;
const
UNIT_TEXT = UNIT_HEADER + ' var foo: real; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, REAL_TYPE_USED);
end;
procedure TTestWarnings.TestRealType2;
const
UNIT_TEXT = UNIT_HEADER + ' const foo: Real48 = 4.5; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, REAL48_TYPE_USED);
end;
procedure TTestWarnings.TestRealType3;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; var foo: Real48; begin end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, [EMPTY_BEGIN_END, REAL48_TYPE_USED]);
end;
procedure TTestWarnings.TestRealType4;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; var foo: Real48; bar: real; begin end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, [EMPTY_BEGIN_END, REAL_TYPE_USED, REAL48_TYPE_USED]);
end;
procedure TTestWarnings.TestDestroy;
const
UNIT_TEXT = UNIT_HEADER + ' procedure fred; begin Destroy; end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'Destroy should not normally be called');
end;
procedure TTestWarnings.TestDestroy2;
const
UNIT_TEXT = UNIT_HEADER + ' procedure TFoo.fred; begin Destroy; end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'TFoo.fred');
end;
procedure TTestWarnings.TestCaseNoElse1;
const
UNIT_TEXT = UNIT_HEADER +
'procedure fred; var li: integer; begin case li of 1: end; end; ' + UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'Case statement has no else case');
end;
procedure TTestWarnings.TestCaseNoElse2;
const
// this one has an else, should have no warning
UNIT_TEXT = UNIT_HEADER +
'procedure fred; var li: integer; begin case li of 1: ; else; end; end; ' +
UNIT_FOOTER;
begin
TestNoWarnings(UNIT_TEXT);
end;
procedure TTestWarnings.TestWarnUnusedParam1;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
'procedure fred(foo: integer); var li: integer; begin li := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParam2;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
'procedure fred(const foo: integer); var li: integer; begin li := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParam3;
const
// this one should have 2 param warning
UNIT_TEXT = UNIT_HEADER +
'procedure fred(var foo, bar: integer); var li: integer; begin li := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, ['is not used', 'is not used']);
end;
procedure TTestWarnings.TestWarnUnusedParam4;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
'function fred(const foo: integer): integer; begin Result := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParam5;
const
// this one should have 2 param warnings out of 4 params
UNIT_TEXT = UNIT_HEADER +
'function fred(var foo1, foo2, foo3, foo4: integer): integer; begin foo3 := foo1; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, ['foo2', 'foo4']);
end;
procedure TTestWarnings.TestWarnUnusedParam6;
const
// this one should have only paramC unused
UNIT_TEXT = UNIT_HEADER +
' function fred(var paramA, paramB, paramC: integer): integer; ' + NativeLineBreak +
' begin if b > 10 then Result := foo(paramA, paramB, paramB - 1) else Result := paramA + paramB; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'paramC');
end;
procedure TTestWarnings.TestWarnUnusedParam7;
const
// this one should have only paramC unused
UNIT_TEXT = UNIT_HEADER +
' function TMyList.GetItem(Index: integer): TMyItem; ' + NativeLineBreak +
' begin Result := TMyItem(inherited Items[Index]); end; ' +
UNIT_FOOTER;
begin
TestNoWarnings(UNIT_TEXT);
end;
procedure TTestWarnings.TestWarnUnusedParamClass;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TMyClass = class ' + NativeLineBreak +
' public function fred(const foo: integer): integer; end; ' + NativeLineBreak +
' function TMyClass.fred(const foo: integer): integer; begin Result := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParamConstructor;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TMyClass = class ' + NativeLineBreak +
' public constructor Create(const foo: integer); end; ' + NativeLineBreak +
'constructor TMyClass.Create(const foo: integer); begin inherited; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParamClassFn;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TMyClass = class ' + NativeLineBreak +
' public class function fred(const foo: integer): integer; end; ' + NativeLineBreak +
'class function TMyClass.fred(const foo: integer): integer; ' + NativeLineBreak +
'begin Result := 3; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'is not used');
end;
procedure TTestWarnings.TestWarnUnusedParamOpOverload;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TMyClass = class ' + NativeLineBreak +
' class operator Add(A,B: TMyClass): TMyClass; end; ' + NativeLineBreak +
' class operator TMyClass.Add(paramA, paramB: TMyClass): TMyClass; ' + NativeLineBreak +
' begin Result := paramA; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'paramB');
end;
procedure TTestWarnings.TestUnusedParamClassConstructor;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TMyClass = class ' + NativeLineBreak +
' class constructor Create(const ParamA: integer); end; ' + NativeLineBreak +
' class constructor TMyClass.Create(const ParamA: integer); ' + NativeLineBreak +
' begin inherited Create(); end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'paramA');
end;
procedure TTestWarnings.TestUnusedInnerClass;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
' type TOuterClass = class ' + NativeLineBreak +
' type TInnerClass = class ' + NativeLineBreak +
' procedure innerProc(const paramA, paramB: integer); ' + NativeLineBreak +
' end; end; ' + NativeLineBreak +
' procedure TOuterClass.TInnerClass.innerProc(var paramA, paramB: integer); ' + NativeLineBreak +
' begin paramB := paramB; end; ' +
UNIT_FOOTER;
begin
TestWarnings(UNIT_TEXT, 'paramA');
end;
// test the switch to turn it off
procedure TTestWarnings.TestWarnUnusedParamOff;
const
// this one should have 1 param warning
UNIT_TEXT = UNIT_HEADER +
'procedure fred(foo: integer); var li: integer; begin li := 3; end; ' +
UNIT_FOOTER;
begin
// off
JcfFormatSettings.Clarify.WarnUnusedParams := False;
TestNoWarnings(UNIT_TEXT);
// on
JcfFormatSettings.Clarify.WarnUnusedParams := True;
TestWarnings(UNIT_TEXT, 'foo');
// excluded
JcfFormatSettings.Clarify.IgnoreUnusedParams.Clear;
JcfFormatSettings.Clarify.IgnoreUnusedParams.Add('foo');
TestNoWarnings(UNIT_TEXT);
// not excluded
JcfFormatSettings.Clarify.IgnoreUnusedParams.Clear;
JcfFormatSettings.Clarify.IgnoreUnusedParams.Add('oof');
TestWarnings(UNIT_TEXT, 'foo');
end;
initialization
TestFramework.RegisterTest('Processes', TTestWarnings.Suite);
end.
|
unit uDBConfig;
interface
uses
DBSQLite, DBMySql;
type
TDBConfig = class
public
Default: TDBSQLite; //必须有Default成员变量名
MYSQL: TDBMySql;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TDBConfig }
constructor TDBConfig.Create;
begin
Default := TDBSQLite.Create('SQLite');
MYSQL := TDBMySql.Create('MYSQL');
end;
destructor TDBConfig.Destroy;
begin
Default.Free;
MYSQL.Free;
inherited;
end;
end.
|
unit TestSecurityDescriptorManipulator;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
SysUtils, TestFramework, Windows,
OS.SecurityDescriptor;
type
// Test methods for class TSCSIBufferInterpreter
TestTSecurityDescriptorManipulator = class(TTestCase)
public
FSecurityDescriptorManipulator: TSecurityDescriptorManipulator;
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSecurityDescriptor;
end;
ACLWithBuffer = record
Header: ACL;
Contents: Array[0..63] of Byte;
end;
implementation
procedure TestTSecurityDescriptorManipulator.SetUp;
begin
FSecurityDescriptorManipulator := TSecurityDescriptorManipulator.Create;
end;
procedure TestTSecurityDescriptorManipulator.TearDown;
begin
FSecurityDescriptorManipulator.Free;
FSecurityDescriptorManipulator := nil;
end;
procedure TestTSecurityDescriptorManipulator.TestSecurityDescriptor;
var
TestResultPointer: PSECURITY_DESCRIPTOR;
TestResult: SECURITY_DESCRIPTOR;
ACLResult: ACLWithBuffer;
ExpectedACL: ACLWithBuffer;
const
ExpectedResult: SECURITY_DESCRIPTOR = (
Revision: 1; Sbz1: 0; Control: 4);
ExpectedACLHeader: ACL = (AclRevision: 2; Sbz1: 0; AclSize: 52; AceCount: 2;
Sbz2: 0);
ExpectedACLContents: Array[0..63] of Byte = (
0, 0, 20, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 24, 0, 0,
0, 0, 16, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 171, 171, 171,
171, 171, 171, 171, 171, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
begin
TestResultPointer := FSecurityDescriptorManipulator.GetSecurityDescriptor;
CopyMemory(@TestResult, TestResultPointer, SizeOf(SECURITY_DESCRIPTOR));
CheckEquals(true,
CompareMem(@TestResult, @ExpectedResult,
SizeOf(SECURITY_DESCRIPTOR) - SizeOf(Pointer)),
'Unexpected Security Descriptor');
ZeroMemory(@ACLResult, SizeOf(ACLResult));
ExpectedACL.Header := ExpectedACLHeader;
Move(ExpectedACLContents, ExpectedACL.Contents,
SizeOf(ExpectedACL.Contents));
CopyMemory(@ACLResult, TestResult.Dacl, SizeOf(ACL));
CopyMemory(@ACLResult, TestResult.Dacl,
SizeOf(ACL) + ACLResult.Header.AclSize);
CheckEquals(true,
CompareMem(@ACLResult, TestResult.Dacl,
SizeOf(ACL) + ACLResult.Header.AclSize),
'Unexpected ACL');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTSecurityDescriptorManipulator.Suite);
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*****************************************************************
The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net
and KadC library http://kadc.sourceforge.net/
*****************************************************************
}
{
Description:
DHT low level search code
}
unit dht_search;
interface
uses
dht_int160,classes,classes2,math,dht_consts,windows,
sysutils;
type
TmDHTsearch=class(Tobject)
m_type:Tmdhtsearchtype;
m_stoping:boolean;
m_created,
m_answers:cardinal; //Used for gui reasons.. May not be needed later..
m_lastResponse:cardinal;
m_target:CU_INT160;
m_possible,
m_tried,
m_responded,
m_best,
m_delete,
m_inUse:tmylist;
constructor create;
destructor destroy; override;
function StartIDSearch:boolean;
procedure sendFindID(ip:cardinal; port:word);
procedure sendGetPEERS(ip:cardinal; port:word);
function Find_Replying_Contact(IP:Cardinal;Port:word):Tmdhtbucket;
procedure processResponse(fromIP:cardinal; fromPort:word; results:tmylist);
procedure expire;
procedure CheckExpire;
function has_contacts_withID(list:tmylist; id:pCU_INT160):boolean;
end;
implementation
uses
helper_datetime,thread_bittorrent,
dht_socket,helper_strings;
constructor TmDHTsearch.create;
begin
m_created:=time_now;
m_type:=UNDEFINED;
m_answers:=0;
m_stoping:=false;
m_lastResponse:=m_created;
m_possible:=tmylist.create;
m_tried:=tmylist.create;
m_responded:=tmylist.create;
m_best:=tmylist.create;
m_delete:=tmylist.create;
m_inUse:=tmylist.create;
end;
destructor TmDHTsearch.destroy;
var
c:Tmdhtbucket;
begin
while (m_delete.count>0) do begin
c:=m_delete[m_delete.count-1];
m_delete.delete(m_delete.count-1);
c.free;
end;
m_possible.free;
m_tried.free;
m_responded.free;
m_best.free;
m_delete.free;
m_inUse.free;
inherited;
end;
procedure TmDHTSearch.CheckExpire; //every second
var
count,donecount:integer;
bucket:tmdhtbucket;
distanceFromTarget:cu_int160;
begin
if m_possible.count=0 then begin
if m_type<>NODE then begin
if ((m_created+SEC(10)<time_now)) then begin
expire;
exit;
end;
end else begin
expire;
exit;
end;
end;
if m_lastResponse+SEC(3)>time_now then exit;
// if m_type=dht_consts.FINDSOURCE then
// outputdebugstring(pchar('3 seconds of inactivity go on with possible count:'+inttostr(m_possible.count)));
thread_bittorrent.mdht_sortCloserContacts(m_possible,@m_target);
donecount:=0;
count:=4;
while ((m_possible.count>0) and (donecount<count)) do begin
bucket:=m_possible[0];
m_possible.delete(0);
if has_contacts_withid(m_tried,@bucket.ID) then continue;
// Move to tried
m_tried.add(bucket);
if (m_type=dht_consts.FINDSOURCE) and (bucket.ID[0] xor m_target[0] < MDHT_SEARCH_TOLERANCE) then begin
CU_Int160_FillNXor(@distanceFromTarget,@bucket.id,@m_target);
// outputdebugstring(pchar('FINDPEER:'+CU_INT160_tohexstr(@bucket.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
sendGetPeers(bucket.ipC, bucket.portW);
end else begin
// if (m_type=dht_consts.FINDSOURCE) and
// (bucket.ID[0] xor m_target[0] >= SEARCH_TOLERANCE) then outputdebugstring(pchar('Search tolerance too big'));
sendFindID( bucket.ipC, bucket.portW);
end;
if m_type=NODE then break;
inc(donecount);
end;
end;
function TmDHTSearch.has_contacts_withID(list:tmylist; id:pCU_INT160):boolean;
var
i:integer;
c:tmdhtbucket;
begin
result:=false;
for i:=0 to list.count-1 do begin
c:=list[i];
if CU_INT160_compare(id,@c.id) then begin
result:=true;
exit;
end;
end;
end;
function TmDHTSearch.Find_Replying_Contact(IP:Cardinal; Port:word):Tmdhtbucket;
var
h:integer;
begin
result:=nil;
for h:=0 to m_tried.count-1 do begin
result:=m_tried[h];
if ((result.ipC=IP) and
(result.portW=Port)) then exit;
end;
result:=nil;
end;
procedure tmDHTsearch.processResponse(fromIP:cardinal; fromPort:word; results:tmylist);
var
i:integer;
c,from,worstcontact:tmdhtbucket;
distanceFromTarget:CU_INT160;
sendquery:boolean;
begin
m_lastResponse:=time_now;
// Remember the contacts to be deleted when finished
for i:=0 to results.count-1 do begin
c:=results[i];
m_delete.add(c);
end;
// Not interested in responses for FIND_NODE, will be added to contacts by thread_bittorent
if m_type=dht_consts.NODE then begin
inc(m_answers);
m_possible.clear;
results.clear;
exit;
end;
from:=Find_Replying_contact(FromIp,FromPort);
if from=nil then begin
exit;
end;
//CU_INT160_fillNXor(@fromDistance,@from.m_clientid,@m_target);
// Add to list of people who responded
m_responded.add(from);
if m_type=dht_consts.NODE then begin
CU_Int160_FillNXor(@distanceFromTarget,@from.id,@m_target);
outputdebugstring(pchar('Response from:'+CU_INT160_tohexstr(@from.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
//thread_bittorrent.mdht_sortCloserContacts(results,@target);
// for i:=0 to results.count-1 do begin
// c:=results[i];
// CU_Int160_FillNXor(@distanceFromTarget,@c.id,@m_target);
// outputdebugstring(pchar('Host:'+CU_INT160_tohexstr(@c.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
// end;
end;
// Loop through their responses
for i:=0 to results.count-1 do begin
c:=results[i];
// Ignore this contact if already know him
if has_contacts_withid(m_possible,@c.ID) then continue;
if has_contacts_withid(m_tried,@c.ID) then continue;
// Add to possible
m_possible.add(c);
//CU_INT160_FillNXor(@distance,@c.m_clientID,@m_target);
// outputdebugstring(pchar('Result ID:'+CU_INT160_tohexstr(@c.id,true)));
if c.ID[0] xor m_target[0]>from.ID[0] xor m_target[0] then begin
//outputdebugstring(pchar('ecc 1'));
continue; // has better hosts then himself?
end;
sendquery:=false;
if m_best.count<MDHT_ALPHA_QUERY then begin //add it without any comparison
m_best.add(c);
thread_bittorrent.mdht_sortCloserContacts(m_best,@m_target);
sendquery:=true;
end else begin // add him only if he's better then the worst one
thread_bittorrent.mdht_sortCloserContacts(m_best,@m_target);
worstContact:=m_best[m_best.count-1];
if c.ID[0] xor m_target[0] < worstContact.ID[0] xor m_target[0] then begin
m_best.delete(m_best.count-1); // delete previous worst result
m_best.add(c);
thread_bittorrent.mdht_sortCloserContacts(m_best,@m_target);
sendquery:=true;
end else begin
// outputdebugstring(pchar('ecc 2'));
end;
end;
if sendquery then begin
m_tried.add(c);
if (m_type=dht_consts.FINDSOURCE) and (c.ID[0] xor m_target[0] < MDHT_SEARCH_TOLERANCE) then begin
// CU_Int160_FillNXor(@distanceFromTarget,@c.id,@m_target);
// outputdebugstring(pchar('FINDPEER:'+CU_INT160_tohexstr(@c.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
sendGetPeers(c.ipC, c.portW);
end else begin
if m_type=dht_consts.NODE then begin
CU_Int160_FillNXor(@distanceFromTarget,@c.id,@m_target);
outputdebugstring(pchar('Search on node:'+CU_INT160_tohexstr(@c.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
end;
sendFindID( c.ipC, c.portW);
end;
end;
end; //for results loop
if m_type=NODECOMPLETE then begin
inc(m_answers);
end;
results.clear;
end;
function TmDHTsearch.StartIDSearch:boolean;
var
i:integer;
count,donecount:integeR;
strtarget:string;
bucket:tmdhtbucket;
added,numstart:integer;
distanceFromMe,distanceFromTarget:CU_int160;
begin
result:=false;
// Start with a lot of possible contacts, this is a fallback in case search stalls due to dead contacts
if m_possible.count=0 then begin
CU_Int160_FillNXor(@distanceFromMe,@DHTme160,@m_target);
MDHT_routingZone.getClosestTo(3, @m_target, @distanceFromMe, 50, m_possible, true, true);
end;
if m_possible.count=0 then begin
//if m_type=dht_consts.NODECOMPLETE then outputdebugstring(pchar('no sources found!'));
exit;
end;
result:=true;
//Lets keep our contact list entries in mind to dec the inUse flag.
for i:=0 to m_possible.count-1 do begin
bucket:=m_possible[i];
m_inuse.add(bucket);
end;
// Take top 3 possible
count:=min(3, m_possible.count);
donecount:=0;
while ((m_possible.count>0) and (donecount<count)) do begin
bucket:=m_possible[0];
m_possible.delete(0);
//if m_type=dht_consts.NODECOMPLETE then begin
// CU_Int160_FillNXor(@distanceFromTarget,@bucket.id,@m_target);
// outputdebugstring(pchar('Starting findmyself search:'+CU_INT160_tohexstr(@bucket.id,true)+' Distance:'+CU_INT160_tohexstr(@distanceFromTarget,true)));
// end;
// Move to tried
m_tried.add(bucket);
sendFindID( bucket.ipC, bucket.portW);
if m_type=NODE then break;
inc(donecount);
end;
end;
procedure tmDHTsearch.Expire;
var
baseTime:cardinal;
begin
if m_stoping then exit;
baseTime:=0;
case m_type of
dht_consts.NODE,
dht_consts.NODECOMPLETE:baseTime:=dht_consts.MDHT_SEARCHNODE_LIFETIME;
dht_consts.FINDSOURCE:baseTime:=dht_consts.MDHT_SEARCHFINDSOURCE_LIFETIME
else baseTime:=dht_consts.MDHT_SEARCH_LIFETIME;
end;
m_created:=time_now-baseTime+SEC(15);
m_stoping:=true;
end;
procedure TmDHTsearch.sendFindID(ip:cardinal; port:word);
var
target,me160,outstr:String;
begin
if m_stoping then exit;
target:=CU_INT160_tohexbinstr(@m_target,true);
me160:=CU_INT160_tohexbinstr(@DHTme160);
//d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe
outstr:='d'+
'1:a'+
'd'+
'2:id20:'+me160+
'6:target20:'+target+
'e'+
'1:q9:find_node'+
'1:t2:'+int_2_word_string(mdht_currentOutpacketIndex)+
'1:y1:q'+
'e';
MDHT_len_tosend:=length(outstr);
move(outstr[1],MDHT_buffer,length(outstr));
dht_socket.mdht_send(ip,port,dht_socket.query_findnode,self);
end;
procedure TmDHTsearch.sendGetPEERS(ip:cardinal; port:word);
var
target,me160,outstr:String;
begin
if m_stoping then exit;
target:=CU_INT160_tohexbinstr(@m_target,true);
me160:=CU_INT160_tohexbinstr(@DHTme160);
//d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe
outstr:='d'+
'1:a'+
'd'+
'2:id20:'+me160+
'9:info_hash20:'+target+
'e'+
'1:q9:get_peers'+
'1:t2:'+int_2_word_string(mdht_currentOutpacketIndex)+
'1:y1:q'+
'e';
MDHT_len_tosend:=length(outstr);
move(outstr[1],MDHT_buffer,length(outstr));
dht_socket.mdht_send(ip,port,dht_socket.query_getpeer,self);
end;
end. |
unit test_main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, FngDirWatch;
const
Status_State = 0;
Status_Directory = 1;
type
TMainForm = class(TForm)
ToolbarPanel: TPanel;
StatusBar: TStatusBar;
Bevel: TBevel;
StartBtn: TButton;
SetDirBtn: TButton;
Memo: TMemo;
ClearBtn: TButton;
FDirWatch: TFnugryDirWatch;
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure StartBtnClick(Sender: TObject);
procedure SetDirCmd(Sender: TObject);
procedure ClearCmd(Sender: TObject);
procedure DirWatchChange(Sender :TObject);
procedure DirWatchNotify(Sender :TObject;
Action :Integer; const FileName :String);
private
procedure UpdateStatus;
procedure UpdateControls;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FDirWatch.free;
end;
procedure TMainForm.UpdateStatus;
begin
if assigned(FDirWatch) then
begin
StatusBar.Panels[Status_Directory].Text := FDirWatch.Directory;
if FDirWatch.Enabled then
StatusBar.Panels[Status_State].Text := 'Enabled'
else
StatusBar.Panels[Status_State].Text := 'Disabled';
end
else
begin
StatusBar.Panels[Status_Directory].Text := 'none';
StatusBar.Panels[Status_State].Text := 'none'
end;
end;
procedure TMainForm.UpdateControls;
begin
StartBtn.Enabled := assigned(FDirWatch);
SetDirBtn.Enabled := assigned(FDirWatch);
if assigned(FDirWatch) then
if FDirWatch.Enabled then
StartBtn.Caption := 'Stop'
else
StartBtn.Caption := 'Start';
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
UpdateStatus;
UpdateControls;
end;
procedure TMainForm.DirWatchChange(Sender :TObject);
begin
UpdateStatus;
UpdateControls;
end;
procedure TMainForm.StartBtnClick(Sender: TObject);
begin
FDirWatch.Enabled := not FDirWatch.Enabled;
end;
procedure TMainForm.SetDirCmd(Sender: TObject);
var
S :String;
begin
//
S := FDirWatch.Directory;
if InputQuery('Change Directory', 'Directory to watch:', S)then
FDirWatch.Directory := S;
end;
procedure TMainForm.DirWatchNotify(Sender :TObject;
Action :Integer; const FileName :String);
begin
memo.lines.add(format('[%s] %s:'#9'%s',
[FormatDateTime('hh:nn:ss', now),
FDirWatch.ActionName(Action), FIleName]));
end;
procedure TMainForm.ClearCmd(Sender: TObject);
begin
memo.clear;
end;
end.
|
unit set_in_2;
interface
implementation
type
TEnum = (i1, i2, i3, i4);
var
S: set of TEnum;
G1, G2: Boolean;
procedure Test;
begin
S := [i1, i3];
G1 := (i3 in S) and (i2 in S);
G2 := (i4 in S) or (i1 in S);
end;
initialization
Test();
finalization
Assert(G1 = False);
Assert(G2 = True);
end. |
{*
* GetBreakType: Detects the type of line break in a file.
* Jonas Raoni Soares da Silva <http://raoni.org>
* https://github.com/jonasraoni/get-break-type
*}
TBreakType = (btUnknown, btWindows, btMacintosh, btUnix, btBinary);
function GetBreakType(const Filename: string; const MaxDataToRead: Cardinal = 5 * 1024): TBreakType;
var
FS: TFileStream;
Buffer, BufferStart, BufferEnd: PChar;
begin
Result := btUnknown;
if not FileExists(Filename) then
raise Exception.Create('GetBreakType: invalid file name');
try
FS := TFileStream.Create(Filename, fmOpenRead);
GetMem(Buffer, MaxDataToRead + 1);
BufferEnd := (Buffer + FS.Read(Buffer^, MaxDataToRead));
BufferStart := Buffer;
BufferEnd^ := #0;
except
raise Exception.Create('GetBreakType: error allocating memory');
end;
try
while Buffer^ <> #0 do begin
if Result = btUnknown then
if Buffer^ = ASCII_CR then begin
if (Buffer + 1)^ = ASCII_LF then begin
Result := btWindows;
Inc(Buffer);
end
else
Result := btMacintosh;
end
else if Buffer^ = ASCII_LF then
Result := btUnix;
Inc(Buffer);
end;
if Buffer <> BufferEnd then
Result := btBinary;
finally
FreeMem(BufferStart, MaxDataToRead + 1);
FS.Free;
end;
end; |
unit FIToolkit.Main;
interface
uses
System.SysUtils, System.Types;
type
TExitCode = type LongWord;
function RunApplication(const FullExePath : TFileName; const CmdLineOptions : TStringDynArray) : TExitCode;
function TerminateApplication(E : Exception) : TExitCode;
implementation
uses
System.Classes, System.IOUtils, System.Math, System.Generics.Defaults, System.Rtti,
FIToolkit.ExecutionStates, FIToolkit.Exceptions, FIToolkit.Types, FIToolkit.Consts, FIToolkit.Utils,
FIToolkit.Commons.FiniteStateMachine.FSM, //TODO: remove when "F2084 Internal Error: URW1175" fixed
FIToolkit.Commons.StateMachine, FIToolkit.Commons.Utils,
FIToolkit.CommandLine.Options, FIToolkit.CommandLine.Consts,
FIToolkit.Config.Manager,
FIToolkit.Logger.Default;
type
TFIToolkit = class sealed (TLoggable)
private
type
//TODO: replace when "F2084 Internal Error: URW1175" fixed
IStateMachine = IFiniteStateMachine<TApplicationState, TApplicationCommand, EStateMachineError>;
TStateMachine = TFiniteStateMachine<TApplicationState, TApplicationCommand, EStateMachineError>;
strict private
FConfig : TConfigManager;
FOptions : TCLIOptions;
FStateMachine : IStateMachine;
FWorkflowState : TWorkflowStateHolder;
strict private
procedure InitConfig(GenerateFlag : Boolean);
procedure InitOptions(const CmdLineOptions : TStringDynArray);
procedure InitStateMachine;
private
FNoExitBehavior : TNoExitBehavior;
procedure ActualizeExitCode(var CurrentCode : TExitCode);
procedure ProcessOptions;
// Application commands implementation:
procedure PrintHelp;
procedure PrintVersion;
procedure SetLogFile;
procedure SetNoExitBehavior;
public
class procedure PrintAbout;
class procedure PrintHelpSuggestion(const FullExePath : TFileName);
constructor Create(const FullExePath : TFileName; const CmdLineOptions : TStringDynArray);
destructor Destroy; override;
function Run : TExitCode;
end;
{ Utils }
function _IsInDebugMode : Boolean;
begin
Result := FindCmdLineSwitch(STR_CMD_LINE_SWITCH_DEBUG, True);
end;
function _CanExit(Instance : TFIToolkit; E : Exception) : Boolean;
begin
if not Assigned(Instance) then
Result := True
else
begin
case Instance.FNoExitBehavior of
neDisabled:
Result := True;
neEnabled:
Result := False;
neEnabledOnException:
Result := not Assigned(E);
else
Assert(False, 'Unhandled no-exit behavior while terminating application.');
raise AbortException;
end;
end;
end;
procedure _OnException(E : Exception; out AnExitCode : TExitCode);
begin
if Log.Enabled then
Log.Fatal(E.ToString(True) + sLineBreak)
else
PrintLn(E.ToString(True) + sLineBreak);
AnExitCode := UINT_EC_ERROR_OCCURRED;
end;
procedure _OnTerminate(AnExitCode : TExitCode; CanExit : Boolean);
begin
PrintLn;
if not Log.Enabled then
PrintLn(Format(RSTerminatingWithExitCode, [AnExitCode]))
else
case AnExitCode of
UINT_EC_NO_ERROR:
Log.InfoFmt(RSTerminatingWithExitCode, [AnExitCode]);
UINT_EC_ERROR_OCCURRED:
Log.FatalFmt(RSTerminatingWithExitCode, [AnExitCode]);
else
Log.WarningFmt(RSTerminatingWithExitCode, [AnExitCode]);
end;
if not CanExit then
begin
PrintLn;
PressAnyKeyPrompt;
end;
end;
{ Export }
function RunApplication(const FullExePath : TFileName; const CmdLineOptions : TStringDynArray) : TExitCode;
var
App : TFIToolkit;
begin
InitConsoleLog(_IsInDebugMode);
if Length(CmdLineOptions) = 0 then
begin
TFIToolkit.PrintHelpSuggestion(FullExePath);
Result := UINT_EC_ERROR_OCCURRED;
_OnTerminate(Result, _CanExit(nil, nil));
Exit;
end;
TFIToolkit.PrintAbout;
App := TFIToolkit.Create(FullExePath, CmdLineOptions);
try
try
Result := App.Run;
_OnTerminate(Result, _CanExit(App, nil));
except
on E: Exception do
begin
_OnException(E, Result);
_OnTerminate(Result, _CanExit(App, E));
end;
end;
finally
App.Free;
end;
end;
function TerminateApplication(E : Exception) : TExitCode;
begin
if Assigned(E) then
_OnException(E, Result)
else
Result := UINT_EC_NO_ERROR;
_OnTerminate(Result, _CanExit(nil, E));
end;
{ TFIToolkit }
procedure TFIToolkit.ActualizeExitCode(var CurrentCode : TExitCode);
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.ActualizeExitCode, [CurrentCode]);
if FStateMachine.CurrentState = asFinal then
if FConfig.ConfigData.NonZeroExitCodeMsgCount > 0 then
begin
Log.InfoFmt(RSAcceptableMessageCountThreshold, [FConfig.ConfigData.NonZeroExitCodeMsgCount]);
if FWorkflowState.TotalMessages >= FConfig.ConfigData.NonZeroExitCodeMsgCount then
CurrentCode := UINT_EC_ANALYSIS_MESSAGES_FOUND;
end;
Log.DebugFmt('CurrentCode = %d', [CurrentCode]);
Log.LeaveMethod(TFIToolkit, @TFIToolkit.ActualizeExitCode);
end;
constructor TFIToolkit.Create(const FullExePath : TFileName; const CmdLineOptions : TStringDynArray);
begin
inherited Create;
InitOptions(CmdLineOptions);
InitStateMachine;
end;
destructor TFIToolkit.Destroy;
begin
FStateMachine := nil;
FreeAndNil(FWorkflowState);
FreeAndNil(FConfig);
FreeAndNil(FOptions);
inherited Destroy;
end;
procedure TFIToolkit.InitConfig(GenerateFlag : Boolean);
var
sConfigOptionName : String;
ConfigOption : TCLIOption;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.InitConfig, [GenerateFlag]);
sConfigOptionName := Iff.Get<String>(GenerateFlag, STR_CLI_OPTION_GENERATE_CONFIG, STR_CLI_OPTION_SET_CONFIG);
if FOptions.Find(sConfigOptionName, ConfigOption, not IsCaseSensitiveCLIOption(sConfigOptionName)) and
TPath.IsApplicableFileName(ConfigOption.Value) and
(TFile.Exists(ConfigOption.Value) or GenerateFlag)
then
try
Log.DebugFmt('ConfigOption.Value = "%s"', [ConfigOption.Value]);
FConfig := TConfigManager.Create(ConfigOption.Value, GenerateFlag, True)
except
if GenerateFlag then
Exception.RaiseOuterException(EUnableToGenerateConfig.Create)
else
Exception.RaiseOuterException(EErroneousConfigSpecified.Create);
end
else
begin
Log.DebugFmt('ConfigOption.Value = "%s"', [ConfigOption.Value]);
raise ENoValidConfigSpecified.Create;
end;
Log.LeaveMethod(TFIToolkit, @TFIToolkit.InitConfig);
end;
procedure TFIToolkit.InitOptions(const CmdLineOptions : TStringDynArray);
var
S : String;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.InitOptions, [String.Join(STR_CLI_OPTIONS_DELIMITER, CmdLineOptions)]);
FOptions := TCLIOptions.Create;
FOptions.Capacity := Length(CmdLineOptions);
for S in CmdLineOptions do
FOptions.AddUnique(S, not IsCaseSensitiveCLIOption(TCLIOption(S).Name));
Log.LeaveMethod(TFIToolkit, @TFIToolkit.InitOptions);
end;
procedure TFIToolkit.InitStateMachine;
begin //FI:C101
Log.EnterMethod(TFIToolkit, @TFIToolkit.InitStateMachine, []);
FStateMachine := TStateMachine.Create(asInitial);
{ Common states }
FStateMachine
.AddTransition(asInitial, asNoExitBehaviorSet, acSetNoExitBehavior,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
SetNoExitBehavior;
end
)
.AddTransitions([asInitial, asNoExitBehaviorSet], asLogFileSet, acSetLogFile,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
SetLogFile;
end
)
.AddTransitions(ARR_INITIAL_APPSTATES, asHelpPrinted, acPrintHelp,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
PrintHelp;
end
)
.AddTransitions(ARR_INITIAL_APPSTATES, asVersionPrinted, acPrintVersion,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
PrintVersion;
end
);
{ Config states }
FStateMachine
.AddTransitions(ARR_INITIAL_APPSTATES, asConfigGenerated, acGenerateConfig,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
InitConfig(True);
Log.Info(RSConfigWasGenerated + sLineBreak + RSEditConfigManually);
end
)
.AddTransitions(ARR_INITIAL_APPSTATES, asConfigSet, acSetConfig,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.DebugFmt('%s: %s → %s', [UsedCommand.ToString, PreviousState.ToString, CurrentState.ToString]);
InitConfig(False);
end
);
{ Execution states }
FStateMachine.AddTransition(asConfigSet, asInitial, acStart);
Log.LeaveMethod(TFIToolkit, @TFIToolkit.InitStateMachine);
end;
class procedure TFIToolkit.PrintAbout;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.PrintAbout, []);
PrintLn(RSApplicationAbout);
Log.LeaveMethod(TFIToolkit, @TFIToolkit.PrintAbout);
end;
procedure TFIToolkit.PrintHelp;
var
RS : TResourceStream;
SL : TStringList;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.PrintHelp, []);
RS := TResourceStream.Create(HInstance, STR_RES_HELP, RT_RCDATA);
try
SL := TStringList.Create;
try
SL.LoadFromStream(RS, TEncoding.UTF8);
PrintLn(SL.Text);
finally
SL.Free;
end;
finally
RS.Free;
end;
Log.LeaveMethod(TFIToolkit, @TFIToolkit.PrintHelp);
end;
class procedure TFIToolkit.PrintHelpSuggestion(const FullExePath : TFileName);
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.PrintHelpSuggestion, [FullExePath]);
PrintLn(Format(RSHelpSuggestion,
[TPath.GetFileName(FullExePath) + STR_CLI_OPTIONS_DELIMITER + STR_CLI_OPTION_PREFIX + STR_CLI_OPTION_HELP]));
Log.LeaveMethod(TFIToolkit, @TFIToolkit.PrintHelpSuggestion);
end;
procedure TFIToolkit.PrintVersion;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.PrintVersion, []);
PrintLn(GetAppVersionInfo);
Log.LeaveMethod(TFIToolkit, @TFIToolkit.PrintVersion);
end;
procedure TFIToolkit.ProcessOptions;
var
Opt : TCLIOption;
Cmd : TApplicationCommand;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.ProcessOptions, []);
FOptions.Sort(TComparer<TCLIOption>.Construct(
function (const Left, Right : TCLIOption) : Integer
begin
Result := CompareValue(
GetCLIOptionProcessingOrder(Left.Name, not IsCaseSensitiveCLIOption(Left.Name)),
GetCLIOptionProcessingOrder(Right.Name, not IsCaseSensitiveCLIOption(Right.Name))
);
end
));
Log.Debug('FOptions.ToString = ' + FOptions.ToString);
for Opt in FOptions do
if TryCLIOptionToAppCommand(Opt.Name, not IsCaseSensitiveCLIOption(Opt.Name), Cmd) then
begin
Log.DebugFmt('Opt.Name = "%s" → Cmd = "%s"', [Opt.Name, Cmd.ToString]);
FStateMachine.Execute(Cmd);
end;
Log.LeaveMethod(TFIToolkit, @TFIToolkit.ProcessOptions);
end;
function TFIToolkit.Run : TExitCode;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.Run, []);
Result := UINT_EC_NO_ERROR;
try
ProcessOptions;
except
Exception.RaiseOuterException(ECLIOptionsProcessingFailed.Create);
end;
Log.Debug('FStateMachine.CurrentState = ' + FStateMachine.CurrentState.ToString);
if not (FStateMachine.CurrentState in SET_FINAL_APPSTATES) then
try
if not Assigned(FConfig) then
raise ENoValidConfigSpecified.Create;
Log.EnterSection(RSPreparingWorkflow);
FWorkflowState := TWorkflowStateHolder.Create(FConfig.ConfigData);
TExecutiveTransitionsProvider.PrepareWorkflow(FStateMachine, FWorkflowState);
Log.LeaveSection(RSWorkflowPrepared);
FStateMachine
.Execute(acStart)
.Execute(acExtractProjects)
.Execute(acExcludeProjects)
.Execute(acRunFixInsight)
.Execute(acParseReports)
.Execute(acExcludeUnits)
.Execute(acBuildReport)
.Execute(acMakeArchive)
.Execute(acTerminate);
Log.InfoFmt(RSTotalDuration, [String(FWorkflowState.TotalDuration)]);
Log.InfoFmt(RSTotalMessages, [FWorkflowState.TotalMessages]);
ActualizeExitCode(Result);
except
Exception.RaiseOuterException(EApplicationExecutionFailed.Create);
end;
Log.LeaveMethod(TFIToolkit, @TFIToolkit.Run, Result);
end;
procedure TFIToolkit.SetLogFile;
var
LogFileOption : TCLIOption;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.SetLogFile, []);
if FOptions.Find(STR_CLI_OPTION_LOG_FILE, LogFileOption, not IsCaseSensitiveCLIOption(STR_CLI_OPTION_LOG_FILE)) then
begin
Log.DebugFmt('LogFileOption.Value = "%s"', [LogFileOption.Value]);
if TPath.IsApplicableFileName(LogFileOption.Value) then
InitFileLog(LogFileOption.Value);
end;
Log.LeaveMethod(TFIToolkit, @TFIToolkit.SetLogFile);
end;
procedure TFIToolkit.SetNoExitBehavior;
var
NoExitOption : TCLIOption;
iValue : Integer;
begin
Log.EnterMethod(TFIToolkit, @TFIToolkit.SetNoExitBehavior, []);
if FOptions.Find(STR_CLI_OPTION_NO_EXIT, NoExitOption, not IsCaseSensitiveCLIOption(STR_CLI_OPTION_NO_EXIT)) then
begin
Log.DebugFmt('NoExitOption.Value = "%s"', [NoExitOption.Value]);
if Integer.TryParse(NoExitOption.Value, iValue) then
if InRange(iValue, Integer(Low(TNoExitBehavior)), Integer(High(TNoExitBehavior))) then
FNoExitBehavior := TNoExitBehavior(iValue);
end;
Log.DebugVal(['FNoExitBehavior = ', TValue.From<TNoExitBehavior>(FNoExitBehavior)]);
Log.LeaveMethod(TFIToolkit, @TFIToolkit.SetNoExitBehavior);
end;
end.
|
{ 25/05/2007 11:16:46 (GMT+1:00) > [Akadamia] checked in }
{ 14/02/2007 08:32:06 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:31:52 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:16:54 (GMT+0:00) > [Akadamia] checked in }
{ 08/02/2007 14:08:09 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: NCU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of No Callback example to Delphi
Responds to the user aircraft brakes, without a callback function
History:
-----------------------------------------------------------------------------}
unit NCU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TGroupId = (Group10);
TEventID = (EventBrakes10);
// The form
TNoCallbackForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
end;
var
NoCallbackForm: TNoCallbackForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TNoCallbackForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TNoCallbackForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TNoCallbackForm.SimConnectMessage(var Message: TMessage);
var
pData: PSimConnectRecv;
cbData: DWORD;
hr: HRESULT;
Evt: PSimconnectRecvEvent;
begin
hr := SimConnect_GetNextDispatch(hSimConnect, pData, cbData);
if SUCCEEDED(hr) then
begin
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EventBrakes10:
Memo.Lines.Add(Format('Event brakes: %d', [evt^.dwData]));
end;
end;
SIMCONNECT_RECV_ID_QUIT: // enter code to handle exiting the application
quit := True;
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TNoCallbackForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'No Callback', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventBrakes10),
'brakes');
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect,
Ord(Group10), Ord(EventBrakes10));
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(Group10),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TNoCallbackForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
pData: PSimConnectRecv;
cbData: DWORD;
Evt: PSimconnectRecvEvent;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventBrakes10),
'brakes');
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect,
Ord(Group10), Ord(EventBrakes10));
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(Group10),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
hr := SimConnect_GetNextDispatch(hSimConnect, &pData, &cbData);
if SUCCEEDED(hr) then
begin
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EventBrakes10:
Memo.Lines.Add(Format('Event brakes: %d', [evt^.dwData]));
end;
end;
SIMCONNECT_RECV_ID_QUIT: // enter code to handle exiting the application
quit := True;
end;
end;
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit ncCommPlusIndy;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils, Classes, SyncObjs, ExtCtrls, dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, idURI;
type
TplusReq = class
ptrTokenNex : TGUID;
ptrTokenPlus : String;
ptrURL : String;
ptrGettingToken : Boolean;
ptrResp: TStrings;
FLastError : String;
protected
procedure prepareRequest; virtual;
procedure prepare_getToken;
function ptrTokenNexStr: String;
function ptrKey: String;
destructor Destroy; virtual;
public
constructor Create; virtual;
procedure Start;
property Resposta: TStrings read ptrResp;
end;
TplusPostTranReq = class ( TplusReq )
ptrConta : String;
ptrParceiro : String;
ptrIDTranParceiro : String;
ptrIDTranNex : String;
ptrDTTranNex : TDateTime;
ptrDescr : String;
ptrDTTranParceiro : TDateTime;
ptrValor : Double;
ptrPIN : String;
ptrSucesso : Boolean;
ptrObs : String;
protected
procedure prepareRequest; override;
public
constructor Create; override;
end;
TplusReqProdutos = class ( TplusReq )
protected
procedure prepareRequest; override;
public
function ItemCount: Integer;
function ProdutoExiste(aCodParceiro, aCodigo: String): Boolean;
function Codigo(I: Integer): String;
function CodParceiro(I: Integer): String;
function Nome(I: Integer): String;
function url_imagem(I: Integer): String;
function url_vendas(I: Integer): String;
end;
TplusReqParceiros = class ( TplusReq )
protected
procedure prepareRequest; override;
public
function ItemCount: Integer;
function ParceiroExiste(aCodParceiro: String): Boolean;
function Codigo(i: Integer): String;
function Nome(i: Integer): String;
function KeyIndex(i: Integer): String;
function url_imagem(i: Integer): String;
function url_timeout(I: Integer): String;
end;
TplusReqAdesoes = class ( TplusReq )
praConta : String;
protected
procedure prepareRequest; override;
public
function AdesaoExiste(aCodParceiro: String): Boolean;
constructor Create; override;
end;
TplusReqUpdateAll = class ( TThread )
private
FSucesso : Boolean;
FReqParceiros: TplusReqParceiros;
FReqProdutos: TplusReqProdutos;
FReqAdesoes: TplusReqAdesoes;
FTag: Integer;
protected
procedure Execute; override;
procedure OnTimerFree(Sender: TObject);
public
constructor Create;
// destructor Destroy; override;
procedure Destruir;
procedure Executar;
property Sucesso: Boolean read FSucesso;
property Tag: Integer read FTag write FTag;
property ReqParceiros: TplusReqParceiros read FReqParceiros;
property ReqProdutos: TplusReqProdutos read FReqProdutos;
property ReqAdesoes: TplusReqAdesoes read FReqAdesoes;
end;
implementation
uses ncaK, ncClassesBase, ncShellStart, ncDebug;
const
BoolStr : Array[Boolean] of Char = ('0', '1');
HostStr : String = 'http://plus.nexcafe.com.br';
{ TplusReq }
function GetNStr(S: String; P: Integer): String;
begin
while (P>1) do begin
Delete(S, 1, Pos(';', S));
Dec(P);
end;
if Pos(';', S)>0 then
Delete(S, Pos(';', S), 1000);
Result := Trim(S);
end;
constructor TplusReq.Create;
begin
FLastError := '';
ptrGettingToken := False;
ptrResp := TStringList.Create;
CreateGUID(ptrTokenNex)
end;
destructor TplusReq.Destroy;
begin
ptrResp.Free;
inherited;
end;
procedure TplusReq.prepareRequest;
begin
end;
procedure TplusReq.prepare_getToken;
begin
ptrGettingToken := True;
ptrURL := HostStr + '/api/tokenplus/get/'; // do not localize
end;
function TplusReq.ptrKey: String;
begin
nexGetKH(1, ptrTokenPlus, '', '');
end;
function TplusReq.ptrTokenNexStr: String;
begin
Result := GUIDToString(ptrTokenNex);
end;
procedure TplusReq.Start;
var
H : TidHTTP;
S : String;
begin
H := TidHttp.Create(nil);
try
H.HandleRedirects := True;
try
ptrTokenPlus := '';
ptrResp.Text := '';
prepare_getToken;
ptrResp.Text := H.Get(ptrURL);
ptrGettingToken := False;
ptrTokenPlus := ptrResp[0];
ptrResp.Text := '';
prepareRequest;
S := H.Get(ptrURL);
if S='lkjasdlkjasldkjasd' then Exit; // do not localize
ptrResp.Text := UTF8ToANsi(S);
DebugMsg('TplusReq.Start - Resp: ' + ptrResp.Text); // do not localize
except
on E: Exception do begin
S := ptrURL;
if S='zzzzzzz' then Exit; // do not localize
S := E.Message;
if S='asdasdasdasd' then Exit; // do not localize
Raise;
end;
end;
finally
H.Free;
end;
end;
{ TplusPostTranReq }
constructor TplusPostTranReq.Create;
begin
inherited;
ptrConta := gConfig.Conta;
ptrParceiro := '';
ptrDescr := '';
ptrIDTranParceiro := '';
ptrIDTranNex := '';
ptrDTTranParceiro := 0;
ptrDTTranNex := 0;
ptrValor := 0;
ptrPIN := '';
ptrSucesso := False;
ptrObs := '';
end;
procedure TplusPostTranReq.prepareRequest;
var S, sValor: String; Code: Integer;
procedure AddParam(aName, aValue: String);
begin
if S>'' then
S := S + '&' else
S := '?';
S := S + aName+'='+TidURI.ParamsEncode(aValue);
end;
begin
inherited;
S := '';
AddParam('account', ptrConta ); // do not localize
AddParam('partner_id', ptrParceiro); // do not localize
AddParam('transaction_partner_id', ptrIDTranParceiro); // do not localize
AddParam('transaction_partner_datetime', FormatDateTime('yyyy-mm-dd hh:mm:ss', ptrDTTranParceiro)); // do not localize
AddParam('transaction_nexcafe_id', ptrIDTranNex); // do not localize
AddParam('transaction_nexcafe_datetime', FormatDateTime('yyyy-mm-dd hh:mm:ss', ptrDTTranNex)); // do not localize
Str(ptrValor:0:2, sValor);
AddParam('description', ptrDescr); // do not localize
AddParam('value', S); // do not localize
AddParam('pin', ptrPIN); // do not localize
AddParam('success', BoolStr[ptrSucesso]); // do not localize
AddParam('comment', ptrObs); // do not localize
AddParam('key', nexGetKH(1, ptrTokenPlus, '', '')); // do not localize
AddParam('tokennex', ptrTokenNexStr); // do not localize
AddParam('tokenplus', ptrTokenPlus); // do not localize
ptrURL := HostStr+'/api/transacoes/salvar/'+S; // do not localize
end;
{ TplusReqProdutos }
function TplusReqProdutos.Codigo(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 1);
end;
function TplusReqProdutos.CodParceiro(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 2);
end;
function TplusReqProdutos.ItemCount: Integer;
begin
Result := ptrResp.Count - 1;
end;
function TplusReqProdutos.Nome(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 3);
end;
procedure TplusReqProdutos.prepareRequest;
var S: String;
procedure AddParam(aName, aValue: String);
begin
if S>'' then
S := S + '&' else
S := '?';
S := S + aName+'='+TidURI.ParamsEncode(aValue);
end;
begin
inherited;
S := '';
AddParam('key', nexGetKH(1, ptrTokenPlus, '', '')); // do not localize
AddParam('tokennex', ptrTokenNexStr); // do not localize
AddParam('tokenplus', ptrTokenPlus); // do not localize
ptrURL := HostStr + '/api/produtos/' + S; // do not localize
end;
function TplusReqProdutos.ProdutoExiste(aCodParceiro, aCodigo: String): Boolean;
var I: Integer;
begin
for I := 1 to ItemCount do
if SameText(Codigo(I), aCodigo) and SameText(CodParceiro(I), aCodParceiro) then begin
Result := True;
Exit;
end;
Result := False;
end;
function TplusReqProdutos.url_imagem(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 4);
end;
function TplusReqProdutos.url_vendas(I: Integer): String;
var S: String;
begin
S := ptrResp[i];
Result := GetNStr(S, 5);
end;
{ TplusReqParceiros }
function TplusReqParceiros.Codigo(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 1);
end;
function TplusReqParceiros.ItemCount: Integer;
begin
Result := ptrResp.Count-1;
end;
function TplusReqParceiros.KeyIndex(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 3);
end;
function TplusReqParceiros.Nome(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 2);
end;
function TplusReqParceiros.ParceiroExiste(aCodParceiro: String): Boolean;
var I: Integer;
begin
for I := 1 to ItemCount do
if SameText(Codigo(I), aCodParceiro) then begin
Result := True;
Exit;
end;
Result := False;
end;
procedure TplusReqParceiros.prepareRequest;
var S: String;
procedure AddParam(aName, aValue: String);
begin
if S>'' then
S := S + '&' else
S := '?';
S := S + aName+'='+TidURI.ParamsEncode(aValue);
end;
begin
inherited;
S := '';
AddParam('key', nexGetKH(1, ptrTokenPlus, '', '')); // do not localize
AddParam('tokennex', ptrTokenNexStr); // do not localize
AddParam('tokenplus', ptrTokenPlus); // do not localize
ptrURL := HostStr + '/api/parceiros/' + S; // do not localize
end;
function TplusReqParceiros.url_imagem(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 4);
end;
function TplusReqParceiros.url_timeout(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 5);
end;
{ TplusReqAdesoes }
function TplusReqAdesoes.AdesaoExiste(aCodParceiro: String): Boolean;
var
S, sCod: String;
P: Integer;
begin
S := Resposta.Values['Adesoes']; // do not localize
Result := False;
while (not Result) and (Length(S)>0) do begin
P := Pos(';', S);
if P>0 then begin
sCod := Trim(Copy(S, 1, P-1));
Delete(S, 1, P);
end else begin
sCod := Trim(S);
S := '';
end;
if SameText(aCodParceiro, sCod) then
Result := True;
end;
end;
constructor TplusReqAdesoes.Create;
begin
inherited;
praConta := gConfig.Conta;
end;
procedure TplusReqAdesoes.prepareRequest;
var S: String;
procedure AddParam(aName, aValue: String);
begin
if S>'' then
S := S + '&' else
S := '?';
S := S + aName+'='+TidURI.ParamsEncode(aValue);
end;
begin
inherited;
S := '';
AddParam('account', praConta); // do not localize
AddParam('key', nexGetKH(1, ptrTokenPlus, '', '')); // do not localize
AddParam('tokennex', ptrTokenNexStr); // do not localize
AddParam('tokenplus', ptrTokenPlus); // do not localize
ptrURL := HostStr + '/api/adesoes/' + S; // do not localize
end;
{ TplusReqUpdateAll }
constructor TplusReqUpdateAll.Create;
begin
inherited Create(True);
FTag := 0;
FSucesso := False;
FreeOnTerminate := False;
FReqParceiros := TplusReqParceiros.Create;
FReqProdutos := TplusReqProdutos.Create;
FReqAdesoes := TplusReqAdesoes.Create;
end;
procedure TplusReqUpdateAll.Destruir;
begin
if Self <> nil then
with TTimer.Create(nil) do begin
Interval := 50;
OnTimer := OnTimerFree;
Enabled := True;
end;
end;
procedure TplusReqUpdateAll.Executar;
begin
Resume;
end;
procedure TplusReqUpdateAll.Execute;
begin
FSucesso := False;
try
FReqParceiros.Resposta.Clear;
FReqProdutos.Resposta.Clear;
FReqAdesoes.Resposta.Clear;
FReqParceiros.Start;
FReqProdutos.Start;
FReqAdesoes.Start;
FSucesso := True;
except
FSucesso := False;
end;
end;
procedure TplusReqUpdateAll.OnTimerFree(Sender: TObject);
begin
try
Sender.Free;
finally
if Self <> nil then Free;
end;
end;
end.
|
unit LLVM.Imports.DisassemblerTypes;
interface
//based on DisassemblerTypes.h
uses
LLVM.Imports,
LLVM.Imports.Types;
type
TLLVMDisasmContextRef = type TLLVMRef;
(**
* The type for the operand information call back function. This is called to
* get the symbolic information for an operand of an instruction. Typically
* this is from the relocation information, symbol table, etc. That block of
* information is saved when the disassembler context is created and passed to
* the call back in the DisInfo parameter. The instruction containing operand
* is at the PC parameter. For some instruction sets, there can be more than
* one operand with symbolic information. To determine the symbolic operand
* information for each operand, the bytes for the specific operand in the
* instruction are specified by the Offset parameter and its byte widith is the
* size parameter. For instructions sets with fixed widths and one symbolic
* operand per instruction, the Offset parameter will be zero and Size parameter
* will be the instruction width. The information is returned in TagBuf and is
* Triple specific with its specific information defined by the value of
* TagType for that Triple. If symbolic information is returned the function
* returns 1, otherwise it returns 0.
*)
TLLVMOpInfoCallback = function(DisInfo: Pointer; PC: UInt64; Offset: UInt64; Size: UInt64; TagType: Integer; TagBuf: Pointer): LongBool; cdecl;
(**
* The initial support in LLVM MC for the most general form of a relocatable
* expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets
* this full form is encoded in the relocation information so that AddSymbol and
* SubtractSymbol can be link edited independent of each other. Many other
* platforms only allow a relocatable expression of the form AddSymbol + Offset
* to be encoded.
*
* The LLVMOpInfoCallback() for the TagType value of 1 uses the struct
* LLVMOpInfo1. The value of the relocatable expression for the operand,
* including any PC adjustment, is passed in to the call back in the Value
* field. The symbolic information about the operand is returned using all
* the fields of the structure with the Offset of the relocatable expression
* returned in the Value field. It is possible that some symbols in the
* relocatable expression were assembly temporary symbols, for example
* "Ldata - LpicBase + constant", and only the Values of the symbols without
* symbol names are present in the relocation information. The VariantKind
* type is one of the Target specific #defines below and is used to print
* operands like "_foo@GOT", ":lower16:_foo", etc.
*)
TLLVMOpInfoSymbol1 = packed record
Present: UInt64; // 1 if this symbol is present
Name : PLLVMChar; // symbol name if not NULL
Value : UInt64; // symbol value if name is NULL
end;
TLLVMOpInfo1 = packed record
AddSymbol : TLLVMOpInfoSymbol1;
SubtractSymbol : TLLVMOpInfoSymbol1;
Value : UInt64;
VariantKind : UInt64;
end;
const
(**
* The operand VariantKinds for symbolic disassembly.
*)
LLVMDisassembler_VariantKind_None = 0; {/* all targets */}
(**
* The ARM target VariantKinds.
*)
LLVMDisassembler_VariantKind_ARM_HI16 = 1; {/* :upper16: */}
LLVMDisassembler_VariantKind_ARM_LO16 = 2; {/* :lower16: */}
LLVMDisassembler_VariantKind_ARM64_PAGE = 1; {/* @page */}
LLVMDisassembler_VariantKind_ARM64_PAGEOFF = 2; {/* @pageoff */}
LLVMDisassembler_VariantKind_ARM64_GOTPAGE = 3; {/* @gotpage */}
LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF = 4; {/* @gotpageoff */}
LLVMDisassembler_VariantKind_ARM64_TLVP = 5; {/* @tvlppage */}
LLVMDisassembler_VariantKind_ARM64_TLVOFF = 6; {/* @tvlppageoff */}
type
(**
* The type for the symbol lookup function. This may be called by the
* disassembler for things like adding a comment for a PC plus a constant
* offset load instruction to use a symbol name instead of a load address value.
* It is passed the block information is saved when the disassembler context is
* created and the ReferenceValue to look up as a symbol. If no symbol is found
* for the ReferenceValue NULL is returned. The ReferenceType of the
* instruction is passed indirectly as is the PC of the instruction in
* ReferencePC. If the output reference can be determined its type is returned
* indirectly in ReferenceType along with ReferenceName if any, or that is set
* to NULL.
*)
TLLVMSymbolLookupCallback = function(DisInfo: Pointer; ReferenceValue: UInt64; ReferenceType: UInt64; ReferencePC: UInt64; var ReferenceName: PLLVMChar): PLLVMChar; cdecl;
const
(**
* The reference types on input and output.
*)
{No input reference type or no output reference type.}
LLVMDisassembler_ReferenceType_InOut_None = 0;
{The input reference is from a branch instruction.}
LLVMDisassembler_ReferenceType_In_Branch = 1;
{The input reference is from a PC relative load instruction.}
LLVMDisassembler_ReferenceType_In_PCrel_Load = 2;
{The input reference is from an ARM64::ADRP instruction.}
LLVMDisassembler_ReferenceType_In_ARM64_ADRP = $100000001;
{The input reference is from an ARM64::ADDXri instruction.}
LLVMDisassembler_ReferenceType_In_ARM64_ADDXri = $100000002;
{The input reference is from an ARM64::LDRXui instruction.}
LLVMDisassembler_ReferenceType_In_ARM64_LDRXui = $100000003;
{The input reference is from an ARM64::LDRXl instruction.}
LLVMDisassembler_ReferenceType_In_ARM64_LDRXl = $100000004;
{The input reference is from an ARM64::ADR instruction.}
LLVMDisassembler_ReferenceType_In_ARM64_ADR = $100000005;
{The output reference is to as symbol stub.}
LLVMDisassembler_ReferenceType_Out_SymbolStub = 1;
{The output reference is to a symbol address in a literal pool.}
LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr = 2;
{The output reference is to a cstring address in a literal pool.}
LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr = 3;
{The output reference is to a Objective-C CoreFoundation string.}
LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref = 4;
{The output reference is to a Objective-C message.}
LLVMDisassembler_ReferenceType_Out_Objc_Message = 5;
{The output reference is to a Objective-C message ref.}
LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref = 6;
{The output reference is to a Objective-C selector ref.}
LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref = 7;
{The output reference is to a Objective-C class ref.}
LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref = 8;
{The output reference is to a C++ symbol name.}
LLVMDisassembler_ReferenceType_DeMangled_Name = 9;
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ WSDL Items }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WSDLItems;
interface
uses
{$IFDEF MSWINDOWS}Windows, Messages, {$ENDIF}SysUtils, Variants, Classes, TypInfo, XMLIntf, XMLDoc,
xmldom, XmlSchema, {$IFDEF MSWINDOWS}msxmldom, {$ENDIF}WSDLIntf, WSDLBind, HTTPUtil, Types;
type
TWSDLItems = class;
IWSDLItems = interface
['{F71B4B05-C5AB-4484-B994-64F3F9E805C7}']
function GetWSDLItems: TWSDLItems;
function GetWSDLDoc: IWSDLDocument;
procedure Load(const WSDLFileName: WideString);
end;
IQualifiedName = interface
['{0173ABA2-34AB-4CB1-ADF0-AA99C98FCFBD}']
function GetName: WideString;
procedure SetName(const name: WideString);
function GetNamespace: WideString;
procedure SetNamespace(const ns: WideString);
property Name: WideString read GetName write SetName;
property Namespace: WideString read GetNamespace write SetNamespace;
end;
IQualifiedNameArray = array of IQualifiedName;
IHeaderInfo = interface
['{3331A5D4-BA6D-4E76-80F3-279DB879EDCB}']
function GetPart: IPart;
procedure SetPart(const P: IPart);
function GetRequired: Boolean;
procedure SetRequired(Req: Boolean);
function GetUse: WideString;
procedure SetUse(const U: WideString);
function GetEncodingStyle: WideString;
procedure SetEncodingStyle(const EncStyl: WideString);
function GetNamespace: WideString;
procedure SetNamespace(const N: WideString);
function GetName: WideString;
procedure SetName(const N: WideString);
property Part: IPart read GetPart write SetPart;
property Required: Boolean read GetRequired write SetRequired;
property Use: WideString read GetUse write SetUse;
property EncodingStyle: WideString read GetEncodingStyle write SetEncodingStyle;
property Namespace: WideString read GetNamespace write SetNamespace;
property Name: WideString read GetName write SetName;
end;
IHeaderInfoArray = array of IHeaderInfo;
{ Options passed to Proc. when iterating through imports }
IterateImportOptions = (ioBeforeLoad, ioLoaded);
{ Callback when iterating through imports of a WSDL document }
TWSDLIterateProc = procedure (const Options: IterateImportOptions;
const WSDLItems: IWSDLItems;
const XMLSchemaDoc: IXMLSchemaDoc;
const Name: WideString) of object;
{ Helper class to get WSDL Items }
TWSDLItems = class(TWSDLDocument, IWSDLItems)
private
FWSDLStreamLoader: IStreamLoader;
{ Helper methods to Import WSDL documents }
function GetGenericBindingAttribute(const BindingName: WideString;
const NodeName: WideString;
const Namespace: WideString;
Attribute: WideString): WideString;
function MakeTNSName(const Name: WideString): WideString;
procedure GetBindingOfType(const BindingTypeName: WideString;
const TNS: WideString;
var BindingArray: IQualifiedNameArray); overload;
protected
function GetName: WideString;
function GetTargetNamespace: WideString;
function GetTargetNamespacePrefix: WideString;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(const WSDLItems: TWSDLItems; const StreamLoader: IStreamLoader); overload; virtual;
{ IWSDLItems }
function GetWSDLItems: TWSDLItems;
function GetWSDLDoc: IWSDLDocument;
procedure Load(const WSDLFileName: WideString);
function CompareName(const NodeName: WideString;
const OtherName: WideString;
const TNS: WideString = ''): boolean;
{ Helper methods to get WSDL Items }
procedure GetServices(ServiceNames: TWideStrings; QualifiedNames: Boolean = False);
function GetServiceNode(const ServiceName: WideString): IXMLNode;
procedure GetMessages(MessageNames: TWideStrings; QualifiedNames: Boolean = False);
function GetMessageNode(const MessageName: WideString): IXMLNode;
procedure GetParts(const MessageName: WideString; PartNames: TWideStrings; QualifiedNames: Boolean = False);
function GetPartNode(const MessageName, PartName: WideString): IXMLNode;
function IsPortTypeHTTPBound(const PortType: WideString): Boolean;
procedure GetPortTypes(PortTypeNames: TWideStrings; SkipHttpBindings: Boolean = True;
QualifiedNames: Boolean = False);
function GetPortTypeNode(const PortTypeName: WideString): IXMLNode;
procedure GetOperations(const PortTypeName: WideString; OperationNames: TWideStrings; QualifiedNames: Boolean = False);
function GetOperationNode(const PortTypeName, OperationName: WideString): IXMLNode;
procedure GetPortsForService(const ServiceName: WideString; PortNames: TWideStrings;
SkipHttpBindings: Boolean = True; QualifiedNames: Boolean = False);
{ Returns a Binding for the specified Service/Port combination }
function GetBindingForServicePort(const ServiceName, PortName: WideString): IQualifiedName;
{ Returns the Service/Port of the specified Binding }
function GetServiceAndPortOfBinding(const BindingName: IQualifiedName;
var ServiceName: WideString;
var PortName: WideString): Boolean;
{ Returns the endpoint/location for the specified Service/Port combination }
function GetSoapAddressForServicePort(const ServiceName, PortName: WideString): WideString;
{ Imports }
procedure GetImports(ImportNames: TWideStrings);
procedure IterateImports(IterateProc: TWSDLIterateProc);
function GetLocationForImport(const ImportNameSpace: WideString): WideString;
{ Schemas }
function HasTypesNode: Boolean;
procedure GetSchemas(SchemaNames: TWideStrings);
function GetSchemaNode(const SchemaTns: WideString) : IXMLNode;
{ Bindings }
procedure GetBindings(BindingNames: TWideStrings; QualifiedNames: Boolean = False);
function GetBindingType(const BindingName: WideString): WideString;
function GetBindingOfType(const BindingTypeName: WideString;
const TNS: WideString = ''): IQualifiedNameArray; overload;
function GetSoapBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString;
function GetHttpBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString; overload;
function GetHttpBindingAttribute(const QualifiedName: IQualifiedName; Attribute: WideString): WideString; overload;
procedure GetOperationsForBinding(const BindingName: WideString; OperationNames: TWideStrings; QualifiedNames: Boolean = False);
function GetBindingOperationNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IBindingOperation;
function GetSoapOperationAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
function GetSoapAction(const BindingName, Operation: WideString; OverloadIndex: Integer): WideString;
function GetSoapOperationStyle(const BindingName, Operation: WideString; OverloadIndex: Integer): WideString;
procedure GetSoapActionList(const BindingName: WideString; ActionList: TWideStrings; QualifiedNames: Boolean = False);
function GetSoapBindingIONode(const BindingName, Operation: WideString; Input: Boolean; OverloadIndex: Integer): IXMLNode;
function GetSoapBindingInputNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IXMLNode;
function GetSoapBindingOutputNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IXMLNode;
function GetSoapBodyAttribute(const BindingName, Operation, IOType, Attribute: WideString; OverloadIndex: Integer): WideString;
function GetSoapBodyInputAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
function GetSoapBodyOutputAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
function GetSoapBodyNamespace(const BindingPortType: WideString): WideString;
{ Headers }
function GetSoapHeaders(BindingName: IQualifiedName;
const Operation: WideString;
Input: Boolean;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
function GetSoapInputHeaders(BindingName: IQualifiedName;
const Operation: WideString;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
function GetSoapOutputHeaders(BindingName: IQualifiedName;
const Operation: WideString;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
function GetPartsForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings): Boolean;
property StreamLoader: IStreamLoader read FWSDLStreamLoader;
property TargetNamespace: WideString read GetTargetNamespace;
end;
{ Helper functions }
function HasDefinition(const WSDLDoc: IWSDLDocument): Boolean; overload;
function HasDefinition(const WSDLItems: IWSDLItems): Boolean; overload;
function NewQualifiedName(const Name: WideString = ''; const Namespace: WideString = ''): IQualifiedName;
implementation
uses SOAPConst;
type
TQualifiedName = class(TInterfacedObject, IQualifiedName)
private
FName: WideString;
FNamespace: WideString;
public
function GetName: WideString;
procedure SetName(const name: WideString);
function GetNamespace: WideString;
procedure SetNamespace(const ns: WideString);
end;
THeaderInfo = class(TInterfacedObject, IHeaderInfo)
private
FPart: IPart;
FRequired: Boolean;
FUse: WideString;
FEncodingStyle: WideString;
FNamespace: WideString;
FName: WideString;
public
function GetPart: IPart;
procedure SetPart(const P: IPart);
function GetRequired: Boolean;
procedure SetRequired(Req: Boolean);
function GetUse: WideString;
procedure SetUse(const U: WideString);
function GetEncodingStyle: WideString;
procedure SetEncodingStyle(const EncStyl: WideString);
function GetNamespace: WideString;
procedure SetNamespace(const N: WideString);
function GetName: WideString;
procedure SetName(const N: WideString);
end;
function NewQualifiedName(const Name: WideString; const Namespace: WideString): IQualifiedName;
begin
Result := TQualifiedName.Create;
Result.Name := Name;
Result.Namespace := Namespace;
end;
function NewHeaderInfo: IHeaderInfo;
begin
Result := THeaderInfo.Create;
end;
function TQualifiedName.GetName: WideString;
begin
Result := FName;
end;
procedure TQualifiedName.SetName(const name: WideString);
begin
FName := name;
end;
function TQualifiedName.GetNamespace: WideString;
begin
Result := FNamespace;
end;
procedure TQualifiedName.SetNamespace(const ns: WideString);
begin
FNamespace := ns;
end;
constructor TWSDLItems.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWSDLStreamLoader := HTTPUtil.GetDefaultStreamLoader;
end;
constructor TWSDLItems.Create(const WSDLItems: TWSDLItems; const StreamLoader: IStreamLoader);
begin
inherited Create(nil);
if Assigned(StreamLoader) then
FWSDLStreamLoader := StreamLoader
else if Assigned(WSDLItems) then
FWSDLStreamLoader := WSDLItems.StreamLoader;
end;
procedure TWSDLItems.Load(const WSDLFileName: WideString);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
try
FWSDLStreamLoader.Load(WSDLFileName, Stream);
if Stream.Size > 0 then
LoadFromStream(Stream)
else
raise Exception.Create(SEmptyWSDL);
FileName := WSDLFIleName;
except
{ DOM exceptions tend to be cryptic }
on E: Exception do
raise Exception.CreateFmt(SCantLoadLocation, [WSDLFileName, E.Message]);
end;
finally;
Stream.Free;
end;
end;
{ Returns whether the WSDL/XML document had a <definition> node }
function HasDefinition(const WSDLDoc: IWSDLDocument): Boolean;
var
XMLNodeList: IXMLNodeList;
begin
XMLNodeList := WSDLDoc.ChildNodes;
Result := (XMLNodeList <> nil) and (XMLNodeList.FindNode(SDefinitions, Wsdlns) <> nil);
end;
function HasDefinition(const WSDLItems: IWSDLItems): Boolean;
begin
Result := HasDefinition(WSDLItems.GetWSDLDoc);
end;
{ TWSDLItems implementation }
function TWSDLItems.GetWSDLItems: TWSDLItems;
begin
Result := Self;
end;
function TWSDLItems.GetWSDLDoc: IWSDLDocument;
begin
Result := Self;
end;
{ Returns the path of the underlying WSDL document }
function TWSDLItems.GetName: WideString;
begin
Result := Definition.Name;
end;
function TWSDLItems.GetTargetNamespace: WideString;
begin
Result := Definition.GetTargetNamespace;
end;
function TWSDLItems.GetTargetNamespacePrefix: WideString;
var
XMLNode: IXMLNode;
begin
Result := '';
XMLNode := Definition.FindNamespaceDecl(GetTargetNamespace);
if XMLNode <> nil then
Result := ExtractLocalName(XMLNode.NodeName);
end;
function TWSDLItems.CompareName(const NodeName: WideString;
const OtherName: WideString;
const TNS: WideString): boolean;
var
LocalName1, LocalName2: WideString;
Prefix1, Prefix2: WideString;
TNS1, TNS2: WideString;
begin
Result := False;
LocalName1 := ExtractLocalName(NodeName);
LocalName2 := ExtractLocalName(OtherName);
{ Check local names first }
if (LocalName1 <> LocalName2) then
Exit;
{ Extract Prefixes }
Prefix1 := ExtractPrefix(NodeName);
Prefix2 := ExtractPrefix(OtherName);
{ Check Prefixes }
{ NOTE: Technically this is not accurate. In cases where there are imports
similar prefixes don't imply same namespace.... }
if Prefix1 = Prefix2 then
begin
Result := True;
Exit;
end;
{ First prefix }
if (Prefix1 = '') then
TNS1 := GetTargetNamespace
else
TNS1 := Definition.FindNamespaceURI(Prefix1);
{ Second prefix may be overriden }
if (TNS <> '') then
TNS2 := TNS
else
begin
if Prefix2 = '' then
TNS2 := GetTargetNamespace
else
TNS2 := Definition.FindNamespaceURI(Prefix2);
end;
{ Compare actual namespaces }
Result := SameNamespace(TNS1, TNS2);
end;
function TWSDLItems.MakeTNSName(const Name: WideString): WideString;
begin
Result := MakeNodeName(GetTargetNamespacePrefix, Name)
end;
procedure TWSDLItems.GetServices(ServiceNames: TWideStrings; QualifiedNames: Boolean = False);
var
Count, Index: Integer;
Services: IServices;
Service: IService;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Services := Definition.Services;
if Services <> nil then
begin
for Count:= 0 to Services.Count-1 do
begin
Service := Services[Count];
if QualifiedNames then
begin
ServiceNames.Add(MakeTNSName(Service.Name))
end
else
ServiceNames.Add(Service.Name);
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
WSDLItems.GetWSDLItems.GetServices(ServiceNames, QualifiedNames);
end;
end;
end;
function TWSDLItems.GetServiceNode(const ServiceName: WideString): IXMLNode;
var
Count: Integer;
Services: IServices;
ServiceNode: IXMLNode;
begin
Services := Definition.Services;
for Count:= 0 to Services.Count-1 do
if (ServiceName = Services[Count].Name) then
begin
ServiceNode := Services[Count] as IXMLNode;
break;
end;
Result := ServiceNode;
end;
procedure TWSDLItems.GetPortsForService(const ServiceName: WideString;
PortNames: TWideStrings;
SkipHttpBindings: Boolean = True;
QualifiedNames: Boolean = False);
var
I,Index,Count: Integer;
Services: IServices;
Service: IService;
Ports: IPorts;
Port: IPort;
PortName: WideString;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Services := Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
begin
Service := Services[Count];
if (CompareName(Service.Name, ServiceName)) then
begin
Ports := Service.Ports;
for I := 0 to Ports.Count-1 do
begin
Port := Ports[I];
PortName := MakeTNSName(Port.Name);
{ Check for HTTP Binding if we're skipping }
if SkipHttpBindings and
(GetHttpBindingAttribute(GetBindingForServicePort(ServiceName, PortName), SVerb) <> '') then
continue;
if QualifiedNames then
PortNames.Add(PortName)
else
PortNames.Add(Port.Name);
end;
end;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
WSDLItems.GetWSDLItems.GetPortsForService(ServiceName, PortNames, QualifiedNames);
end;
end;
end;
function TWSDLItems.GetBindingForServicePort(const ServiceName, PortName: WideString): IQualifiedName;
var
I, Index, Count: Integer;
Services: IServices;
Ports: IPorts;
Port: IPort;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Result := nil;
Services := Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
begin
if CompareName(Services[Count].Name, ServiceName) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
begin
if CompareName(Ports[I].Name, PortName) then
begin
Port := Ports[I];
Result := NewQualifiedName(Port.Binding);
Exit;
end;
end;
end;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
Result := WSDLItems.GetWSDLItems.GetBindingForServicePort(ServiceName, PortName);
if Result <> nil then
Exit;
end;
end;
end;
function TWSDLItems.GetSoapAddressForServicePort(const ServiceName, PortName: WideString): WideString;
var
I, Index, Count: Integer;
Services: IServices;
AddressNode: IXMLNode;
Ports: IPorts;
WSDLItems: IWSDLItems;
Imports: IImports;
begin
Result := '';
Services := Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
begin
if CompareName(Services[Count].Name, ServiceName) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
begin
if CompareName(Ports[I].Name, PortName) then
begin
if (Ports[I].HasChildNodes) then
begin
AddressNode := Ports[I].ChildNodes.FindNode(SAddress, Soapns);
if AddressNode <> nil then
begin
Result := AddressNode.Attributes[SLocation];
Exit;
end;
end;
end;
end;
end;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
Result := WSDLItems.GetWSDLItems.GetSoapAddressForServicePort(ServiceName, PortName);
if Result <> '' then
Exit;
end;
end;
end;
procedure TWSDLItems.GetMessages(MessageNames: TWideStrings; QualifiedNames: Boolean);
var
Count: Integer;
Messages: IMessages;
MessageName: WideString;
begin
Messages := Definition.Messages;
for Count:= 0 to Messages.Count-1 do
begin
MessageName := Messages[Count].Name;
if QualifiedNames then
MessageNames.Add(MakeTNSName(MessageName))
else
MessageNames.Add(MessageName);
end;
end;
function TWSDLItems.GetMessageNode(const MessageName: WideString): IXMLNode;
var
Count: Integer;
MessageNode: IXMLNode;
Messages: IMessages;
begin
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
if CompareName(Messages[Count].Name, MessageName) then
begin
MessageNode := Messages[Count] as IXMLNode;
break;
end;
Result := MessageNode;
end;
procedure TWSDLItems.GetParts(const MessageName: WideString; PartNames: TWideStrings; QualifiedNames: Boolean);
var
I, Count: Integer;
Messages: IMessages;
Parts: IParts;
Part: IPart;
begin
Parts := nil;
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
begin
if CompareName(Messages[Count].Name, MessageName) then
begin
Parts := Messages[Count].Parts;
break;
end;
end;
if Parts <> nil then
for I := 0 to Parts.Count -1 do
begin
Part := Parts[I];
if QualifiedNames then
PartNames.Add(MakeTNSName(Part.Name))
else
PartNames.Add(Part.Name);
end;
end;
function TWSDLItems.GetPartNode(const MessageName, PartName: WideString): IXMLNode;
var
I, Count: Integer;
Messages: IMessages;
Parts: IParts;
begin
Result := nil;
Parts := nil;
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
if CompareName(Messages[Count].Name, MessageName) then
begin
Parts := Messages[Count].Parts;
break;
end;
if Parts <> nil then
begin
for I := 0 to Parts.Count -1 do
begin
if CompareName(Parts[I].Name, PartName) then
begin
Result := Parts[I] as IXMLNode;
Exit;
end;
end;
end;
end;
function TWSDLItems.IsPortTypeHTTPBound(const PortType: WideString): Boolean;
var
Bindings: IQualifiedNameArray;
I: Integer;
begin
Result := False;
Bindings := GetBindingOfType(PortType, TargetNamespace);
for I := 0 to Length(Bindings)-1 do
begin
if GetHttpBindingAttribute(Bindings[I], SVerb) <> '' then
begin
Result := True;
Exit;
end;
end;
end;
procedure TWSDLItems.GetPortTypes(PortTypeNames: TWideStrings; SkipHttpBindings: Boolean;
QualifiedNames: Boolean);
var
Count, Index: Integer;
PortTypes: IPortTypes;
Imports: IImports;
PortTypeName: string;
WSDLItems: IWSDLItems;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
begin
PortTypeName:= PortTypes[Count].Name;
if SkipHttpBindings and IsPortTypeHTTPBound(PortTypeName) then
continue;
if QualifiedNames then
PortTypeNames.Add(MakeTNSName(PortTypeName))
else
PortTypeNames.Add(PortTypeName);
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
WSDLItems.GetWSDLItems.GetPortTypes(PortTypeNames, SkipHttpBindings, QualifiedNames);
end;
end;
end;
function TWSDLItems.GetPortTypeNode(const PortTypeName: WideString): IXMLNode;
var
Count: Integer;
PortTypes: IPortTypes;
begin
Result := nil;
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if CompareName(PortTypes[Count].Name, PortTypeName) then
begin
Result := PortTypes[Count] as IXMLNode;
Exit;
end;
end;
procedure TWSDLItems.GetOperations(const PortTypeName: WideString; OperationNames: TWideStrings; QualifiedNames: Boolean);
var
I, Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
Operation: IOperation;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if CompareName(PortTypes[Count].Name, PortTypeName) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
if Operations <> nil then
begin
for I:=0 to Operations.Count -1 do
begin
Operation := Operations[I];
if QualifiedNames then
OperationNames.Add(MakeTNSName(Operation.Name))
else
OperationNames.Add(Operation.Name);
end;
end;
end;
function TWSDLItems.GetOperationNode(const PortTypeName, OperationName: WideString): IXMLNode;
var
I, Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
begin
Operations := nil;
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if CompareName(PortTypes[Count].Name, PortTypeName) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
if Operations <> nil then
begin
for I:=0 to Operations.Count -1 do
begin
if CompareName(Operations[I].Name, OperationName) then
begin
Result := Operations[I] as IXMLNode;
Exit;
end;
end;
end;
end;
function TWSDLItems.GetPartsForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings): Boolean;
var
I,Index,Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Result := False;
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
begin
if CompareName(PortTypes[Count].Name, PortTypeName) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
end;
if (Operations <> nil) and (Operations.Count > 0) then
begin
for I:=0 to Operations.Count -1 do
begin
if CompareName(Operations[I].Name, OperationName) and (OperationIndex = I) then
begin
if (Operations[I].Input.Message <> '') then
begin
GetParts(Operations[I].Input.Message, PartNames);
Result := True;
end;
end;
end;
end
else
begin
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
if (WSDLItems.GetWSDLItems.GetPartsForOperation(PortTypeName, OperationName, OperationIndex, PartNames)) then
begin
Result := True;
Exit;
end;
end;
end;
end;
end;
procedure TWSDLItems.GetImports(ImportNames: TWideStrings);
var
Count: Integer;
Imports: IImports;
begin
Imports := Definition.Imports;
for Count := 0 to Imports.Count -1 do
ImportNames.Add(Imports[Count].Namespace);
end;
procedure TWSDLItems.IterateImports(IterateProc: TWSDLIterateProc);
var
Index: Integer;
Imports: IImports;
ImportWSDLItems: IWSDLItems;
SchemaDoc: IXMLSchemaDoc;
Stream: TMemoryStream;
begin
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
Stream := TMemoryStream.Create;
try
IterateProc(ioBeforeLoad, nil, nil, Imports[Index].Location);
StreamLoader.Load(Imports[Index].Location, Stream);
{ Check if it's a WSDL document }
ImportWSDLItems := TWSDLItems.Create(Self, nil);
ImportWSDLItems.GetWSDLItems.LoadFromStream(Stream);
if HasDefinition(ImportWSDLItems) then
begin
{ Recurse - depth first }
ImportWSDLItems.GetWSDLItems.IterateImports(IterateProc);
{ Invoke proc }
IterateProc(ioLoaded, ImportWSDLItems, nil, Imports[Index].Location);
end
else
begin
SchemaDoc := TXMLSchemaDoc.Create(nil);
SchemaDoc.LoadFromStream(Stream);
SchemaDoc.Active := True;
SchemaDoc.FileName := Imports[Index].Location;
IterateProc(ioLoaded, nil, SchemaDoc, Imports[Index].Location);
end;
finally
Stream.Free;
end;
end;
end;
end;
function TWSDLItems.GetLocationForImport(const ImportNameSpace: WideString): WideString;
var
Count: Integer;
Location: WideString;
Imports: IImports;
begin
Imports := Definition.Imports;
for Count := 0 to Imports.Count -1 do
if (ImportNameSpace = Imports[Count].Namespace) then
begin
Location := Imports[Count].Location;
break;
end;
Result := Location;
end;
procedure TWSDLItems.GetBindings(BindingNames: TWideStrings; QualifiedNames: Boolean);
var
Count: Integer;
Bindings: IBindings;
Binding: IBinding;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
begin
Binding := Bindings[Count];
if QualifiedNames then
BindingNames.Add(MakeTNSName(Binding.Name))
else
BindingNames.Add(Binding.Name);
end;
end;
function TWSDLItems.GetServiceAndPortOfBinding(const BindingName: IQualifiedName;
var ServiceName: WideString;
var PortName: WideString): Boolean;
var
Count, I: Integer;
Services: IServices;
Ports: IPorts;
Service: IService;
Port: IPort;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Result := False;
Services := Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
begin
Service := Services[Count];
Ports := Service.Ports;
for I := 0 to Ports.Count-1 do
begin
Port := Ports[I];
if CompareName(Port.Binding, BindingName.Name, BindingName.Namespace) then
begin
ServiceName := Service.Name;
PortName := Port.Name;
Result := True;
Exit;
end;
end;
end;
end;
{ Get any imported WSDL }
if not Result then
begin
Imports := Definition.Imports;
if Imports <> nil then
begin
for I := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[I].Location);
if HasDefinition(WSDLItems) then
Result := WSDLItems.GetWSDLItems.GetServiceAndPortOfBinding(BindingName, ServiceName, PortName);
if Result then
Exit;
end;
end;
end;
end;
{ Returns PortType that maps to the specified Binding }
function TWSDLItems.GetBindingType(const BindingName: WideString): WideString;
var
Count: Integer;
BindingTypeName: WideString;
Bindings: IBindings;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if CompareName(Bindings[Count].Name, BindingName) then
begin
BindingTypeName := Bindings[Count].Type_;
break;
end;
Result := BindingTypeName;
end;
procedure TWSDLItems.GetBindingOfType(const BindingTypeName: WideString;
const TNS: WideString;
var BindingArray: IQualifiedNameArray);
function InArray(const Name, NS: WideString): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Length(BindingArray)-1 do
if (BindingArray[I].Name = Name) and
(BindingArray[I].Namespace = NS) then
begin
Result := True;
Exit;
end;
end;
var
Count: Integer;
Bindings: IBindings;
Binding: IBinding;
Imports: IImports;
I, Len: Integer;
WSDLItems: IWSDLItems;
Name, NS: WideString;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
begin
Binding := Bindings[Count];
if CompareName(Binding.Type_, BindingTypeName, TNS) then
begin
Name := Binding.Name;
NS := Self.TargetNamespace;
if not InArray(Name, NS) then
begin
Len := Length(BindingArray);
SetLength(BindingArray, Len+1);
BindingArray[Len] := NewQualifiedName(Name, NS);
end;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
{ Keep namespace for comparisons }
if TNS = '' then
NS := TargetNamespace
else
NS := TNS;
for I := 0 to Imports.Count-1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[I].Location);
if HasDefinition(WSDLItems) then
WSDLItems.GetWSDLItems.GetBindingOfType(BindingTypeName, NS, BindingArray);
end;
end;
end;
{ Returns the Binding whose type="xxx" attribute value corresponds to the specified name (i.e. a PortType name) }
function TWSDLItems.GetBindingOfType(const BindingTypeName: WideString;
const TNS: WideString): IQualifiedNameArray;
begin
SetLength(Result, 0);
GetBindingOfType(BindingTypeName, TNS, Result);
end;
function TWSDLItems.GetGenericBindingAttribute(const BindingName: WideString;
const NodeName: WideString;
const Namespace: WideString;
Attribute: WideString): WideString;
var
I,Count: Integer;
Bindings: IBindings;
Node: IXMLNode;
XMLNodeList: IXMLNodeList;
begin
Result := '';
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
begin
if CompareName(Bindings[Count].Name, BindingName) then
begin
if Bindings[Count].HasChildNodes then
begin
for I := 0 to Bindings[Count].ChildNodes.Count -1 do
begin
XMLNodeList := Bindings[Count].ChildNodes;
Node := XMLNodeList.FindNode(NodeName, Namespace);
if Node <> nil then
begin
if Node.HasAttribute(Attribute) then
begin
Result := Node.GetAttribute(Attribute);
Exit;
end;
end;
end;
end;
end;
end;
end;
{ Retrieve <soap:binding attribute=xxxxx> values - For example, the 'transport' }
{ - 'http://schemas.xmlsoap.org/soap/http' - or the style ( 'rpc' vs. 'document'}
function TWSDLItems.GetSoapBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString;
begin
Result := GetGenericBindingAttribute(BindingName, SBinding, Soapns, Attribute);
end;
{ Retrieve <http:binding attribute=xxxx> values - For example, 'verb' (GET or POST }
function TWSDLItems.GetHttpBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString;
begin
Result := GetGenericBindingAttribute(BindingName, SBinding, Httpns, Attribute);
end;
function TWSDLItems.GetHttpBindingAttribute(const QualifiedName: IQualifiedName; Attribute: WideString): WideString;
begin
Result := '';
if QualifiedName <> nil then
Result := GetHttpBindingAttribute(QualifiedName.Name, Attribute);
end;
procedure TWSDLItems.GetOperationsForBinding(const BindingName: WideString;
OperationNames: TWideStrings;
QualifiedNames: Boolean);
var
I,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
BindOperation: IBindingOperation;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
begin
if CompareName(Bindings[Count].Name, BindingName) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
BindOperation := BindOperations[I];
if QualifiedNames then
OperationNames.Add(MakeTNSName(BindOperation.Name))
else
OperationNames.Add(BindOperation.Name);
end;
break;
end;
end;
end;
function TWSDLItems.GetBindingOperationNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IBindingOperation;
var
Count, OverloadCount, I: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
Imports: IImports;
WSDLItems: IWSDLItems;
begin
Result := nil;
Bindings := Definition.Bindings;
OverloadCount := OverloadIndex;
for Count := 0 to Bindings.Count -1 do
begin
if CompareName(Bindings[Count].Name, BindingName) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if CompareName(BindOperations[I].Name, Operation) then
begin
if OverloadCount > 0 then
Dec(OverloadCount)
else
begin
Result := BindOperations[I];
Exit;
end;
end;
end;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for I := (Imports.Count-1) downto 0 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.GetWSDLDoc.Options := WSDLItems.GetWSDLDoc.Options- [doNodeAutoCreate];
WSDLItems.Load(Imports[I].Location);
if HasDefinition(WSDLItems) then
Result := WSDLItems.GetWSDLItems.GetBindingOperationNode(BindingName, Operation, OverloadIndex);
if Result <> nil then
Exit;
end;
end;
end;
function TWSDLItems.GetSoapOperationAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
var
BindingNode, SoapOperationNode: IXMLNode;
XMLNodeList: IXMLNodeList;
begin
Result := '';
BindingNode := GetBindingOperationNode(BindingName, Operation, OverloadIndex);
if (BindingNode <> nil) and (BindingNode.HasChildNodes) then
begin
XMLNodeList := BindingNode.ChildNodes;
if XMLNodeList <> nil then
begin
SoapOperationNode := XMLNodeList.FindNode(SOperation, Soapns);
if SoapOperationNode <> nil then
begin
if SoapOperationNode.HasAttribute(Attribute) then
Result := SoapOperationNode.Attributes[Attribute];
end;
end;
end;
end;
{ Returns the value of the 'soapAction' attribute for the specified Binding/Operation }
function TWSDLItems.GetSoapAction(const BindingName, Operation: WideString; OverloadIndex: Integer): WideString;
begin
Result := GetSoapOperationAttribute(BindingName, Operation, SSoapAction, OverloadIndex);
end;
{ Returns the value of the style="xxxx" attribute of the <soap:operation ..> node
for the specified Binding/Operation combination }
function TWSDLItems.GetSoapOperationStyle(const BindingName, Operation: WideString; OverloadIndex: Integer): WideString;
begin
Result := GetSoapOperationAttribute(BindingName, Operation, SStyle, OverloadIndex);
end;
procedure TWSDLItems.GetSoapActionList(const BindingName: WideString; ActionList: TWideStrings; QualifiedNames: Boolean);
var
Operations: TWideStrings;
I: Integer;
Operation: WideString;
begin
Operations := TWideStrings.Create;
try
GetOperationsForBinding(BindingName, Operations, QualifiedNames);
for I := 0 to (Operations.Count-1) do
begin
Operation := Operations.Strings[I];
ActionList.Add(Operation+'='+GetSoapAction(BindingName, Operation, 0));
end;
finally
Operations.Free;
end;
end;
function TWSDLItems.GetSoapBodyInputAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
begin
Result := GetSoapBodyAttribute(BindingName, Operation, SInput, Attribute, OverloadIndex);
end;
function TWSDLItems.GetSoapBodyOutputAttribute(const BindingName, Operation, Attribute: WideString; OverloadIndex: Integer): WideString;
begin
Result := GetSoapBodyAttribute(BindingName, Operation, SOutput, Attribute, OverloadIndex);
end;
function TWSDLItems.GetSoapBodyAttribute(const BindingName, Operation, IOType, Attribute: WideString; OverloadIndex: Integer): WideString;
var
IONode, SoapBodyNode: IXMLNode;
XMLNodeList: IXMLNodeList;
begin
IONode := GetSoapBindingIONode(BindingName, Operation, SameText(IOType, SInput), OverloadIndex);
if (IONode <> nil) and (IONode.HasChildNodes) then
begin
XMLNodeList := IONode.ChildNodes;
SoapBodyNode := XMLNodeList.FindNode(SBody, Soapns);
if SoapBodyNode <> nil then
begin
if SoapBodyNode.HasAttribute(Attribute) then
begin
Result := SoapBodyNode.Attributes[Attribute];
Exit;
end;
end;
end;
end;
function TWSDLItems.GetSoapBindingIONode(const BindingName, Operation: WideString; Input: Boolean; OverloadIndex: Integer): IXMLNode;
var
BindingNode: IBindingOperation;
begin
Result := nil;
BindingNode := GetBindingOperationNode(BindingName, Operation, OverloadIndex);
if (BindingNode <> nil) and (BindingNode.HasChildNodes) then
begin
if Input then
Result := BindingNode.Input
else
Result := BindingNode.Output;
end;
end;
function TWSDLItems.GetSoapBindingInputNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IXMLNode;
begin
Result := GetSoapBindingIONode(BindingName, Operation, True, OverloadIndex);
end;
function TWSDLItems.GetSoapBindingOutputNode(const BindingName, Operation: WideString; OverloadIndex: Integer): IXMLNode;
begin
Result := GetSoapBindingIONode(BindingName, Operation, False, OverloadIndex);
end;
function TWSDLItems.GetSoapBodyNamespace(const BindingPortType: WideString): WideString;
var
Index, Count, I: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
Imports: IImports;
WSDLItems: IWSDLItems;
function FindSoapBodyNamespace(const Node: IXMLNode): WideString;
var
SoapBodyNode: IXMLNode;
begin
Result := '';
if Node.HasChildNodes then
begin
SoapBodyNode := Node.ChildNodes.FindNode(SBody, Soapns);
if Assigned(SoapBodyNode) and SoapBodyNode.HasAttribute(SNamespace) then
Result := SoapBodyNode.Attributes[SNamespace];
end;
end;
begin
Result := '';
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
begin
if CompareName(BindingPortType, Bindings[Count].Type_) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
Result := FindSoapBodyNamespace(BindOperations[I].Input);
if Result <> '' then
Exit;
Result := FindSoapBodyNamespace(BindOperations[I].Output);
if Result <> '' then
Exit;
end;
break;
end;
end;
{ Get any imported WSDL }
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
WSDLItems := TWSDLItems.Create(Self, nil);
WSDLItems.Load(Imports[Index].Location);
if HasDefinition(WSDLItems) then
begin
Result := WSDLItems.GetWSDLItems.GetSoapBodyNamespace(BindingPortType);
if Result <> '' then
Exit;
end;
end;
end;
end;
function TWSDLItems.HasTypesNode: Boolean;
begin
Result := False;
if (Definition.Types <> nil) then
Result := True;
end;
procedure TWSDLItems.GetSchemas(SchemaNames: TWideStrings);
var
Types: ITypes;
Tns: WideString;
Index: Integer;
begin
Types := Definition.Types;
if (Types <> nil) and (Types.SchemaDefs.Count > 0) then
begin
for Index := 0 to Types.SchemaDefs.Count - 1 do
begin
Tns := Types.SchemaDefs[Index].Attributes[sTns];
SchemaNames.Add(Tns);
end;
end;
end;
function TWSDLItems.GetSchemaNode(const SchemaTns: WideString) : IXMLNode;
var
Index: Integer;
Types: ITypes;
SchemaRootNode: IXMLNode;
begin
Types := Definition.Types;
if (Types <> nil) and (Types.SchemaDefs.Count > 0) then
begin
for Index := 0 to Types.SchemaDefs.Count - 1 do
begin
if ( SchemaTns = Types.SchemaDefs[Index].Attributes[sTns] ) then
begin
SchemaRootNode := Types.SchemaDefs[Index] as IXMLNode;
break;
end;
end;
end;
Result := SchemaRootNode;
end;
function TWSDLItems.GetSoapHeaders(BindingName: IQualifiedName;
const Operation: WideString;
Input: Boolean;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
var
I, J, K, HeaderLen: Integer;
IONode, Node: IXMLNode;
XMLNodeList: IXMLNodeList;
Msg, Prt, Attr: WideString;
Messages: IMessages;
Message: IMessage;
Parts: IParts;
Part: IPart;
begin
SetLength(Result, 0);
IONode := GetSoapBindingIONode(BindingName.Name, Operation, Input, OverloadIndex);
if (IONode <> nil) and (IONode.HasChildNodes) then
begin
XMLNodeList := IONode.ChildNodes;
for I := 0 to XMLNodeList.Count-1 do
begin
Node := XMLNodeList[I];
if SameText(ExtractLocalName(Node.NodeName), SHeader) and
SameText(Node.NamespaceURI, Soapns) then
begin
if Node.HasAttribute(SMessage) and
Node.HasAttribute(SPart) then
begin
HeaderLen := Length(Result);
SetLength(Result, HeaderLen+1);
Result[HeaderLen] := NewHeaderInfo;
{ Message/Part }
Msg := Node.Attributes[SMessage];
Prt:= Node.Attributes[SPart];
{ Name }
Result[HeaderLen].Name := Prt;
{ Required ?? }
if Node.HasAttribute(SRequired, Wsdlns) then
begin
Attr := Node.GetAttributeNS(SRequired, Wsdlns);
Result[HeaderLen].Required := SameText(Attr, 'true') or SameText(Attr, '1');
end;
{ Namespace }
if Node.HasAttribute(SNamespace) then
Result[HeaderLen].Namespace := Node.GetAttribute(SNamespace);
{ Use }
if Node.HasAttribute(SUse) then
Result[HeaderLen].Use := Node.GetAttribute(SUse);
{ Encoding }
if Node.HasAttribute(SEncodingStyle) then
Result[HeaderLen].EncodingStyle := Node.GetAttribute(SEncodingStyle);
Messages := Definition.Messages;
for J := 0 to Messages.Count -1 do
begin
Message := Messages[J];
if CompareName(Message.Name, Msg) then
begin
Parts := Messages[J].Parts;
for K := 0 to Parts.Count -1 do
begin
Part := Parts[K];
if Part.Name = Prt then
begin
Result[HeaderLen].Part := Part;
Result[HeaderLen].Name := Part.Name;
break;
end;
end;
end;
end;
end;
end;
end;
end;
end;
function TWSDLItems.GetSoapInputHeaders(BindingName: IQualifiedName;
const Operation: WideString;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
begin
Result := GetSoapHeaders(BindingName, Operation, True, OverloadIndex, MessageName);
end;
function TWSDLItems.GetSoapOutputHeaders(BindingName: IQualifiedName;
const Operation: WideString;
OverloadIndex: Integer;
const MessageName: WideString = ''): IHeaderInfoArray;
begin
Result := GetSoapHeaders(BindingName, Operation, False, OverloadIndex, MessageName);
end;
{ THeaderInfo }
function THeaderInfo.GetEncodingStyle: WideString;
begin
Result := FEncodingStyle;
end;
function THeaderInfo.GetName: WideString;
begin
Result := FName;
end;
function THeaderInfo.GetNamespace: WideString;
begin
Result := FNamespace;
end;
function THeaderInfo.GetPart: IPart;
begin
Result := FPart;
end;
function THeaderInfo.GetRequired: Boolean;
begin
Result := FRequired;
end;
function THeaderInfo.GetUse: WideString;
begin
Result := FUse;
end;
procedure THeaderInfo.SetEncodingStyle(const EncStyl: WideString);
begin
FEncodingStyle := EncStyl;
end;
procedure THeaderInfo.SetName(const N: WideString);
begin
FName := N;
end;
procedure THeaderInfo.SetNamespace(const N: WideString);
begin
FNamespace := N;
end;
procedure THeaderInfo.SetPart(const P: IPart);
begin
FPart := P;
end;
procedure THeaderInfo.SetRequired(Req: Boolean);
begin
FRequired := Req;
end;
procedure THeaderInfo.SetUse(const U: WideString);
begin
FUse := U;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO
Description : DAO Easy access
Author : Kike Pérez
Version : 1.1
Created : 22/06/2018
Modified : 07/04/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.DAO;
{$i QuickDAO.inc}
interface
uses
Classes,
SysUtils,
Rtti,
TypInfo,
Generics.Collections,
Variants,
{$IFDEF FPC}
rttiutils,
fpjson,
jsonparser,
strUtils,
//jsonreader,
//fpjsonrtti,
Quick.Json.fpc.Compatibility,
{$ELSE}
{$IFDEF DELPHIXE7_UP}
System.Json,
{$ENDIF}
{$ENDIF}
Quick.RTTI.Utils,
Quick.Commons,
Quick.Json.Serializer;
type
{$IFNDEF FPC}
TMapField = class(TCustomAttribute)
private
fName : string;
public
constructor Create(const aName: string);
property Name : string read fName;
end;
TFieldVARCHAR = class(TCustomAttribute)
private
fSize : Integer;
public
constructor Create(aSize : Integer);
property Size : Integer read fSize;
end;
TFieldDECIMAL = class(TCustomAttribute)
private
fSize : Integer;
fDecimals : Integer;
public
constructor Create(aSize, aDecimals : Integer);
property Size : Integer read fSize;
property Decimals : Integer read fdecimals;
end;
{$ENDIF}
TDBProvider = (
daoMSAccess2000 = $00010,
daoMSAccess2007 = $00011,
daoMSSQL = $00020,
daoMSSQLnc10 = $00021,
daoMSSQLnc11 = $00022,
daoMySQL = $00030,
daoSQLite = $00040,
daoIBM400 = $00050,
daoFirebase = $00060);
TDAODataType = (dtString, dtstringMax, dtChar, dtInteger, dtAutoID, dtInt64, dtFloat, dtBoolean, dtDate, dtTime, dtDateTime, dtCreationDate, dtModifiedDate);
EDAOModelError = class(Exception);
EDAOCreationError = class(Exception);
EDAOUpdateError = class(Exception);
EDAOSelectError = class(Exception);
EDAODeleteError = class(Exception);
TDAORecord = class;
TDAORecordArray = array of TDAORecord;
TDAORecordClass = class of TDAORecord;
TDAORecordClassArray = array of TDAORecordClass;
TDAOIndexOrder = (orAscending, orDescending);
TFieldNamesArray = array of string;
TAutoID = type Int64;
TDAOIndex = class
private
fTable : TDAORecordClass;
fFieldNames : TFieldNamesArray;
fOrder : TDAOIndexOrder;
public
property Table : TDAORecordClass read fTable write fTable;
property FieldNames : TFieldNamesArray read fFieldNames write fFieldNames;
property Order : TDAOIndexOrder read fOrder write fOrder;
end;
TDAOIndexes = class
private
fList : TObjectList<TDAOIndex>;
public
constructor Create;
destructor Destroy; override;
property List : TObjectList<TDAOIndex> read fList write fList;
procedure Add(aTable: TDAORecordClass; aFieldNames: TFieldNamesArray; aOrder : TDAOIndexOrder);
end;
TDAOField = class
private
fName : string;
fDataType : TDAODataType;
fDataSize : Integer;
fPrecision : Integer;
fIsPrimaryKey : Boolean;
public
property Name : string read fName write fName;
property DataType : TDAODataType read fDataType write fDataType;
property DataSize : Integer read fDataSize write fDataSize;
property Precision : Integer read fPrecision write fPrecision;
property IsPrimaryKey : Boolean read fIsPrimaryKey write fIsPrimaryKey;
end;
TDAOFields = TObjectList<TDAOField>;
TDBField = record
FieldName : string;
Value : variant;
function IsEmptyOrEmpty : Boolean;
end;
TDAOModel = class
private
fTable : TDAORecordClass;
fTableName : string;
fPrimaryKey : TDAOField;
fFields : TDAOFields;
fFieldsMap : TDictionary<string,TDAOField>;
procedure GetFields;
procedure SetTable(const Value: TDAORecordClass);
procedure SetPrimaryKey(const Value: TDAOField);
public
constructor Create;
destructor Destroy; override;
property Table : TDAORecordClass read fTable write SetTable;
property TableName : string read fTableName write fTableName;
property PrimaryKey : TDAOField read fPrimaryKey write SetPrimaryKey;
property Fields : TDAOFields read fFields;
function GetFieldNames(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
function GetFieldByName(const aName : string) : TDAOField;
function HasPrimaryKey : Boolean;
function IsPrimaryKey(const aName : string) : Boolean;
end;
TDAOModels = class
private
fList : TObjectDictionary<TDAORecordClass,TDAOModel>;
fPluralizeTableNames : Boolean;
function GetTableNameFromClass(aTable : TDAORecordClass) : string;
public
constructor Create;
destructor Destroy; override;
property List : TObjectDictionary<TDAORecordClass,TDAOModel> read fList write fList;
property PluralizeTableNames : Boolean read fPluralizeTableNames write fPluralizeTableNames;
procedure Add(aTable: TDAORecordClass; const aPrimaryKey: string; const aTableName : string = '');
function GetPrimaryKey(aTable : TDAORecordClass) : string;
function Get(aTable : TDAORecordClass) : TDAOModel; overload;
function Get(aDAORecord : TDAORecord) : TDAOModel; overload;
procedure Clear;
end;
IDAOResult<T : class> = interface
['{0506DF8C-2749-4DB0-A0E9-44793D4E6AB7}']
function Count : Integer;
function HasResults : Boolean;
function GetEnumerator: TEnumerator<T>;
function ToList : TList<T>;
function ToObjectList : TObjectList<T>;
function ToArray : TArray<T>;
function GetOne(aDAORecord : T) : Boolean;
end;
IDAOQuery<T> = interface
['{6AA202B4-CBBC-48AA-9D5A-855748D02DCC}']
function Eof : Boolean;
function MoveNext : Boolean;
function GetCurrent : T;
function GetModel : TDAOModel;
procedure FillRecordFromDB(aDAORecord : T);
function GetFieldValue(const aName : string) : Variant;
function CountResults : Integer;
function AddOrUpdate(aDAORecord : TDAORecord) : Boolean;
function Add(aDAORecord : TDAORecord) : Boolean;
function Update(aDAORecord : TDAORecord) : Boolean; overload;
function Update(const aFieldNames : string; const aFieldValues : array of const) : Boolean; overload;
function Delete(aDAORecord : TDAORecord) : Boolean; overload;
function Delete(const aQuery : string) : Boolean; overload;
end;
IDAOQueryGenerator = interface
['{9FD0E61E-0568-49F4-A9D4-2D540BE72384}']
function Name : string;
function CreateTable(const aTable : TDAOModel) : string;
function ExistsTable(aModel : TDAOModel) : string;
function ExistsColumn(aModel : TDAOModel; const aFieldName : string) : string;
function AddColumn(aModel : TDAOModel; aField : TDAOField) : string;
function SetPrimaryKey(aModel : TDAOModel) : string;
function CreateIndex(aModel : TDAOModel; aIndex : TDAOIndex) : string;
function Select(const aTableName, aFieldNames : string; aLimit : Integer; const aWhere : string; aOrderFields : string; aOrderAsc : Boolean) : string;
function Sum(const aTableName, aFieldName, aWhere : string) : string;
function Count(const aTableName : string; const aWhere : string) : string;
function Add(const aTableName: string; const aFieldNames, aFieldValues : string) : string;
function AddOrUpdate(const aTableName: string; const aFieldNames, aFieldValues : string) : string;
function Update(const aTableName, aFieldPairs, aWhere : string) : string;
function Delete(const aTableName : string; const aWhere : string) : string;
function DateTimeToDBField(aDateTime : TDateTime) : string;
function DBFieldToDateTime(const aValue : string) : TDateTime;
function QuotedStr(const aValue : string) : string;
end;
IDAOLinqQuery<T : class> = interface
['{5655FDD9-1D4C-4B67-81BB-7BDE2D2C860B}']
function Where(const aFormatSQLWhere: string; const aValuesSQLWhere: array of const) : IDAOLinqQuery<T>; overload;
function Where(const aWhereClause: string) : IDAOLinqQuery<T>; overload;
function Select : IDAOResult<T>; overload;
function Select(const aFieldNames : string) : IDAOResult<T>; overload;
function SelectFirst : T;
function SelectLast : T;
function SelectTop(aNumber : Integer) : IDAOResult<T>;
function Sum(const aFieldName : string) : Int64;
function Count : Int64;
function Update(const aFieldNames : string; const aFieldValues : array of const) : Boolean;
function Delete : Boolean;
function OrderBy(const aFieldValues : string) : IDAOLinqQuery<T>;
function OrderByDescending(const aFieldValues : string) : IDAOLinqQuery<T>;
end;
TDAOResult<T : class, constructor> = class(TInterfacedObject,IDAOResult<T>)
type
TDAOEnumerator = class(TEnumerator<T>)
private
fDAOQuery : IDAOQuery<T>;
fModel : TDAOModel;
protected
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(aDAOQuery: IDAOQuery<T>);
end;
private
fDAOQuery : IDAOQuery<T>;
public
constructor Create(aDAOQuery : IDAOQuery<T>);
function GetEnumerator: TEnumerator<T>; inline;
function GetOne(aDAORecord : T) : Boolean;
function ToList : TList<T>;
function ToObjectList : TObjectList<T>;
function ToArray : TArray<T>;
function Count : Integer;
function HasResults : Boolean;
end;
TDAOQueryGenerator = class(TInterfacedObject)
function QuotedStr(const aValue: string): string; virtual;
end;
TDAORecord = class
private
fTableName : string;
fPrimaryKey : TDBField;
public
constructor Create;
[TNotSerializableProperty]
property PrimaryKey : TDBField read fPrimaryKey write fPrimaryKey;
end;
TCreationDate = type TDateTime;
TModifiedDate = type TDateTime;
TDAORecordTS = class(TDAORecord)
private
fCreationDate : TCreationDate;
fModifiedDate : TModifiedDate;
published
property CreationDate : TCreationDate read fCreationDate write fCreationDate;
property ModifiedDate : TModifiedDate read fModifiedDate write fModifiedDate;
end;
function QuotedStrEx(const aValue : string) : string;
function FormatSQLParams(const aSQLClause : string; aSQLParams : array of const) : string;
function IsEmptyOrNull(const Value: Variant): Boolean;
implementation
uses
Quick.DAO.Factory.QueryGenerator;
function QuotedStrEx(const aValue : string) : string;
var
sb : TStringBuilder;
begin
sb := TStringBuilder.Create;
try
sb.Append('''');
sb.Append(aValue);
sb.Append('''');
Result := sb.ToString(0, sb.Length - 1);
finally
sb.Free;
end;
end;
function FormatSQLParams(const aSQLClause : string; aSQLParams : array of const) : string;
var
i : Integer;
begin
Result := aSQLClause;
if aSQLClause = '' then
begin
Result := '1=1';
Exit;
end;
for i := 0 to aSQLClause.CountChar('?') - 1 do
begin
case aSQLParams[i].VType of
vtInteger : Result := StringReplace(Result,'?',IntToStr(aSQLParams[i].VInteger),[]);
vtInt64 : Result := StringReplace(Result,'?',IntToStr(aSQLParams[i].VInt64^),[]);
vtExtended : Result := StringReplace(Result,'?',FloatToStr(aSQLParams[i].VExtended^),[]);
vtBoolean : Result := StringReplace(Result,'?',BoolToStr(aSQLParams[i].VBoolean),[]);
vtAnsiString : Result := StringReplace(Result,'?',string(aSQLParams[i].VAnsiString),[]);
vtWideString : Result := StringReplace(Result,'?',string(aSQLParams[i].VWideString^),[]);
{$IFNDEF NEXTGEN}
vtString : Result := StringReplace(Result,'?',aSQLParams[i].VString^,[]);
{$ENDIF}
vtChar : Result := StringReplace(Result,'?',aSQLParams[i].VChar,[]);
vtPChar : Result := StringReplace(Result,'?',aSQLParams[i].VPChar,[]);
else Result := StringReplace(Result,'?', QuotedStr(string(aSQLParams[i].VUnicodeString)),[]);
end;
end;
end;
{ TDAORecord }
constructor TDAORecord.Create;
begin
fTableName := Copy(Self.ClassName,2,Length(Self.ClassName));
//fPrimaryKey.FieldName := aDataBase.Models.GetPrimaryKey(TDAORecordClass(Self.ClassType));
end;
function IsEmptyOrNull(const Value: Variant): Boolean;
begin
Result := VarIsClear(Value) or VarIsEmpty(Value) or VarIsNull(Value) or (VarCompareValue(Value, Unassigned) = vrEqual);
if (not Result) and VarIsStr(Value) then
Result := Value = '';
end;
{ TMapField }
{$IFNDEF FPC}
constructor TMapField.Create(const aName: string);
begin
fName := aName;
end;
{$ENDIF}
{ TDAOIndexes }
procedure TDAOIndexes.Add(aTable: TDAORecordClass; aFieldNames: TFieldNamesArray; aOrder : TDAOIndexOrder);
var
daoindex : TDAOIndex;
begin
daoindex := TDAOIndex.Create;
daoindex.Table := aTable;
daoindex.FieldNames := aFieldNames;
daoindex.Order := aOrder;
fList.Add(daoindex);
end;
constructor TDAOIndexes.Create;
begin
fList := TObjectList<TDAOIndex>.Create(True);
end;
destructor TDAOIndexes.Destroy;
begin
fList.Free;
inherited;
end;
{ TDAOModels }
procedure TDAOModels.Add(aTable: TDAORecordClass; const aPrimaryKey: string; const aTableName : string = '');
var
daomodel : TDAOModel;
begin
daomodel := TDAOModel.Create;
daomodel.Table := aTable;
{$IFNDEF FPC}
if aTableName = '' then daomodel.TableName := GetTableNameFromClass(aTable)
{$ELSE}
if aTableName = '' then daomodel.TableName := GetTableNameFromClass(aTable)
{$ENDIF}
else daomodel.TableName := aTableName;
if not aPrimaryKey.IsEmpty then daomodel.PrimaryKey := daomodel.GetFieldByName(aPrimaryKey);
fList.Add(aTable,daomodel);
end;
procedure TDAOModels.Clear;
begin
fList.Clear;
end;
constructor TDAOModels.Create;
begin
fList := TObjectDictionary<TDAORecordClass,TDAOModel>.Create([doOwnsValues]);
fPluralizeTableNames := False;
end;
destructor TDAOModels.Destroy;
begin
fList.Free;
inherited;
end;
function TDAOModels.Get(aTable: TDAORecordClass): TDAOModel;
begin
if not fList.TryGetValue(aTable,Result) then raise EDAOModelError.CreateFmt('Model "%s" not exists in database',[aTable.ClassName]);
end;
function TDAOModels.Get(aDAORecord : TDAORecord) : TDAOModel;
begin
if aDAORecord = nil then raise EDAOModelError.Create('Model is empty');
Result := Get(TDAORecordClass(aDAORecord.ClassType));
end;
function TDAOModels.GetPrimaryKey(aTable: TDAORecordClass): string;
begin
Result := Get(aTable).PrimaryKey.Name;
end;
function TDAOModels.GetTableNameFromClass(aTable: TDAORecordClass): string;
begin
Result := Copy(aTable.ClassName,2,aTable.ClassName.Length);
if fPluralizeTableNames then Result := Result + 's';
end;
{$IFNDEF FPC}
{ TFieldVARCHAR }
constructor TFieldVARCHAR.Create(aSize: Integer);
begin
fSize := aSize;
end;
{ TFieldDECIMAL }
constructor TFieldDECIMAL.Create(aSize, aDecimals: Integer);
begin
fSize := aSize;
fDecimals := aDecimals;
end;
{$ENDIF}
{ TDAOModel }
constructor TDAOModel.Create;
begin
fFields := TObjectList<TDAOField>.Create(True);
fFieldsMap := TDictionary<string,TDAOField>.Create;
end;
destructor TDAOModel.Destroy;
begin
fFieldsMap.Free;
fFields.Free;
inherited;
end;
function TDAOModel.GetFieldByName(const aName: string): TDAOField;
begin
if not fFieldsMap.TryGetValue(aName,Result) then raise EDAOModelError.CreateFmt('Field "%s" not found in table "%s"!',[aName,Self.TableName]);
end;
function TDAOModel.GetFieldNames(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
var
value : TValue;
skip : Boolean;
field : TDAOField;
begin
Result := TStringList.Create;
Result.Delimiter := ',';
Result.StrictDelimiter := True;
try
for field in fFields do
begin
skip := False;
if field.IsPrimaryKey then
begin
if (not aExcludeAutoIDFields) and (aDAORecord <> nil) then
begin
if field.DataType = dtAutoID then
begin
value := TRTTI.GetPropertyValue(aDAORecord,field.Name);
if (value.IsEmpty) or (value.AsInt64 = 0) then skip := True;
end;
end
else skip := True;
end;
if not skip then Result.Add(Format('[%s]',[field.Name]));
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting field names "%s" : %s',[Self.ClassName,e.Message]);
end;
end;
end;
procedure TDAOModel.GetFields;
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
daofield : TDAOField;
value : TValue;
begin
try
rType := ctx.GetType(Self.Table.ClassInfo);
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(Self.Table,propertyname) then
begin
daofield := TDAOField.Create;
daofield.DataSize := 0;
daofield.Precision := 0;
{$IFNDEF FPC}
//get datasize from attributes
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
if attr is TFieldVARCHAR then daofield.DataSize := TFieldVARCHAR(attr).Size;
if attr is TFieldDecimal then
begin
daofield.DataSize := TFieldDECIMAL(attr).Size;
daofield.Precision := TFieldDECIMAL(attr).Decimals;
end;
end;
{$ENDIF}
daofield.Name := propertyname;
//value := rProp.GetValue(Self.Table);
//propType := rProp.PropertyType.TypeKind;
case rProp.PropertyType.TypeKind of
tkDynArray, tkArray, tkClass, tkRecord :
begin
daofield.DataType := dtstringMax;
end;
tkString, tkLString, tkWString, tkUString{$IFDEF FPC}, tkAnsiString{$ENDIF} :
begin
//get datasize from index
{$IFNDEF FPC}
if TRttiInstanceProperty(rProp).Index > 0 then daofield.DataSize := TRttiInstanceProperty(rProp).Index;
{$ELSE}
if GetPropInfo(Self.Table,propertyname).Index > 0 then daofield.DataSize := GetPropInfo(Self.Table,propertyname).Index;
{$ENDIF}
if daofield.DataSize = 0 then daofield.DataType := dtstringMax
else daofield.DataType := dtString;
end;
tkChar, tkWChar :
begin
daofield.DataType := dtString;
daofield.DataSize := 1;
end;
tkInteger : daofield.DataType := dtInteger;
tkInt64 :
begin
if rProp.PropertyType.Name = 'TAutoID' then daofield.DataType := dtAutoId
else daofield.DataType := dtInt64;
end;
{$IFDEF FPC}
tkBool : daofield.DataType := dtBoolean;
{$ENDIF}
tkFloat :
begin
value := rProp.GetValue(Self.Table);
if value.TypeInfo = TypeInfo(TCreationDate) then
begin
daofield.DataType := dtCreationDate;
end
else if value.TypeInfo = TypeInfo(TModifiedDate) then
begin
daofield.DataType := dtModifiedDate;
end
else if value.TypeInfo = TypeInfo(TDateTime) then
begin
daofield.DataType := dtDateTime;
end
else if value.TypeInfo = TypeInfo(TDate) then
begin
daofield.DataType := dtDate;
end
else if value.TypeInfo = TypeInfo(TTime) then
begin
daofield.DataType := dtTime;
end
else
begin
daofield.DataType := dtFloat;
if daofield.DataSize = 0 then daofield.DataSize := 10;
//get decimals from index
{$IFNDEF FPC}
if TRttiInstanceProperty(rProp).Index > 0 then daofield.Precision := TRttiInstanceProperty(rProp).Index;
{$ELSE}
if GetPropInfo(Self.Table,propertyname).Index > 0 then daofield.Precision := GetPropInfo(Self.Table,propertyname).Index;
{$ENDIF}
if daofield.Precision = 0 then daofield.Precision := 4;
end;
end;
tkEnumeration :
begin
value := rProp.GetValue(Self.Table);
if (value.TypeInfo = System.TypeInfo(Boolean)) then
begin
daofield.DataType := dtBoolean;
end
else
begin
daofield.DataType := dtInteger;
end;
end;
end;
fFields.Add(daofield);
fFieldsMap.Add(daofield.Name,daofield);
end;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting fields "%s" : %s',[Self.ClassName,e.Message]);
end;
end;
end;
function TDAOModel.HasPrimaryKey: Boolean;
begin
Result := not fPrimaryKey.Name.IsEmpty;
end;
function TDAOModel.IsPrimaryKey(const aName: string): Boolean;
begin
Result := HasPrimaryKey and (CompareText(PrimaryKey.Name,aName) = 0);
end;
procedure TDAOModel.SetPrimaryKey(const Value: TDAOField);
begin
fPrimaryKey := Value;
fPrimaryKey.IsPrimaryKey := True;
end;
procedure TDAOModel.SetTable(const Value: TDAORecordClass);
begin
fTable := Value;
GetFields;
end;
{ TDAOResult }
constructor TDAOResult<T>.Create(aDAOQuery: IDAOQuery<T>);
begin
fDAOQuery := aDAOQuery;
end;
function TDAOResult<T>.GetEnumerator: TEnumerator<T>;
begin
Result := TDAOEnumerator.Create(fDAOQuery);
end;
function TDAOResult<T>.GetOne(aDAORecord: T): Boolean;
begin
//Result := not fDAOQuery.Eof;
//if not Result then Exit;
Result := fDAOQuery.MoveNext;
if not Result then Exit;
fDAOQuery.FillRecordFromDB(aDAORecord);
end;
function TDAOResult<T>.ToArray: TArray<T>;
var
daorecord : T;
i : Integer;
begin
SetLength(Result,Self.Count);
i := 0;
for daorecord in Self do
begin
Result[i] := daorecord;
Inc(i);
end;
end;
function TDAOResult<T>.ToList: TList<T>;
var
daorecord : T;
begin
Result := TList<T>.Create;
Result.Capacity := Self.Count;
for daorecord in Self do Result.Add(daorecord);
end;
function TDAOResult<T>.ToObjectList: TObjectList<T>;
var
daorecord : T;
begin
Result := TObjectList<T>.Create(True);
Result.Capacity := Self.Count;
for daorecord in Self do Result.Add(daorecord);
end;
function TDAOResult<T>.Count: Integer;
begin
Result := fDAOQuery.CountResults;
end;
function TDAOResult<T>.HasResults: Boolean;
begin
Result := fDAOQuery.CountResults > 0;
end;
{ TDAOResult<T>.TEnumerator }
constructor TDAOResult<T>.TDAOEnumerator.Create(aDAOQuery: IDAOQuery<T>);
begin
fDAOQuery := aDAOQuery;
fModel := aDAOQuery.GetModel;
end;
function TDAOResult<T>.TDAOEnumerator.DoGetCurrent: T;
var
{$IFNDEF FPC}
daorecord : TDAORecord;
{$ELSE}
daorecord : T;
{$ENDIF}
begin
{$IFNDEF FPC}
daorecord := fDAOQuery.GetModel.Table.Create;
{$ELSE}
daorecord := T.Create;
{$ENDIF}
fDAOQuery.FillRecordFromDB(daorecord);
Result := daorecord as T;
//Result := fDAOQuery.GetCurrent;
end;
function TDAOResult<T>.TDAOEnumerator.DoMoveNext: Boolean;
begin
Result := fDAOQuery.MoveNext;
end;
{ TDAOQueryGenerator }
function TDAOQueryGenerator.QuotedStr(const aValue: string): string;
begin
Result := '''' + aValue + '''';
end;
{ TDBField }
function TDBField.IsEmptyOrEmpty: Boolean;
begin
Result := VarIsClear(Value) or VarIsEmpty(Value) or VarIsNull(Value) or (VarCompareValue(Value, Unassigned) = vrEqual);
if (not Result) and VarIsStr(Value) then Result := Value = '';
end;
end.
|
program CircleMoving;
uses SwinGame, sgTypes;
const
CIRCLE_RADIUS = 150; //Using Constants to avoid Magic Numbers
procedure Main();
var
x,y : Integer;
begin
openGraphicsWindow('Circle Moving', 800, 600);
x := 400;
y := 300;
REPEAT
//Moving The circle Logic
If KeyDown(LeftKey) and (ScreenWidth()-x + CIRCLE_RADIUS < ScreenWidth()) then
x := x-1;
if KeyDown(RightKey) and (x + CIRCLE_RADIUS < ScreenWidth()) then
x := x+1;
If KeyDown(DownKey) and (y + CIRCLE_RADIUS < ScreenHeight()) then
y := y+1;
If KeyDown(UpKey) and (ScreenHeight()-y + CIRCLE_RADIUS < ScreenHeight()) then
y := y-1;
///end of Logic////
ClearScreen();
DrawCircle(ColorGreen, x, y, CIRCLE_RADIUS);
ProcessEvents();
RefreshScreen(60); //to mainatin 60 fps
UNTIL WindowCloseRequested() ;
end;
begin
Main();
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Strings Editor Dialog }
{ }
{ Copyright (c) 1999-2001 Borland Software Corp. }
{ }
{*******************************************************}
unit StringsEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StrEdit, Menus, StdCtrls, ExtCtrls, ComCtrls;
type
TStringsEditDlg = class(TStrEditDlg)
LineCount: TLabel;
Bevel1: TBevel;
Memo: TRichEdit;
procedure Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure UpdateStatus(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
SingleLine: string;
MultipleLines: string;
protected
function GetLines: TStrings; override;
procedure SetLines(const Value: TStrings); override;
function GetLinesControl: TWinControl; override;
public
{ Public declarations }
end;
implementation
{$R *.DFM}
uses DesignConst;
function TStringsEditDlg.GetLinesControl: TWinControl;
begin
Result := Memo;
end;
procedure TStringsEditDlg.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then CancelButton.Click;
end;
procedure TStringsEditDlg.UpdateStatus(Sender: TObject);
var
Count: Integer;
LineText: string;
begin
if Sender = Memo then FModified := True;
Count := Memo.Lines.Count;
if Count = 1 then LineText := SingleLine
else LineText := MultipleLines;
LineCount.Caption := Format('%d %s', [Count, LineText]);
end;
procedure TStringsEditDlg.FormCreate(Sender: TObject);
begin
inherited;
SingleLine := srLine;
MultipleLines := srLines;
end;
function TStringsEditDlg.GetLines: TStrings;
begin
Result := Memo.Lines;
end;
procedure TStringsEditDlg.SetLines(const Value: TStrings);
begin
Memo.Lines.Assign(Value);
end;
end.
|
{$i deltics.inc}
unit Test.InterfaceReference;
interface
uses
Deltics.Smoketest;
type
TInterfaceReferenceTests = class(TTest)
private
fOnDestroyCallCount: Integer;
procedure OnDestroyCallCounter(aSender: TObject);
published
procedure SetupMethod;
procedure InterfaceReferenceMaintainsStrongReference;
procedure IsReferenceToIsTRUEWhenReferenceIsTheSameAndNotNIL;
procedure IsReferenceToIsTRUEWhenReferencesAreNIL;
procedure IsReferenceToIsFALSEWhenOneIsNIL;
procedure IsReferenceToIsFALSEWhenReferencesAreDifferent;
end;
implementation
uses
Deltics.InterfacedObjects,
Deltics.Multicast;
{ TInterfacedObjectTests }
procedure TInterfaceReferenceTests.OnDestroyCallCounter(aSender: TObject);
begin
Inc(fOnDestroyCallCount);
end;
procedure TInterfaceReferenceTests.SetupMethod;
begin
fOnDestroyCallCount := 0;
end;
procedure TInterfaceReferenceTests.InterfaceReferenceMaintainsStrongReference;
var
foo: IUnknown;
sut: TInterfaceReference;
iod: IOn_Destroy;
begin
foo := TComInterfacedObject.Create;
iod := foo as IOn_Destroy;
iod.Add(OnDestroyCallCounter);
iod := NIL;
sut := TInterfaceReference.Create(foo);
try
// NIL'ing foo leaves the TInterfaceReference as the only reference
// to foo (it should not have been destroyed)
foo := NIL;
Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(0);
finally
// Freeing the interface reference removes the last reference to
// foo - it should have been destroyed
sut.Free;
Test('OnDestroyCallCount').Assert(fOnDestroyCallCount).Equals(1);
end;
end;
procedure TInterfaceReferenceTests.IsReferenceToIsFALSEWhenReferencesAreDifferent;
var
a, b: IUnknown;
sut: TInterfaceReference;
begin
a := TComInterfacedObject.Create;
b := TComInterfacedObject.Create;
sut := TInterfaceReference.Create(a);
try
Test('IsReferenceTo').Assert(NOT sut.IsReferenceTo(b));
finally
sut.Free;
end;
end;
procedure TInterfaceReferenceTests.IsReferenceToIsFALSEWhenOneIsNIL;
var
a, b: IUnknown;
sut: TInterfaceReference;
begin
a := TComInterfacedObject.Create;
b := NIL;
sut := TInterfaceReference.Create(a);
try
Test('IsReferenceTo(NIL)').Assert(NOT sut.IsReferenceTo(b));
finally
sut.Free;
end;
sut := TInterfaceReference.Create(b);
try
Test('IsReferenceTo(<intf>)').Assert(NOT sut.IsReferenceTo(a));
finally
sut.Free;
end;
end;
procedure TInterfaceReferenceTests.IsReferenceToIsTRUEWhenReferenceIsTheSameAndNotNIL;
var
a, b: IUnknown;
sut: TInterfaceReference;
begin
a := TComInterfacedObject.Create;
b := a;
sut := TInterfaceReference.Create(a);
try
Test('IsReferenceTo').Assert(sut.IsReferenceTo(b));
finally
sut.Free;
end;
end;
procedure TInterfaceReferenceTests.IsReferenceToIsTRUEWhenReferencesAreNIL;
var
sut: TInterfaceReference;
begin
sut := TInterfaceReference.Create(NIL);
try
Test('IsReferenceTo').Assert(sut.IsReferenceTo(NIL));
finally
sut.Free;
end;
end;
end.
|
unit Unit1;
interface
uses
SysUtils, Variants, Classes, QGraphics, QControls, QForms,
QDialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
QStdCtrls, QExtCtrls, Sockets;
type
TForm1 = class(TForm)
Panel1: TPanel;
Memo1: TMemo;
Panel2: TPanel;
Label3: TLabel;
Label4: TLabel;
EditServer: TEdit;
EditCommand: TEdit;
Label1: TLabel;
EditUser: TEdit;
Label2: TLabel;
EditPass: TEdit;
Button1: TButton;
ConnectLight: TShape;
Label5: TLabel;
client: TTcpClient;
ButtonClose: TButton;
ButtonClear: TButton;
procedure Button1Click(Sender: TObject);
procedure clientConnected(Sender: TObject);
procedure clientConnect(sender: TObject);
procedure clientError(sender: TObject; SocketError: Integer);
procedure ButtonCloseClick(Sender: TObject);
procedure ButtonClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.xfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if NOT Client.Connected then
begin
ConnectLight.Brush.Color:= clGreen;
ConnectLight.Repaint;
Client.RemoteHost:= EditServer.Text;
Client.Active := true;
Client.connect;
end;
end;
procedure TForm1.clientConnected(Sender: TObject);
var
outln : String;
begin
end;
procedure TForm1.clientConnect(sender: TObject);
var
outln : String;
begin
client.Sendln('0',#0);
client.Sendln(EditUser.Text,#0);
client.Sendln(EditPass.Text,#0);
client.Sendln(editCommand.Text,#0);
while client.WaitForData(10000) do
begin
outln := Client.Receiveln(#10);
memo1.lines.add(outln);
end;
Client.Close;
ConnectLight.Brush.Color:= clRed;
end;
procedure TForm1.clientError(sender: TObject; SocketError: Integer);
begin
memo1.lines.Add('Socket Error # ' + IntToStr(SocketError));
ConnectLight.Brush.Color:= clRed;
end;
procedure TForm1.ButtonCloseClick(Sender: TObject);
begin
Client.Close;
end;
procedure TForm1.ButtonClearClick(Sender: TObject);
begin
Memo1.Lines.Clear;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Data.DbxInterbase"'} {Do not Localize}
unit Data.DbxInterbase;
interface
uses
Data.DBXDynalink,
Data.DBXDynalinkNative,
Data.DBXCommon, Data.DbxInterBaseReadOnlyMetaData, Data.DbxInterBaseMetaData;
type
TDBXInterBaseProperties = class(TDBXProperties)
strict private
const StrServerCharSet = 'ServerCharSet';
function GetDatabase: string;
function GetPassword: string;
function GetUserName: string;
function GetServerCharSet: string;
procedure SetServerCharSet(const Value: string);
procedure SetDatabase(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
public
constructor Create(DBXContext: TDBXContext); override;
published
property Database: string read GetDatabase write SetDatabase;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property ServerCharSet: string read GetServerCharSet write SetServerCharSet;
end;
TDBXInterBaseDriver = class(TDBXDynalinkDriverNative)
public
constructor Create(DBXDriverDef: TDBXDriverDef); override;
end;
implementation
uses
Data.DBXPlatform, System.SysUtils;
const
sDriverName = 'InterBase';
{ TDBXInterBaseDriver }
constructor TDBXInterBaseDriver.Create(DBXDriverDef: TDBXDriverDef);
var
Props: TDBXInterBaseProperties;
I, Index: Integer;
begin
Props := TDBXInterBaseProperties.Create(DBXDriverDef.FDBXContext);
if DBXDriverDef.FDriverProperties <> nil then
begin
for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do
begin
Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]);
if Index > -1 then
Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I];
end;
Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties);
DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties);
end;
inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props);
end;
{ TDBXInterBaseProperties }
constructor TDBXInterBaseProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXInterbase';
Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXInterBaseDriver160.bpl';
Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXInterbaseMetaDataCommandFactory,DbxInterBaseDriver160.bpl';
Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXInterbaseMetaDataCommandFactory,Borland.Data.DbxInterBaseDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverINTERBASE';
Values[TDBXPropertyNames.LibraryName] := 'dbxint.dll';
Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlib.dylib';
Values[TDBXPropertyNames.VendorLib] := 'gds32.dll';
Values[TDBXPropertyNames.VendorLibWin64] := 'ibclient64.dll';
Values[TDBXPropertyNames.VendorLibOsx] := 'libgds.dylib';
Values[TDBXPropertyNames.Database] := 'database.gdb';
Values[TDBXPropertyNames.UserName] := 'sysdba';
Values[TDBXPropertyNames.Password] := 'masterkey';
Values[TDBXPropertyNames.Role] := 'RoleName';
Values[TDBXPropertyNames.MaxBlobSize] := '-1';
Values[TDBXPropertyNames.ErrorResourceFile] := '';
Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000';
Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted';
Values['ServerCharSet'] := '';
Values['SQLDialect'] := '3';
Values['CommitRetain'] := 'False';
Values['WaitOnLocks'] := 'True';
Values['TrimChar'] := 'False';
end;
function TDBXInterBaseProperties.GetDatabase: string;
begin
Result := Values[TDBXPropertyNames.Database];
end;
function TDBXInterBaseProperties.GetPassword: string;
begin
Result := Values[TDBXPropertyNames.Password];
end;
function TDBXInterBaseProperties.GetServerCharSet: string;
begin
Result := Values[StrServerCharSet];
end;
function TDBXInterBaseProperties.GetUserName: string;
begin
Result := Values[TDBXPropertyNames.UserName];
end;
procedure TDBXInterBaseProperties.SetDatabase(const Value: string);
begin
Values[TDBXPropertyNames.Database] := Value;
end;
procedure TDBXInterBaseProperties.SetPassword(const Value: string);
begin
Values[TDBXPropertyNames.Password] := Value;
end;
procedure TDBXInterBaseProperties.SetServerCharSet(const Value: string);
begin
Values[StrServerCharSet] := Value;
end;
procedure TDBXInterBaseProperties.SetUserName(const Value: string);
begin
Values[TDBXPropertyNames.UserName] := Value;
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXInterBaseDriver);
end.
|
unit uModel.Interfaces;
interface
uses System.Classes, uModel.Endereco;
type
iPessoaContatoModel = interface;
iPessoaContatoList = interface;
iPessoaModel = interface
['{5CEAF308-2BD1-46B8-A649-1FE6E519CC28}']
function Id: Integer; overload;
function Id(Value: Integer): iPessoaModel; overload;
function Nome: string; overload;
function Nome(Value: string): iPessoaModel; overload;
function Endereco: TEnderecoModel;
function Contatos: iPessoaContatoList;
end;
iPessoaContatoModel = interface
['{90A4772F-9D3E-4F9C-87CF-04291481AD58}']
function Id: Integer; overload;
function Id(Value: Integer): iPessoaContatoModel; overload;
function IdPessoa: Integer; overload;
function IdPessoa(Value: Integer): iPessoaContatoModel; overload;
function Tipo: string; overload;
function Tipo(Value: string): iPessoaContatoModel; overload;
function Contato: string; overload;
function Contato(Value: string): iPessoaContatoModel; overload;
end;
iPessoaContatoList = interface
['{B2F5491D-17BC-42E5-A6D8-200FA63CBC31}']
function Add(Value: iPessoaContatoModel): iPessoaContatoList;
function Get(pIndex: Integer): iPessoaContatoModel;
function Delete(pIndex: Integer): iPessoaContatoList;
function Count: Integer;
function Clear: iPessoaContatoList;
end;
implementation
end.
|
unit ProductsBaseView1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ProductsBaseView0, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles,
cxTL, cxMaskEdit, cxDBLookupComboBox, cxDropDownEdit, cxButtonEdit,
cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinsDefaultPainters, cxCalendar,
cxCurrencyEdit, Vcl.ExtCtrls, Vcl.Menus, System.Actions, Vcl.ActnList, dxBar,
cxBarEditItem, cxClasses, Vcl.ComCtrls, cxInplaceContainer, cxDBTL, cxTLData,
BaseProductsViewModel1, ExtraChargeSimpleView, ProductsBaseQuery, Data.DB,
cxDataControllerConditionalFormattingRulesManagerDialog;
type
TViewProductsBase1 = class(TViewProductsBase0)
dxBarManagerBar2: TdxBar;
cxbeiExtraChargeType: TcxBarEditItem;
cxbeiExtraCharge: TcxBarEditItem;
dxbcWholeSale: TdxBarCombo;
actRubToDollar: TAction;
dxbcMinWholeSale: TdxBarCombo;
dxbbRubToDollar: TdxBarButton;
dxbcRetail: TdxBarCombo;
actCommit: TAction;
actRollback: TAction;
actDelete: TAction;
actCreateBill: TAction;
actOpenInParametricTable: TAction;
actClearPrice: TAction;
procedure actClearPriceExecute(Sender: TObject);
procedure actCommitExecute(Sender: TObject);
procedure actCreateBillExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actOpenInParametricTableExecute(Sender: TObject);
procedure actRollbackExecute(Sender: TObject);
procedure actRubToDollarExecute(Sender: TObject);
procedure cxbeiExtraChargeTypePropertiesChange(Sender: TObject);
procedure dxbcMinWholeSaleChange(Sender: TObject);
procedure dxbcRetailChange(Sender: TObject);
procedure dxbcWholeSaleChange(Sender: TObject);
procedure dxbcWholeSaleDrawItem(Sender: TdxBarCustomCombo; AIndex: Integer;
ARect: TRect; AState: TOwnerDrawState);
private
FViewExtraChargeSimple: TViewExtraChargeSimple;
procedure DoAfterCancelUpdates(Sender: TObject);
procedure DoOnCloseExtraChargesPopup(Sender: TObject);
procedure DoOnRubToDollarChange(Sender: TObject);
function GetIDExtraChargeType: Integer;
function GetModel: TBaseProductsViewModel1;
function GetProductW: TProductW;
function GetViewExtraChargeSimple: TViewExtraChargeSimple;
function SaveBarComboValue(AdxBarCombo: TdxBarCombo): Double;
procedure SetIDExtraChargeType(const Value: Integer);
procedure SetModel(const Value: TBaseProductsViewModel1);
procedure UpdateAllBarComboText;
{ Private declarations }
protected
procedure DoOnSelectionChange; override;
procedure LoadWholeSale;
procedure UpdateFieldValue(AFields: TArray<TField>;
AValues: TArray<Variant>);
property IDExtraChargeType: Integer read GetIDExtraChargeType
write SetIDExtraChargeType;
property ViewExtraChargeSimple: TViewExtraChargeSimple
read GetViewExtraChargeSimple;
public
function CheckAndSaveChanges: Integer;
procedure UpdateView; override;
property Model: TBaseProductsViewModel1 read GetModel write SetModel;
property ProductW: TProductW read GetProductW;
{ Public declarations }
end;
implementation
uses
NotifyEvents, DBLookupComboBoxHelper, System.Generics.Collections,
SettingsController, MinWholeSaleForm, DialogUnit, CreateBillForm, DataModule,
System.StrUtils;
const
clClickedColor = clRed;
{$R *.dfm}
procedure TViewProductsBase1.actClearPriceExecute(Sender: TObject);
begin
inherited;
BeginUpdate;
try
Model.qProductsBase.ClearInternalCalcFields;
FocusFirstNode;
finally
EndUpdate;
end;
UpdateView;
end;
procedure TViewProductsBase1.actCommitExecute(Sender: TObject);
var
AMinWholeSale: Double;
ASave: Boolean;
begin
inherited;
Model.qProductsBase.W.TryPost;
// если есть записи, которые были добавлены
if Model.qProductsBase.HaveInsertedProducts then
begin
AMinWholeSale := TSettings.Create.MinWholeSale;
if TfrmMinWholeSale.DoShowModal(AMinWholeSale, ASave) then
begin
if ASave then
// Сохраняем минимальную оптовую наценку по умолчанию в настройках
TSettings.Create.MinWholeSale := AMinWholeSale;
// Применяем минимальную оптовую наценку
Model.qProductsBase.ApplyMinWholeSale(AMinWholeSale);
end;
end;
// Мы просто завершаем транзакцию
Model.qProductsBase.ApplyUpdates;
UpdateView;
end;
procedure TViewProductsBase1.actCreateBillExecute(Sender: TObject);
var
AfrmCreateBill: TFrmCreateBill;
begin
inherited;
AfrmCreateBill := TFrmCreateBill.Create(nil);
try
if AfrmCreateBill.ShowModal <> mrOK then
Exit;
// Создаём новый счёт
TDM.Create.AddBill(Model.qProductsBase, AfrmCreateBill);
finally
FreeAndNil(AfrmCreateBill);
end;
end;
procedure TViewProductsBase1.actDeleteExecute(Sender: TObject);
var
AID: Integer;
APKArray: TArray<Variant>;
S: string;
begin
inherited;
if cxDBTreeList.SelectionCount = 0 then
Exit;
if cxDBTreeList.Selections[0].IsGroupNode then
S := 'Удалить группу компонентов с текущего склада?'
else
S := Format('Удалить %s?', [IfThen(cxDBTreeList.SelectionCount = 1,
'компонент', 'компоненты')]);
if not(TDialog.Create.DeleteRecordsDialog(S)) then
Exit;
// Заполняем список идентификаторов узлов, которые будем удалять
APKArray := GetSelectedValues(W.PKFieldName);
cxDBTreeList.BeginUpdate;
try
for AID in APKArray do
Model.qProductsBase.DeleteNode(AID);
// Это почему-то не работает
// cxDBTreeList.DataController.DeleteFocused;
finally
cxDBTreeList.EndUpdate;
end;
UpdateView;
end;
procedure TViewProductsBase1.actOpenInParametricTableExecute(Sender: TObject);
begin
inherited;
Assert(Model.qProductsBase.FDQuery.RecordCount > 0);
if ProductW.Value.F.AsString.Trim.IsEmpty then
begin
TDialog.Create.ErrorMessageDialog('Не задано наименование');
Exit;
end;
if ProductW.IDProducer.F.AsInteger = 0 then
begin
TDialog.Create.ErrorMessageDialog('Не задан производитель');
Exit;
end;
if not Model.qProductsBase.LocateInComponents then
begin
TDialog.Create.ErrorMessageDialog
(Format('Компонент %s не найден в теоретической базе',
[ProductW.Value.F.AsString]));
Exit;
end;
end;
procedure TViewProductsBase1.actRollbackExecute(Sender: TObject);
begin
inherited;
cxDBTreeList.BeginUpdate;
try
Model.qProductsBase.CancelUpdates;
cxDBTreeList.FullCollapse;
finally
cxDBTreeList.EndUpdate;
end;
UpdateView;
end;
procedure TViewProductsBase1.actRubToDollarExecute(Sender: TObject);
begin
inherited;
Model.qProductsBase.RubToDollar := not Model.qProductsBase.RubToDollar;
UpdateView;
end;
function TViewProductsBase1.CheckAndSaveChanges: Integer;
begin
Result := 0;
if Model.qProductsBase = nil then
Exit;
UpdateView;
if Model.qProductsBase.HaveAnyChanges then
begin
Result := TDialog.Create.SaveDataDialog;
case Result of
IDYES:
actCommit.Execute;
IDNO:
begin
actRollback.Execute;
end;
end;
end;
end;
procedure TViewProductsBase1.cxbeiExtraChargeTypePropertiesChange
(Sender: TObject);
var
A: TArray<String>;
S: string;
begin
inherited;
if cxbeiExtraChargeType.Tag <> 0 then
Exit;
(Sender as TcxLookupComboBox).PostEditValue;
// Фильтруем оптовые наценки по типу
Model.ExtraChargeGroup.qExtraCharge2.W.FilterByType
(cxbeiExtraChargeType.EditValue);
ViewExtraChargeSimple.MainView.ApplyBestFit;
// Помещаем пустое значение в качестве выбранного
dxbcWholeSale.Tag := 1;
try
dxbcWholeSale.ItemIndex := -1;
// Получаем список оптовых наценок
A := Model.ExtraChargeGroup.qExtraCharge2.W.GetWholeSaleList;
// Заполняем выпадающий список оптовых наценок
dxbcWholeSale.Items.Clear;
for S in A do
dxbcWholeSale.Items.Add(S);
finally
dxbcWholeSale.Tag := 0;
end;
end;
procedure TViewProductsBase1.DoAfterCancelUpdates(Sender: TObject);
begin
UpdateAllBarComboText;
end;
procedure TViewProductsBase1.DoOnCloseExtraChargesPopup(Sender: TObject);
var
AIDExtraCharge: Integer;
AWholeSale: string;
begin
AIDExtraCharge := Model.ExtraChargeGroup.qExtraCharge2.W.ID.F.AsInteger;
cxbeiExtraCharge.EditValue := Model.ExtraChargeGroup.qExtraCharge2.W.Range.
F.AsString;
AWholeSale := Model.ExtraChargeGroup.qExtraCharge2.W.WholeSale.F.AsString;
dxbcWholeSale.Tag := 1;
dxbcWholeSale.ItemIndex := dxbcWholeSale.Items.IndexOf(AWholeSale);
dxbcWholeSale.Tag := 0;
// Сохраняем выбранный диапазон и значение оптовой наценки
UpdateFieldValue([ProductW.IDExtraChargeType.F, ProductW.IDExtraCharge.F,
ProductW.WholeSale.F], [IDExtraChargeType, AIDExtraCharge,
Model.ExtraChargeGroup.qExtraCharge2.W.WholeSale.F.Value]);
// Выбираем это значение в выпадающем списке
UpdateBarComboText(dxbcWholeSale,
Model.ExtraChargeGroup.qExtraCharge2.W.WholeSale.F.Value);
end;
procedure TViewProductsBase1.DoOnRubToDollarChange(Sender: TObject);
begin
Assert(Model <> nil);
actRubToDollar.Checked := Model.qProductsBase.RubToDollar;
if not FResyncDataSetMessagePosted then
begin
FResyncDataSetMessagePosted := True;
PostMessage(Handle, WM_RESYNC_DATASET, 0, 0);
end;
end;
procedure TViewProductsBase1.DoOnSelectionChange;
begin
inherited;
UpdateAllBarComboText;
end;
procedure TViewProductsBase1.dxbcMinWholeSaleChange(Sender: TObject);
var
AdxBarCombo: TdxBarCombo;
AValue: Double;
begin
inherited;
AdxBarCombo := Sender as TdxBarCombo;
if AdxBarCombo.Tag = 1 then
Exit;
// Сохраняем значение в выпадающем списке
AValue := SaveBarComboValue(AdxBarCombo);
// Сохраняем значение в БД
UpdateFieldValue([ProductW.MinWholeSale.F], [AValue]);
end;
procedure TViewProductsBase1.dxbcRetailChange(Sender: TObject);
var
AdxBarCombo: TdxBarCombo;
AValue: Double;
begin
inherited;
AdxBarCombo := Sender as TdxBarCombo;
if AdxBarCombo.Tag = 1 then
Exit;
// Сохраняем значение в выпадающем списке
AValue := SaveBarComboValue(AdxBarCombo);
// Сохраняем значение в БД
UpdateFieldValue([ProductW.Retail.F], [AValue]);
end;
procedure TViewProductsBase1.dxbcWholeSaleChange(Sender: TObject);
var
AdxBarCombo: TdxBarCombo;
AValue: Double;
begin
inherited;
AdxBarCombo := Sender as TdxBarCombo;
if AdxBarCombo.Tag <> 0 then
Exit;
AValue := SaveBarComboValue(AdxBarCombo);
// Сохраняем выбранный диапазон и значение оптовой наценки
UpdateFieldValue([ProductW.IDExtraChargeType.F, ProductW.IDExtraCharge.F,
ProductW.WholeSale.F], [NULL, NULL, AValue]);
cxbeiExtraChargeType.Tag := 1;
cxbeiExtraChargeType.EditValue := NULL;
cxbeiExtraChargeType.Tag := 0;
// Фильтруем оптовые наценки по типу
Model.ExtraChargeGroup.qExtraCharge2.W.FilterByType(0);
cxbeiExtraCharge.EditValue := NULL;
end;
procedure TViewProductsBase1.dxbcWholeSaleDrawItem(Sender: TdxBarCustomCombo;
AIndex: Integer; ARect: TRect; AState: TOwnerDrawState);
var
S: string;
begin
inherited;
if odSelected in AState then
begin
Brush.Color := clClickedColor;
Font.Color := clHighlightText;
end
else
begin
Brush.Color := clWindow;
Font.Color := clWindowText;
end;
Sender.Canvas.FillRect(ARect);
if odFocused in AState then
DrawFocusRect(Sender.Canvas.Handle, ARect);
if AIndex >= 0 then
S := Sender.Items[AIndex]
else
S := Sender.Text;
if S <> '' then
S := S + '%';
Sender.Canvas.TextOut(ARect.Left + 2, ARect.Top + 2, S);
end;
function TViewProductsBase1.GetIDExtraChargeType: Integer;
begin
if VarIsNull(cxbeiExtraChargeType.EditValue) then
Result := 0
else
Result := cxbeiExtraChargeType.EditValue;
end;
function TViewProductsBase1.GetModel: TBaseProductsViewModel1;
begin
Result := M as TBaseProductsViewModel1;
end;
function TViewProductsBase1.GetProductW: TProductW;
begin
Result := Model.qProductsBase.W;
end;
function TViewProductsBase1.GetViewExtraChargeSimple: TViewExtraChargeSimple;
begin
if FViewExtraChargeSimple = nil then
begin
FViewExtraChargeSimple := TViewExtraChargeSimple.Create(Self);
TNotifyEventWrap.Create(FViewExtraChargeSimple.OnClosePopup,
DoOnCloseExtraChargesPopup);
end;
Result := FViewExtraChargeSimple;
end;
procedure TViewProductsBase1.LoadWholeSale;
var
AWholeSale: string;
AWholeSaleList: TArray<String>;
begin
AWholeSaleList := Model.ExtraChargeGroup.qExtraCharge2.W.GetWholeSaleList;
dxbcWholeSale.Items.BeginUpdate;
try
dxbcWholeSale.Items.Clear;
for AWholeSale in AWholeSaleList do
dxbcWholeSale.Items.Add(AWholeSale);
finally
dxbcWholeSale.Items.EndUpdate;
end;
end;
function TViewProductsBase1.SaveBarComboValue(AdxBarCombo: TdxBarCombo): Double;
begin
Assert(AdxBarCombo <> nil);
Result := 0;
if AdxBarCombo.Tag = 1 then
Exit;
Result := StrToFloatDef(AdxBarCombo.Text, 0);
if Result < 0 then
Result := 0;
// если ввели какое-то недопустимое значение или 0
if Result = 0 then
UpdateBarComboText(AdxBarCombo, NULL);
UpdateView;
end;
procedure TViewProductsBase1.SetIDExtraChargeType(const Value: Integer);
begin
cxbeiExtraChargeType.EditValue := Value;
end;
procedure TViewProductsBase1.SetModel(const Value: TBaseProductsViewModel1);
begin
if M = Value then
Exit;
M := Value;
if M = nil then
Exit;
TNotifyEventWrap.Create(Model.qProductsBase.OnRubToDollarChange,
DoOnRubToDollarChange, FEventList);
// Обновляем состояние кнопки
actRubToDollar.Checked := Model.qProductsBase.RubToDollar;
dxbbRubToDollar.Down := actRubToDollar.Checked;
// Фильтруем оптовые надбавки по типу
Model.ExtraChargeGroup.qExtraChargeType.W.TryOpen;
Model.ExtraChargeGroup.qExtraCharge2.W.TryOpen;
Model.ExtraChargeGroup.qExtraCharge2.W.FilterByType(0);
ViewExtraChargeSimple.MainView.ApplyBestFit;
// Привязываем представление оптовых надбавок
TDBLCB.InitProp(cxbeiExtraChargeType.Properties as
TcxLookupComboBoxProperties,
Model.ExtraChargeGroup.qExtraChargeType.W.DataSource,
Model.ExtraChargeGroup.qExtraChargeType.W.PK.FieldName,
Model.ExtraChargeGroup.qExtraChargeType.W.Name.FieldName, lsFixedList);
ViewExtraChargeSimple.qExtraCharge := Model.ExtraChargeGroup.qExtraCharge2;
ViewExtraChargeSimple.Font.Size := 9;
(cxbeiExtraCharge.Properties as TcxPopupEditproperties).PopupControl :=
ViewExtraChargeSimple;
LoadWholeSale;
TNotifyEventWrap.Create(M.qProductsBase0.AfterCancelUpdates,
DoAfterCancelUpdates, FEventList);
end;
procedure TViewProductsBase1.UpdateAllBarComboText;
var
ARange: Variant;
begin
if (W.DataSet.RecordCount > 0) and (cxDBTreeList.SelectionCount > 0) then
begin
// Отображаем розничную наценку у текущей записи
UpdateBarComboText(dxbcRetail, ProductW.Retail.F.Value);
// Отображаем оптовую наценку у текущей записи
UpdateBarComboText(dxbcWholeSale, ProductW.WholeSale.F.Value);
// Отображаем минимальную оптовую наценку у текущей записи
UpdateBarComboText(dxbcMinWholeSale, ProductW.MinWholeSale.F.Value);
if IDExtraChargeType <> ProductW.IDExtraChargeType.F.AsInteger then
begin
IDExtraChargeType := ProductW.IDExtraChargeType.F.AsInteger;
// Фильтруем оптовые наценки по типу
Model.ExtraChargeGroup.qExtraCharge2.W.FilterByType(IDExtraChargeType);
ViewExtraChargeSimple.MainView.ApplyBestFit;
end;
ARange := NULL;
if ProductW.IDExtraCharge.F.AsInteger > 0 then
begin
if Model.ExtraChargeGroup.qExtraCharge2.W.LocateByPK
(ProductW.IDExtraCharge.F.AsInteger) then
ARange := Model.ExtraChargeGroup.qExtraCharge2.W.Range.F.AsVariant;
end;
cxbeiExtraCharge.Tag := 1;
cxbeiExtraCharge.EditValue := ARange;
cxbeiExtraCharge.Tag := 0;
end
else
begin
// Выпадающий список "Стоимость"
cxbeiExtraChargeType.EditValue := NULL;
// Выпадающий список "Кол-во"
cxbeiExtraCharge.EditValue := NULL;
// Отображаем ПУСТУЮ оптовую наценку у текущей записи
UpdateBarComboText(dxbcWholeSale, NULL);
// Отображаем ПУСТУЮ минимальную оптовую наценку у текущей записи
UpdateBarComboText(dxbcMinWholeSale, NULL);
// Отображаем ПУСТУЮ розничную наценку
UpdateBarComboText(dxbcRetail, NULL);
end;
end;
procedure TViewProductsBase1.UpdateFieldValue(AFields: TArray<TField>;
AValues: TArray<Variant>);
var
ANode: TcxDBTreeListNode;
AUpdatedIDList: TList<Integer>;
i: Integer;
begin
AUpdatedIDList := TList<Integer>.Create;
Model.qProductsBase.FDQuery.DisableControls;
try
for i := 0 to cxDBTreeList.SelectionCount - 1 do
begin
ANode := cxDBTreeList.Selections[i] as TcxDBTreeListNode;
Model.qProductsBase.UpdateFieldValue(ANode.Values[clID.ItemIndex],
AFields, AValues, AUpdatedIDList);
end;
finally
Model.qProductsBase.FDQuery.EnableControls;
FreeAndNil(AUpdatedIDList);
MyApplyBestFit;
end;
end;
procedure TViewProductsBase1.UpdateView;
var
OK: Boolean;
begin
inherited;
OK := (cxDBTreeList.DataController.DataSource <> nil) and (Model <> nil) and
(Model.qProductsBase.FDQuery.Active) and IsViewOK and
(cxDBTreeList.DataController.DataSet <> nil);
actOpenInParametricTable.Enabled := OK and (cxDBTreeList.FocusedNode <> nil)
and (cxDBTreeList.SelectionCount = 1) and (W.DataSet.State = dsBrowse) and
(not W.IsGroup.F.IsNull) and (W.IsGroup.F.AsInteger = 0);
actExportToExcelDocument.Enabled := OK and
(cxDBTreeList.DataController.DataSet.RecordCount > 0);
actDelete.Enabled := OK and (cxDBTreeList.FocusedNode <> nil) and
(cxDBTreeList.SelectionCount > 0) and
(cxDBTreeList.DataController.DataSet.RecordCount > 0);
actCreateBill.Enabled := OK and (Model.qProductsBase.BasketW <> nil) and
(Model.qProductsBase.BasketW.RecordCount > 0) and
(W.DataSet.State = dsBrowse);
{ and (FqProductsBase.DollarCource > 0) and (FqProductsBase.EuroCource > 0) };
actClearPrice.Enabled := OK and
(cxDBTreeList.DataController.DataSet.RecordCount > 0) and
(W.DataSet.State = dsBrowse) and (not Model.qProductsBase.HaveAnyChanges);
actRubToDollar.Enabled := OK and
(cxDBTreeList.DataController.DataSet.RecordCount > 0);
actCommit.Enabled := OK and Model.qProductsBase.HaveAnyChanges;
actRollback.Enabled := actCommit.Enabled;
end;
end.
|
unit UnitSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, Spin;
type
TFormSettings = class(TForm)
CbAlphaBlend: TCheckBox;
CbAutoVol: TCheckBox;
CbStayOnTop: TCheckBox;
TbDarkLevel: TTrackBar;
Label1: TLabel;
TbAlphaBlendLevel: TTrackBar;
CbScardRmb: TCheckBox;
CbShowDot: TCheckBox;
TimerWinamp: TTimer;
Label2: TLabel;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
procedure CbStayOnTopClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure RadioButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormSettings: TFormSettings;
implementation
uses UnitMainForm, UnitWinamp;
{$R *.dfm}
procedure TFormSettings.CbStayOnTopClick(Sender: TObject);
begin
TbAlphaBlendLevel.Enabled := CbAlphaBlend.Checked;
if CbStayOnTop.Checked then With MainForm do
{SetWindowPos(Handle, HWND_TOPMOST, Left, Top, Width, Height, 0) else
With MainForm do
SetWindowPos(Handle, HWND_TOP, Left, Top, Width, Height, 0); }
UnitMainForm.AutoVol := CbAutoVol.Checked;
MainForm.AlphaBlend := CbAlphaBlend.Checked;
MainForm.AlphaBlendValue := TbAlphaBlendLevel.Position;
if UnitMainForm.DarkLevel <> TbDarkLevel.Position then
begin
UnitMainForm.DarkLevel := TbDarkLevel.Position;
MainForm.DarkColorLevel;
end;
UnitMainForm.ShowSpectDot := CbShowDot.Checked;
end;
procedure TFormSettings.FormShow(Sender: TObject);
begin
if MainForm.FormStyle = fsStayOnTop then CbStayOnTop.Checked := True else
CbStayOnTop.Checked := False;
CbAutoVol.Checked := UnitMainForm.AutoVol;
CbAlphaBlend.Checked := MainForm.AlphaBlend;
TbAlphaBlendLevel.Position := MainForm.AlphaBlendValue;
TbDarkLevel.Position := UnitMainForm.DarkLevel;
CbShowDot.Checked := UnitMainForm.ShowSpectDot;
end;
procedure TFormSettings.RadioButton1Click(Sender: TObject);
begin
if RadioButton1.Checked then VisDelay := False else VisDelay := True;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIEdit.pas
// Creator : Shen Min
// Date : 2002-08-22 V1-V3
// 2003-06-20 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIEdit;
interface
{$I SUIPack.inc}
uses Windows, Classes, Controls, StdCtrls, Forms, Graphics, Messages, Mask,
SysUtils,
SUIThemes, SUIMgr, SUIButton;
type
TsuiEdit = class(TCustomEdit)
private
m_BorderColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure UIStyleChanged(); virtual;
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property Anchors;
property AutoSelect;
property AutoSize;
property BiDiMode;
property CharCase;
property Color;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property ImeMode;
property ImeName;
property MaxLength;
property OEMConvert;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
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;
TsuiMaskEdit = class(TCustomMaskEdit)
private
m_BorderColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property Anchors;
property AutoSelect;
property AutoSize;
property BiDiMode;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property EditMask;
property Font;
property ImeMode;
property ImeName;
property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
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;
TsuiNumberEdit = class(TsuiEdit)
private
m_Mask: string;
m_Value: Real;
m_AutoSelectSigns: Integer;
procedure SetValue(Value: Real);
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure DoExit; override;
procedure DoEnter; override;
procedure Change; override;
procedure KeyPress(var Key: Char); override;
procedure Click; override;
public
constructor Create(AOwner: TComponent); override;
published
property Mask: string read m_Mask write m_Mask;
property Value: Real read m_Value write SetValue;
property AutoSelectSigns: Integer read m_AutoSelectSigns write m_AutoSelectSigns;
property AutoSelect;
property AutoSize;
property BorderStyle;
property CharCase;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property ImeMode;
property ImeName;
property MaxLength;
property OEMConvert;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TsuiSpinButtons = class(TWinControl)
private
m_UpButton: TsuiArrowButton;
m_DownButton: TsuiArrowButton;
m_OnUpClick: TNotifyEvent;
m_OnDownClick: TNotifyEvent;
function CreateButton: TsuiArrowButton;
procedure BtnClick(Sender: TObject);
procedure AdjustSize(var W, H: Integer); reintroduce;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
function GetFileTheme: TsuiFileTheme;
function GetUIStyle: TsuiUIStyle;
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
protected
procedure Loaded; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
published
property OnUpClick: TNotifyEvent read m_OnUpClick write m_OnUpClick;
property OnDownClick: TNotifyEvent read m_OnDownClick write m_OnDownClick;
property FileTheme : TsuiFileTheme read GetFileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read GetUIStyle write SetUIStyle;
end;
TsuiSpinEdit = class(TsuiEdit)
private
m_MinValue: Integer;
m_MaxValue: Integer;
m_Increment: Integer;
m_Button: TsuiSpinButtons;
m_EditorEnabled: Boolean;
function GetValue: Integer;
function CheckValue(NewValue: Integer): Integer;
procedure SetValue(NewValue: Integer);
procedure SetEditRect;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure WMPaste(var Message: TWMPaste); message WM_PASTE;
procedure WMCut(var Message: TWMCut); message WM_CUT;
protected
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
function IsValidChar(Key: Char): Boolean; virtual;
procedure UpClick(Sender: TObject); virtual;
procedure DownClick(Sender: TObject); virtual;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure UIStyleChanged(); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Buttons: TsuiSpinButtons read m_Button;
published
property Anchors;
property AutoSelect;
property AutoSize;
property Color;
property Constraints;
property Ctl3D;
property DragCursor;
property DragMode;
property EditorEnabled: Boolean read m_EditorEnabled write m_EditorEnabled default True;
property Enabled;
property Font;
property Increment: Integer read m_Increment write m_Increment;
property MaxLength;
property MaxValue: Integer read m_MaxValue write m_MaxValue;
property MinValue: Integer read m_MinValue write m_MinValue;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Value: Integer read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
implementation
uses SUIPublic;
{ TsuiEdit }
constructor TsuiEdit.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderStyle := bsNone;
BorderWidth := 2;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiEdit.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiEdit.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiEdit.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR)
else
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
UIStyleChanged();
Repaint();
end;
procedure TsuiEdit.UIStyleChanged;
begin
// do nothing
end;
procedure TsuiEdit.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
procedure TsuiEdit.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
{ TsuiMaskEdit }
constructor TsuiMaskEdit.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
BorderStyle := bsNone;
BorderWidth := 2;
UIStyle := GetSUIFormStyle(AOwner);
end;
procedure TsuiMaskEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiMaskEdit.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiMaskEdit.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiMaskEdit.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR)
else
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
Repaint();
end;
procedure TsuiMaskEdit.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
procedure TsuiMaskEdit.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawControlBorder(self, m_BorderColor, Color);
end;
{ TsuiNumberEdit }
procedure TsuiNumberEdit.Change;
var
S : String;
begin
if (Text <> '') and (Text <> '-') then
begin
try
S := StringReplace(Text, ThousandSeparator, '', [rfReplaceAll]);
m_Value := StrToFloat(S);
except
on E: EConvertError do
begin
SetValue(Value);
raise;
end;
end;
end;
inherited;
end;
procedure TsuiNumberEdit.Click;
begin
inherited;
DoEnter;
end;
procedure TsuiNumberEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
Change();
end;
constructor TsuiNumberEdit.Create(AOwner: TComponent);
begin
inherited;
Mask := '0.00';
Value := 0;
AutoSelectSigns := 2;
end;
procedure TsuiNumberEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style + ES_RIGHT;
end;
procedure TsuiNumberEdit.DoEnter;
begin
inherited;
if (AutoSelectSigns > 0) and AutoSelect then
begin
SelStart := Length(Text) - AutoSelectSigns;
SelLength := AutoSelectSigns;
end;
end;
procedure TsuiNumberEdit.DoExit;
var
S : String;
begin
inherited;
if (Text = '') or (Text = '-') then
Text := '0';
S := StringReplace(Text, ThousandSeparator, '', [rfReplaceAll]);
SetValue(StrToFloat(S));
end;
procedure TsuiNumberEdit.KeyPress(var Key: Char);
function AnsiContainsText(const AText, ASubText: string): Boolean;
begin
Result := AnsiPos(AnsiUppercase(ASubText), AnsiUppercase(AText)) > 0;
end;
var
IsValidKey: Boolean;
begin
inherited;
IsValidKey := (Key in ['0'..'9'])
or ((AnsiContainsText(Mask, '.')
and ((Key = DecimalSeparator)
and not (AnsiContainsText(Text, DecimalSeparator)))))
or (Ord(Key) = VK_BACK)
or (AnsiContainsText(Mask, '-')
and ((GetSelStart = 0)
and (Key = '-'))
and not (AnsiContainsText(Text, '-')));
if not IsValidKey then
begin
Beep();
Abort();
end;
end;
procedure TsuiNumberEdit.SetValue(Value: Real);
begin
m_Value := Value;
Text := FormatFloat(m_Mask, Value);
end;
{ TsuiSpinButtons }
procedure TsuiSpinButtons.AdjustSize(var W, H: Integer);
begin
if (m_UpButton = nil) or (csLoading in ComponentState) then
Exit;
if W < 15 then
W := 15;
m_UpButton.SetBounds(0, 0, W, H div 2 + 1);
m_DownButton.SetBounds(0, m_UpButton.Height - 1, W, H - m_UpButton.Height + 1);
end;
procedure TsuiSpinButtons.BtnClick(Sender: TObject);
begin
if Sender = m_UpButton then
begin
if Assigned(m_OnUpClick) then m_OnUpClick(Self);
end
else
begin
if Assigned(m_OnDownClick) then m_OnDownClick(Self);
end;
end;
constructor TsuiSpinButtons.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] +
[csFramed, csOpaque];
m_UpButton := CreateButton;
m_UpButton.Arrow := suiUp;
m_DownButton := CreateButton;
m_DownButton.Arrow := suiDown;
Width := 20;
Height := 25;
end;
function TsuiSpinButtons.CreateButton: TsuiArrowButton;
begin
Result := TsuiArrowButton.Create(Self);
Result.TabStop := False;
Result.OnClick := BtnClick;
Result.OnMouseContinuouslyDown := BtnClick;
Result.MouseContinuouslyDownInterval := 400;
Result.Visible := True;
Result.Enabled := True;
Result.Parent := Self;
end;
function TsuiSpinButtons.GetFileTheme: TsuiFileTheme;
begin
Result := nil;
if m_UpButton <> nil then
Result := m_UpButton.FileTheme;
end;
function TsuiSpinButtons.GetUIStyle: TsuiUIStyle;
begin
Result := SUI_THEME_DEFAULT;
if m_UpButton <> nil then
Result := m_UpButton.UIStyle;
end;
procedure TsuiSpinButtons.KeyDown(var Key: Word; Shift: TShiftState);
begin
case Key of
VK_UP: m_UpButton.Click;
VK_DOWN: m_DownButton.Click;
end;
end;
procedure TsuiSpinButtons.Loaded;
var
W, H: Integer;
begin
inherited;
W := Width;
H := Height;
AdjustSize(W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds(Left, Top, W, H);
end;
procedure TsuiSpinButtons.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
W, H: Integer;
begin
W := AWidth;
H := AHeight;
AdjustSize(W, H);
inherited;
end;
procedure TsuiSpinButtons.SetFileTheme(const Value: TsuiFileTheme);
begin
if m_UpButton <> nil then
m_UpButton.FileTheme := Value;
if m_DownButton <> nil then
m_DownButton.FileTheme := Value;
SetUIStyle(UIStyle);
end;
procedure TsuiSpinButtons.SetUIStyle(const Value: TsuiUIStyle);
begin
if m_UpButton <> nil then
m_UpButton.UIStyle := Value;
if m_DownButton <> nil then
m_DownButton.UIStyle := Value;
end;
procedure TsuiSpinButtons.WMSize(var Message: TWMSize);
var
W, H: Integer;
begin
inherited;
{ check for minimum size }
W := Width;
H := Height;
AdjustSize(W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds(Left, Top, W, H);
Message.Result := 0;
end;
{ TsuiSpinEdit }
function TsuiSpinEdit.CheckValue(NewValue: Integer): Integer;
begin
Result := NewValue;
if (m_MaxValue <> m_MinValue) then
begin
if NewValue < m_MinValue then
Result := m_MinValue
else if NewValue > m_MaxValue then
Result := m_MaxValue;
end;
end;
procedure TsuiSpinEdit.CMEnter(var Message: TCMGotFocus);
begin
if AutoSelect and not (csLButtonDown in ControlState) then
SelectAll();
inherited;
end;
procedure TsuiSpinEdit.CMExit(var Message: TCMExit);
begin
inherited;
if CheckValue(Value) <> Value then
SetValue(Value);
end;
constructor TsuiSpinEdit.Create(AOwner: TComponent);
begin
inherited;
m_Button := TsuiSpinButtons.Create(Self);
m_Button.Width := 15;
m_Button.Height := 20;
m_Button.Visible := True;
m_Button.Parent := Self;
m_Button.OnUpClick := UpClick;
m_Button.OnDownClick := DownClick;
Text := '0';
m_Increment := 1;
m_EditorEnabled := True;
end;
procedure TsuiSpinEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN;
end;
procedure TsuiSpinEdit.CreateWnd;
begin
inherited;
SetEditRect();
end;
destructor TsuiSpinEdit.Destroy;
begin
m_Button.Free();
m_Button := nil;
inherited;
end;
procedure TsuiSpinEdit.DownClick(Sender: TObject);
begin
if ReadOnly then
MessageBeep(0)
else
Value := Value - m_Increment;
end;
procedure TsuiSpinEdit.GetChildren(Proc: TGetChildProc; Root: TComponent);
begin
// do nothing
end;
function TsuiSpinEdit.GetValue: Integer;
begin
try
Result := StrToInt(Text);
except
Result := m_MinValue;
end;
end;
function TsuiSpinEdit.IsValidChar(Key: Char): Boolean;
begin
Result :=
(Key in ['-', '0'..'9']) or
((Key < #32) and (Key <> Chr(VK_RETURN)));
if not m_EditorEnabled and Result and ((Key >= #32) or
(Key = Char(VK_BACK)) or (Key = Char(VK_DELETE))) then
Result := False;
end;
procedure TsuiSpinEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
if Key = VK_UP then
UpClick(Self)
else if Key = VK_DOWN then
DownClick(Self);
inherited;
end;
procedure TsuiSpinEdit.KeyPress(var Key: Char);
begin
if not IsValidChar(Key) then
begin
Key := #0;
MessageBeep(0)
end;
if Key <> #0 then
inherited;
end;
procedure TsuiSpinEdit.SetEditRect;
var
Loc: TRect;
begin
SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc));
Loc.Bottom := ClientHeight + 1;
Loc.Right := ClientWidth - m_Button.Width - 2;
Loc.Top := 0;
Loc.Left := 0;
SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc));
SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc)); {debug}
end;
procedure TsuiSpinEdit.SetValue(NewValue: Integer);
begin
Text := CurrToStr(CheckValue(NewValue));
end;
procedure TsuiSpinEdit.UIStyleChanged;
begin
if m_Button <> nil then
begin
m_Button.UIStyle := UIStyle;
m_Button.FileTheme := FileTheme;
end;
end;
procedure TsuiSpinEdit.UpClick(Sender: TObject);
begin
if ReadOnly then
MessageBeep(0)
else
Value := Value + m_Increment;
end;
procedure TsuiSpinEdit.WMCut(var Message: TWMCut);
begin
if not m_EditorEnabled or ReadOnly then
Exit;
inherited;
end;
procedure TsuiSpinEdit.WMPaste(var Message: TWMPaste);
begin
if not m_EditorEnabled or ReadOnly then
Exit;
inherited;
end;
procedure TsuiSpinEdit.WMSize(var Message: TWMSize);
var
MinHeight: Integer;
begin
inherited;
MinHeight := 0;
if Height < MinHeight then
Height := MinHeight
else if m_Button <> nil then
begin
m_Button.SetBounds(Width - m_Button.Width - 4, 0, m_Button.Width, Height - 4);
SetEditRect();
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Источники данных, использующее для историю котировок
(IStockDataStorage)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.HC.StockDataSource;
{$I Compiler.inc}
interface
uses SysUtils,Classes,DB, AppEvnts, Controls, Serialization, FC.Definitions,
FC.StockData.StockDataSource,StockChart.Definitions;
type
//---------------------------------------------------------------------------
//Реализация DataSource для History Center
TStockDataSource_HistoryCenter=class(TStockDataSourceMemory_B,IStockDataSourceWriteable,IStockDataSource)
private
FDS : IStockDataQuery;
FDSEventHandler: IStockDataStorageEventHandler;
FAppEvents : TApplicationEvents;
FLastDateTime : TDateTime;
FStockDataStorage: IStockDataStorage;
FStartFrom : TDateTime;
procedure OnIdle(Sender: TObject; var Done: Boolean);
procedure LogMessage(const aMessage: string);
protected
procedure OnLoadPortion(index:integer); override;
procedure CheckFreeDS;
procedure LoadDataFromStorage;
public
function RecordCount: integer; override;
procedure OnAddRecord(const aItem: ISCInputData);
procedure OnEditRecord(const aItem: ISCInputData);
procedure OnDeleteRecord(const aItem: ISCInputData);
function GetDataDateTime(index: integer): TDateTime; override;
//from IStockDataSourceWriteable
procedure UpdateData(const aItem: ISCInputData);
function Tag: string; override;
property StartLoadingFrom: TDateTime read FStartFrom;
constructor Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; const aStorage: IStockDataStorage; const aStartLoadingFrom: TDateTime);
destructor Destroy; override;
end;
TStockDataSource_HistoryCenter_StorageEventHadler = class (TInterfacedObject,IStockDataStorageEventHandler)
private
FOwner: TStockDataSource_HistoryCenter;
public
procedure OnChangeData(const aSymbolID: string; const aInterval: TStockTimeInterval; const aItem: ISCInputData; aType: TStockDataModificationType);
procedure OnChangeCalendarData;
procedure OnMergeData(const aSymbolID: string; const aInterval: TStockTimeInterval; const aItems: ISCInputDataCollection);
constructor Create(aOwner: TStockDataSource_HistoryCenter);
end;
implementation
uses Math,BaseUtils, SystemService, DateUtils, FC.DataUtils, FC.Singletons;
{ TStockDataSource_HistoryCenter }
constructor TStockDataSource_HistoryCenter.Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; const aStorage: IStockDataStorage; const aStartLoadingFrom: TDateTime);
begin
inherited Create(aConnection, aSymbol,aInterval);
FStockDataStorage:=aStorage;
FDSEventHandler:=TStockDataSource_HistoryCenter_StorageEventHadler.Create(self);
FStockDataStorage.AddEventHandler(FDSEventHandler);
FStartFrom:=aStartLoadingFrom;
LoadDataFromStorage;
if RecordCount>0 then
begin
FAppEvents:=TApplicationEvents.Create(nil);
FAppEvents.OnIdle:=OnIdle;
end;
LogMessage('------------------------------------------------------------------------------------------------');
end;
destructor TStockDataSource_HistoryCenter.Destroy;
begin
if FDSEventHandler<>nil then
FStockDataStorage.RemoveEventHandler(FDSEventHandler);
FDSEventHandler:=nil;
FreeAndNil(FAppEvents);
FStockDataStorage:=nil;
inherited;
end;
function TStockDataSource_HistoryCenter.GetDataDateTime(index: integer): TDateTime;
begin
//Оптмизация
if (Index=RecordCount-1) and (FLastDateTime<>-1) then
result:=FLastDateTime
else
result:=inherited GetDataDateTime(index);
end;
function TStockDataSource_HistoryCenter.RecordCount: integer;
begin
if FDS=nil then
result:=FRecordList.Count
else
result:=FDS.RecordCount;
end;
function TStockDataSource_HistoryCenter.Tag: string;
begin
result:=FloatToStr(FStartFrom);
end;
procedure TStockDataSource_HistoryCenter.UpdateData(const aItem: ISCInputData);
begin
FStockDataStorage.UpdateBar(StockSymbol.Name,StockSymbol.TimeInterval,aItem);
FLastDateTime:=-1;
end;
procedure TStockDataSource_HistoryCenter.OnLoadPortion(index: integer);
var
i: integer;
aCursor: TWaitCursor;
begin
aCursor:=nil;
if (index-FRecordList.Count)>1000 then
aCursor:=TWaitCursor.Create;
try
for i:=FRecordList.Count to index do
begin
FRecordList.Add(TStockDataRecord.Create(
FDS.GetDataDateTime,
FDS.GetDataOpen,
FDS.GetDataHigh,
FDS.GetDataLow,
FDS.GetDataClose,
FDS.GetDataVolume));
FDS.Next;
end;
finally
FreeAndNil(aCursor);
end;
CheckFreeDS;
end;
procedure TStockDataSource_HistoryCenter.CheckFreeDS;
begin
if FDS<>nil then
begin
if FDS.RecordCount=0 then
FDS:=nil
else if FDS.RecordCount=FRecordList.Count then
FDS:=nil;
end;
end;
procedure TStockDataSource_HistoryCenter.OnAddRecord(const aItem: ISCInputData);
var
i: integer;
begin
FLastDateTime:=-1;
//Если вставка внутрь списка
if (RecordCount>0) and (GetDataDateTime(RecordCount-1)>=aItem.DataDateTime) then
begin
i:=FindBestMatched(aItem.DataDateTime);
//Если есть точное совадение - это ошибка, нельзя вставить две одинаковые даты
if (i<>-1) and (GetDataDateTime(i)=aItem.DataDateTime) then
raise EStockError.Create('Date unique violation');
if i=-1 then //В самое начало
i:=0
//Проверим чтобы не вставить справа
else if GetDataDateTime(i)>aItem.DataDateTime then
i:=max(0,i-1);
CheckFreeDS; Assert(FDS=nil);//DS уже быть не должно, иначе как вставлять в список, если он недокачан
FRecordList.Insert(i,TStockDataRecord.Create(
aItem.DataDateTime,
aItem.DataOpen,
aItem.DataHigh,
aItem.DataLow,
aItem.DataClose,
aItem.DataVolume));
LogMessage('Insert item with time '+DateTimeToStr(aItem.DataDateTime)+' into '+IntToStr(i));
RaiseChangeDataEvent(-1,idcctChangeAll);
end
//Если вставка в конец списка
else begin
CheckFreeDS; Assert(FDS=nil);//DS уже быть не должно, иначе как вставлять в список, если он недокачан
FRecordList.Add(TStockDataRecord.Create(
aItem.DataDateTime,
aItem.DataOpen,
aItem.DataHigh,
aItem.DataLow,
aItem.DataClose,
aItem.DataVolume));
LogMessage('Add item with time '+DateTimeToStr(aItem.DataDateTime)+' to the end');
RaiseChangeDataEvent(RecordCount-1,idcctAdd);
end;
end;
procedure TStockDataSource_HistoryCenter.OnDeleteRecord(const aItem: ISCInputData);
var
i: integer;
begin
FLastDateTime:=-1;
//Здесь вытаскивается все в кеш и DS отрывается
GetRecord(RecordCount);
i:=IndexOf(aItem.DataDateTime);
if i=-1 then
raise EStockError.Create('Bad stock data');
FRecordList.Delete(i);
RaiseChangeDataEvent(i,idcctDelete);
end;
procedure TStockDataSource_HistoryCenter.OnEditRecord(const aItem: ISCInputData);
var
i: integer;
aRecord: TStockDataRecord;
begin
FLastDateTime:=-1;
i:=IndexOf(aItem.DataDateTime);
if i=-1 then
begin
LogMessage('!!!! Cannot find item with time '+DateTimeToStr(aItem.DataDateTime));
raise EStockError.CreateFmt('Data with time %s not found',[DateTimeToStr(aItem.DataDateTime)]);
end;
aRecord:=GetRecord(i);
//Если даты разные, это какой-то косяк в хранении данных, в самой программе
if (not SameDateTime(aRecord.DataDateTime,aItem.DataDateTime)) then
raise EAssertionFailed.Create('Different dates: '+ DateTimeToStr(aRecord.DataDateTime)+','+DateTimeToStr(aItem.DataDateTime));
if(aRecord.DataOpen<>aItem.DataOpen) or
(aRecord.DataHigh<>aItem.DataHigh) or
(aRecord.DataLow<>aItem.DataLow) or
(aRecord.DataClose<>aItem.DataClose) or
(aRecord.DataVolume<>aItem.DataVolume) then
begin
aRecord.DataOpen:=aItem.DataOpen;
aRecord.DataHigh:=aItem.DataHigh;
aRecord.DataLow:=aItem.DataLow;
aRecord.DataClose:=aItem.DataClose;
aRecord.DataVolume:=aItem.DataVolume;
RaiseChangeDataEvent(i,idcctEdit);
end;
LogMessage('Edit item with time '+DateTimeToStr(aItem.DataDateTime));
end;
procedure TStockDataSource_HistoryCenter.OnIdle(Sender: TObject; var Done: Boolean);
begin
if FRecordList.Count<Self.RecordCount then
begin
//Провоцируем загрузку данных
self.GetRecord(Min(FRecordList.Count+10,Self.RecordCount-1));
Done:=true;
end;
if FRecordList.Count>=Self.RecordCount then
FreeAndNil(FAppEvents);
end;
procedure TStockDataSource_HistoryCenter.LoadDataFromStorage;
var
s: string;
aInfo : TStockSymbolInfo;
begin
FRecordList.Clear;
aInfo:=FStockDataStorage.GetSymbolInfo(StockSymbol.Name);
FPricePrecision:=aInfo.Digits;
FPricesInPoint:=Round(1/aInfo.Point);
s:='';
if FStartFrom>0 then
s:=FStockDataStorage.CreateDataFilterAdapter.DateGE(FStartFrom);
FDS:=FStockDataStorage.QueryStockData(StockSymbol.Name,StockSymbol.TimeInterval,s);
FLastDateTime:=FStockDataStorage.GetLastDateTime(StockSymbol.Name,StockSymbol.TimeInterval);
FRecordList.Capacity:=Round(FDS.RecordCount*1.2);
CheckFreeDS;
end;
procedure TStockDataSource_HistoryCenter.LogMessage(const aMessage: string);
begin
//ssLogMessage('C:\'+StockSymbol.Name+StockSymbol.GetTimeIntervalName+'.log',aMessage,[]);
end;
{ TStockDataSource_HistoryCenter_StorageEventHadler }
constructor TStockDataSource_HistoryCenter_StorageEventHadler.Create(aOwner: TStockDataSource_HistoryCenter);
begin
inherited Create;
FOwner:=aOwner;
end;
procedure TStockDataSource_HistoryCenter_StorageEventHadler.OnChangeCalendarData;
begin
end;
procedure TStockDataSource_HistoryCenter_StorageEventHadler.OnChangeData(const aSymbolID: string;
const aInterval: TStockTimeInterval; const aItem: ISCInputData; aType: TStockDataModificationType);
begin
if FOwner.StockSymbol.IsEqual(aSymbolID,aInterval) then
begin
case aType of
idcctAdd:
FOwner.OnAddRecord(aItem);
idcctEdit:
FOwner.OnEditRecord(aItem);
idcctDelete:
FOwner.OnDeleteRecord(aItem);
idcctChangeAll:
begin
FOwner.LoadDataFromStorage;
FOwner.RaiseChangeDataEvent(-1,aType);
end;
end;
end;
end;
procedure TStockDataSource_HistoryCenter_StorageEventHadler.OnMergeData(const aSymbolID: string; const aInterval: TStockTimeInterval; const aItems: ISCInputDataCollection);
var
i: integer;
aItem : ISCInputData;
begin
if FOwner.StockSymbol.IsEqual(aSymbolID,aInterval) then
begin
for i := 0 to aItems.Count - 1 do
begin
aItem:=aItems[i];
if FOwner.IndexOf(aItem.DataDateTime)=-1 then
FOwner.OnAddRecord(aItem)
else
FOwner.OnEditRecord(aItem);
end;
end;
end;
end.
|
unit UDaoTransportadora;
interface
uses uDao, DB, SysUtils, Messages, UTransportadora, UEndereco, UDaoCidade,
UDaoCondicaoPagamento;
type DaoTransportadora = class(Dao)
private
protected
umTransportadora : Transportadora;
umEndereco : Endereco;
umaDaoCidade : DaoCidade;
umaDaoCondicaoPagamento : DaoCondicaoPagamento;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function VerificaCNPJ (obj : TObject) : Boolean;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
{ DaoTransportadora }
function DaoTransportadora.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umTransportadora: Transportadora;
begin
e := ' and ';
onde := ' where';
prim := true;
umTransportadora := Transportadora(obj);
sql := 'select * from transportadora';
if umTransportadora.getId <> 0 then
begin
if prim then //SE FOR O PRIMEIRO, SETA COMO FLAG COMO FALSO PQ É O PRIMEIRO
begin
prim := false;
sql := sql+onde;
end
else //SE NAO, COLOCA CLAUSULA AND PARA JUNTAR CONDIÇOES
sql := sql+e;
sql := sql+' idtransportadora = '+inttostr(umTransportadora.getId); //COLOCA CONDIÇAO NO SQL
end;
if umTransportadora.getNome_RazaoSoCial <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' razaosocial like '+quotedstr('%'+umTransportadora.getNome_RazaoSoCial+'%');
end;
if umTransportadora.getTelefone <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' telefone like '+quotedstr('%'+umTransportadora.getTelefone+'%');
end;
if umTransportadora.getCPF_CNPJ <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' cnpj = '''+umTransportadora.getCPF_CNPJ+'''';
end;
with umDM do
begin
QTransportadora.Close;
QTransportadora.sql.Text := sql+' order by idtransportadora';
QTransportadora.Open;
if QTransportadora.RecordCount > 0 then
result := True
else
result := false;
end;
end;
procedure DaoTransportadora.AtualizaGrid;
begin
with umDM do
begin
QTransportadora.Close;
QTransportadora.sql.Text := 'select * from transportadora order by idtransportadora';
QTransportadora.Open;
end;
end;
function DaoTransportadora.VerificaCNPJ (obj : TObject) : Boolean;
var sql : string;
umaTransportadora : Transportadora;
begin
umaTransportadora := Transportadora(obj);
sql := 'select * from transportadora where cnpj = '''+umaTransportadora.getCPF_CNPJ+'''';
with umDM do
begin
QTransportadora.Close;
QTransportadora.sql.Text := sql+' order by idtransportadora';
QTransportadora.Open;
if QTransportadora.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoTransportadora.Carrega(obj: TObject): TObject;
var
umTransportadora : Transportadora;
umEndereco : Endereco;
begin
umTransportadora := Transportadora(obj);
umEndereco := Endereco.CrieObjeto;
with umDM do
begin
if not QTransportadora.Active then
QTransportadora.Open;
if umTransportadora.getId <> 0 then
begin
QTransportadora.Close;
QTransportadora.SQL.Text := 'select * from transportadora where idtransportadora = '+IntToStr(umTransportadora.getId);
QTransportadora.Open;
end;
umTransportadora.setId(QTransportadoraidtransportadora.AsInteger);
umTransportadora.setNome_RazaoSoCial(QTransportadorarazaosocial.AsString);
//Endereço
umEndereco.setLogradouro(QTransportadoralogradouro.AsString);
umEndereco.setNumero(QTransportadoranumero.AsString);
umEndereco.setCEP(QTransportadoracep.AsString);
umEndereco.setBairro(QTransportadorabairro.AsString);
umEndereco.setComplemento(QTransportadoracomplemento.AsString);
umTransportadora.setumEndereco(umEndereco);
umTransportadora.setEmail(QTransportadoraemail.AsString);
umTransportadora.setTelefone(QTransportadoratelefone.AsString);
umTransportadora.setCelular(QTransportadoracelular.AsString);
umTransportadora.setCPF_CNPJ(QTransportadoracnpj.AsString);
umTransportadora.setRG_IE(QTransportadoraie.AsString);
umTransportadora.setDataNasc_Fund(QTransportadoradatafundacao.AsDateTime);
umTransportadora.setDataCadastro(QTransportadoradatacadastro.AsDateTime);
umTransportadora.setDataUltAlteracao(QTransportadoradataalteracao.AsDateTime);
umTransportadora.setObservacao(QTransportadoraobservacao.AsString);
//Busca a Cidade referente ao Transportadora
umTransportadora.getumEndereco.getumaCidade.setId(QTransportadoraidcidade.AsInteger);
umaDaoCidade.Carrega(umTransportadora.getumEndereco.getumaCidade);
//Busca a Condicao de Pagamento referente ao Transportadora
umTransportadora.getUmaCondicaoPgto.setId(QTransportadoraidcondicaopagamento.AsInteger);
umaDaoCondicaoPagamento.Carrega(umTransportadora.getUmaCondicaoPgto);
end;
result := umTransportadora;
Self.AtualizaGrid;
end;
constructor DaoTransportadora.CrieObjeto;
begin
inherited;
umaDaoCidade := DaoCidade.CrieObjeto;
umaDaoCondicaoPagamento := DaoCondicaoPagamento.CrieObjeto;
end;
destructor DaoTransportadora.Destrua_se;
begin
inherited;
end;
function DaoTransportadora.Excluir(obj: TObject): string;
var
umTransportadora: Transportadora;
begin
umTransportadora := Transportadora(obj);
with umDM do
begin
try
beginTrans;
QTransportadora.SQL := UpdateTransportadora.DeleteSQL;
QTransportadora.Params.ParamByName('OLD_idtransportadora').Value := umTransportadora.getId;
QTransportadora.ExecSQL;
Commit;
result := 'Transportadora excluída com sucesso!';
except
on e:Exception do
begin
rollback;
if pos('violates foreign key',e.Message)>0 then
result := 'Ocorreu um erro! A Transportadora não pode ser excluída pois ja está sendo usado pelo sistema.'
else
result := 'Ocorreu um erro! Transportadora não foi excluída. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
function DaoTransportadora.GetDS: TDataSource;
begin
Self.AtualizaGrid;
result := umDM.DSTransportadora;
end;
procedure DaoTransportadora.Ordena(campo: string);
begin
umDM.QTransportadora.IndexFieldNames := campo;
end;
function DaoTransportadora.Salvar(obj: TObject): string;
var
umTransportadora : Transportadora;
begin
umTransportadora := Transportadora(obj);
with umDM do
begin
try
beginTrans;
QTransportadora.Close;
if umTransportadora.getId = 0 then
begin
if(Self.Buscar(umTransportadora)) then
begin
Result := 'Esse CNPJ já existe!';
Self.AtualizaGrid;
Exit;
end;
QTransportadora.SQL := UpdateTransportadora.InsertSQL;
end
else
begin
if(not Self.Buscar(umTransportadora)) and (not umTransportadora.verificaNome) and (not umTransportadora.verificaTel) then
begin
if (not Self.VerificaCNPJ(umTransportadora)) then
begin
QTransportadora.SQL := UpdateTransportadora.ModifySQL;
QTransportadora.Params.ParamByName('OLD_idtransportadora').Value := umTransportadora.getId
end
else
begin
Result := 'Esse CNPJ já existe!';
Self.AtualizaGrid;
Exit;
end;
end
else
begin
QTransportadora.SQL := UpdateTransportadora.ModifySQL;
QTransportadora.Params.ParamByName('OLD_idtransportadora').Value := umTransportadora.getId;
end;
end;
QTransportadora.Params.ParamByName('razaosocial').Value := umTransportadora.getNome_RazaoSoCial;
QTransportadora.Params.ParamByName('logradouro').Value := umTransportadora.getumEndereco.getLogradouro;
QTransportadora.Params.ParamByName('numero').Value := umTransportadora.getumEndereco.getNumero;
QTransportadora.Params.ParamByName('cep').Value := umTransportadora.getumEndereco.getCEP;
QTransportadora.Params.ParamByName('bairro').Value := umTransportadora.getumEndereco.getBairro;
QTransportadora.Params.ParamByName('complemento').Value := umTransportadora.getumEndereco.getComplemento;
QTransportadora.Params.ParamByName('idcidade').Value := umTransportadora.getumEndereco.getumaCidade.getId;
QTransportadora.Params.ParamByName('email').Value := umTransportadora.getEmail;
QTransportadora.Params.ParamByName('telefone').Value := umTransportadora.getTelefone;
QTransportadora.Params.ParamByName('celular').Value := umTransportadora.getCelular;
QTransportadora.Params.ParamByName('cnpj').Value := umTransportadora.getCPF_CNPJ;
QTransportadora.Params.ParamByName('ie').Value := umTransportadora.getRG_IE;
QTransportadora.Params.ParamByName('idcondicaopagamento').Value := umTransportadora.getUmaCondicaoPgto.getId;
if umTransportadora.getDataNasc_Fund <> StrToDateTime('30/12/1899') then
QTransportadora.Params.ParamByName('datafundacao').Value := umTransportadora.getDataNasc_Fund;
QTransportadora.Params.ParamByName('datacadastro').Value := umTransportadora.getDataCadastro;
QTransportadora.Params.ParamByName('dataalteracao').Value := umTransportadora.getDataUltAlteracao;
QTransportadora.Params.ParamByName('observacao').Value := umTransportadora.getObservacao;
QTransportadora.ExecSQL;
Commit;
result := 'Transportadora salva com sucesso!';
except
on e: Exception do
begin
rollback;
Result := 'Ocorreu um erro! Transportadora não foi salva. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
unit FSysView;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, PairSplitter,
ComCtrls, FSTree, DTV;
type
TFileSystemView = class;
TFileListView = class;
{ TFileSystemTreeView }
TFileSystemTreeView = class(TDetailledTreeView)
private
function GetFileSystemView: TFileSystemView;
property FSView: TFileSystemView read GetFileSystemView;
public
constructor Create(AOwner: TComponent); override;
end;
{ TFileListView }
TFileListView = class(TCustomListView)
private
function GetFileSystemView: TFileSystemView;
property FSView: TFileSystemView read GetFileSystemView;
end;
{ TFileSystemView }
TFileSystemView = class(TPairSplitter)
private
FFileSystem: TFileSystem;
function GetFileSystem: TFileSystem;
private
FDirectory: string;
FFileListView: TFileListView;
FFSTreeView: TFileSystemTreeView;
function GetFileListView: TFileListView;
function GetFSTreeView: TFileSystemTreeView;
procedure SetDirectory(AValue: string);
property FileSystem: TFileSystem read GetFileSystem;
protected
public
constructor Create(AOwner: TComponent); override;
procedure Loaded; override;
published
property Directory: string read FDirectory write SetDirectory;
property FSTreeView: TFileSystemTreeView read GetFSTreeView;
property FileListView: TFileListView read GetFileListView;
end;
procedure Register;
implementation
uses Patch;
type
TFileDescription = class(TObject)
private
FSR: TSearchRec;
end;
procedure Register;
begin
RegisterComponents('Misc',[TFileSystemView]);
end;
{ TFileListView }
function TFileListView.GetFileSystemView: TFileSystemView;
begin
Result := Owner as TFileSystemView
end;
{ TFileSystemTreeView }
function TFileSystemTreeView.GetFileSystemView: TFileSystemView;
begin
Result := Owner as TFileSystemView
end;
constructor TFileSystemTreeView.Create(AOwner: TComponent);
var
Data: TFileSystemNode;
P, TN: TTreeNode;
begin
inherited Create(AOwner);
P := Items.AddObjectFirst(nil, FSView.FileSystem.Root.NodeName, FSView.FileSystem.Root);
Data := FSView.FileSystem.Root.FirstChild;
if Data <> nil then
if Data.IsDirectory and (Data.NodeName <> '.') and (Data.NodeName <> '..')
then TN := Items.AddChildObjectFirst(P, Data.NodeName, Data);
while Data.Next <> nil do begin
WriteLn(Data.NodeName);
Data := Data.Next;
if Data.IsDirectory and (Data.NodeName <> '.') and (Data.NodeName <> '..')
then TN := Items.AddChildObject(P, Data.NodeName, Data);
end;
P.AlphaSort;
ReadOnly := True;
end;
{ TFileSystemView }
constructor TFileSystemView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
GetFSTreeView;
end;
procedure TFileSystemView.Loaded;
begin
inherited Loaded
end;
function TFileSystemView.GetFileSystem: TFileSystem;
begin
if not Assigned(FFileSystem) then begin
FFileSystem := TFileSystem.Create(Self);
end;
Result := FFileSystem;
end;
function TFileSystemView.GetFileListView: TFileListView;
begin
if not Assigned(FFileListView) then begin
FFileListView := TFileListView.Create(Self);
FFileListView.Parent := Sides[1];
FFileListView.Align := alClient
end;
Result := FFileListView
end;
function TFileSystemView.GetFSTreeView: TFileSystemTreeView;
begin
if not Assigned(FFSTreeView) then begin
FFSTreeView := TFileSystemTreeView.Create(Self);
FFSTreeView.Parent := Sides[0];
FSTreeView.Align := alClient;
end;
Result := FFSTreeView
end;
procedure TFileSystemView.SetDirectory(AValue: string);
var
R: Longint;
SR: TSearchRec;
FD: TFileDescription;
{TN: TTreeNode;}
begin
if not False {(csUpdating in ComponentState)} then begin
{Updating;}
{R := FindFirst(Directory, faDirectory, SR);
if R := 0 then begin
TN := TTreeNode.Create(FSTreeView.Items);
TN.
FSTreeView.Items.Add(;
end;
FindClose(SR);}
R := FindFirst(BuildFileName(Directory, '*'), faDirectory, SR);
while R = 0 do begin
FD := TFileDescription.Create;
Move(SR, FD.FSR, SizeOf(SR));
FileListView.AddItem(SR.Name, FD);
Application.ProcessMessages;
R := FindNext(SR)
end;
FindClose(SR);
{Updated; }
end;
FDirectory := AValue;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit TemplateViewImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
HeadersIntf,
ResponseIntf,
ResponseStreamIntf,
ViewParametersIntf,
ViewIntf,
TemplateFetcherIntf,
TemplateParserIntf,
OutputBufferIntf,
CloneableIntf;
type
(*!------------------------------------------------
* View that can render from a HTML template string
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-------------------------------------------------*)
TTemplateView = class(TInterfacedObject, ICloneable, IView, IResponse, ITemplateFetcher)
private
templateContent : string;
outputBuffer : IOutputBuffer;
templateParser : ITemplateParser;
httpHeaders : IHeaders;
protected
function readFileToString(const templatePath : string) : string;
public
constructor create(
const hdrs : IHeaders;
const outputBufferInst : IOutputBuffer;
const templateParserInst : ITemplateParser;
const templateSrc : string
); virtual;
destructor destroy(); override;
(*!------------------------------------
* get http headers instance
*-------------------------------------
* @return header instance
*-------------------------------------*)
function headers() : IHeaders;
function render(
const viewParams : IViewParameters;
const response : IResponse
) : IResponse;
function write() : IResponse;
function fetch(
const templatePath : string;
const viewParams : IViewParameters
) : string;
function clone() : ICloneable;
(*!------------------------------------
* get response body
*-------------------------------------
* @return response body
*-------------------------------------*)
function body() : IResponseStream;
end;
implementation
uses
classes,
sysutils;
constructor TTemplateView.create(
const hdrs : IHeaders;
const outputBufferInst : IOutputBuffer;
const templateParserInst : ITemplateParser;
const templateSrc : string
);
begin
httpHeaders := hdrs;
outputBuffer := outputBufferInst;
templateParser := templateParserInst;
templateContent := templateSrc;
end;
destructor TTemplateView.destroy();
begin
inherited destroy();
httpHeaders := nil;
outputBuffer := nil;
templateParser := nil;
end;
(*!------------------------------------
* get http headers instance
*-------------------------------------
* @return header instance
*-------------------------------------*)
function TTemplateView.headers() : IHeaders;
begin
result := httpHeaders;
end;
function TTemplateView.render(
const viewParams : IViewParameters;
const response : IResponse
) : IResponse;
begin
outputBuffer.beginBuffering();
try
writeln(templateParser.parse(templateContent, viewParams));
finally
outputBuffer.endBuffering();
end;
httpHeaders.setHeader('Content-Length', intToStr(outputBuffer.size()));
result := self;
end;
function TTemplateView.write() : IResponse;
begin
httpHeaders.writeHeaders();
writeln(outputBuffer.flush());
result := self;
end;
function TTemplateView.readFileToString(const templatePath : string) : string;
var fstream : TFileStream;
len : longint;
begin
//open for read and share but deny write
//so if multiple processes of our application access same file
//at the same time they stil can open and read it
fstream := TFileStream.create(templatePath, fmOpenRead or fmShareDenyWrite);
try
len := fstream.size;
setLength(result, len);
//pascal string start from index 1
fstream.read(result[1], len);
finally
fstream.free();
end;
end;
function TTemplateView.fetch(
const templatePath : string;
const viewParams : IViewParameters
) : string;
var content :string;
begin
try
content := readFileToString(templatePath);
result := templateParser.parse(content, viewParams);
except
on e : Exception do
begin
writeln('Read ' + e.message);
end;
end;
end;
function TTemplateView.clone() : ICloneable;
var clonedObj : TTemplateView;
begin
clonedObj := TTemplateView.create(
httpHeaders.clone() as IHeaders,
outputBuffer,
templateParser,
templateContent
);
//TODO : copy any property
result := clonedObj;
end;
(*!------------------------------------
* get response body
*-------------------------------------
* @return response body
*-------------------------------------*)
function TTemplateView.body() : IResponseStream;
begin
//TODO: implement view response body
result := nil;
end;
end.
|
Unit FaceUnit;
interface
uses windows, sysutils, classes, dialogs, Graphics, PNGImage;
(******************************************************************************)
type
TRGBArray = ARRAY[0..0] OF TRGBTriple;
pRGBArray = ^TRGBArray;
(* face rec & animations*)
type
TFaceRes = (rEyes, rPupils, rMouth, rFace, rOther);
TFaceStatus = record
face,eye,mouth,pupilL,pupilR,other : string[20];
P1,P2 : tPoint; (* pupils pointers x & y *)
end;
TAnimations = array of TFaceStatus;
TDoubleParam = Record
pName : String;
pParam : String;
end;
(******************************************************************************)
procedure DrawFace(Canvas: TCanvas; Face: TFaceStatus);
procedure DrawFacePNG(PNG: TPNGObject; Face: TFaceStatus; UseColor: boolean; Color : cardinal);
procedure DeleteFrame(var animarr: TAnimations; frameid: integer);
procedure ClearFace(var Face: TFaceStatus);
function LoadFace(var Face: TFaceStatus; FaceName: string; errmsg: boolean = false) : boolean;
function SaveFace(Face: TFaceStatus; savename: string) : boolean;
function LoadAnimations(var animarr: TAnimations; animname: string; errmsg: boolean = false) : boolean;
function SaveAnimations(animarr: TAnimations; animname: string) : boolean;
function ExistFaceRes(Face: TFaceStatus) : boolean;
function ExistAnimRes(Anim: TAnimations) : boolean;
function StrToParam(const KeyLine: String; Suffix : Char): TDoubleParam;
function NameToRes(ResName: string; FaceRes: TFaceRes) : string;
function ResToName(ResName: string; FaceRes: TFaceRes) : string;
function IndexByName(Name: string; List: TStrings) : integer;
Procedure ResListToList(ResList: TStrings; List: TStrings);
var
(* stable *)
faces,others,eyes,mouths,pupils : tstringlist;
respth, reseyes, respupils, resmouth, resfaces, resothers : string;
animpath, facepath : string;
(******************************************************************************)
implementation
(******************************************************************************)
function IndexByName(Name: string; List: TStrings) : integer;
var
i : integer;
begin
Result := -1;
for i := 0 to List.Count-1 do
if LowerCase(Name) = LowerCase(list[i]) then begin
Result := i;
exit;
end;
end;
Procedure ResListToList(ResList: TStrings; List: TStrings);
var
i : integer;
begin
List.Add('-');
for i := 0 to ResList.Count-1 do
List.Add(StrToParam(ResList[i],'=').pParam);
end;
(******************************************************************************)
function ResToName(ResName: string; FaceRes: TFaceRes) : string;
var
i : integer;
begin
Result := '';
if ResName = '-' then begin
Result := '-';
exit;
end;
case FaceRes of
rEyes : begin
for i := 0 to eyes.Count-1 do
if StrToParam(eyes[i],'=').pName = ResName then
begin
Result := StrToParam(eyes[i],'=').pParam;
exit;
end;
end;
rPupils: begin
for i := 0 to pupils.Count-1 do
if StrToParam(pupils[i],'=').pName = ResName then
begin
Result := StrToParam(pupils[i],'=').pParam;
exit;
end;
end;
rMouth : begin
for i := 0 to mouths.Count-1 do
if StrToParam(mouths[i],'=').pName = ResName then
begin
Result := StrToParam(mouths[i],'=').pParam;
exit;
end;
end;
rFace : begin
for i := 0 to faces.Count-1 do
if StrToParam(faces[i],'=').pName = ResName then
begin
Result := StrToParam(faces[i],'=').pParam;
exit;
end;
end;
rOther : begin
for i := 0 to others.Count-1 do
if StrToParam(others[i],'=').pName = ResName then
begin
Result := StrToParam(others[i],'=').pParam;
exit;
end;
end;
end;
end;
(******************************************************************************)
function NameToRes(ResName: string; FaceRes: TFaceRes) : string;
var
i : integer;
begin
Result := '';
if ResName = '-' then begin
Result := '-';
exit;
end;
case FaceRes of
rEyes : begin
for i := 0 to eyes.Count-1 do
if StrToParam(eyes[i],'=').pParam = ResName then
begin
Result := StrToParam(eyes[i],'=').pName;
exit;
end;
end;
rPupils: begin
for i := 0 to pupils.Count-1 do
if StrToParam(pupils[i],'=').pParam = ResName then
begin
Result := StrToParam(pupils[i],'=').pName;
exit;
end;
end;
rMouth : begin
for i := 0 to mouths.Count-1 do
if StrToParam(mouths[i],'=').pParam = ResName then
begin
Result := StrToParam(mouths[i],'=').pName;
exit;
end;
end;
rFace : begin
for i := 0 to faces.Count-1 do
if StrToParam(faces[i],'=').pParam = ResName then
begin
Result := StrToParam(faces[i],'=').pName;
exit;
end;
end;
rOther : begin
for i := 0 to others.Count-1 do
if StrToParam(others[i],'=').pParam = ResName then
begin
Result := StrToParam(others[i],'=').pName;
exit;
end;
end;
end;
end;
(******************************************************************************)
Procedure BmpColorize(R0,G0,B0 : integer; var png, png2: tpngobject);
var
x, y : integer;
Rowa : Prgbarray;
Rowb : Prgbarray;
R,G,B : integer;
H0 : integer;
H,S,V : integer;
begin
For y := 0 to png.height-1 do
begin
rowa := png2.Scanline[y];
rowb := png.Scanline[y];
for x := 0 to png.width-1 do
begin
R := (rowa[x].RgbtRed div 2)+ (R0 div 1);
G := (rowa[x].Rgbtgreen div 2)+ (G0 div 2);
B := (rowa[x].Rgbtblue div 2)+ (B0 div 3);
if R > 255 then R := 255 else if R < 0 then R := 0;
if G > 255 then G := 255 else if G < 0 then G := 0;
if B > 255 then B := 255 else if B < 0 then B := 0;
rowb[x].Rgbtred := R;
rowb[x].Rgbtgreen := G;
rowb[x].Rgbtblue := B;
end;
end;
end;
procedure colorizer(acolor : tcolor; var png: tpngobject);
var
R0,G0,B0 : integer;
png2: tpngobject;
begin
png2 := TPNGObject.Create;
png2.Assign(png);
R0 := GetRValue((acolor));
G0 := GetGValue((acolor));
B0 := GetBValue((acolor));
BmpColorize(R0,G0,B0,png2,png);
png.assign(png2);
png2.Free;
end;
(******************************************************************************)
procedure DrawFacePNG(PNG: TPNGObject; Face: TFaceStatus; UseColor: boolean; Color : cardinal);
var
pupilL, pupilR, myface, eyes, mouth, other : TPNGObject;
begin
if not ExistFaceRes(Face) then Exit;
(* *)
pupilL := TPNGObject.Create;
pupilR := TPNGObject.Create;
myface := TPNGObject.Create;
other := TPNGObject.Create;
mouth := TPNGObject.Create;
eyes := TPNGObject.Create;
(* *)
if face.face <> '-' then
myface.LoadFromFile(resfaces+face.face);
if face.other <> '-' then
other.LoadFromFile(resothers+face.other);
if face.pupilL <> '-' then
pupilL.LoadFromFile(respupils+face.pupilL);
if face.pupilR <> '-' then
pupilR.LoadFromFile(respupils+face.pupilR);
if face.eye <> '-' then
eyes.LoadFromFile(reseyes+face.eye);
if face.mouth <> '-' then
mouth.LoadFromFile(resmouth+face.mouth);
(* *)
if UseColor then
colorizer(color,myface);
PNG.Assign(myface);
(* *)
PNG.Canvas.Draw(0,0,eyes);
PNG.Canvas.Draw(0,0,mouth);
PNG.Canvas.Draw(0,0,other);
PNG.Canvas.Draw(Face.P1.X-(pupilL.Width div 2),Face.P1.Y-(pupilL.Height div 2),pupilL);
PNG.Canvas.Draw(Face.P2.X-(pupilR.Width div 2),Face.P2.Y-(pupilR.Width div 2),pupilR);
(* *)
myface.Free;
eyes.Free;
other.Free;
mouth.Free;
pupilL.Free;
pupilR.Free;
end;
(******************************************************************************)
procedure DrawFace(Canvas: TCanvas; Face: TFaceStatus);
var
pupilL, pupilR, myface, eyes, mouth, other : TPNGObject;
begin
if not ExistFaceRes(Face) then Exit;
(* *)
pupilL := TPNGObject.Create;
pupilR := TPNGObject.Create;
myface := TPNGObject.Create;
other := TPNGObject.Create;
mouth := TPNGObject.Create;
eyes := TPNGObject.Create;
(* *)
Canvas.FillRect(Canvas.ClipRect);
(* *)
if face.face <> '-' then
myface.LoadFromFile(resfaces+face.face);
if face.other <> '-' then
other.LoadFromFile(resothers+face.other);
if face.pupilL <> '-' then
pupilL.LoadFromFile(respupils+face.pupilL);
if face.pupilR <> '-' then
pupilR.LoadFromFile(respupils+face.pupilR);
if face.eye <> '-' then
eyes.LoadFromFile(reseyes+face.eye);
if face.mouth <> '-' then
mouth.LoadFromFile(resmouth+face.mouth);
(* *)
Canvas.Draw(0,0,myface);
Canvas.Draw(0,0,eyes);
Canvas.Draw(0,0,mouth);
Canvas.Draw(0,0,other);
Canvas.Draw(Face.P1.X-(pupilL.Width div 2),Face.P1.Y-(pupilL.Height div 2),pupilL);
Canvas.Draw(Face.P2.X-(pupilR.Width div 2),Face.P2.Y-(pupilR.Width div 2),pupilR);
(* *)
myface.Free;
eyes.Free;
other.Free;
mouth.Free;
pupilL.Free;
pupilR.Free;
end;
(******************************************************************************)
procedure DeleteFrame(var animarr: TAnimations; frameid: integer);
var
facest : TFaceStatus;
i : integer;
begin
for i := frameid to length(animarr)-1 do
begin
facest := animarr[i+1];
animarr[i] := facest;
end;
SetLength(animarr,length(animarr)-1);
end;
(******************************************************************************)
function SaveAnimations(animarr: TAnimations; animname: string) : boolean;
var
animpth : string;
i : integer;
rs : file of TFaceStatus;
begin
Result := true;
animpth := animpath;
(*!!! DIR EXISTS TEST*)
AssignFile(rs, animpth+animname);
Rewrite(rs);
try
try
for i:= 0 to length(animarr)-1 do begin
Write (rs, animarr[i]);
end;
except
Result := false;
end;
finally
CloseFile(rs);
end;
end;
(******************************************************************************)
function LoadAnimations(var animarr: TAnimations; animname: string; errmsg: boolean = false) : boolean;
var
facest : TFaceStatus;
animpth : string;
i : integer;
rs : file of TFaceStatus;
begin
Result := false;
animpth := animpath;
if not FileExists(animpth+animname) then begin
if errmsg then
MessageDlg('Файл анимации не наиден.',mtError,[mbOK],0);
exit;
end;
SetLength(animarr,0);
AssignFile(rs, animpth+animname);
Reset(rs);
try
while not Eof(rs) do begin
ZeroMemory(@facest,sizeof(TFaceStatus));
Read (rs, facest);
SetLength(animarr,length(animarr)+1);
animarr[length(animarr)-1] := facest;
end;
except
if errmsg then
MessageDlg('Ошибка загрузки анимации.',mtError,[mbOK],0);
CloseFile(rs);
exit;
end;
Result := true;
CloseFile(rs);
end;
(******************************************************************************)
function SaveFace(Face: TFaceStatus; savename: string) : boolean;
var
i : integer;
facepth : string;
rs : file of TFaceStatus;
begin
Result := true;
facepth := ExtractFilePath(paramstr(0))+'Faces\';
AssignFile(rs, facepth + savename);
Rewrite(rs);
try
try
Write (rs, Face);
except
Result := false;
end;
finally
CloseFile(rs);
end;
end;
(******************************************************************************)
function LoadFace(var Face: TFaceStatus; FaceName: string; errmsg: boolean = false) : boolean;
var
facepth : string;
i : integer;
rs : file of TFaceStatus;
begin
Result := false;
facepth := ExtractFilePath(paramstr(0))+'Faces\';
if not FileExists(facepth+Facename) then begin
if errmsg then
MessageDlg('Файл не наиден.',mtError,[mbOK],0);
exit;
end;
AssignFile(rs, facepth+FaceName);
Reset(rs);
try
while not Eof(rs) do begin
if Eof(rs) then exit;
ZeroMemory(@Face,sizeof(TFaceStatus));
Read (rs, Face);
end;
except
if errmsg then
MessageDlg('Ошибка загрузки.',mtError,[mbOK],0);
CloseFile(rs);
exit;
end;
Result := true;
CloseFile(rs);
end;
(******************************************************************************)
procedure ClearFace(var Face: TFaceStatus);
begin
ZeroMemory(@Face,sizeof(TFaceStatus));
end;
(******************************************************************************)
function ExistFaceRes(Face: TFaceStatus) : boolean;
begin
Result := true;
if not FileExists(resfaces + face.face) and (string(face.face) <> '-') then begin
Result := false;
exit;
end;
if not FileExists(resothers + face.other) and (string(face.other) <> '-') then begin
Result := false;
exit;
end;
if not FileExists(reseyes + face.eye) and (string(face.eye) <> '-') then begin
Result := false;
exit;
end;
if not FileExists(respupils + face.pupilL) and (string(face.pupilL) <> '-') then begin
Result := false;
exit;
end;
if not FileExists(respupils + face.pupilR) and (string(face.pupilR) <> '-') then begin
Result := false;
exit;
end;
if not FileExists(resmouth + face.mouth) and (string(face.mouth) <> '-') then begin
Result := false;
exit;
end;
end;
function ExistAnimRes(Anim: TAnimations) : boolean;
var
i : integer;
begin
Result := true;
for i := 0 to length(Anim)-1 do
if not ExistFaceRes(Anim[i]) then
begin
Result := false;
exit;
end;
end;
(******************************************************************************)
function StrToParam(const KeyLine: String; Suffix : Char): TDoubleParam;
var
tmp,tmp2 : String;
i : integer;
begin
tmp := '';
tmp2 := '';
tmp := Copy(KeyLine, 1, Pos(Suffix,KeyLine)-1);
tmp2 := Copy(KeyLine, Length(tmp)+2, Length(KeyLine));
if tmp2 = Suffix then tmp2 := '';
Result.pName := tmp;
Result.pParam:= tmp2;
end;
(******************************************************************************)
(* *)
(******************************************************************************)
initialization
(* *)
others := TStringList.Create;
faces := TStringList.Create;
eyes := TStringList.Create;
mouths := TStringList.Create;
pupils := TStringList.Create;
(* *)
respth := ExtractFilePath(paramstr(0))+'skin\';
animpath := ExtractFilePath(paramstr(0))+'Animations\';
facepath := ExtractFilePath(paramstr(0))+'Faces\';
resfaces := respth + 'faces\';
resothers := respth + 'others\';
reseyes := respth + 'eyes\';
respupils := respth + 'pupils\';
resmouth := respth + 'mouths\';
if (not DirectoryExists(respth)) or (not DirectoryExists(reseyes)) or
(not DirectoryExists(resfaces)) or (not DirectoryExists(resothers)) or
(not DirectoryExists(respupils)) or (not DirectoryExists(resmouth)) then
begin
MessageDlg('Ошибка загрузки ресурсов. Приложение будет закрыто.',mtError,[mbOK],0);
ExitProcess(0);
end;
(* *)
if (not FileExists(reseyes+'eyes.ini')) or (not FileExists(resmouth+'mouths.ini')) or
(not FileExists(respupils+'pupils.ini')) or (not FileExists(resfaces+'faces.ini')) or
(not FileExists(resothers+'others.ini')) then
begin
MessageDlg('Ошибка загрузки списка ресурсов. Приложение будет закрыто.',mtError,[mbOK],0);
ExitProcess(0);
end;
(* *)
faces.LoadFromFile(resfaces+'faces.ini');
others.LoadFromFile(resothers+'others.ini');
eyes.LoadFromFile(reseyes+'eyes.ini');
mouths.LoadFromFile(resmouth+'mouths.ini');
pupils.LoadFromFile(respupils+'pupils.ini');
(* *)
end.
|
unit BDLoginUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
System.IniFiles, System.Win.Registry, System.Actions, Vcl.ActnList,
plugin, NppForms;
type
TBDLoginForm = class(TNppForm)
Panel1: TPanel;
Panel2: TPanel;
OkBtn: TBitBtn;
CancelBtn: TBitBtn;
GroupBox1: TGroupBox;
Panel3: TPanel;
ServerList: TComboBox;
Login: TComboBox;
SLabel: TLabel;
Label2: TLabel;
Label3: TLabel;
Password: TEdit;
Image1: TImage;
ActionList1: TActionList;
OkAction: TAction;
procedure FormActivate(Sender: TObject);
procedure PasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure LoginKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ServerListDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure OkActionExecute(Sender: TObject);
procedure OkActionUpdate(Sender: TObject);
private
{ Private declarations }
FBDType: TBdType;
procedure FillDSNList(Strings: TStrings);
const cnstMSSqlServersKey0 = 'SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo';
const cnstMSSqlServersKey1 = 'SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo';
const cnstItem = '%s|Server=%s|Port=%s';
const cnstData = '|Login=%s|Password=%s|BdType=%d';
const cnstSrcSybase = 'SQL.INI';
const cnstSybaseName = 'SYBASE';
const cnstSybaseRoot = 'SYBROOT';
const cnstNothing = 'Пусто';
procedure FillNothing;
procedure FillServerListMS;
procedure FillServerListSyb;
procedure FillODBCSources;
public
const constDBList = 'select name from master..sysdatabases order by name';
procedure Get(var aDataSource,aServer,aPort,aLogin,aPassword: string);
function Data: string;
property BDType: TBdType read FBDType write FBDType;
end;
implementation
//ODBC
function SQLDataSources(EnvironmentHandle:LongWord;Direction:Smallint;
ServerName:PAnsiChar;BufferLength1:Smallint;NameLength1Ptr:PSmallInt;
Description:PAnsiChar;BufferLength2:Smallint;NameLength2Ptr:PSmallInt): Smallint; stdcall; external 'odbc32.dll';
function SQLAllocHandle(HandleType:Smallint;InputHandle:Smallint;
OutputHandlePtr:Pointer): Smallint; stdcall; external 'odbc32.dll';
function SQLSetEnvAttr(EnvironmentHandle:LongWord;Attribute:Integer;
ValuePtr:Pointer;StringLength:Integer): Smallint; stdcall; external 'odbc32.dll';
function SQLFreeHandle(HandleType:Smallint;Handle:LongWord): Smallint; stdcall; external 'odbc32.dll';
function SQLAllocEnv(var phenv: Pointer):Smallint; stdcall; external 'odbc32.dll';
function SQLAllocConnect(henv: Pointer;var phdbc: Pointer):Smallint; stdcall; external 'odbc32.dll';
{$R *.dfm}
procedure TBDLoginForm.FillDSNList(Strings: TStrings);
const
MAX_BUF=1024;
SQL_HANDLE_ENV=1;
SQL_NULL_HENV=0;
SQL_ATTR_ODBC_VERSION=200;
SQL_IS_INTEGER=-6;
SQL_FETCH_FIRST_USER=31;
SQL_FETCH_FIRST=2;
SQL_FETCH_NEXT=1;
SQL_OV_ODBC3=3;
SQL_NO_DATA=100;
var
datasrc,descrip:array [0..MAX_BUF-1] of AnsiChar;
direction:Smallint;
rdsrc,rdesc:SmallInt;
hEnv:Cardinal;
begin
rdsrc:=0;
rdesc:=0;
datasrc[0]:=#0;
descrip[0]:=#0;
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HENV, @hEnv);
SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION,POINTER(SQL_OV_ODBC3),SQL_IS_INTEGER);
direction:=SQL_FETCH_FIRST;
Strings.Clear;
while (SQLDataSources(hEnv,direction,@datasrc[0],MAX_BUF,@rdsrc,@descrip[0],MAX_BUF,@rdesc)<>SQL_NO_DATA) do
begin
Strings.Add(AnsiString(datasrc)+ '||');
direction:=SQL_FETCH_NEXT;
end;
SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
end;
function TBDLoginForm.Data: string;
var
i: Integer;
begin
i := ServerList.ItemIndex;
if i >= 0 then
Result := ServerList.Items[ServerList.ItemIndex] +
Format(cnstData,[Login.Text,Password.Text,Integer(FBdType)])
else
Result := '';
end;
procedure TBDLoginForm.FillNothing;
begin
ServerList.Clear;
ServerList.AddItem(cnstNothing,Pointer(1));
ServerList.ItemIndex := 0;
ServerList.Enabled := False;
OkBtn.Enabled := False;
end;
procedure TBDLoginForm.FillODBCSources;
begin
ServerList.clear;
FillDSNList(ServerList.Items);
if ServerList.Items.Count = 0 then
begin
FillNothing;
Exit;
end
else
ServerList.ItemIndex := 0;
end;
procedure TBDLoginForm.FillServerListMS;
var
Registry: TRegistry;
Servers,Servers32 : TStringList;
i,j: integer;
S,FDataSource,FServer,FPort: string;
begin
Registry := TRegistry.Create(KEY_READ);
Servers := TStringList.Create;
Servers.Duplicates := dupIgnore;
Servers32 := TStringList.Create;
Servers32.Duplicates := dupIgnore;
try
try
Registry.RootKey := HKEY_LOCAL_MACHINE;
if Registry.OpenKey(cnstMSSqlServersKey0, False) then
Registry.GetValueNames(Servers);
if Registry.OpenKey(cnstMSSqlServersKey1, False) then
Registry.GetValueNames(Servers32);
Servers.AddStrings(Servers32);
if Servers.Count = 0 then
begin
FillNothing;
Exit;
end;
Servers.Sorted := True;
for i := 0 to Servers.Count - 1 do
begin
S := Registry.ReadString(Servers[i]);
FDataSource := Servers[i];
j := Pos(',',S);
if j > 0 then
begin
FServer := Copy(S,j+1,MaxInt);
j := Pos(',',FServer);
if j > 0 then
begin
FPort := Copy(FServer,j+1,MaxInt);
FServer := Copy(FServer,1,j-1);
end;
end;
ServerList.AddItem(Format(cnstItem,[FDataSource,FServer,FPort]),nil);
end;
finally
Registry.CloseKey;
end;
finally
Registry.Free;
Servers.Free;
Servers32.Free;
if ServerList.Items.Count > 0 then ServerList.ItemIndex := 0;
end;
end;
procedure TBDLoginForm.FillServerListSyb;
procedure GetEnvironmentStrings(Vars: TStrings);
var
ptr: LPWSTR;
s: string;
Done: boolean;
begin
Vars.Clear;
s := '';
Done := FALSE;
ptr := Winapi.Windows.GetEnvironmentStrings;
while Done = false do begin
if ptr^ = #0 then begin
inc(ptr);
if ptr^ = #0 then Done := TRUE
else Vars.Add(s);
s := ptr^;
end else s := s + ptr^;
inc(ptr);
end;
end;
var
Strings: TStringList;
i,j: integer;
FIni: TIniFile;
S,FDataSource,FServer,FPort,FName: string;
begin
Strings := TStringList.Create;
try
FName := '';
GetEnvironmentStrings(Strings);
for i := 0 to Strings.Count-1 do
if (Strings.Names[i] = cnstSybaseName) or (Strings.Names[i] = cnstSybaseRoot) then
begin
FName := Strings.Values[Strings.Names[i]];
break;
end;
if FName = '' then
begin
FillNothing;
Exit;
end;
FName := IncludeTrailingPathDelimiter(FName) + 'ini\' + cnstSrcSybase;
if FileExists(FName) then
begin
FIni := TIniFile.Create(FName);
try
Strings.Clear;
FIni.ReadSections(Strings);
Strings.Sorted := True;
for i := 0 to Strings.Count - 1 do
begin
FDataSource := Strings[i];
S := FIni.ReadString(FDataSource,'query','');
j := Pos(',',S);
if j > 0 then
begin
FServer := Copy(S,j+1,MaxInt);
j := Pos(',',FServer);
if j > 0 then
begin
FPort := Copy(FServer,j+1,MaxInt);
FServer := Copy(FServer,1,j-1);
end;
end;
ServerList.AddItem(Format(cnstItem,[FDataSource,FServer,FPort]),nil);
end;
finally
FIni.Free;
end;
end
else
begin
FillNothing;
Exit;
end;
finally
Strings.Free;
if ServerList.Items.Count > 0 then ServerList.ItemIndex := 0;
end;
end;
procedure TBDLoginForm.FormActivate(Sender: TObject);
begin
inherited;
Caption := constLoginBDCaption + constLoginBDCaptionArray[FBDType];
SLabel.Caption := constDSBDCaptionArray[FBDType];
ServerList.Clear;
if FBDType = bdMSSQL then
FillServerListMS
else
if FBDType = bdSybase then
FillServerListSyb
else
begin
FillODBCSources;
OkAction.OnUpdate := nil;
end;
end;
procedure TBDLoginForm.Get(var aDataSource, aServer, aPort, aLogin,
aPassword: string);
var
Strings: TStringList;
i: Integer;
begin
i := ServerList.ItemIndex;
if i >= 0 then
begin
Strings := TStringList.Create;
try
Strings.Delimiter := '|';
Strings.DelimitedText := ServerList.Items[ServerList.ItemIndex];
aDataSource := Strings[0];
aServer := Strings[1];
aPort := Strings[2];
aLogin := Login.Text;
aPassword := Password.Text;
finally
Strings.Free;
end;
end;
end;
procedure TBDLoginForm.PasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then OkBtn.Click;
if Key = VK_ESCAPE then CancelBtn.Click;
end;
procedure TBDLoginForm.ServerListDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
Bitmap: TBitmap;
Offset: Integer;
S: string;
begin
with (Control as TComboBox).Canvas do { Draw on control canvas, not on the form. }
begin
S := (Control as TComboBox).Items[Index];
FillRect(Rect); { Clear the rectangle. }
Offset := 2; { Provide default offset. }
if Pos('|',S) = 0 then
Offset := 6
else
begin
Bitmap := Image1.Picture.Bitmap;
if Bitmap <> nil then
begin
//DrawIcon(Handle, Rect.Left + Offset, Rect.Top, Icon.Handle);
BrushCopy(
Bounds(Rect.Left + Offset, Rect.Top+2, Bitmap.Width, Bitmap.Height),
Bitmap,
Bounds(0, 0, Bitmap.Width, Bitmap.Height),
clWhite); {render bitmap}
Offset := Bitmap.width + 6; { Add four pixels between bitmap and text. }
end;
S := Copy(S,1,Pos('|',S)-1);
end;
TextOut(Rect.Left + Offset, Rect.Top+1, S);
end;
end;
procedure TBDLoginForm.LoginKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_ESCAPE then CancelBtn.Click;
end;
procedure TBDLoginForm.OkActionExecute(Sender: TObject);
begin
OkBtn.Enabled := False;
Self.Refresh;
end;
procedure TBDLoginForm.OkActionUpdate(Sender: TObject);
begin
OkAction.Enabled := (Login.Text <> '') and
(Password.Text <> '');
end;
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ °æÈ¨ËùÓÐ (C) 2019 ËÕÐËÓ(PRSoft) }
{ }
{*******************************************************}
unit Page;
interface
uses
System.SysUtils, System.Classes, Web.HTTPApp, Web.HTTPProd, FireDAC.Comp.Client,
superobject, uConfig;
type
TPage = class
private
url: string;
plist: TStringList;
public
Page: TStringList;
function HTML(): string;
constructor Create(htmlfile: string; params: TStringList; _url: string);
destructor Destroy; override;
end;
implementation
{ TPage }
constructor TPage.Create(htmlfile: string; params: TStringList; _url: string);
begin
Page := TStringList.Create;
plist := params;
if UpperCase(document_charset) = 'UTF-8' then
begin
Page.LoadFromFile(htmlfile, TEncoding.UTF8);
end
else if UpperCase(document_charset) = 'UTF-7' then
begin
Page.LoadFromFile(htmlfile, TEncoding.UTF7);
end
else if UpperCase(document_charset) = 'UNICODE' then
begin
Page.LoadFromFile(htmlfile, TEncoding.Unicode);
end
else
begin
Page.LoadFromFile(htmlfile, TEncoding.Default);
end;
url := _url;
end;
function TPage.HTML(): string;
begin
Result := Page.Text;
end;
destructor TPage.Destroy;
begin
FreeAndNil(Page);
inherited;
end;
end.
|
unit pdv_abertura_fechamento_caixa;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Menus, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinXmas2008Blue, cxTextEdit, cxCurrencyEdit, cxLabel, StdCtrls,
cxButtons;
type
TTipoLancamentoCaixa = (tlPreAbertura, tlAbertura, tlFechamento);
TfrmAberturaFechamentoCaixa = class(TForm)
panPreAbertura: TPanel;
panBotoes: TPanel;
btnConfirmar: TcxButton;
btnCancelar: TcxButton;
lblVrCaixa: TcxLabel;
edtValorPreAbertura: TcxCurrencyEdit;
panAbertura: TPanel;
cxLabel1: TcxLabel;
edtValorAbertura: TcxCurrencyEdit;
panFechamento: TPanel;
cxLabel2: TcxLabel;
edtVendasCalc: TcxCurrencyEdit;
cxLabel3: TcxLabel;
edtRetiradasCalc: TcxCurrencyEdit;
cxLabel4: TcxLabel;
edtSangriaCalc: TcxCurrencyEdit;
cxLabel5: TcxLabel;
edtEntradaCalc: TcxCurrencyEdit;
cxLabel6: TcxLabel;
edtDebitoCalc: TcxCurrencyEdit;
cxLabel7: TcxLabel;
edtCreditoCalc: TcxCurrencyEdit;
edtVendasConf: TcxCurrencyEdit;
edtSangriaConf: TcxCurrencyEdit;
edtRetiradasConf: TcxCurrencyEdit;
edtEntradaConf: TcxCurrencyEdit;
edtDebitoConf: TcxCurrencyEdit;
edtCreditoConf: TcxCurrencyEdit;
procedure FormShow(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnConfirmarClick(Sender: TObject);
private
{ Private declarations }
FConfirmado : Boolean;
procedure PrepararTelas;
procedure ValidarCampo(edit : TcxCurrencyEdit; const MaiorQueZero : Boolean = False);
procedure GravarValorPreAbertura;
procedure GravarValorAbertura;
procedure GravarValorFechamento;
procedure BuscarValorFechamento;
protected
FTipoLancamento : TTipoLancamentoCaixa;
FidCaixa : Integer;
public
property Confirmado : Boolean read FConfirmado;
{ Public declarations }
end;
var
frmAberturaFechamentoCaixa: TfrmAberturaFechamentoCaixa;
function CaixaPreAberto : Boolean;
function CaixaAberto : Boolean;
function CaixaFechado : Boolean;
implementation
uses lib_db, lib_mensagem, main_base, lib_vmsis;
{$R *.dfm}
function CaixaPreAberto;
begin
Result := False;
frmAberturaFechamentoCaixa := TfrmAberturaFechamentoCaixa.Create(Application);
try
frmAberturaFechamentoCaixa.FTipoLancamento := tlPreAbertura;
frmAberturaFechamentoCaixa.ShowModal;
Result := frmAberturaFechamentoCaixa.Confirmado;
finally
FreeAndNil(frmAberturaFechamentoCaixa);
end;
end;
function CaixaAberto : Boolean;
var
tbAberFechCaixa : TObjetoDB;
begin
tbAberFechCaixa := TObjetoDB.create('aberfechcaixa');
try
tbAberFechCaixa.AddParametro('status', 'A');
tbAberFechCaixa.Select(['id']);
if not tbAberFechCaixa.IsEmpty then
begin
Result := True;
Exit;
end;
finally
FreeAndNil(tbAberFechCaixa);
end;
Result := False;
frmAberturaFechamentoCaixa := TfrmAberturaFechamentoCaixa.Create(Application);
try
frmAberturaFechamentoCaixa.FTipoLancamento := tlAbertura;
frmAberturaFechamentoCaixa.ShowModal;
Result := frmAberturaFechamentoCaixa.Confirmado;
finally
FreeAndNil(frmAberturaFechamentoCaixa);
end;
end;
function CaixaFechado : Boolean;
begin
Result := False;
frmAberturaFechamentoCaixa := TfrmAberturaFechamentoCaixa.Create(Application);
try
frmAberturaFechamentoCaixa.FTipoLancamento := tlFechamento;
frmAberturaFechamentoCaixa.ShowModal;
Result := frmAberturaFechamentoCaixa.Confirmado;
finally
FreeAndNil(frmAberturaFechamentoCaixa);
end;
end;
procedure TfrmAberturaFechamentoCaixa.FormShow(Sender: TObject);
begin
PrepararTelas;
edtValorPreAbertura.Value := 0;
edtValorAbertura.Value := 0;
// edtValorAbertura.Text
end;
procedure TfrmAberturaFechamentoCaixa.btnCancelarClick(Sender: TObject);
begin
FConfirmado := False;
Close;
end;
procedure TfrmAberturaFechamentoCaixa.PrepararTelas;
const
VALOR_ADICIONAL = 31;
begin
case FTipoLancamento of
tlPreAbertura :
begin
panPreAbertura.Visible := True;
frmAberturaFechamentoCaixa.Height := panPreAbertura.Height + panBotoes.Height + VALOR_ADICIONAL;
frmAberturaFechamentoCaixa.Caption := 'Definir valor inicial para próxima abertura';
end;
tlAbertura:
begin
panAbertura.Visible := True;
frmAberturaFechamentoCaixa.Height := panAbertura.Height + panBotoes.Height + VALOR_ADICIONAL;;
frmAberturaFechamentoCaixa.Caption := 'Abertura do caixa';
end;
tlFechamento:
begin
panFechamento.Visible := True;
frmAberturaFechamentoCaixa.Height := panFechamento.Height + panBotoes.Height + VALOR_ADICIONAL;;
frmAberturaFechamentoCaixa.Width := frmAberturaFechamentoCaixa.Width + 3;
frmAberturaFechamentoCaixa.Caption := 'Fechamento do caixa';
BuscarValorFechamento;
end;
end;
frmAberturaFechamentoCaixa.AutoScroll := False;
panBotoes.Visible := True;
end;
procedure TfrmAberturaFechamentoCaixa.ValidarCampo(edit: TcxCurrencyEdit;
const MaiorQueZero: Boolean = False);
begin
if (edit.Value = Null) or (MaiorQueZero and (edit.Value <= 0) ) then
begin
Aviso(INFORMAR_VALOR);
if edit.CanFocus then
edit.SetFocus;
Abort;
end;
end;
procedure TfrmAberturaFechamentoCaixa.GravarValorPreAbertura;
var
tbAberFechCaixa : TObjetoDB;
tbCaixa : TObjetoDB;
begin
FConfirmado := False;
ValidarCampo(edtValorPreAbertura);
tbAberFechCaixa := TobjetoDB.create('aberfechcaixa');
try
tbAberFechCaixa.AddSqlAdicional(' where status in (''P'', ''A'') ');
tbAberFechCaixa.Select(['ID']);
if not tbAberFechCaixa.IsEmpty then
begin
Aviso(EXISTENCIA_CAIXA_ABERTO);
Abort;
end;
tbAberFechCaixa.Reset;
tbCaixa := TObjetoDB.create('caixa');
try
tbCaixa.Select(['id']);
tbCaixa.First;
tbAberFechCaixa.AddParametro('id_caixa', tbCaixa.GetVal('id'));
finally
FreeAndNil(tbCaixa);
end;
tbAberFechCaixa.AddParametro('vrinicial',(StringReplace(edtValorPreAbertura.Text, ',', '.', [rfReplaceAll])));
tbAberFechCaixa.AddParametro('funcipreabertura', frmMainBase.IdUsuario);
tbAberFechCaixa.AddParametro('dtmovi', TUtilidades.GetDateToMySql(Date));
tbAberFechCaixa.AddParametro('status', 'P');
tbAberFechCaixa.Insert;
FConfirmado := True;
finally
FreeAndNil(tbAberFechCaixa);
end;
end;
procedure TfrmAberturaFechamentoCaixa.btnConfirmarClick(Sender: TObject);
begin
case FTipoLancamento of
tlPreAbertura: GravarValorPreAbertura;
tlAbertura: GravarValorAbertura;
tlFechamento: GravarValorFechamento;
end;
close;
end;
procedure TfrmAberturaFechamentoCaixa.GravarValorAbertura;
var
tbAberFechCaixa : TObjetoDB;
begin
FConfirmado := False;
tbAberFechCaixa := TObjetoDB.create('aberfechcaixa');
try
tbAberFechCaixa.AddParametro('status', 'A');
tbAberFechCaixa.Select(['ID']);
if not tbAberFechCaixa.IsEmpty then
begin
FConfirmado := True;
Exit;
end;
tbAberFechCaixa.Reset;
tbAberFechCaixa.AddParametro('status', 'P');
tbAberFechCaixa.Select(['vrcorrigido', 'dtmovi', 'funciconfabertura', 'status']);
if tbAberFechCaixa.IsEmpty then
begin
GravarValorPreAbertura;
tbAberFechCaixa.Select(['vrcorrigido', 'dtmovi', 'funciconfabertura', 'status']);
if tbAberFechCaixa.IsEmpty then
begin
Aviso(FALHA_ABRIR_CAIXA);
Abort;
end;
end;
tbAberFechCaixa.ChangeValue('vrcorrigido', edtValorAbertura.Value);
tbAberFechCaixa.ChangeValue('dtmovi', Date);
tbAberFechCaixa.ChangeValue('funciconfabertura', frmMainBase.IdUsuario);
tbAberFechCaixa.ChangeValue('status', 'A');
tbAberFechCaixa.SaveChanges;
FConfirmado := True;
finally
FreeAndNil(tbAberFechCaixa);
end;
end;
procedure TfrmAberturaFechamentoCaixa.GravarValorFechamento;
var
tbAberFechCaixa : TObjetoDB;
begin
tbAberFechCaixa := TobjetoDB.create('aberfechcaixa');
try
tbAberFechCaixa.AddParametro('status', 'A');
tbAberFechCaixa.AddParametro('id_caixa', FidCaixa);
tbAberFechCaixa.Select(['*']);
tbAberFechCaixa.ChangeValue('vrvenda', edtVendasConf.Value);
tbAberFechCaixa.ChangeValue('vrretirada', edtRetiradasConf.Value);
tbAberFechCaixa.ChangeValue('vrsangria', edtSangriaConf.Value);
tbAberFechCaixa.ChangeValue('vrentrada', edtEntradaConf.Value);
tbAberFechCaixa.ChangeValue('vrdebio', edtDebitoConf.Value);
tbAberFechCaixa.ChangeValue('vrcredito', edtCreditoConf.Value);
tbAberFechCaixa.ChangeValue('status', 'F');
tbAberFechCaixa.ChangeValue('funcifechamento', frmMainBase.IdUsuario);
tbAberFechCaixa.SaveChanges;
FConfirmado := True;
finally
FreeAndNil(tbAberFechCaixa);
end;
end;
procedure TfrmAberturaFechamentoCaixa.BuscarValorFechamento;
var
tbAberFechCaixa : TObjetoDB;
tbMovCaixa : TObjetoDB;
tbCaixa : TObjetoDB;
IdCaixa : Integer;
DataMovimento : TDate;
const
ENTRADA = 'E';
VENDA = 'V';
SANGRIA = 'S';
RETIRADA = 'R';
CREDITO = 'CR';
DEBITO = 'DE';
begin
tbCaixa := TObjetoDB.create('caixa');
try
tbCaixa.Select(['id']);
IdCaixa := tbCaixa.GetVal('id');
finally
FreeAndNil(tbCaixa);
end;
tbAberFechCaixa := TobjetoDB.create('aberfechcaixa');
try
tbAberFechCaixa.AddParametro('status', 'A');
tbAberFechCaixa.AddParametro('id_caixa', IdCaixa);
tbAberFechCaixa.Select(['dtmovi']);
DataMovimento := tbAberFechCaixa.GetVal('dtmovi');
finally
FreeAndNil(tbAberFechCaixa);
end;
tbMovCaixa := TObjetoDB.create('movcaixa');
try
//valores por tipo
tbMovCaixa.AddParametro('dtmovi', FormatDateTime('yyy-MM-dd', DataMovimento), ' >= ');
tbMovCaixa.AddSqlAdicional(' group by tpmovi');
tbMovCaixa.Select(['sum(vrmovi) as vrmovi', 'tpmovi']);
if tbMovCaixa.Find('tpmovi', VENDA) then
edtVendasCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtVendasCalc.Value := 0;
if tbMovCaixa.Find('tpmovi', RETIRADA) then
edtRetiradasCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtRetiradasCalc.Value := 0;
if tbMovCaixa.Find('tpmovi', SANGRIA) then
edtSangriaCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtSangriaCalc.Value := 0;
if tbMovCaixa.Find('tpmovi', ENTRADA) then
edtEntradaCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtEntradaCalc.Value := 0;
//valores por forma de pagamento
tbMovCaixa.ClearSqlAdicional;
tbMovCaixa.AddSqlAdicional(' group by formpgto');
tbMovCaixa.Select(['sum(vrmovi) as vrmovi', 'formpgto']);
if tbMovCaixa.Find('formpgto', DEBITO) then
edtDebitoCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtDebitoCalc.Value := 0;
if tbMovCaixa.Find('formpgto', CREDITO) then
edtCreditoCalc.Value := tbMovCaixa.GetVal('vrmovi')
else
edtCreditoCalc.Value := 0;
edtVendasConf.Value := edtVendasCalc.Value;
edtSangriaConf.Value := edtSangriaCalc.Value;
edtRetiradasConf.Value := edtRetiradasCalc.Value;
edtEntradaConf.Value := edtEntradaCalc.Value;
edtDebitoConf.Value := edtDebitoCalc.Value;
edtCreditoConf.Value := edtCreditoCalc.Value;
FidCaixa := IdCaixa;
finally
FreeAndNil(tbMovCaixa);
end;
end;
end.
|
unit TestMaxBlankLines;
{ AFS 10 Nov 2003
Test blank lines removal }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestMaxBlankLines, released November 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2003 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess;
type
TTestRemoveBlankLines = class(TBaseTestProcess)
private
fiMaxLines, fiMaxLinesInSection: integer;
fbRemoveCosecutiveBlankLines: Boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNone;
procedure Test1;
procedure TestVarLines0;
procedure TestVarLines1;
procedure TestVarLines2;
procedure TestVarLines3;
procedure TestVarLines4;
procedure TestProcHeaderLines0;
procedure TestProcHeaderLines1;
procedure TestProcHeaderLines2;
procedure TestProcHeaderLines3;
procedure TestProcHeaderLines4;
end;
implementation
uses
JcfStringUtils,
JcfSettings, SetReturns,
RemoveConsecutiveReturns, RemoveBlankLinesInVars, RemoveBlankLinesAfterProcHeader;
procedure TTestRemoveBlankLines.Setup;
begin
inherited;
fiMaxLines := JcfFormatSettings.Returns.MaxConsecutiveBlankLines;
fiMaxLinesInSection := JcfFormatSettings.Returns.MaxBlankLinesInSection;
fbRemoveCosecutiveBlankLines := JcfFormatSettings.Returns.RemoveConsecutiveBlankLines;
JcfFormatSettings.Returns.MaxConsecutiveBlankLines := 4;
JcfFormatSettings.Returns.RemoveConsecutiveBlankLines := True;
end;
procedure TTestRemoveBlankLines.TearDown;
begin
inherited;
// restore initial values
JcfFormatSettings.Returns.MaxConsecutiveBlankLines := fiMaxLines;
JcfFormatSettings.Returns.MaxBlankLinesInSection := fiMaxLinesInSection;
JcfFormatSettings.Returns.RemoveConsecutiveBlankLines := fbRemoveCosecutiveBlankLines;
end;
procedure TTestRemoveBlankLines.TestNone;
const
IN_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
begin
TestProcessResult(TRemoveConsecutiveReturns, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestRemoveBlankLines.Test1;
const
IN_UNIT_TEXT = UNIT_HEADER +
NativeLineBreak + NativeLineBreak +
NativeLineBreak + NativeLineBreak +
NativeLineBreak + NativeLineBreak +
NativeLineBreak + NativeLineBreak +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER +
NativeLineBreak + NativeLineBreak +
NativeLineBreak +
UNIT_FOOTER;
begin
TestProcessResult(TRemoveConsecutiveReturns, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
const
UNIT_TEXT_VAR_LINES_0 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_VAR_LINES_1 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_VAR_LINES_2 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
NativeLineBreak +
NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_VAR_LINES_3 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
NativeLineBreak +
NativeLineBreak +
NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
procedure TTestRemoveBlankLines.TestVarLines0;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 0;
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_0, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_1, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_2, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_3, UNIT_TEXT_VAR_LINES_0);
end;
procedure TTestRemoveBlankLines.TestVarLines1;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 1;
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_0, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_1, UNIT_TEXT_VAR_LINES_1);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_2, UNIT_TEXT_VAR_LINES_1);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_3, UNIT_TEXT_VAR_LINES_1);
end;
procedure TTestRemoveBlankLines.TestVarLines2;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 2;
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_0, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_1, UNIT_TEXT_VAR_LINES_1);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_2, UNIT_TEXT_VAR_LINES_2);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_3, UNIT_TEXT_VAR_LINES_2);
end;
procedure TTestRemoveBlankLines.TestVarLines3;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 3;
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_0, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_1, UNIT_TEXT_VAR_LINES_1);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_2, UNIT_TEXT_VAR_LINES_2);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_3, UNIT_TEXT_VAR_LINES_3);
end;
procedure TTestRemoveBlankLines.TestVarLines4;
begin
// as per 3
JcfFormatSettings.Returns.MaxBlankLinesInSection := 4;
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_0, UNIT_TEXT_VAR_LINES_0);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_1, UNIT_TEXT_VAR_LINES_1);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_2, UNIT_TEXT_VAR_LINES_2);
TestProcessResult(TRemoveBlankLinesInVars, UNIT_TEXT_VAR_LINES_3, UNIT_TEXT_VAR_LINES_3);
end;
const
UNIT_TEXT_HEADER_LINES_0 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_HEADER_LINES_1 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_HEADER_LINES_2 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_TEXT_HEADER_LINES_3 = UNIT_HEADER +
' procedure foo; ' + NativeLineBreak +
NativeLineBreak +
'var' + NativeLineBreak +
' a: integer;' + NativeLineBreak +
'begin end;' + NativeLineBreak +
UNIT_FOOTER;
procedure TTestRemoveBlankLines.TestProcHeaderLines0;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 0;
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_0, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_1, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_2, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_3, UNIT_TEXT_HEADER_LINES_0);
end;
procedure TTestRemoveBlankLines.TestProcHeaderLines1;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 1;
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_0, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_1, UNIT_TEXT_HEADER_LINES_1);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_2, UNIT_TEXT_HEADER_LINES_1);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_3, UNIT_TEXT_HEADER_LINES_1);
end;
procedure TTestRemoveBlankLines.TestProcHeaderLines2;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 2;
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_0, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_1, UNIT_TEXT_HEADER_LINES_1);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_2, UNIT_TEXT_HEADER_LINES_2);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_3, UNIT_TEXT_HEADER_LINES_2);
end;
procedure TTestRemoveBlankLines.TestProcHeaderLines3;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 3;
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_0, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_1, UNIT_TEXT_HEADER_LINES_1);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_2, UNIT_TEXT_HEADER_LINES_2);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_3, UNIT_TEXT_HEADER_LINES_3);
end;
procedure TTestRemoveBlankLines.TestProcHeaderLines4;
begin
JcfFormatSettings.Returns.MaxBlankLinesInSection := 4;
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_0, UNIT_TEXT_HEADER_LINES_0);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_1, UNIT_TEXT_HEADER_LINES_1);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_2, UNIT_TEXT_HEADER_LINES_2);
TestProcessResult(TRemoveBlankLinesAfterProcHeader, UNIT_TEXT_HEADER_LINES_3, UNIT_TEXT_HEADER_LINES_3);
end;
initialization
TestFramework.RegisterTest('Processes', TTestRemoveBlankLines.Suite);
end.
|
unit uParentedPanel;
interface
uses
SysUtils, Classes, Controls, ExtCtrls;
type
TOnParentModifiedEvent = procedure(Sender: TObject; aParent:TWinControl) of object;
TParentedPanel = class(TPanel)
private
FOnParentModified : TOnParentModifiedEvent;
{ Private declarations }
protected
procedure SetParent(AParent: TWinControl); override;
{ Protected declarations }
published
{ Public declarations }
property OnParentModified : TOnParentModifiedEvent read
FOnParentModified write FOnParentModified;
end;
implementation
{ TParentedPanel }
procedure TParentedPanel.SetParent(AParent: TWinControl);
begin
inherited;
if assigned(FOnParentModified) then
FOnParentModified(Self, AParent);
end;
end.
|
unit AutoBindingDescriptionForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, cxGroupBox, cxCheckBox, Vcl.Menus, System.Actions,
Vcl.ActnList, Vcl.StdCtrls, cxButtons, dxCheckGroupBox;
type
TfrmAutoBindingDescriptions = class(TForm)
cxbtnAllDB: TcxButton;
cxbtnCategoryDB: TcxButton;
cxbtnCancel: TcxButton;
ActionList: TActionList;
actAll: TAction;
actCategory: TAction;
dxCheckGroupBox1: TdxCheckGroupBox;
CheckBox1: TCheckBox;
procedure actAllUpdate(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
{ Public declarations }
end;
implementation
uses
FormsHelper, ProjectConst;
{$R *.dfm}
constructor TfrmAutoBindingDescriptions.Create(AOwner: TComponent);
begin
inherited;
TFormsHelper.SetFont(Self, BaseFontSize);
end;
procedure TfrmAutoBindingDescriptions.actAllUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := True;
end;
end.
|
unit uObjInspFntChngr;
interface
procedure Register;
implementation
uses
SysUtils, Graphics, Forms;
var
FSavedFont: TFont;
const
PreferParentFont = True;
PreferFontName = 'Tahoma';
PreferFontSize = 8;
function FindObjectInspecotr: TCustomForm;
var
I: Integer;
begin
for I := 0 to Screen.CustomFormCount - 1 do
if Screen.CustomForms[I].Name = 'PropertyInspector' then
begin
Result := Screen.CustomForms[I];
Exit;
end;
Result := nil;
end;
procedure Register;
var
F: TCustomForm;
begin
F := FindObjectInspecotr;
if Assigned(F) then
begin
FSavedFont := TFont.Create;
FSavedFont.Assign(F.Font);
if not PreferParentFont then
begin
F.Font.Name := PreferFontName;
F.Font.Size := PreferFontSize;
end else
TForm(F).ParentFont := True;
end;
end;
procedure Unregister;
var
F: TCustomForm;
begin
if Assigned(FSavedFont) then
begin
F := FindObjectInspecotr;
if Assigned(F) then
F.Font.Assign(FSavedFont);
end;
FreeAndNil(FSavedFont);
end;
initialization
FSavedFont := nil;
finalization
Unregister;
end.
|
{***************************************************************
*
* Project : echoclient
* Unit Name: main
* Purpose : Demonstrates usage of the ECHO client
* Date : 21/01/2001 - 12:59:11
* History :
*
****************************************************************}
unit main;
interface
uses
{$IFDEF Linux}
QControls, QForms, QStdCtrls, QGraphics, QDialogs,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes, IdComponent, IdTCPConnection, IdTCPClient, IdEcho,
IdBaseComponent;
type
TformEchoTest = class(TForm)
edtSendText: TEdit;
lblTextToEcho: TLabel;
lblTotalTime: TLabel;
edtEchoServer: TEdit;
lblEchoServer: TLabel;
btnConnect: TButton;
btnDisconnect: TButton;
IdEcoTestConnection: TIdEcho;
lblReceivedText: TLabel;
Button1: TButton;
lablTime: TLabel;
lablReceived: TLabel;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnConnectClick(Sender: TObject);
procedure btnDisconnectClick(Sender: TObject);
procedure edtEchoServerChange(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
public
end;
var
formEchoTest: TformEchoTest;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TformEchoTest.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
IdEcoTestConnection.Disconnect;
end;
procedure TformEchoTest.btnConnectClick(Sender: TObject);
begin
try
IdEcoTestConnection.Connect;
{we only can echo after we connect to the server}
edtSendText.Enabled := True;
edtSendText.color := clWhite;
btnConnect.Enabled := False;
btnDisconnect.Enabled := True;
except
IdEcoTestConnection.Disconnect;
end; //try..except
end;
procedure TformEchoTest.btnDisconnectClick(Sender: TObject);
begin
IdEcoTestConnection.Disconnect;
btnConnect.Enabled := True;
edtSendText.Enabled := False;
edtSendText.color := clSilver;
btnDisconnect.Enabled := False;
end;
procedure TformEchoTest.edtEchoServerChange(Sender: TObject);
begin
IdEcoTestConnection.Host := edtEchoServer.Text;
end;
procedure TformEchoTest.Button1Click(Sender: TObject);
begin
{This echos the text to the server}
lablReceived.Caption := IdEcoTestConnection.Echo ( edtSendText.Text );
{This displays the round trip time}
lablTime.Caption := IntToStr ( IdEcoTestConnection.EchoTime );
end;
end.
|
namespace OxygeneLogo;
interface
uses
System.Windows,
System.Windows.Controls,
System.Windows.Data,
System.Windows.Documents,
System.Windows.Media,
System.Windows.Navigation,
System.Windows.Shapes;
type
OxygeneWindow = public partial class(Window)
private
// To use Loaded event put the Loaded="WindowLoaded" attribute in root element of .xaml file.
// method WindowLoaded(sender: Object; e: EventArgs );
// Sample event handler:
// method ButtonClick(sender: Object; e: RoutedEventArgs);
public
constructor;
end;
implementation
constructor OxygeneWindow;
begin
InitializeComponent();
end;
end. |
unit plc_1;
interface
uses system;
type
TPLCObjectResult = (plcResultOK, plcResultWait, plcResultError);
TModBusDeviceStatus = (mdbNormal = 0,mdbError = 1);
//=====================================
PM2827 = class;
TA2_c = class;
TL_Ms = class;
//=====================================
PM2827 = class
J1_1: Boolean;
J1_2: Boolean;
J1_3: Boolean;
J1_4: Boolean;
J1_5: Boolean;
J1_6: Boolean;
J1_7: Boolean;
J1_8: Boolean;
J1_9: Boolean;
J1_10: Boolean;
J1_11: Boolean;
J1_12: Boolean;
J2_1: Boolean;
J2_2: Boolean;
J2_3: Boolean;
J2_4: Boolean;
J2_5: Boolean;
J2_6: Boolean;
J2_7: Boolean;
J2_8: Boolean;
J2_9: Boolean;
J2_10: Boolean;
J2_11: Boolean;
J2_12: Boolean;
Status: TModbusDeviceStatus;
Data: array[4] of byte;
end;
TA2_c = class(PM2827)
property I_1PI_F: Boolean read J1_1;
property I_2PI_F: Boolean read J1_2;
property I_ChDP_F: Boolean read J1_3;
property I_612SP_F: Boolean read J1_5;
property I_1416SP_F: Boolean read J1_7;
property I_1P_F: Boolean read J1_9;
property I_IIP_F: Boolean read J1_11;
property I_3P_F: Boolean read J2_1;
property I_5P_F: Boolean read J2_3;
property I_7P_F: Boolean read J2_5;
property I_Ch1IP1_F: Boolean read J2_7;
property I_NG1_F: Boolean read J2_9;
property I_1VV_F: Boolean read J2_10;
property I_2VV_F: Boolean read J2_11;
end;
TL_Ms = class
A2_c: TA2_c;
State: Boolean;
Meandr: Boolean;
MCnt: Int32;
function Execute: TPLCObjectResult;
end;
implementation
function TL_Ms.Execute: TPLCObjectResult;
begin
State := not (A2_c.I_1PI_F AND A2_c.I_2PI_F AND A2_c.I_2VV_F);
if State then
begin
if MCnt > 0 then
dec(MCnt)
else begin
Meandr := not Meandr;
MCnt := 8;
end;
end else
Meandr := False;
end;
var
A2_c: TA2_c;
L_Ms: TL_Ms;
procedure Test;
begin
A2_c := TA2_c.Create();
L_Ms := TL_Ms.Create();
L_Ms.A2_c := A2_c;
L_Ms.Execute();
end;
initialization
Test();
end.
|
{ ---------------------------------------------------------------------------- }
{ HeightMapGenerator MB3D }
{ Copyright (C) 2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit HeightMapGenUI;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VertexList, Vcl.ExtCtrls,
Vcl.Buttons, Vcl.StdCtrls, VectorMath, Vcl.ComCtrls, JvExExtCtrls,
JvExtComponent, JvOfficeColorButton, JvExControls, JvColorBox, JvColorButton,
SpeedButtonEx, BulbTracerUITools, HeightMapGenPreview;
type
TMapType = (mt8BitPNG, mt16BitPBM);
THeightMapGenFrm = class(TForm)
NavigatePnl: TPanel;
Label15: TLabel;
Label16: TLabel;
LoadMeshBtn: TButton;
SaveMapBtn: TButton;
MapNumberUpDown: TUpDown;
MapNumberEdit: TEdit;
Label19: TLabel;
MapTypeCmb: TComboBox;
Label1: TLabel;
SaveImgBtn: TButton;
SaveImgDialog: TSaveDialog;
OpenDialog1: TOpenDialog;
Label2: TLabel;
ResetBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(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 FormMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure LoadMeshBtnClick(Sender: TObject);
procedure SaveMapBtnClick(Sender: TObject);
procedure SaveImgBtnClick(Sender: TObject);
procedure FormDblClick(Sender: TObject);
procedure NavigatePnlClick(Sender: TObject);
procedure ResetBtnClick(Sender: TObject);
private
{ Private declarations }
FDragging: Boolean;
FXPosition, FYPosition: Double;
FXAngle, FYAngle, FScale: Double;
FStartMouseX, FStartMouseY: Integer;
FOpenGLHelper: TOpenGLHelper;
FRefreshing: Boolean;
FFaces: TFacesList;
procedure SetWindowCaption(const Msg: String);
function GetHeightMapFileExtension: String;
procedure EnableControls;
public
{ Public declarations }
procedure UpdateMesh(const FacesList: TFacesList); overload;
procedure UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList); overload;
end;
var
HeightMapGenFrm: THeightMapGenFrm;
implementation
uses MeshReader, Maps;
{$R *.dfm}
const
MOVE_SCALE: Double = 0.001;
SIZE_SCALE: Double = 0.01;
ROTATE_SCALE: Double = 0.2;
function THeightMapGenFrm.GetHeightMapFileExtension: String;
begin
case MapTypeCmb.ItemIndex of
0: Result := 'png';
1: Result := 'pgm';
else
raise Exception.Create('Invalid format');
end;
end;
procedure THeightMapGenFrm.SaveImgBtnClick(Sender: TObject);
begin
case MapTypeCmb.ItemIndex of
0: begin
SaveImgDialog.Filter := 'Portable Network Graphic|*.png';
SaveImgDialog.DefaultExt := 'png';
end;
1: begin
SaveImgDialog.Filter := 'Portable Gray Map|*.pgm';
SaveImgDialog.DefaultExt := 'pgm';
end;
else
raise Exception.Create('Invalid format');
end;
SaveImgDialog.InitialDir := GetHeighMapFolder;
if SaveImgDialog.Execute then
FOpenGLHelper.SaveHeightMap(0, 0, ClientWidth, ClientHeight, SaveImgDialog.FileName);
end;
procedure THeightMapGenFrm.SaveMapBtnClick(Sender: TObject);
var
Filename: String;
begin
Filename := MakeHeightMapFilename( MapNumberUpDown.Position, GetHeightMapFileExtension );
if FileExists( Filename ) or ( FindHeightMap( MapNumberUpDown.Position ) <> '' ) then begin
if MessageDlg('This file already exists. Do you really want to overwrite it?', mtConfirmation, mbYesNo, 0) <> mrOK then
exit;
end;
FOpenGLHelper.SaveHeightMap(0, 0, ClientWidth, ClientHeight, Filename);
end;
procedure THeightMapGenFrm.FormCreate(Sender: TObject);
var
I: Integer;
begin
FOpenGLHelper := TOpenGLHelper.Create(Canvas);
FOpenGLHelper.SetWindowCaptionEvent := SetWindowCaption;
FFaces := TFacesList.Create;
MapTypeCmb.Items.Clear;
MapTypeCmb.Items.Add('8 Bit PNG');
MapTypeCmb.Items.Add('16 Bit PGM');
MapTypeCmb.ItemIndex := 1;
I := 1;
while FindHeightMap( I ) <> '' do begin
Inc( I );
end;
MapNumberUpDown.Position := I;
EnableControls;
end;
procedure THeightMapGenFrm.FormDblClick(Sender: TObject);
begin
NavigatePnl.Visible := not NavigatePnl.Visible;
end;
procedure THeightMapGenFrm.FormDestroy(Sender: TObject);
begin
FOpenGLHelper.Free;
FFaces.Free;
end;
procedure THeightMapGenFrm.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 THeightMapGenFrm.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 THeightMapGenFrm.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
end;
procedure THeightMapGenFrm.FormMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
FOpenGLHelper.Scale := FOpenGLHelper.Scale - SIZE_SCALE * 3.0;
end;
procedure THeightMapGenFrm.FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
FOpenGLHelper.Scale := FOpenGLHelper.Scale + SIZE_SCALE * 3.0;
end;
procedure THeightMapGenFrm.FormResize(Sender: TObject);
begin
FOpenGLHelper.AfterResize(ClientWidth, ClientHeight);
end;
procedure THeightMapGenFrm.FormShow(Sender: TObject);
begin
FOpenGLHelper.InitGL;
end;
procedure THeightMapGenFrm.LoadMeshBtnClick(Sender: TObject);
begin
if OpenDialog1.Execute then begin
with TWavefrontObjFileReader.Create do try
LoadFromFile( OpenDialog1.Filename, FFaces);
finally
Free;
end;
FFaces.DoCenter(2.0);
FFaces.DoScale(1,-1.0,1.0);
UpdateMesh( FFaces );
EnableControls;
end;
end;
procedure THeightMapGenFrm.NavigatePnlClick(Sender: TObject);
begin
NavigatePnl.Visible := False;
end;
procedure THeightMapGenFrm.ResetBtnClick(Sender: TObject);
begin
FOpenGLHelper.ResetPosition;
FOpenGLHelper.Scale := HeightMapGenPreview.DFLT_SCALE;
FXPosition := FOpenGLHelper.XPosition;
FYPosition := FOpenGLHelper.YPosition;
FXAngle := FOpenGLHelper.XAngle;
FYAngle := FOpenGLHelper.YAngle;
FScale := FOpenGLHelper.Scale;
end;
procedure THeightMapGenFrm.UpdateMesh(const FacesList: TFacesList);
begin
FOpenGLHelper.UpdateMesh(FacesList);
end;
procedure THeightMapGenFrm.UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList);
begin
FOpenGLHelper.UpdateMesh(VertexList, ColorList);
end;
procedure THeightMapGenFrm.SetWindowCaption(const Msg: String);
begin
Caption := Msg;
end;
procedure THeightMapGenFrm.EnableControls;
begin
SaveMapBtn.Enabled := FFaces.Count > 0;
SaveImgBtn.Enabled := FFaces.Count > 0;
end;
end.
|
unit uMoveMacrosForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, KbdMacro;
type
TMacrosMoveForm = class(TForm)
Label1: TLabel;
FromLabel: TLabel;
FromDevice: TLabel;
ToLabel: TLabel;
ToDevice: TComboBox;
ResultLabel: TLabel;
ResultText: TLabel;
MoveButton: TButton;
CancelButton: TButton;
OKButton: TButton;
procedure MoveButtonClick(Sender: TObject);
private
{ Private declarations }
fSourceDev: THIDKeyboard;
procedure SetSourceDev(const Value: THIDKeyboard);
public
{ Public declarations }
property SourceDev: THIDKeyboard read fSourceDev write SetSourceDev;
end;
implementation
uses uGlobals;
{$R *.dfm}
{ TMacrosMoveForm }
procedure TMacrosMoveForm.MoveButtonClick(Sender: TObject);
var
lMoved, lNotMoved: Integer;
begin
if ToDevice.ItemIndex >= 0 then
begin
Glb.MacrosList.MoveFromTo(fSourceDev,
THIDKeyboard(ToDevice.Items.Objects[ToDevice.ItemIndex]),
lMoved, lNotMoved);
if lNotMoved = 0 then
if lMoved = 0 then
ResultText.Caption := 'No macros found.'
else
ResultText.Caption := Format('All %d macros were moved.', [lMoved])
else
ResultText.Caption := Format('Out of %d existing macros %d were moved. ' +
'Remaining %d macros can not be moved because same trigger is already used on target device.',
[lMoved + lNotMoved, lMoved, lNotMoved]);
MoveButton.Visible := False;
CancelButton.Visible := False;
OKButton.Visible := True;
end;
end;
procedure TMacrosMoveForm.SetSourceDev(const Value: THIDKeyboard);
var
I: Integer;
begin
fSourceDev := Value;
ToDevice.Items.Clear;
for I := 0 to Glb.HIDControl.Count - 1 do
if (Value.ClassType = Glb.HIDControl.Items[i].ClassType) and
(Value <> Glb.HIDControl.Items[i]) then
ToDevice.Items.AddObject(Glb.HIDControl.Items[i].Name, Glb.HIDControl.Items[i]);
FromDevice.Caption := Value.Name;
ToDevice.ItemIndex := 0;
end;
end.
|
unit PlayerSessionStorage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Fgl, dmxPlayer;
const
PLAYER_DATE_FORMAT = 'YYYY-MM-DD HH:MM:SS';
type
TPlayerFileInfo = packed record
Size: Int64;
CreatedAt: TDateTime;
end;
{ TPlayerPoint }
TPlayerPoint = packed record
rn: Integer;
lat, lon: Double;
time: TDateTime;
course, speed: Double;
ptype: String;
end;
TPlayerFileList = specialize TFPGMap<String, TPlayerFileInfo>;
TPlayerPointArray = array of TPlayerPoint;
{ TPlayerSessionStorage }
TPlayerSessionStorage = class
private
FDataFile: String;
procedure PrepareDataModule;
procedure PrepareDatabase;
public
constructor Create(ADataFile: String); virtual;
procedure AddSession(const ASessionId, crc32: String;
Files: TPlayerFileList);
procedure AddPoints(const SessionId: String; const TrackRn: Integer;
Points: TPlayerPointArray);
procedure FinalizeSession(const ASessionID: String);
function FindSession(const crc32: String; const FilesCount: Integer): String;
procedure GenerateGpx(const ASessionId: String);
end;
procedure LoadTextFromResource(AList: TStrings; const ResourceName: String);
operator = (A, B: TPlayerPoint) R: Boolean;
implementation
uses
db, sqlite3, Forms, PlayerOptions, PlayerGPX;
{$R sql.rc}
operator=(A, B: TPlayerPoint)R: Boolean;
begin
R:=(A.ptype = B.ptype) and (A.lon = B.lon) and (A.lat = B.lat) and
(A.course = B.course) and (A.speed = B.speed) and (A.time = B.time);
end;
procedure LoadTextFromResource(AList: TStrings;
const ResourceName: String);
var
ResourceStream: TResourceStream;
begin
ResourceStream:=TResourceStream.Create(HInstance, ResourceName, RT_RCDATA);
try
AList.LoadFromStream(ResourceStream);
finally
ResourceStream.Free;
end;
end;
{ TPlayerSessionStorage }
procedure TPlayerSessionStorage.PrepareDataModule;
begin
dmPlayer.Connection.DatabaseName:=FDataFile;
try
dmPlayer.Connection.Open;
except
if FileExists(FDataFile) then DeleteFile(FDataFile);
end;
with dmPlayer do
begin
if not Connection.Connected then Connection.Open;
PrepareDatabase;
end;
end;
procedure TPlayerSessionStorage.PrepareDatabase;
begin
with dmPlayer do
begin
// TODO: Connection.LoadConnection fails?
sqlite3_enable_load_extension(Connection.Handle, 1);
sqlite3_load_extension(Connection.Handle, 'sqlite/libsqlitefunctions.so', nil, nil);
Script.Script.Clear;
LoadTextFromResource(Script.Script, 'DB');
Script.Execute;
Transaction.Commit;
end;
end;
constructor TPlayerSessionStorage.Create(ADataFile: String);
begin
inherited Create;
FDataFile:=ADataFile;
if dmPlayer = nil then dmPlayer:=TdmPlayer.Create(Application);
PrepareDataModule;
end;
procedure TPlayerSessionStorage.AddSession(const ASessionId, crc32: String;
Files: TPlayerFileList);
var
Index: Integer;
begin
with dmPlayer do
begin
Script.Script.Clear;
Script.Script.Add('insert into sessions(id, cc, crc32) values(%s, %d, %s);',
[QuotedStr(ASessionId), Files.Count, QuotedStr(crc32)]);
for Index:=0 to Files.Count - 1 do
Script.Script.Add('insert into tracks(session_id, rn, filename, ' +
'created_at, size) values(%s, %d, %s, %s, %d);',
[QuotedStr(ASessionId), Index + 1,
QuotedStr(Files.Keys[Index]),
QuotedStr(FormatDateTime(PLAYER_DATE_FORMAT, Files.Data[Index].CreatedAt)),
Files.Data[Index].Size]);
Script.Execute;
Transaction.Commit;
end;
end;
procedure TPlayerSessionStorage.AddPoints(const SessionId: String;
const TrackRn: Integer; Points: TPlayerPointArray);
var
TrackId: Integer;
Point: TPlayerPoint;
begin
if Length(Points) = 0 then Exit;
with dmPlayer do
begin
Query.SQL.Text:=Format(
'select rowid id from tracks where session_id = %s and rn = %d limit 1',
[QuotedStr(SessionId), TrackRn + 1]
);
Query.Open;
if Query.EOF then
raise Exception.CreateFmt('no track for %s, %d', [SessionId, TrackRn]);
TrackId:=Query.FieldByName('id').AsInteger;
Query.Close;
Script.Script.Clear;
for Point in Points do
Script.Script.Add(
'insert into points(track_id, rn, lat, lon, time, course, speed, type) ' +
'values(%d, %d, %.6n, %.6n, %s, %n, %n, %s);', [TrackId,
Point.rn,
Point.lat,
Point.lon,
QuotedStr(FormatDateTime(PLAYER_DATE_FORMAT, Point.time)),
Point.course,
Point.speed, QuotedStr(Point.ptype)]);
Script.Execute;
Transaction.Commit;
end;
end;
function TPlayerSessionStorage.FindSession(const crc32: String;
const FilesCount: Integer): String;
begin
Result:='';
with dmPlayer do
try
Query.SQL.Text:=Format('select id from sessions where crc32 = %s ' +
'and cc = %d and loaded = 1 limit 1', [QuotedStr(crc32), FilesCount]);
Query.Open;
if not Query.EOF then Result:=Query.FieldByName('id').AsString;
finally
Query.Close;
end;
end;
procedure TPlayerSessionStorage.GenerateGpx(const ASessionId: String);
var
GpxFileName: String;
Id: Integer;
begin
with dmPlayer do
begin
Query.SQL.Text:='select rowid, gpx from trips where session_id = :session_id';
Query.UpdateSQL.Text:='update trips set gpx = :gpx where rowid = :rowid;';
Query.ParamByName('session_id').AsString:=ASessionID;
Query.Open;
try
while not Query.EOF do
begin
Id:=Query.FieldByName('rowid').AsInteger;
GpxFileName:=IncludeTrailingPathDelimiter(opts.TempDir + ASessionId) +
Format('trip_%d.gpx', [Id]);
with TPlayerGPX.Create(Id, GpxFileName) do
try
Convert;
Query.Edit;
(Query.FieldByName('gpx') as TBlobField).LoadFromFile(GpxFileName);
Query.Post;
Query.ApplyUpdates;
finally
Free;
end;
Query.Next;
end;
Transaction.Commit;
finally
Query.Close;
end;
end;
end;
procedure TPlayerSessionStorage.FinalizeSession(const ASessionID: String);
var
SQL: TStringArray;
Index: Integer;
begin
with dmPlayer do
begin
LoadTextFromResource(Query.SQL, 'TRIPS');
SQL:=Query.SQL.Text.Split(';');
for Index:=0 to High(SQL) do
begin
if SQL[Index].Trim = '' then Continue;
Query.SQL.Text:=SQL[Index];
if Index = 0 then
Query.ParamByName('session_id').AsString:=ASessionID;
Query.ExecSQL;
end;
Script.Script.Text:=Format('update sessions set loaded = 1 where id = %s;',
[QuotedStr(ASessionID)]);
Script.Execute;
Transaction.Commit;
end;
end;
end.
|
unit NtUtils.Processes;
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntpsapi, NtUtils.Exceptions, NtUtils.Objects;
const
// Ntapi.ntpsapi
NtCurrentProcess: THandle = THandle(-1);
type
TProcessHandleEntry = Ntapi.ntpsapi.TProcessHandleTableEntryInfo;
// Open a process (always succeeds for the current PID)
function NtxOpenProcess(out hxProcess: IHandle; PID: NativeUInt;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
// Reopen a handle to the current process with the specific access
function NtxOpenCurrentProcess(out hxProcess: IHandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
// Query variable-size information
function NtxQueryProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
out xMemory: IMemory): TNtxStatus;
// Set variable-size information
function NtxSetProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
Data: Pointer; DataSize: Cardinal): TNtxStatus;
type
NtxProcess = class
// Query fixed-size information
class function Query<T>(hProcess: THandle;
InfoClass: TProcessInfoClass; out Buffer: T): TNtxStatus; static;
// Set fixed-size information
class function SetInfo<T>(hProcess: THandle;
InfoClass: TProcessInfoClass; const Buffer: T): TNtxStatus; static;
end;
// Query a string
function NtxQueryStringProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
out Str: String): TNtxStatus;
// Try to query image name in Win32 format
function NtxTryQueryImageProcessById(PID: NativeUInt): String;
// Suspend/resume a process
function NtxSuspendProcess(hProcess: THandle): TNtxStatus;
function NtxResumeProcess(hProcess: THandle): TNtxStatus;
// Terminate a process
function NtxTerminateProcess(hProcess: THandle; ExitCode: NTSTATUS): TNtxStatus;
{$IFDEF Win32}
// Fail if the current process is running under WoW64
// NOTE: you don't run under WoW64 if you are compiled as Win64
function RtlxAssertNotWoW64(out Status: TNtxStatus): Boolean;
{$ENDIF}
// Query if a process runs under WoW64
function NtxQueryIsWoW64Process(hProcess: THandle; out WoW64: Boolean):
TNtxStatus;
// Check if the target if WoW64. Fail, if it isn't while we are.
function RtlxAssertWoW64Compatible(hProcess: THandle;
out TargetIsWoW64: Boolean): TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntobapi, Ntapi.ntseapi, Ntapi.ntpebteb,
NtUtils.Access.Expected;
function NtxOpenProcess(out hxProcess: IHandle; PID: NativeUInt;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus;
var
hProcess: THandle;
ClientId: TClientId;
ObjAttr: TObjectAttributes;
begin
if PID = NtCurrentProcessId then
begin
hxProcess := TAutoHandle.Capture(NtCurrentProcess);
Result.Status := STATUS_SUCCESS;
end
else
begin
InitializeObjectAttributes(ObjAttr, nil, HandleAttributes);
ClientId.Create(PID, 0);
Result.Location := 'NtOpenProcess';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @ProcessAccessType;
Result.Status := NtOpenProcess(hProcess, DesiredAccess, ObjAttr, ClientId);
if Result.IsSuccess then
hxProcess := TAutoHandle.Capture(hProcess);
end;
end;
function NtxOpenCurrentProcess(out hxProcess: IHandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus;
var
hProcess: THandle;
Flags: Cardinal;
begin
// Duplicating the pseudo-handle is more reliable then opening process by PID
if DesiredAccess and MAXIMUM_ALLOWED <> 0 then
begin
Flags := DUPLICATE_SAME_ACCESS;
DesiredAccess := 0;
end
else
Flags := 0;
Result.Location := 'NtDuplicateObject';
Result.Status := NtDuplicateObject(NtCurrentProcess, NtCurrentProcess,
NtCurrentProcess, hProcess, DesiredAccess, HandleAttributes, Flags);
if Result.IsSuccess then
hxProcess := TAutoHandle.Capture(hProcess);
end;
function NtxQueryProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
out xMemory: IMemory): TNtxStatus;
var
Buffer: Pointer;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtQueryInformationProcess';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TProcessInfoClass);
RtlxComputeProcessQueryAccess(Result.LastCall, InfoClass);
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtQueryInformationProcess(hProcess, InfoClass, Buffer,
BufferSize, @Required);
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if Result.IsSuccess then
xMemory := TAutoMemory.Capture(Buffer, BufferSize);
end;
function NtxSetProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
Data: Pointer; DataSize: Cardinal): TNtxStatus;
begin
Result.Location := 'NtSetInformationProcess';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TProcessInfoClass);
RtlxComputeProcessSetAccess(Result.LastCall, InfoClass);
Result.Status := NtSetInformationProcess(hProcess, InfoClass, Data, DataSize);
end;
class function NtxProcess.Query<T>(hProcess: THandle;
InfoClass: TProcessInfoClass; out Buffer: T): TNtxStatus;
begin
Result.Location := 'NtQueryInformationProcess';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TProcessInfoClass);
RtlxComputeProcessQueryAccess(Result.LastCall, InfoClass);
Result.Status := NtQueryInformationProcess(hProcess, InfoClass, @Buffer,
SizeOf(Buffer), nil);
end;
class function NtxProcess.SetInfo<T>(hProcess: THandle;
InfoClass: TProcessInfoClass; const Buffer: T): TNtxStatus;
begin
Result := NtxSetProcess(hProcess, InfoClass, @Buffer, SizeOf(Buffer));
end;
function NtxQueryStringProcess(hProcess: THandle; InfoClass: TProcessInfoClass;
out Str: String): TNtxStatus;
var
xMemory: IMemory;
begin
case InfoClass of
ProcessImageFileName, ProcessImageFileNameWin32,
ProcessCommandLineInformation:
begin
Result := NtxQueryProcess(hProcess, InfoClass, xMemory);
if Result.IsSuccess then
Str := PUNICODE_STRING(xMemory.Address).ToString;
end;
else
Result.Location := 'NtxQueryStringProcess';
Result.Status := STATUS_INVALID_INFO_CLASS;
Exit;
end;
end;
function NtxTryQueryImageProcessById(PID: NativeUInt): String;
var
hxProcess: IHandle;
begin
Result := '';
if not NtxOpenProcess(hxProcess, PID, PROCESS_QUERY_LIMITED_INFORMATION
).IsSuccess then
Exit;
NtxQueryStringProcess(hxProcess.Handle, ProcessImageFileNameWin32, Result);
end;
function NtxSuspendProcess(hProcess: THandle): TNtxStatus;
begin
Result.Location := 'NtSuspendProcess';
Result.LastCall.Expects(PROCESS_SUSPEND_RESUME, @ProcessAccessType);
Result.Status := NtSuspendProcess(hProcess);
end;
function NtxResumeProcess(hProcess: THandle): TNtxStatus;
begin
Result.Location := 'NtResumeProcess';
Result.LastCall.Expects(PROCESS_SUSPEND_RESUME, @ProcessAccessType);
Result.Status := NtResumeProcess(hProcess);
end;
function NtxTerminateProcess(hProcess: THandle; ExitCode: NTSTATUS): TNtxStatus;
begin
Result.Location := 'NtResumeProcesNtTerminateProcesss';
Result.LastCall.Expects(PROCESS_TERMINATE, @ProcessAccessType);
Result.Status := NtTerminateProcess(hProcess, ExitCode);
end;
{$IFDEF Win32}
function RtlxAssertNotWoW64(out Status: TNtxStatus): Boolean;
begin
Result := RtlIsWoW64;
if Result then
begin
Status.Location := '[WoW64 check]';
Status.Status := STATUS_ASSERTION_FAILURE;
end;
end;
{$ENDIF}
function NtxQueryIsWoW64Process(hProcess: THandle; out WoW64: Boolean):
TNtxStatus;
var
WoW64Peb: Pointer;
begin
Result := NtxProcess.Query(hProcess, ProcessWow64Information, WoW64Peb);
if Result.IsSuccess then
WoW64 := Assigned(WoW64Peb);
end;
function RtlxAssertWoW64Compatible(hProcess: THandle;
out TargetIsWoW64: Boolean): TNtxStatus;
begin
// Check if the target is a WoW64 process
Result := NtxQueryIsWoW64Process(hProcess, TargetIsWoW64);
{$IFDEF Win32}
// Prevent WoW64 -> Native access scenarious
if Result.IsSuccess and not TargetIsWoW64 then
RtlxAssertNotWoW64(Result);
{$ENDIF}
end;
end.
|
unit Legend;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, StrUtils;
type
TLegendForm = class(TForm)
btn_Print: TBitBtn;
btn_cancel: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure btn_PrintClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
LegendForm: TLegendForm;
implementation
uses MainDM, public_unit;
{$R *.dfm}
procedure TLegendForm.FormCreate(Sender: TObject);
begin
self.Left := trunc((screen.Width -self.Width)/2);
self.Top := trunc((Screen.Height - self.Height)/2);
end;
procedure TLegendForm.btn_PrintClick(Sender: TObject);
var
strFileName, strL_names, strSQL, stra_no,sub_no,drl_no,drl_elev: string;
SptRealNum : string; //标准贯入的实测击数
FileList: TStringList;
begin
if g_ProjectInfo.prj_no ='' then exit;
FileList := TStringList.Create;
strFileName:= g_AppInfo.PathOfChartFile + 'legend.ini';
try
FileList.Add('[图纸信息]');
FileList.Add('保存用文件名=图例图');
FileList.Add('[图例]');
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
FileList.Add('图纸名称='+g_ProjectInfo.prj_name+'图例图')
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
FileList.Add('图纸名称='+g_ProjectInfo.prj_name_en+' Legend');
FileList.Add('工程编号='+g_ProjectInfo.prj_no);
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
FileList.Add('工程名称='+g_ProjectInfo.prj_name)
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
FileList.Add('工程名称='+g_ProjectInfo.prj_name_en) ;
//开始加入剖面图图例
strL_names:='';
//取得当前工程的土的图例
strSQL:='select et.ea_name,ISNULL(et.ea_name_en,'''') as ea_name_en'
+' from earthtype et'
+' inner join (select DISTINCT ea_name from stratum_description'
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''') as sd'
+' on sd.ea_name=et.ea_name';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
strL_names:= strL_names + FieldByName('ea_name').AsString;
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names
+ REPORT_PRINT_SPLIT_CHAR
+ FieldByName('ea_name_en').AsString;
strL_names:= strL_names + ',';
next;
end;
close;
end;
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
FileList.Add('剖面图图例='+ strL_names);
strL_names := '';
strL_names:= strL_names + '静探曲线';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'The Curve of CPT';
strL_names:= strL_names + ',';
strL_names:= strL_names + '标准贯入';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'Position of samples and SPT blows';
strL_names:= strL_names + ',';
strL_names:= strL_names + '土层编号';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'Strata No.';
strL_names:= strL_names + ',';
strL_names:= strL_names + '水位线';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'Groud_water level';
strL_names:= strL_names + ',';
strL_names:= strL_names + '孔号标高';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'Boring No. and elevation';
strL_names:= strL_names + ',';
strL_names:= strL_names + '地层界线推测地层界线';
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
strL_names:= strL_names + REPORT_PRINT_SPLIT_CHAR + 'Strata boundary Presumed strata boundary';
strL_names:= strL_names + ',';
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
FileList.Add('平面图图例='+ strL_names); //
//实际上这是剖面图的,只是为了CAD程序不要改动,把上面这些固定的写到平面图图例中
//取得当前工程的一个土层编号
strSQL:='SELECT top 1 stra_no,sub_no from stratum_description'
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' ORDER BY id';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
if not eof then
begin
stra_no:= FieldByName('stra_no').AsString;
sub_no := FieldByName('sub_no').AsString;
if sub_no<>'0' then
stra_no:= stra_no + REPORT_PRINT_SPLIT_CHAR + sub_no;
end;
close;
end;
FileList.Add('土层编号='+ stra_no);
//取得当前工程的第一个剖面的第一个孔号和标高
strSQL:='SELECT drl_no,drl_elev FROM drills WHERE '
+' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND drl_no = (SELECT top 1 drl_no FROM section_drill WHERE '
+' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no=(SELECT MIN(sec_no) FROM section WHERE '
+' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL +''''+') ORDER BY id)';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
if not eof then
begin
drl_no := FieldByName('drl_no').AsString;
drl_elev := FormatFloat('0.00',FieldByName('drl_elev').AsFloat);
end;
close;
end;
if drl_no='' then
begin
drl_no := 'C1';
drl_elev:='2.34';
end;
FileList.Add('孔号标高='+ drl_no+REPORT_PRINT_SPLIT_CHAR+drl_elev);
//取得当前工程的标准贯入的一个值,如果没有,不要写入文件
strSQL:='SELECT top 1 real_num1+real_num2+real_num3 as real_num '
+' FROM SPT '
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +'''';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
if not eof then
begin
SptRealNum := FormatFloat('0',FieldByName('real_num').AsFloat);
end;
close;
end;
FileList.Add('标准贯入='+ SptRealNum);
FileList.SaveToFile(strFileName);
finally
FileList.Free;
end;
winexec(pAnsichar(getCadExcuteName+' '+PrintChart_Legend+','+strFileName+ ','
+ REPORT_PRINT_SPLIT_CHAR),sw_normal);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.