text stringlengths 14 6.51M |
|---|
unit langunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, regexpr, inifileunit;
procedure SetLanguage(langSetting: string = 'zh_cn'; force: Boolean = False; dir: string = '');
procedure LoadLang(langSetting: string = 'zh_cn'; dir: string = '');
function GetLang(key: string; defaultValue: string = ''): string;overload;
function GetLang(section: string; key: string; defaultValue: string): string;overload;
procedure setConfigFileForLang(configFile: TIniFile);
const
LANG_DIR = 'languages';
var
lang : TStringList;
language : string;
langName : string;
langDir : string;
_configFile : TIniFile;
implementation
procedure setConfigFileForLang(configFile: TIniFile);
begin
_configFile := configFile;
end;
procedure SetLanguage(langSetting: string = 'zh_cn'; force: Boolean = False; dir: string = '');
begin
if dir <> '' then langDir := dir + LANG_DIR;
if (langSetting <> language) or force then begin
LoadLang(langSetting);
end;
end;
procedure LoadLang(langSetting: string = 'zh_cn'; dir: string = '');
var
langFile : TStringList;
i : integer;
line, section : string;
sectionRegex, nameValueRegex : TRegExpr;
begin
language := langSetting;
if not Assigned(lang) then begin
lang := TStringList.Create;
lang.Sorted := True;
lang.Duplicates := dupIgnore;
end;
langFile := TStringList.Create;
try
langFile.LoadFromFile(langDir + '/' + language + '.ini');
if langFile.Count > 0 then begin
lang.Clear;
sectionRegex := TRegExpr.Create;
sectionRegex.Expression := '\[(.+)\]';
nameValueRegex := TRegExpr.Create;
nameValueRegex.Expression := '([\w/]+)\s*=\s*(.*)';
section := '';
for i := 0 to (langFile.Count - 1) do
begin
line := Trim(langFile[i]);
if Pos(';', line) = 1 then continue;
if sectionRegex.Exec(line) then begin
section := sectionRegex.Match[1];
end else if nameValueRegex.Exec(line) then begin
lang.Values[section + '/' + nameValueRegex.Match[1]] := nameValueRegex.Match[2];
end;
end;
sectionRegex.Free;
nameValueRegex.Free;
end;
finally
langFile.Free;
end;
langName := GetLang('lang/name', langSetting);
end;
function GetLang(key: string; defaultValue: string = ''): string;overload;
begin
if _configFile <> nil then begin
Result := _configFile.get('lang/' + language + '/' + key, '');
end;
if Result = '' then Result := lang.Values[key];
if Result = '' then Result := defaultValue;
end;
function GetLang(section: string; key: string; defaultValue: string): string;overload;
begin
Result := GetLang(section + '/' + key, defaultValue);
end;
end.
|
unit Chatmain;
interface
uses
Classes, QControls, QStdCtrls, QExtCtrls, QButtons, QForms, Sockets;
type
TForm1 = class(TForm)
memRecv: TMemo;
Panel1: TPanel;
memSend: TMemo;
Panel2: TPanel;
btnSend: TButton;
Panel3: TPanel;
Label1: TLabel;
edtRemoteHost: TEdit;
Label2: TLabel;
edtRemotePort: TEdit;
Label3: TLabel;
edtLocalPort: TEdit;
btnActivateServer: TButton;
TcpClient1: TTcpClient;
TcpServer1: TTcpServer;
procedure btnSendClick(Sender: TObject);
procedure TcpServer1Accept(sender: TObject;
ClientSocket: TCustomIpClient);
procedure btnActivateServerClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
// you must create your own thread to synch
// writing to a gui component
TClientDataThread = class(TThread)
private
public
ListBuffer :TStringList;
TargetList :TStrings;
procedure synchAddDataToControl;
constructor Create(CreateSuspended: Boolean);
procedure Execute; override;
procedure Terminate;
end;
var
Form1: TForm1;
//DataThread: TClientDataThread;
implementation
{$R *.xfm}
//------------- TClientDataThread impl -----------------------------------------
constructor TClientDataThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := true;
ListBuffer := TStringList.Create;
end;
procedure TClientDataThread.Terminate;
begin
ListBuffer.Free;
inherited;
end;
procedure TClientDataThread.Execute;
begin
Synchronize(synchAddDataToControl);
end;
procedure TClientDataThread.synchAddDataToControl;
begin
TargetList.AddStrings(ListBuffer);
end;
//------------- end TClientDataThread impl -------------------------------------
procedure TForm1.btnActivateServerClick(Sender: TObject);
begin
TcpServer1.LocalPort := edtLocalPort.Text;
TcpServer1.Active := True;
end;
procedure TForm1.btnSendClick(Sender: TObject);
var
I: Integer;
begin
TcpClient1.RemoteHost := edtRemoteHost.Text;
TcpClient1.RemotePort := edtRemotePort.Text;
try
if TcpClient1.Connect then
for I := 0 to memSend.Lines.Count - 1 do
TcpClient1.Sendln(memSend.Lines[I]);
finally
TcpClient1.Disconnect;
end;
end;
procedure TForm1.TcpServer1Accept(sender: TObject;
ClientSocket: TCustomIpClient);
var
s: string;
DataThread: TClientDataThread;
begin
// create thread
DataThread:= TClientDataThread.Create(true);
// set the TagetList to the gui list that you
// with to synch with.
DataThread.TargetList := memRecv.lines;
// Load the Threads ListBuffer
DataThread.ListBuffer.Add('*** Connection Accepted ***');
DataThread.ListBuffer.Add('Remote Host: ' + ClientSocket.LookupHostName(ClientSocket.RemoteHost) +
' (' + ClientSocket.RemoteHost + ')');
DataThread.ListBuffer.Add('===== Begin message =====');
s := ClientSocket.Receiveln;
while s <> '' do
begin
DataThread.ListBuffer.Add(s);
s := ClientSocket.Receiveln;
end;
DataThread.ListBuffer.Add('===== End of message =====');
// Call Resume which will execute and synch the
// ListBuffer with the TargetList
DataThread.Resume;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Datasnap.DSProxyCppRest"'} {Do not Localize}
unit Datasnap.DSProxyCppRest;
interface
uses System.Classes, Datasnap.DSProxyWriter, Datasnap.DSCommonProxy, Datasnap.DSProxyDelphiRest;
type
TDSClientProxyWriterCppRest = class(TDSProxyWriter)
public
function CreateProxyWriter: TDSCustomProxyWriter; override;
function Properties: TDSProxyWriterProperties; override;
function FileDescriptions: TDSProxyFileDescriptions; override;
end;
TDSCustomCppRestProxyWriter = class abstract(TDSCustomNativeRestProxyWriter)
public
constructor Create;
procedure WriteProxy; override;
protected
FUnitName: string;
function CanMarshal: Boolean; override;
procedure StartCppHeader; virtual; abstract;
procedure EndCppHeader; virtual; abstract;
procedure WriteFileHeader; override;
function GetDelphiTypeName(const Param: TDSProxyParameter): UnicodeString; override;
procedure WriteInterface; override;
procedure WriteImplementation; override;
function GetAssignmentString: UnicodeString; override;
function GetCreateDataSetReader(const Param: TDSProxyParameter): UnicodeString; override;
function GetCreateParamsReader(const Param: TDSProxyParameter): UnicodeString; override;
function IncludeMethod(const ProxyMethod: TDSProxyMethod): Boolean; override;
private
procedure WriteHeaderUses;
procedure WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean;
AOptions: TNativeRestProxyWriterOptions);
procedure WriteClassInterface(const ProxyClass: TDSProxyClass);
procedure WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions = []);
procedure WriteOutgoingParameter(const Lhs: UnicodeString; const InRhs: UnicodeString; const Param: TDSProxyParameter; const CommandName: UnicodeString; const ParamName: UnicodeString);
procedure WriteClassImplementation(const ProxyClass: TDSProxyClass);
procedure WriteTDSRestParameterMetaData;
procedure WriteClassTDSRestParameterMetaData(ProxyClass: TDSProxyClass);
procedure WriteMethodTDSRestParameterMetaData(ProxyClass: TDSProxyClass;
Method: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions = []);
function MakeTDSRestParameterMetaDataTypeName(ProxyClass: TDSProxyClass;
Method: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions = []): string;
procedure GetHTTPMethodAndPrefix(Method: TDSProxyMethod;
out AServerMethodPrefix, AHTTPMethodName: string);
function GetCacheValueInterfaceTypeName(
const ACachedValueClassName: string): string;
end;
TDSCppRestProxyWriter = class(TDSCustomCppRestProxyWriter)
private
FStreamWriter: TStreamWriter;
FHeaderStreamWriter: TStreamWriter;
FWritingHeader: Boolean;
protected
procedure DerivedWrite(const Line: UnicodeString); override;
procedure DerivedWriteLine; override;
procedure StartCppHeader; override;
procedure EndCppHeader; override;
public
property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter;
property HeaderStreamWriter: TStreamWriter read FHeaderStreamWriter write FHeaderStreamWriter;
destructor Destroy; override;
end;
const
sCPlusPlusBuilderRestProxyWriter = 'C++Builder REST';
implementation
uses Data.DBXCommon, System.StrUtils, System.SysUtils;
function TDSCustomCppRestProxyWriter.CanMarshal: Boolean;
begin
Result := False; // Can't marshal TCustomer as TJSONValue
end;
constructor TDSCustomCppRestProxyWriter.Create;
begin
inherited Create;
FIndentIncrement := 2;
FIndentString := '';
FUnitName := ChangeFileExt(ExtractFileName(FUnitFileName), '');
end;
procedure TDSCustomCppRestProxyWriter.WriteProxy;
begin
FUnitName := ChangeFileExt(ExtractFileName(FUnitFileName), '');
inherited;
end;
procedure TDSCustomCppRestProxyWriter.WriteFileHeader;
begin
inherited WriteFileHeader;
WriteLine('#include "' + FUnitName + '.h"');
WriteLine;
WriteTDSRestParameterMetaData;
end;
function TDSCustomCppRestProxyWriter. GetCacheValueInterfaceTypeName(const ACachedValueClassName: string): string;
begin
Result := '_di_I' + ACachedValueClassName;
end;
function TDSCustomCppRestProxyWriter.GetDelphiTypeName(const Param: TDSProxyParameter): UnicodeString;
var
Name: UnicodeString;
begin
Name := Param.TypeName;
if SameText(Name, 'string') then
Result := 'System::UnicodeString'
else if Name = 'WideString' then
Result := 'System::WideString'
else if Name = 'WideString' then
Result := 'System::WideString'
else if Name = 'AnsiString' then
Result := 'System::AnsiString'
else if Name = 'TDateTime' then
Result := 'System::TDateTime'
else if Name = 'Currency' then
Result := 'System::Currency'
else if Name = 'ShortInt' then
Result := 'System::ShortInt' // 'signed char'
else if Name = 'Byte' then
Result := 'System::Byte' // 'unsigned char'
else if Name = 'OleVariant' then
Result := 'System::OleVariant'
else if Name = 'TDBXTime' then
Result := 'Dbxcommon::TDBXTime'
else if Name = 'TDBXDate' then
Result := 'Dbxcommon::TDBXDate'
else if Name = 'SmallInt' then
Result := 'short'
else if Name = 'Boolean' then
Result := 'bool'
else if Name = 'Int64' then
Result := '__int64'
else if Name = 'Single' then
Result := 'float'
else if Name = 'Double' then
Result := 'double'
else if Name = 'Integer' then
Result := 'int'
else if Name = 'Word' then
Result := 'unsigned short'
else if Name = 'TDBXReader' then
Result := 'TDBXReader*'
else if Name = 'TDBXConnection' then
Result := 'TDBXConnection*'
else if (not CanMarshal) and (Param.DataType = TDBXDataTypes.JsonValueType) and (not IsKnownJSONTypeName(Name)) then
Result := 'TJSONObject*'
else
Result := inherited GetDelphiTypeName(Param) + '*';
end;
procedure TDSCustomCppRestProxyWriter.WriteHeaderUses;
begin
WriteLine('#include "DBXCommon.hpp"');
WriteLine('#include "Classes.hpp"');
WriteLine('#include "SysUtils.hpp"');
WriteLine('#include "DB.hpp"');
WriteLine('#include "SqlExpr.hpp"');
WriteLine('#include "DBXDBReaders.hpp"');
WriteLine('#include "DSProxyRest.hpp"');
end;
procedure TDSCustomCppRestProxyWriter.WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean;
AOptions: TNativeRestProxyWriterOptions);
var
Line: UnicodeString;
ParamCount: Integer;
ProcessedCount: Integer;
Parameters: TDSProxyParameter;
Param: TDSProxyParameter;
LDelphiTypeName: string;
LIsPointer: Boolean;
LSupportsRequestFilter: Boolean;
LRequestFilter: string;
LCachedValueClassName: string;
begin
Parameters := Method.Parameters;
ParamCount := Method.ParameterCount;
if Method.HasReturnValue then
begin
ParamCount := ParamCount - 1;
Param := Method.ReturnParameter;
Line := GetDelphiTypeName(Param) + ' ';
if (optCacheParameters in AOptions) and IsCachableParameter(Param, LCachedValueClassName) then
Line := GetCacheValueInterfaceTypeName(LCachedValueClassName) + ' '
else
Line := GetDelphiTypeName(Param) + ' ';
end
else
Line := 'void ';
Line := Line + '__fastcall ';
if IsInterface then
Line := Line + Method.ProxyMethodName
else
Line := Line + ProxyClass.ProxyClassName + 'Client::' + Method.ProxyMethodName;
if optCacheParameters in AOptions then
Line := Line + '_Cache';
LSupportsRequestFilter := SupportsRequestFilter(Method);
if LSupportsRequestFilter then
if IsInterface then
LRequestFilter := 'const String& ARequestFilter = String()'
else
LRequestFilter := 'const String& ARequestFilter';
if ParamCount > 0 then
begin
Line := Line + '(';
Param := Parameters;
ProcessedCount := 0;
while (Param <> nil) and (ProcessedCount < ParamCount) do
begin
if (Param.ParameterDirection = TDBXParameterDirections.OutParameter) and
(optCacheParameters in AOptions) and IsCachableParameter(Param, LCachedValueClassName) then
begin
//Line := Line + 'out ' + Param.ParameterName + ': I' + LCachedValueClassName;
Line := Line + GetCacheValueInterfaceTypeName(LCachedValueClassName) + ' &' + Param.ParameterName;
end
else
begin
LDelphiTypeName := GetDelphiTypeName(Param);
LIsPointer := LDelphiTypeName[Length(LDelphiTypeName)] = '*';
Line := Line + LDelphiTypeName + ' ';
if not LIsPointer then
case Param.ParameterDirection of
TDBXParameterDirections.OutParameter:
Line := Line + ' &';
TDBXParameterDirections.InOutParameter:
if not IsKnownDBXValueTypeName(Param.TypeName) then
if not ((optCacheParameters in AOptions) and IsCachableParameter(Param, LCachedValueClassName)) then
Line := Line + ' &';
end;
Line := Line + Param.ParameterName;
if (optCacheParameters in AOptions) and IsCachableParameter(Param, LCachedValueClassName) and
(Param.ParameterDirection = TDBXParameterDirections.InOutParameter) then
begin
Line := Line + ', ';
//Line := Line + 'out ' + Param.ParameterName + '_Cache: I' + LCachedValueClassName;
Line := Line + GetCacheValueInterfaceTypeName(LCachedValueClassName) +
' &' + Param.ParameterName + '_Cache';
end;
end;
ProcessedCount := ProcessedCount + 1;
if (ProcessedCount) < ParamCount then
Line := Line + ', ';
Param := Param.Next;
end;
if LSupportsRequestFilter then
begin
if ProcessedCount > 0 then
Line := Line + ', ';
Line := Line + LRequestFilter;
end;
Line := Line + ')';
end
else
begin
if LSupportsRequestFilter then
Line := Line + '(' + LRequestFilter + ')'
else
Line := Line + '()';
end;
if IsInterface then
Line := Line + ';';
WriteLine(Line);
end;
procedure TDSCustomCppRestProxyWriter.WriteClassInterface(const ProxyClass: TDSProxyClass);
var
Methods: TDSProxyMethod;
ClassName: UnicodeString;
LAncestor: string;
begin
LAncestor := GetAncestor(ProxyClass);
ClassName := ProxyClass.ProxyClassName + 'Client';
Indent;
WriteLine('class ' + ClassName + ' : public ' + LAncestor);
WriteLine('{');
WriteLine('private:');
Indent;
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteLine('TDSRestCommand *F' + Methods.ProxyMethodName + 'Command;');
if IncludeCacheMethod(Methods) then
WriteLine('TDSRestCommand *F' + Methods.ProxyMethodName + 'Command_Cache;');
Methods := Methods.Next;
end;
Outdent;
WriteLine('public:');
Indent;
WriteLine('__fastcall ' + ClassName + '::' + ClassName + '(TDSRestConnection *ARestConnection);');
WriteLine('__fastcall ' + ClassName + '::' + ClassName + '(TDSRestConnection *ADBXConnection, bool AInstanceOwner);');
WriteLine('__fastcall ' + ClassName + '::~' + ClassName + '();');
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteMethodSignature(ProxyClass, Methods, True, []);
if IncludeCacheMethod(Methods) then
WriteMethodSignature(ProxyClass, Methods, True, [optCacheParameters]);
Methods := Methods.Next;
end;
Outdent;
WriteLine('};');
Outdent;
WriteLine;
end;
procedure TDSCustomCppRestProxyWriter.WriteInterface;
var
Item: TDSProxyClass;
begin
StartCppHeader;
WriteLine('#ifndef ' + FUnitName + 'H');
WriteLine('#define ' + FUnitName + 'H');
WriteLine;
WriteHeaderUses;
WriteLine;
Item := Metadata.Classes;
while Item <> nil do
begin
if IncludeClass(Item) then
WriteClassInterface(Item);
Item := Item.Next;
end;
//WriteTDSRestParameterMetaData;
WriteLine('#endif');
EndCppHeader;
end;
const
sAcceptServerMethodPrefix = 'accept';
sUpdateServerMethodPrefix = 'update';
sCancelServerMethodPrefix = 'cancel';
sHTTPMethodGet = 'GET';
sHTTPMethodPost = 'POST';
sHTTPMethodDelete = 'DELETE';
sHTTPMethodPut = 'PUT';
procedure TDSCustomCppRestProxyWriter.GetHTTPMethodAndPrefix(Method: TDSProxyMethod; out AServerMethodPrefix, AHTTPMethodName: string);
var
ParamCount: Integer;
Parameters: TDSProxyParameter;
Param: TDSProxyParameter;
LTypeName: string;
LRequiresRequestContent: Boolean;
begin
LRequiresRequestContent := False;
Parameters := Method.Parameters;
ParamCount := Method.ParameterCount;
if ParamCount > 0 then
begin
Param := Parameters;
while Param <> nil do
begin
case Param.ParameterDirection of
TDBXParameterDirections.InParameter,
TDBXParameterDirections.InOutParameter:
begin
case Param.DataType of
TDBXDataTypes.TableType, TDBXDataTypes.BinaryBlobType:
LRequiresRequestContent := True;
TDBXDataTypes.JsonValueType:
begin
LTypeName := Param.TypeName;
if not IsKnownJSONTypeName(LTypeName) then // Do not localize
LRequiresRequestContent := True
else if SameText(LTypeName, 'TJSONValue') or SameText(LTypeName, 'TJSONObject') or SameText(LTypeName, 'TJSONArray') then // Do not localize
LRequiresRequestContent := True;
end;
end;
if LRequiresRequestContent then
break;
end;
end;
Param := Param.Next;
end;
end;
AServerMethodPrefix := '';
if LRequiresRequestContent then
AHTTPMethodName := sHTTPMethodPost
else
AHTTPMethodName := sHTTPMethodGet;
{$IFDEF MAPPREFIXES}
// Accept = PUT
// Update = POST
// Cancel = DELETE
if StrUtils.StartsText(sAcceptServerMethodPrefix, Method.ProxyMethodName) then
begin
AServerMethodPrefix := sAcceptServerMethodPrefix;
AHTTPMethodName := sHTTPMethodPut;
end
else if StrUtils.StartsText(sUpdateServerMethodPrefix, Method.ProxyMethodName) then
begin
AServerMethodPrefix := sUpdateServerMethodPrefix;
AHTTPMethodName := sHTTPMethodPost;
end
else if StrUtils.StartsText(sCancelServerMethodPrefix, Method.ProxyMethodName) then
begin
// May need to ignore prefix in order to pass parameters in http request
if not LRequiresRequestContent then
begin
AServerMethodPrefix := sCancelServerMethodPrefix;
AHTTPMethodName := sHTTPMethodDelete;
end;
end;
{$ENDIF}
end;
function QuoteMethodAlias(const AMethodAlias: string): string;
var
I: Integer;
begin
I := Pos('.', AMethodAlias);
if I > 0 then
if (AMethodAlias[I+1] <> '"') and (AMethodAlias[I+1] <> '''') then
Result := Copy(AMethodAlias, 0, I) + '\"' + Copy(AMethodAlias, I+1) + '\"';
end;
procedure TDSCustomCppRestProxyWriter.WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions);
var
CommandName: UnicodeString;
ParamCount: Integer;
Params: TDSProxyParameter;
Param: TDSProxyParameter;
InputCount: Integer;
OutputCount: Integer;
Ordinal: Integer;
Rhs: UnicodeString;
Lhs: UnicodeString;
LServerMethodPrefix, LHTTPMethodName: string;
LMethodAlias: string;
LExecute: string;
LCachedValueClassName: string;
begin
GetHTTPMethodAndPrefix(ProxyMethod, LServerMethodPrefix, LHTTPMethodName);
if (LServerMethodPrefix = '') and (LHTTPMethodName <> sHTTPMethodGet) then
// Quote method name to prevent REST service from prepending "accept", "update" or "delete" for
// verbs other than "GET"
LMethodAlias := QuoteMethodAlias(ProxyMethod.MethodAlias)
{$IFDEF MAPPREFIXES}
else if LServerMethodPrefix <> '' then
// Remove prefix from method name
LMethodAlias := ProxyClass.ProxyClassName + '.' + Copy(ProxyMethod.ProxyMethodName, Length(LServerMethodPrefix)+1, MaxInt)
{$ENDIF}
else
LMethodAlias := ProxyMethod.MethodAlias;
WriteMethodSignature(ProxyClass, ProxyMethod, False, AOptions);
WriteLine('{');
Indent;
CommandName := 'F' + ProxyMethod.ProxyMethodName + 'Command';
if optCacheParameters in AOptions then
CommandName := CommandName + '_Cache';
WriteLine('if (' + CommandName + ' == NULL)');
WriteLine('{');
Indent;
WriteLine(CommandName + ' = FConnection->CreateCommand();');
WriteLine(CommandName + '->RequestType = "' + LHTTPMethodName + '";');
WriteLine(CommandName + '->Text = "' + LMethodAlias + '";');
if ProxyMethod.ParameterCount > 0 then
WriteLine(CommandName + '->Prepare(' + MakeTDSRestParameterMetaDataTypeName(ProxyClass, ProxyMethod, AOptions) + ', ' + IntToStr(ProxyMethod.ParameterCount-1) + ');');
Outdent;
WriteLine('}');
Params := ProxyMethod.Parameters;
ParamCount := ProxyMethod.ParameterCount;
if ProxyMethod.HasReturnValue then
ParamCount := ParamCount - 1;
InputCount := ProxyMethod.InputCount;
OutputCount := ProxyMethod.OutputCount;
if InputCount > 0 then
begin
Param := Params;
Ordinal := 0;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.InParameter) then
begin
if IsKnownDBXValueTypeName(Param.TypeName) then
begin
WriteLine('if (' + Param.ParameterName + ' == NULL) ');
Indent;
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->SetNull();');
Outdent;
WriteLine('else');
Indent;
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->SetValue(' + Param.ParameterName + ');');
Outdent;
end
else
WriteLine(CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->' + GetSetter(Param) + ';');
end;
Ordinal := Ordinal + 1;
Param := Param.Next;
end;
end;
if optCacheParameters in AOptions then
LExecute := 'ExecuteCache'
else
LExecute := 'Execute';
if SupportsRequestFilter(ProxyMethod) then
WriteLine(CommandName + '->' + LExecute + '(ARequestFilter);')
else
WriteLine(CommandName + '->' + LExecute + '();');
if OutputCount > 0 then
begin
Param := Params;
Ordinal := 0;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.OutParameter) then
begin
if (optCacheParameters in AOptions) and IsCachableParameter(Param, LCachedValueClassName) then
begin
Lhs := Param.ParameterName;
if Param.ParameterDirection = TDBXParameterDirections.InOutParameter then
Lhs := Lhs + '_Cache'; // Add parameter
//Lhs := Lhs + ' = ';
Rhs := 'new T' + LCachedValueClassName + '(' + CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->GetString())' +
'->GetInterface(' + Lhs + ')';
WriteLine(Rhs + ';');
end
else
if IsKnownDBXValueTypeName(Param.TypeName) then
begin
WriteLine('if (' + Param.ParameterName + ' != NULL)');
Indent;
WriteLine(Param.ParameterName + '->SetValue(' + CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value);');
Outdent;
end
else
begin
Lhs := Param.ParameterName + ' = ';
Rhs := CommandName + '->Parameters->Parameter[' + IntToStr(Ordinal) + ']->Value->' + GetGetter(Param);
WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, Param.ParameterName);
end;
end;
Ordinal := Ordinal + 1;
Param := Param.Next;
end;
end;
if ProxyMethod.HasReturnValue then
begin
if (optCacheParameters in AOptions) and IsCachableParameter(ProxyMethod.ReturnParameter, LCachedValueClassName) then
begin
WriteLine(GetCacheValueInterfaceTypeName(LCachedValueClassName) + ' _resultIntf;');
WriteLine('new T' + LCachedValueClassName + '(' + CommandName + '->Parameters->Parameter[' + IntToStr(ParamCount) + ']->Value->GetString())' +
'->GetInterface(_resultIntf);');
WriteLine('return _resultIntf;');
end
else
begin
if ProxyMethod.ReturnParameter.DataType = TDBXDataTypes.DBXConnectionType then
WriteLine('return FRestConnection;')
else if IsKnownDBXValueTypeName(ProxyMethod.ReturnParameter.TypeName) then
begin
WriteLine(GetDelphiTypeName(ProxyMethod.ReturnParameter) + ' result = new ' + ProxyMethod.ReturnParameter.TypeName + '();');
WriteLine('result->SetValue(' + CommandName + '->Parameters->Parameter[' + IntToStr(ParamCount) + ']->Value)');
WriteLine('return result;');
end
else
begin
Lhs := GetDelphiTypeName(ProxyMethod.ReturnParameter) + ' result = ';
Param := ProxyMethod.ReturnParameter;
Rhs := CommandName + '->Parameters->Parameter[' + IntToStr(ParamCount) + ']->Value->' + GetGetter(Param);
WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, 'result');
WriteLine('return result;');
end;
end;
end;
Outdent;
WriteLine('}');
WriteLine;
end;
procedure TDSCustomCppRestProxyWriter.WriteOutgoingParameter(const Lhs: UnicodeString; const InRhs: UnicodeString; const Param: TDSProxyParameter; const CommandName: UnicodeString; const ParamName: UnicodeString);
var
Rhs: UnicodeString;
LTypeName: string;
begin
Rhs := InRhs;
if (Param.DataType = TDBXDataTypes.TableType) and IsKnownTableTypeName(Param.TypeName) then
begin
if CompareText(Param.TypeName, 'TDataSet') = 0 then
begin
Rhs := 'new TCustomSQLDataSet(NULL, ' + Rhs + '(False), True)';
WriteLine(Lhs + Rhs + ';');
WriteLine(ParamName + '->Open();');
end
else if CompareText(Param.TypeName, 'TParams') = 0 then
begin
Rhs := 'TDBXParamsReader::ToParams(NULL, ' + Rhs + '(False), True)';
WriteLine(Lhs + Rhs + ';');
end
else
WriteLine(Lhs + Rhs + ';');
WriteLine('if (FInstanceOwner)');
Indent;
WriteLine(CommandName + '->FreeOnExecute(' + ParamName + ');');
Outdent;
end
else if (Param.DataType = TDBXDataTypes.TableType) or (Param.DataType = TDBXDataTypes.BinaryBlobType) then
WriteLine(Lhs + Rhs + '(FInstanceOwner);')
else if Param.DataType = TDBXDataTypes.JsonValueType then
begin
LTypeName := GetDelphiTypeName(Param);
if not SameText(LTypeName, 'TJSONValue*') then
WriteLine(Lhs + '(' + LTypeName + ')' + Rhs + '(FInstanceOwner);')
else
WriteLine(Lhs + Rhs + '(FInstanceOwner);')
end
else if ContainsText(Rhs,'->Get') then
WriteLine(Lhs + Rhs + '();')
else
WriteLine(Lhs + Rhs + ';');
end;
procedure TDSCustomCppRestProxyWriter.WriteClassImplementation(const ProxyClass: TDSProxyClass);
var
Methods: TDSProxyMethod;
LCommandName: string;
begin
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteMethodImplementation(ProxyClass, Methods);
if IncludeCacheMethod(Methods) then
WriteMethodImplementation(ProxyClass, Methods, [optCacheParameters]);
Methods := Methods.Next;
end;
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::' + ProxyClass.ProxyClassName + 'Client(TDSRestConnection *ARestConnection): ' + GetAncestor(ProxyClass) + '(ARestConnection)');
WriteLine('{');
WriteLine('}');
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::' + ProxyClass.ProxyClassName + 'Client(TDSRestConnection *ARestConnection, bool AInstanceOwner): ' + GetAncestor(ProxyClass) + '(ARestConnection, AInstanceOwner)');
WriteLine('{');
WriteLine('}');
WriteLine;
WriteLine('__fastcall ' + ProxyClass.ProxyClassName + 'Client::~' + ProxyClass.ProxyClassName + 'Client()');
WriteLine('{');
Indent;
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
begin
LCommandName := 'F' + Methods.ProxyMethodName + 'Command';
WriteLine('delete ' + LCommandName + ';');
end;
if IncludeCacheMethod(Methods) then
begin
LCommandName := 'F' + Methods.ProxyMethodName + 'Command_Cache';
WriteLine('delete ' + LCommandName + ';');
end;
Methods := Methods.Next;
end;
Outdent;
WriteLine('}');
WriteLine;
end;
function TDSCustomCppRestProxyWriter.MakeTDSRestParameterMetaDataTypeName(ProxyClass: TDSProxyClass; Method: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions): string;
begin
Result := ProxyClass.ProxyClassName + '_' + Method.ProxyMethodName;
if optCacheParameters in AOptions then
Result := Result + '_Cache';
end;
procedure TDSCustomCppRestProxyWriter.WriteMethodTDSRestParameterMetaData(ProxyClass: TDSProxyClass; Method: TDSProxyMethod; AOptions: TNativeRestProxyWriterOptions);
var
Param: TDSProxyParameter;
ParamCount: Integer;
Line: string;
LClassName: string;
LParameterDirection: Integer;
LDataType: Integer;
LTypeName: string;
begin
ParamCount := Method.ParameterCount;
if ParamCount = 0 then
Exit;
Indent;
WriteLine(Format('struct TDSRestParameterMetaData %s[] =',
[MakeTDSRestParameterMetaDataTypeName(ProxyClass, Method, AOptions)]));
WriteLine('{');
Indent;
if ParamCount > 0 then
begin
Param := Method.Parameters;
while Param <> nil do
begin
Line := '{';
Line := Line + '"' + Param.ParameterName + '", ';
if (optCacheParameters in AOptions) and IsCachableParameter(Param, LClassName) then
begin
LTypeName := 'String';
if Param.ParameterDirection <> TDBXParameterDirections.ReturnParameter then
LParameterDirection := TDBXParameterDirections.OutParameter
else
LParameterDirection := Param.ParameterDirection;
LDataType := TDBXDataTypes.WideStringType;
end
else
begin
LParameterDirection := Param.ParameterDirection;
LDataType := Param.DataType;
LTypeName := Param.TypeName;
end;
Line := Line + IntToStr(LParameterDirection) + ', ';
Line := Line + IntToStr(LDataType) + ', ';
Line := Line + '"' + LTypeName + '"}';
Param := Param.Next;
if Param <> nil then
Line := Line + ',';
WriteLine(Line);
end;
end;
OutDent;
WriteLine('};');
OutDent;
WriteLine;
end;
procedure TDSCustomCppRestProxyWriter.WriteClassTDSRestParameterMetaData(ProxyClass: TDSProxyClass);
var
Methods: TDSProxyMethod;
begin
Methods := ProxyClass.FirstMethod;
while Methods <> nil do
begin
if IncludeMethod(Methods) then
WriteMethodTDSRestParameterMetaData(ProxyClass, Methods);
if IncludeCacheMethod(Methods) then
WriteMethodTDSRestParameterMetaData(ProxyClass, Methods, [optCacheParameters]);
Methods := Methods.Next;
end;
end;
procedure TDSCustomCppRestProxyWriter.WriteTDSRestParameterMetaData;
var
Item: TDSProxyClass;
begin
Item := Metadata.Classes;
while Item <> nil do
begin
if IncludeClass(Item) then
WriteClassTDSRestParameterMetaData(Item);
Item := Item.Next;
end;
end;
procedure TDSCustomCppRestProxyWriter.WriteImplementation;
var
Item: TDSProxyClass;
begin
Item := Metadata.Classes;
while Item <> nil do
begin
if IncludeClass(Item) then
WriteClassImplementation(Item);
Item := Item.Next;
end;
end;
function TDSCustomCppRestProxyWriter.GetAssignmentString: UnicodeString;
begin
Result := '=';
end;
function TDSCustomCppRestProxyWriter.GetCreateDataSetReader(const Param: TDSProxyParameter): UnicodeString;
begin
Result := '(new TDBXDataSetReader(' + Param.ParameterName + ', FInstanceOwner), True)';
end;
function TDSCustomCppRestProxyWriter.GetCreateParamsReader(const Param: TDSProxyParameter): UnicodeString;
begin
Result := '(new TDBXParamsReader(' + Param.ParameterName + ', FInstanceOwner), True)';
end;
{ TDSCppRestProxyWriter }
procedure TDSCppRestProxyWriter.DerivedWrite(const Line: UnicodeString);
begin
if FWritingHeader then
if FHeaderStreamWriter <> nil then
FHeaderStreamWriter.Write(Line)
else
ProxyWriters[sInterface].Write(Line)
else
if FStreamWriter <> nil then
FStreamWriter.Write(Line)
else
ProxyWriters[sImplementation].Write(Line);
end;
procedure TDSCppRestProxyWriter.DerivedWriteLine;
begin
if FWritingHeader then
if HeaderStreamWriter <> nil then
FHeaderStreamWriter.WriteLine
else
ProxyWriters[sInterface].WriteLine
else
if FStreamWriter <> nil then
FStreamWriter.WriteLine
else
ProxyWriters[sImplementation].WriteLine;
end;
destructor TDSCppRestProxyWriter.Destroy;
begin
FreeAndNil(FHeaderStreamWriter);
FreeAndNil(FStreamWriter);
inherited;
end;
procedure TDSCppRestProxyWriter.EndCppHeader;
begin
FWritingHeader := False;
end;
procedure TDSCppRestProxyWriter.StartCppHeader;
begin
FWritingHeader := True;
end;
function TDSCustomCppRestProxyWriter.IncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean;
begin
// C++ does not support marshalling/unmarshalling
// But will support as JSONObject
Result := inherited; // and not ProxyMethod.HasParametersWithUserType;
end;
{ TDSClientProxyWriterCppRest }
function TDSClientProxyWriterCppRest.CreateProxyWriter: TDSCustomProxyWriter;
begin
Result := TDSCppRestProxyWriter.Create;
end;
function TDSClientProxyWriterCppRest.FileDescriptions: TDSProxyFileDescriptions;
begin
SetLength(Result, 2);
Result[0].ID := sImplementation;
Result[0].DefaultFileExt := '.cpp';
Result[1].ID := sInterface;
Result[1].DefaultFileExt := '.h';
end;
function TDSClientProxyWriterCppRest.Properties: TDSProxyWriterProperties;
begin
Result.UsesUnits := 'DSProxyCppRest';
Result.DefaultExcludeClasses := sDSAdminClassName + ';' + sDSMetadataClassName; // 'DSMetadata;DSAdmin';
Result.DefaultExcludeMethods := sASMethodsPrefix;
Result.Author := 'Embarcadero'; // do not localize
Result.Comment := '';
Result.Language := sDSProxyCppLanguage;
Result.Features := [feConnectsWithDSRestConnection, feRESTClient];
Result.DefaultEncoding := TEncoding.UTF8;
end;
initialization
TDSProxyWriterFactory.RegisterWriter(sCPlusPlusBuilderRestProxyWriter, TDSClientProxyWriterCppRest);
finalization
TDSProxyWriterFactory.UnregisterWriter(sCPlusPlusBuilderRestProxyWriter);
end.
|
{-Test program reproducing Nessie Anubis test vectors, (c) we Aug.2008}
{ anubis-test-vectors-xxx.txt, xxx = 128, 160, 192, 224, 256, 288, 320 from}
{ http://www.larc.usp.br/~pbarreto/anubis-tweak-test-vectors.zip}
{ Note that the 'Test vectors -- set 4' is only generated if all_sets is
{ defined. To generate a text vector file for a given key size, assign
{ the key bit size to the const KeyBits and redirect stdout to a file}
program t_an_bs1;
{$i STD.INC}
{.$define all_sets} {set 4 is VERY time consuming}
{$ifdef APPCONS}
{$apptype console}
{$endif}
uses
{$ifdef WINCRT}
wincrt,
{$endif}
BTypes,mem_util,anu_base;
const
KeyBits = 320;
var
key: array[0..79] of byte;
ctx: TANUContext;
plain : TANUBlock;
cipher : TANUBlock;
decrypted : TANUBlock;
{Pascal translation of Anubis submission bctestvectors.c}
{---------------------------------------------------------------------------}
procedure print_data(str: str255; pval: pointer; len: word);
begin
writeln(str:25,'=',HexStr(pval, len));
end;
{---------------------------------------------------------------------------}
procedure DumpTV(ks: word);
{-dump Nessie TV for key bit size ks}
var
v,err: integer;
i: longint;
begin
writeln('Test vectors -- set 1');
writeln('=====================');
writeln;
for v:=0 to ks-1 do begin
fillchar(plain, sizeof(plain), 0);
fillchar(key, sizeof(key), 0);
key[v shr 3] := 1 shl (7-(v and 7));
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
ANU_Encrypt(ctx, plain, cipher);
err := ANU_Init_Decr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Decr error: ', err);
halt;
end;
ANU_Decrypt(ctx, cipher, decrypted);
writeln('Set 1, vector#',v:3,':');
print_data('key', @key, ks div 8);
print_data('plain', @plain, ANUBLKSIZE);
print_data('cipher', @cipher, ANUBLKSIZE);
print_data('decrypted', @decrypted, ANUBLKSIZE);
if not compmem(@plain, @decrypted, ANUBLKSIZE) then begin
writeln('** Decryption error: **');
writeln(' Decrypted ciphertext is different than the plaintext!');
end;
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
for i:=2 to 100 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 100 times', @cipher, ANUBLKSIZE);
for i:=101 to 1000 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 1000 times', @cipher, ANUBLKSIZE);
writeln;
end;
writeln('Test vectors -- set 2');
writeln('=====================');
writeln;
for v:=0 to pred(8*ANUBLKSIZE) do begin
fillchar(plain, sizeof(plain), 0);
fillchar(key, sizeof(key), 0);
plain[v shr 3] := 1 shl (7-(v and 7));
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
ANU_Decrypt(ctx, plain, cipher);
err := ANU_Init_Decr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Decr error: ', err);
halt;
end;
ANU_Encrypt(ctx, cipher, decrypted);
writeln('Set 2, vector#',v:3,':');
print_data('key', @key, ks div 8);
print_data('plain', @plain, ANUBLKSIZE);
print_data('cipher', @cipher, ANUBLKSIZE);
print_data('decrypted', @decrypted, ANUBLKSIZE);
if not compmem(@plain, @decrypted, ANUBLKSIZE) then begin
writeln('** Decryption error: **');
writeln(' Decrypted ciphertext is different than the plaintext!');
end;
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
for i:=2 to 100 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 100 times', @cipher, ANUBLKSIZE);
for i:=101 to 1000 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 1000 times', @cipher, ANUBLKSIZE);
writeln;
end;
writeln('Test vectors -- set 3');
writeln('=====================');
writeln;
for v:=0 to 255 do begin
fillchar(plain, sizeof(plain), v);
fillchar(key, sizeof(key), v);
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
ANU_Encrypt(ctx, plain, cipher);
err := ANU_Init_Decr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Decr error: ', err);
halt;
end;
ANU_Decrypt(ctx, cipher, decrypted);
writeln('Set 3, vector#',v:3,':');
print_data('key', @key, ks div 8);
print_data('plain', @plain, ANUBLKSIZE);
print_data('cipher', @cipher, ANUBLKSIZE);
print_data('decrypted', @decrypted, ANUBLKSIZE);
if not compmem(@plain, @decrypted, ANUBLKSIZE) then begin
writeln('** Decryption error: **');
writeln(' Decrypted ciphertext is different than the plaintext!');
end;
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
for i:=2 to 100 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 100 times', @cipher, ANUBLKSIZE);
for i:=101 to 1000 do ANU_Encrypt(ctx, cipher, cipher);
print_data('Iterated 1000 times', @cipher, ANUBLKSIZE);
writeln;
end;
{$ifdef all_sets}
{WARNING!!!! This is VERY time consuming!!}
{=========================================}
writeln('Test vectors -- set 4');
writeln('=====================');
writeln;
for v:=0 to 3 do begin
fillchar(plain, sizeof(plain), v);
fillchar(key, sizeof(key), v);
if ANU_Init_Encr(key, ks, ctx)<>0 then halt;
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
writeln('Set 4, vector#',v:3,':');
print_data('key', @key, ks div 8);
print_data('plain', @plain, ANUBLKSIZE);
for i:=1 to 99999999 do begin
fillchar(key, sizeof(key), cipher[ANUBLKSIZE-1]);
err := ANU_Init_Encr(key, ks, ctx);
if err<>0 then begin
writeln('** ANU_Init_Encr error: ', err);
halt;
end;
ANU_Encrypt(ctx, cipher, cipher);
end;
print_data('Iterated 10^8 times', @cipher, ANUBLKSIZE);
writeln;
end;
writeln;
{$endif}
writeln;
writeln('End of test vectors');
end;
begin
HexUpper := true;
DumpTV(320);
end.
|
unit PeriodClose;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDBGrid, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData,
Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar, cxClasses, dsdDB,
Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxPC, cxButtonEdit, cxCalendar, dxSkinsCore, dxSkinsDefaultPainters,
dxSkinscxPCPainter, dxSkinsdxBarPainter, cxContainer, Vcl.ComCtrls, dxCore,
cxDateUtils, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, Vcl.ExtCtrls;
type
TPeriodCloseForm = class(TAncestorDBGridForm)
RoleName: TcxGridDBColumn;
OperDate: TcxGridDBColumn;
UserName: TcxGridDBColumn;
CloseDate: TcxGridDBColumn;
Period: TcxGridDBColumn;
actUserForm_excl: TOpenChoiceForm;
actRoleForm: TOpenChoiceForm;
actBranchForm: TOpenChoiceForm;
spInsertUpdate: TdsdStoredProc;
UpdateDataSet: TdsdUpdateDataSet;
Code: TcxGridDBColumn;
Name: TcxGridDBColumn;
RoleCode: TcxGridDBColumn;
UserName_list: TcxGridDBColumn;
isUserName: TcxGridDBColumn;
UserCode_excl: TcxGridDBColumn;
UserName_excl: TcxGridDBColumn;
CloseDate_excl: TcxGridDBColumn;
DescId: TcxGridDBColumn;
DescName: TcxGridDBColumn;
DescId_excl: TcxGridDBColumn;
DescName_excl: TcxGridDBColumn;
PaidKindCode: TcxGridDBColumn;
PaidKindName: TcxGridDBColumn;
BranchCode: TcxGridDBColumn;
BranchName: TcxGridDBColumn;
actPaidKindForm: TOpenChoiceForm;
Panel: TPanel;
deOperDate: TcxDateEdit;
cxLabel1: TcxLabel;
actUpdate_CloseDate: TdsdExecStoredProc;
spUpdate_CloseDate: TdsdStoredProc;
bbUpdate_PeriodClose_all: TdxBarButton;
mactUpdate_CloseDate: TMultiAction;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TPeriodCloseForm);
end.
|
unit PlayerExtractors;
{$mode objfpc}{$H+}
interface
uses
{$ifdef unix}
cthreads,
cmem,
{$endif}
Classes,
SysUtils,
PlayerThreads,
PlayerSubtitleExtractors,
PlayerSessionStorage,
PlayerExporters;
type
{ TPlayerInfoExtractor }
TPlayerInfoExtractor = class
private
FFailed: Boolean;
FList: TPlayerFileList;
FLoaded: Boolean;
FOnFinish: TNotifyEvent;
FOnProcess: TPlayerProcessEvent;
FSessionID: String;
FTempDir: String;
FCrc32: String;
FStorage: TPlayerSessionStorage;
FProcessedCount: Integer;
function FindSession: Boolean;
function GetCount: Integer;
function GetFileInfo(const Index: Integer): TPlayerFileInfo;
function GetFileInfoByName(const AFileName: String): TPlayerFileInfo;
function GetFileName(const Index: Integer): String;
procedure PrepareSession;
procedure PrepareTempDir(const ATempDir: String);
protected
procedure DoFinish; virtual;
procedure DoProcess; virtual;
public
constructor Create(AFileList: TStrings);
destructor Destroy; override;
function LoadData: TPlayerThreadManager;
property Count: Integer read GetCount;
property FileName[Index: Integer]: String read GetFileName; default;
property FileInfo[Index: Integer]: TPlayerFileInfo read GetFileInfo;
property FileInfoByName[AFileName: String]: TPlayerFileInfo
read GetFileInfoByName;
property Crc32: String read FCrc32;
property Failed: Boolean read FFailed;
property Loaded: Boolean read FLoaded;
property SessionID: String read FSessionID;
property TempDir: String read FTempDir;
property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
property OnProcess: TPlayerProcessEvent read FOnProcess write FOnProcess;
end;
{ TPlayerExtractorManager }
TPlayerExtractorManager = class(TPlayerThreadManager)
private
FExtractor: TPlayerInfoExtractor;
FCount: Integer;
FCriticalSection: TRTLCriticalSection;
protected
procedure Execute; override;
function GetNextThread: TPlayerThread; override;
public
constructor Create(AExtractor: TPlayerInfoExtractor);
destructor Destroy; override;
procedure Interrupt(const Force: Boolean = False); override;
property Extractor: TPlayerInfoExtractor read FExtractor;
end;
{ TPlayerExtractorThread }
TPlayerExtractorThread = class(TPlayerThread)
private
FIndex: Integer;
FDataFile: String;
FService: TPlayerExtractorService;
function GetExtractor: TPlayerInfoExtractor;
function GetManager: TPlayerExtractorManager;
procedure ExtractTrack;
procedure ParseTrack;
procedure SavePoints(Sender: TPlayerTrackParser;
Points: TPlayerPointArray);
protected
procedure Execute; override;
public
constructor Create(AManager: TPlayerExtractorManager; const AIndex: Integer);
property Extractor: TPlayerInfoExtractor read GetExtractor;
property Manager: TPlayerExtractorManager read GetManager;
end;
implementation
uses
FileUtil, crc, PlayerLogger, PlayerOptions;
{ TPlayerExtractorThread }
function TPlayerExtractorThread.GetManager: TPlayerExtractorManager;
begin
Result:=inherited Manager as TPlayerExtractorManager;
end;
procedure TPlayerExtractorThread.ExtractTrack;
var
Service: TPlayerSubtitleExtractor;
begin
FDataFile:=Format('%ssubtitles_%d.data', [Extractor.TempDir, FIndex]);
Service:=TPlayerSubtitleFfmpegExtractor.Create(Extractor[FIndex], FDataFile);
try
FService:=Service;
logger.Log('extracting track in session %s, %d(%s) into %s',
[Extractor.FSessionID, FIndex, Extractor[FIndex], FDataFile]);
Service.Extract;
finally
Service.Free;
FService:=nil;
end;
end;
procedure TPlayerExtractorThread.ParseTrack;
var
Service: TPlayerTrackParser;
begin
Service:=TPlayerNmeaTrackParser.Create(FDataFile, Self);
try
FService:=Service;
logger.Log('parsing track in session %s, %d (%s)',
[Extractor.FSessionID, FIndex, FDataFile]);
Service.OnSave:=@SavePoints;
Service.Parse;
finally
Service.Free;
FService:=nil;
end;
end;
procedure TPlayerExtractorThread.SavePoints(Sender: TPlayerTrackParser;
Points: TPlayerPointArray);
begin
EnterCriticalsection(Manager.FCriticalSection);
try
logger.Log('saving track points in session %s, %d, points: %d',
[Extractor.FSessionID, FIndex, Length(Points)]);
Extractor.FStorage.AddPoints(Extractor.SessionID, FIndex, Points);
finally
LeaveCriticalsection(Manager.FCriticalSection);
end;
end;
function TPlayerExtractorThread.GetExtractor: TPlayerInfoExtractor;
begin
Result:=Manager.Extractor;
end;
procedure TPlayerExtractorThread.Execute;
begin
try
if not Terminated then ExtractTrack;
if not Terminated then ParseTrack;
if not Terminated then
Synchronize(@Extractor.DoProcess);
except
on E: Exception do
begin
logger.Log('error on extractor thread %d, session %s, text: %s',
[FIndex, Extractor.FSessionID, E.Message]);
Extractor.FFailed:=True;
Manager.Interrupt(True);
end;
end;
end;
constructor TPlayerExtractorThread.Create(AManager: TPlayerExtractorManager;
const AIndex: Integer);
begin
inherited Create(AManager);
FIndex:=AIndex;
end;
{ TPlayerExtractorManager }
procedure TPlayerExtractorManager.Execute;
begin
try
try
inherited;
if not (FCount < Extractor.Count) then
begin
logger.Log('finalizing session %s', [FExtractor.FSessionID]);
FExtractor.FStorage.FinalizeSession(FExtractor.FSessionID);
Extractor.FStorage.GenerateGpx(FExtractor.FSessionID);
Extractor.FLoaded:=True;
end;
except
on E: Exception do
begin
logger.Log('error on extracting session %s, text: %s',
[Extractor.FSessionID, E.Message]);
Interrupt(True);
FExtractor.FFailed:=True;
end;
end;
finally
Synchronize(@FExtractor.DoFinish);
end;
end;
function TPlayerExtractorManager.GetNextThread: TPlayerThread;
begin
if not (FCount < Extractor.Count) then Result:=nil else
begin
logger.Log('starting new extractor thread: %d for session %s',
[FCount, Extractor.FSessionID]);
Result:=TPlayerExtractorThread.Create(Self, FCount);
Inc(FCount);
end
end;
constructor TPlayerExtractorManager.Create(AExtractor: TPlayerInfoExtractor);
begin
FExtractor:=AExtractor;
FCount:=0;
InitCriticalSection(FCriticalSection);
inherited Create;
end;
destructor TPlayerExtractorManager.Destroy;
begin
DeleteDirectory(FExtractor.FTempDir, False);
DoneCriticalsection(FCriticalSection);
inherited;
end;
procedure TPlayerExtractorManager.Interrupt(const Force: Boolean);
var
List: TList;
Index: Integer;
CurThread: TPlayerExtractorThread;
begin
inherited;
if not Force then Exit;
List:=ThreadList.LockList;
try
for Index:=0 to List.Count - 1 do
begin
CurThread:=TPlayerExtractorThread(List[Index]);
if CurThread.FService <> nil then
CurThread.FService.StopProcess;
end;
finally
ThreadList.UnlockList;
end;
end;
{ TPlayerInfoExtractor }
function TPlayerInfoExtractor.GetFileName(const Index: Integer): String;
begin
Result:=FList.Keys[Index];
end;
procedure TPlayerInfoExtractor.PrepareSession;
var
Guid: TGUID;
begin
if CreateGUID(Guid) <> 0 then raise Exception.Create('error');
FSessionID:=LowerCase(GUIDToString(Guid));
Delete(FSessionID, 1, 1);
Delete(FSessionID, Length(FSessionID), 1);
logger.Log('new session: %s', [FSessionID]);
FTempDir:=IncludeTrailingPathDelimiter(FTempDir + FSessionID);
logger.Log('session dir: %s', [FTempDir]);
ForceDirectories(FTempDir);
end;
procedure TPlayerInfoExtractor.PrepareTempDir(const ATempDir: String);
var
db: String;
begin
FTempDir:=IncludeTrailingPathDelimiter(ATempDir);
logger.Log('temp dir: %s', [FTempDir]);
ForceDirectories(FTempDir);
db:=FTempDir + 'player.db';
logger.Log('database: %s', [db]);
FStorage:=TPlayerSessionStorage.Create(db);
end;
procedure TPlayerInfoExtractor.DoFinish;
begin
if @FOnFinish <> nil then
FOnFinish(Self);
end;
procedure TPlayerInfoExtractor.DoProcess;
begin
Inc(FProcessedCount);
if @FOnProcess <> nil then
FOnProcess(Self, FProcessedCount);
end;
constructor TPlayerInfoExtractor.Create(AFileList: TStrings);
var
FileItemName: String;
FileItemData: TPlayerFileInfo;
Index: Integer;
begin
inherited Create;
FLoaded:=False;
logger.Log('extractor started');
FList:=TPlayerFileList.Create;
for FileItemName in AFileList do
if FileExists(FileItemName) then
begin
FileAge(FileItemName, FileItemData.CreatedAt);
FileItemData.Size:=FileUtil.FileSize(FileItemName);
Index:=FList.Add(FileItemName, FileItemData);
logger.Log('File added "%s", created_at %s, size: %d, index: %d',
[FileItemName,
FormatDateTime(PLAYER_DATE_FORMAT, FileItemData.CreatedAt),
FileItemData.Size,
Index
]);
end;
PrepareTempDir(opts.TempDir);
FLoaded:=FindSession;
if not FLoaded then PrepareSession;
end;
function TPlayerInfoExtractor.FindSession: Boolean;
var
List: TStringList;
Index: Integer;
Info: TPlayerFileInfo;
CrcValue: Cardinal;
begin
List:=TStringList.Create;
try
for Index:=0 to Count - 1 do
begin
Info:=Self.FileInfo[Index];
List.Add(Format('%s,%d,%s',
[Self[Index], Info.Size, FormatDateTime(PLAYER_DATE_FORMAT, Info.CreatedAt)]));
end;
List.Sort;
CrcValue:=0;
CrcValue:=crc.crc32(CrcValue, PByte(List.Text), Length(List.Text));
FCrc32:=IntToHex(CrcValue, 8);
FSessionID:=FStorage.FindSession(FCrc32, FList.Count);
logger.Log('find session: %s', [FCrc32]);
Result:=FSessionID <> '';
logger.Log('session exists: %s', [BoolToStr(Result, 'yes', 'no')]);
finally
List.Free;
end;
end;
function TPlayerInfoExtractor.GetCount: Integer;
begin
Result:=FList.Count;
end;
function TPlayerInfoExtractor.GetFileInfo(const Index: Integer): TPlayerFileInfo;
begin
Result:=FList.Data[Index];
end;
function TPlayerInfoExtractor.GetFileInfoByName(const AFileName: String
): TPlayerFileInfo;
begin
Result:=FList.KeyData[AFileName];
end;
destructor TPlayerInfoExtractor.Destroy;
begin
FStorage.Free;
FList.Free;
logger.Log('extraction finish');
inherited;
end;
function TPlayerInfoExtractor.LoadData: TPlayerThreadManager;
begin
Result:=nil;
FFailed:=False;
if Loaded then Exit;
FProcessedCount:=0;
logger.Log('loading session: %s', [FSessionID]);
FStorage.AddSession(FSessionID, FCrc32, FList);
Result:=TPlayerExtractorManager.Create(Self);
Result.Start;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MS Access metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MSAccMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator, FireDAC.Phys;
type
TFDPhysMSAccMetadata = class (TFDPhysConnectionMetadata)
protected
function GetKind: TFDRDBMSKind; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetTruncateSupported: Boolean; override;
function GetIdentityInsertSupported: Boolean; override;
function GetIdentityInWhere: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetAsyncAbortSupported: Boolean; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalEscapeEscape(AEscape: Char; const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
function IsNameValid(const AName: String): Boolean; override;
public
constructor Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String);
end;
TFDPhysMSAccCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override;
function GetIdentity(ASessionScope: Boolean): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Option, FireDAC.Stan.Param;
{-------------------------------------------------------------------------------}
{ TFDPhysMSAccMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysMSAccMetadata.Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; const ACSVKeywords: String);
begin
inherited Create(AConnectionObj, AServerVersion, AClientVersion, True);
if ACSVKeywords <> '' then
FKeywords.CommaText := ACSVKeywords + ',PASSWORD';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MSAccess;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetParamNameMaxLength: Integer;
begin
Result := 30;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
Result := ' ';
case AQuote of
ncDefault:
if ASide = nsLeft then
Result := '['
else
Result := ']';
ncSecond:
Result := '"';
ncThird:
Result := '`';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetTruncateSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetIdentityInWhere: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvDefVals;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'DATEVALUE(' + AnsiQuotedStr(AStr, '''') + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'CDATE(' + AnsiQuotedStr(AStr, '''') + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'TIMEVALUE(' + AnsiQuotedStr(AStr, '''') + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
i: Integer;
sEnd: String;
A1, A2, A3, A4: String;
function Intv2Acc(AIntv: String): String;
begin
AIntv := UpperCase(FDUnquote(Trim(AIntv), ''''));
if AIntv = 'YEAR' then
Result := '''yyyy'''
else if AIntv = 'QUARTER' then
Result := '''Q'''
else if AIntv = 'MONTH' then
Result := '''m'''
else if AIntv = 'WEEK' then
Result := '''ww'''
else if AIntv = 'DAY' then
Result := '''d'''
else if AIntv = 'HOUR' then
Result := '''H'''
else if AIntv = 'MINUTE' then
Result := '''N'''
else if AIntv = 'SECOND' then
Result := '''S'''
else
UnsupportedEscape(ASeq);
end;
begin
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then begin
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
end;
case ASeq.FFunc of
// the same
// char
efASCII,
efCHAR,
efCONCAT,
efLCASE,
efLEFT,
efLOCATE,
efLTRIM,
efREPEAT,
efRIGHT,
efRTRIM,
efSPACE,
efSUBSTRING,
efUCASE,
// numeric
efATAN,
efABS,
efCEILING,
efCOS,
efCOT,
efEXP,
efFLOOR,
efLOG,
efMOD,
efPOWER,
efROUND,
efSIGN,
efSIN,
efSQRT,
efTAN,
efRANDOM,
efATAN2,
// date and time
efCURDATE,
efCURTIME,
efNOW,
efDAYNAME,
efDAYOFMONTH,
efDAYOFWEEK,
efDAYOFYEAR,
efHOUR,
efMINUTE,
efMONTH,
efMONTHNAME,
efQUARTER,
efSECOND,
efWEEK,
efYEAR: Result := '{fn ' + ASeq.FName + '(' + AddEscapeSequenceArgs(ASeq) + ')}';
// system
efIFNULL: Result := 'IIF(' + A1 + ' IS NULL, ' + A2 + ', ' + A1 + ')';
efIF: Result := 'IIF(' + AddEscapeSequenceArgs(ASeq) + ')';
efDECODE:
begin
i := 1;
sEnd := '';
Result := '';
while i <= Length(ASeq.FArgs) - 2 do begin
if i > 1 then
Result := Result + ', ';
Result := Result + 'IIF(' + A1 + ' = ' + ASeq.FArgs[i] +
', ' + ASeq.FArgs[i + 1];
sEnd := sEnd + ')';
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then begin
if i > 1 then
Result := Result + ', ';
Result := Result + ASeq.FArgs[i];
end;
Result := Result + sEnd;
end;
// char
efPOSITION: Result := 'INSTR(1, ' + A2 + ', ' + A1 + ')';
efBIT_LENGTH: Result := '(LEN(' + A1 + ') * 8)';
efCHAR_LENGTH,
efLENGTH,
efOCTET_LENGTH: Result := 'LEN(' + A1 + ')';
efINSERT: Result := 'MID(' + A1 + ', 1, ' + A2 + '- 1) & ' + A4 +
'& MID(' + A1 + ', (' + A2 + ') + (' + A3 + '), LEN(' + A1 + '))';
efREPLACE: Result := 'REPLACE(' + AddEscapeSequenceArgs(ASeq) + ')';
// date and time
efEXTRACT: Result := 'DATEPART(' + Intv2Acc(A1) + ', ' + A2 + ')';
efTIMESTAMPADD: Result := 'DATEADD(' + Intv2Acc(A1) + ', ' + A2 + ', ' + A3 + ')';
efTIMESTAMPDIFF:Result := 'DATEDIFF(' + Intv2Acc(A1) + ', ' + A2 + ', ' + A3 + ')';
// system
efCATALOG: Result := '{fn DATABASE()}';
efSCHEMA: Result := '{fn USER()';
// numeric
efACOS: Result := '{fn ATAN(({fn SQRT(1 - (' + A1 + ') * (' + A1 + '))}) / (' + A1 + '))}';
efASIN: Result := '{fn ATAN((' + A1 + ') / {fn SQRT(1 - (' + A1 + ') * (' + A1 + '))})}';
efDEGREES: Result := '(180 * (' + A1 + ') / ' + S_FD_Pi + ')';
efLOG10: Result := '(LOG(' + A1 + ') / LOG(10))';
efPI: Result := S_FD_Pi;
efRADIANS: Result := '(' + S_FD_Pi + ' * (' + A1 + ') / 180)';
efTRUNCATE: Result := 'INT(' + A1 + ')';
// convert
efCONVERT:
begin
A2 := Trim(UpperCase(A2));
if A2[1] = '''' then
A2 := Copy(A2, 2, Length(A2) - 2);
if A2 = 'CHAR' then
A2 := 'VARCHAR';
Result := '{fn CONVERT(' + A1 + ', SQL_' + A2 + ')}';
end;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalEscapeEscape(AEscape: Char;
const AStr: String): String;
var
i: Integer;
begin
Result := AStr;
i := 1;
while i <= Length(Result) do
if Result[i] = AEscape then begin
Result := Copy(Result, 1, i - 1) + '[' + Result[i + 1] + ']' +
Copy(Result, i + 2, Length(Result));
Inc(i, 3);
end
else
Inc(i);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'BEGIN' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'TRANSACTION' then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccMetadata.IsNameValid(const AName: String): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(AName) do
if not ((i = 1) and FDInSet(AName[i], ['a' .. 'z', 'A' .. 'Z', '_']) or
(i > 1) and FDInSet(AName[i], ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '$'])) then begin
Result := False;
Break;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSAccCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysMSAccCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
oParam: TFDParam;
rName: TFDPhysParsedName;
lWasParam: Boolean;
begin
Result := Result + 'EXECUTE ';
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
rName.FObject := AProc;
Result := Result + FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
lWasParam := False;
for i := 0 to FParams.Count - 1 do begin
oParam := FParams[i];
if oParam.ParamType <> ptResult then begin
if lWasParam then
Result := Result + ', ';
Result := Result + '?';
lWasParam := True;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
Result := '@@IDENTITY';
end;
{-------------------------------------------------------------------------------}
// http://msdn.microsoft.com/en-us/library/bb177899%28v=office.12%29.aspx
// http://msdn.microsoft.com/en-us/library/bb208866(v=office.12).aspx
function TFDPhysMSAccCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
if caAutoInc in AColumn.ActualAttributes then begin
Result := 'COUNTER';
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'BIT';
dtSByte,
dtInt16:
Result := 'SMALLINT';
dtInt32,
dtUInt16:
Result := 'INTEGER';
dtInt64,
dtUInt32,
dtUInt64:
Result := 'DECIMAL';
dtByte:
Result := 'TINYINT';
dtSingle:
Result := 'REAL';
dtDouble,
dtExtended:
Result := 'FLOAT';
dtCurrency:
Result := 'MONEY';
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime,
dtTime,
dtDate,
dtDateTimeStamp:
Result := 'DATETIME';
dtAnsiString,
dtWideString:
if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 255) then
Result := 'CHAR' + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1)
else
Result := 'TEXT';
dtByteString:
Result := 'BINARY' + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
dtBlob,
dtHBlob,
dtHBFile:
Result := 'IMAGE';
dtMemo,
dtWideMemo,
dtXML,
dtHMemo,
dtWideHMemo:
Result := 'TEXT';
dtGUID:
Result := 'UNIQUEIDENTIFIER';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.MSAccess, S_FD_MSAcc_RDBMS);
end.
|
unit uReservedAction;
interface
uses
classes, AssThreadTimer, Contnrs;
type
TReservedAction = class
private
FTimer : TAssThreadTimer;
FInterval : integer;
FIntervalName : string;
FAction : TNotifyEvent;
FStartTime : Int64;
procedure TimerTick(Sender : TObject);
procedure CreateTimer;
public
constructor Create; overload;
constructor Create(aAction : TNotifyEvent; interval : integer); overload;
constructor Create(aAction : TNotifyEvent; intervalName : string); overload;
destructor Destroy; override;
procedure Start;
procedure Stop;
function IsRunning : boolean;
end;
TReservedManager = class
private
FItems : TObjectList;
public
constructor Create;
destructor Destroy; override;
procedure Add(obj : TReservedAction);
procedure StopAll;
class function GetInstance: TReservedManager;
end;
implementation
uses
fChannelSpy, uPerformanceCounter;
var
ReservedManagerInstance : TReservedManager;
{ TReservedAction }
constructor TReservedAction.Create;
begin
CreateTimer;
FAction := nil;
FIntervalName := '';
end;
constructor TReservedAction.Create(aAction: TNotifyEvent;
interval : integer);
begin
CreateTimer;
FAction := aAction;
FIntervalName := '';
FInterval := interval;
end;
constructor TReservedAction.Create(aAction: TNotifyEvent;
intervalName: string);
begin
CreateTimer;
FAction := aAction;
FIntervalName := intervalName;
end;
procedure TReservedAction.CreateTimer;
begin
FTimer := TAssThreadTimer.Create(nil);
FTimer.OnTimer := TimerTick;
FTimer.Interval := 50;
FTimer.Enabled := false;
end;
destructor TReservedAction.Destroy;
begin
FTimer.Enabled := false;
FTimer.Free;
inherited;
end;
function TReservedAction.IsRunning: boolean;
begin
result := FTimer.Enabled;
end;
procedure TReservedAction.Start;
begin
if IsRunning then exit;
if FIntervalName <> '' then
begin
if frmChannelSpy.SysServer.ChannelExist(FIntervalName) then
FInterval := frmChannelSpy.SysServer.AsInteger[FIntervalName]
else
FInterval := 15000;
end;
FStartTime := GetMillisecondsTick;
FTimer.Enabled := true;
end;
procedure TReservedAction.Stop;
begin
FTimer.Enabled := false;
end;
procedure TReservedAction.TimerTick(Sender: TObject);
begin
if (GetMillisecondsTick - FStartTime) > FInterval then
begin
try
if Assigned(FAction) then
FAction(Sender);
finally
FTimer.Enabled := false;
end;
end;
end;
{ TReservedManager }
procedure TReservedManager.Add(obj: TReservedAction);
begin
FItems.Add(obj);
end;
constructor TReservedManager.Create;
begin
FItems := TObjectList.Create;
end;
destructor TReservedManager.Destroy;
begin
FItems.Free;
inherited;
end;
class function TReservedManager.GetInstance: TReservedManager;
begin
if Assigned(ReservedManagerInstance) = false then
ReservedManagerInstance := TReservedManager.Create;
result := ReservedManagerInstance;
end;
procedure TReservedManager.StopAll;
var
i : integer;
item : TReservedAction;
begin
for i := 0 to FItems.Count - 1 do
begin
item := TReservedAction(FItems[i]);
if Assigned(item) then
item.Stop;
end;
end;
end.
|
unit NtUtils.Exec.Win32;
interface
uses
NtUtils.Exec, Winapi.ProcessThreadsApi, NtUtils.Exceptions,
NtUtils.Environment, NtUtils.Objects;
type
TExecCreateProcessAsUser = class(TExecMethod)
class function Supports(Parameter: TExecParam): Boolean; override;
class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo):
TNtxStatus; override;
end;
TExecCreateProcessWithToken = class(TExecMethod)
class function Supports(Parameter: TExecParam): Boolean; override;
class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo):
TNtxStatus; override;
end;
IStartupInfo = interface
function StartupInfoEx: PStartupInfoExW;
function CreationFlags: Cardinal;
function HasExtendedAttbutes: Boolean;
function Environment: Pointer;
end;
TStartupInfoHolder = class(TInterfacedObject, IStartupInfo)
strict protected
SIEX: TStartupInfoExW;
strDesktop: String;
hxParent: IHandle;
hpParent: THandle;
dwCreationFlags: Cardinal;
objEnvironment: IEnvironment;
procedure PrepateAttributes(ParamSet: IExecProvider;
Method: TExecMethodClass);
public
constructor Create(ParamSet: IExecProvider; Method: TExecMethodClass);
function StartupInfoEx: PStartupInfoExW;
function CreationFlags: Cardinal;
function HasExtendedAttbutes: Boolean;
function Environment: Pointer;
destructor Destroy; override;
end;
TRunAsInvoker = class(TInterfacedObject, IInterface)
private const
COMPAT_NAME = '__COMPAT_LAYER';
COMPAT_VALUE = 'RunAsInvoker';
private var
OldValue: String;
OldValuePresent: Boolean;
public
constructor SetCompatState(Enabled: Boolean);
destructor Destroy; override;
end;
implementation
uses
Winapi.WinError, Ntapi.ntobapi, Ntapi.ntstatus, Ntapi.ntseapi;
{ TStartupInfoHolder }
constructor TStartupInfoHolder.Create(ParamSet: IExecProvider;
Method: TExecMethodClass);
begin
GetStartupInfoW(SIEX.StartupInfo);
SIEX.StartupInfo.dwFlags := 0;
dwCreationFlags := CREATE_UNICODE_ENVIRONMENT;
if Method.Supports(ppDesktop) and ParamSet.Provides(ppDesktop) then
begin
// Store the string in our memory before we reference it as PWideChar
strDesktop := ParamSet.Desktop;
SIEX.StartupInfo.lpDesktop := PWideChar(strDesktop);
end;
if Method.Supports(ppShowWindowMode) and ParamSet.Provides(ppShowWindowMode) then
begin
SIEX.StartupInfo.dwFlags := SIEX.StartupInfo.dwFlags or STARTF_USESHOWWINDOW;
SIEX.StartupInfo.wShowWindow := ParamSet.ShowWindowMode
end;
if Method.Supports(ppEnvironment) and ParamSet.Provides(ppEnvironment) then
objEnvironment := ParamSet.Environment;
if Method.Supports(ppCreateSuspended) and ParamSet.Provides(ppCreateSuspended)
and ParamSet.CreateSuspended then
dwCreationFlags := dwCreationFlags or CREATE_SUSPENDED;
if Method.Supports(ppBreakaway) and ParamSet.Provides(ppBreakaway) and
ParamSet.Breakaway then
dwCreationFlags := dwCreationFlags or CREATE_BREAKAWAY_FROM_JOB;
if Method.Supports(ppNewConsole) and ParamSet.Provides(ppNewConsole) and
ParamSet.NewConsole then
dwCreationFlags := dwCreationFlags or CREATE_NEW_CONSOLE;
// Extended attributes
PrepateAttributes(ParamSet, Method);
if Assigned(SIEX.lpAttributeList) then
begin
SIEX.StartupInfo.cb := SizeOf(TStartupInfoExW);
dwCreationFlags := dwCreationFlags or EXTENDED_STARTUPINFO_PRESENT;
end
else
SIEX.StartupInfo.cb := SizeOf(TStartupInfoW);
end;
function TStartupInfoHolder.CreationFlags: Cardinal;
begin
Result := dwCreationFlags;
end;
destructor TStartupInfoHolder.Destroy;
begin
if Assigned(SIEX.lpAttributeList) then
begin
DeleteProcThreadAttributeList(SIEX.lpAttributeList);
FreeMem(SIEX.lpAttributeList);
SIEX.lpAttributeList := nil;
end;
inherited;
end;
function TStartupInfoHolder.Environment: Pointer;
begin
if Assigned(objEnvironment) then
Result := objEnvironment.Environment
else
Result := nil;
end;
function TStartupInfoHolder.HasExtendedAttbutes: Boolean;
begin
Result := Assigned(SIEX.lpAttributeList);
end;
procedure TStartupInfoHolder.PrepateAttributes(ParamSet: IExecProvider;
Method: TExecMethodClass);
var
BufferSize: NativeUInt;
begin
if Method.Supports(ppParentProcess) and ParamSet.Provides(ppParentProcess)
then
begin
hxParent := ParamSet.ParentProcess;
if Assigned(hxParent) then
hpParent := hxParent.Handle
else
hpParent := 0;
BufferSize := 0;
InitializeProcThreadAttributeList(nil, 1, 0, BufferSize);
if not WinTryCheckBuffer(BufferSize) then
Exit;
SIEX.lpAttributeList := AllocMem(BufferSize);
if not InitializeProcThreadAttributeList(SIEX.lpAttributeList, 1, 0,
BufferSize) then
begin
FreeMem(SIEX.lpAttributeList);
SIEX.lpAttributeList := nil;
Exit;
end;
// NOTE: ProcThreadAttributeList stores pointers istead of storing the
// data. By referencing the value in the object's field we make sure it
// does not go anywhere.
if not UpdateProcThreadAttribute(SIEX.lpAttributeList, 0,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, @hpParent, SizeOf(hpParent)) then
begin
DeleteProcThreadAttributeList(SIEX.lpAttributeList);
FreeMem(SIEX.lpAttributeList);
SIEX.lpAttributeList := nil;
Exit;
end;
end
else
SIEX.lpAttributeList := nil;
end;
function TStartupInfoHolder.StartupInfoEx: PStartupInfoExW;
begin
Result := @SIEX;
end;
{ TExecCreateProcessAsUser }
class function TExecCreateProcessAsUser.Execute(ParamSet: IExecProvider;
out Info: TProcessInfo): TNtxStatus;
var
hToken: THandle;
CommandLine: String;
CurrentDir: PWideChar;
Startup: IStartupInfo;
RunAsInvoker: IInterface;
ProcessInfo: TProcessInformation;
begin
// Command line should be in writable memory
CommandLine := PrepareCommandLine(ParamSet);
if ParamSet.Provides(ppCurrentDirectory) then
CurrentDir := PWideChar(ParamSet.CurrentDircetory)
else
CurrentDir := nil;
// Set RunAsInvoker compatibility mode. It will be reverted
// after exiting from the current function.
if ParamSet.Provides(ppRunAsInvoker) then
RunAsInvoker := TRunAsInvoker.SetCompatState(ParamSet.RunAsInvoker);
Startup := TStartupInfoHolder.Create(ParamSet, Self);
if ParamSet.Provides(ppToken) and Assigned(ParamSet.Token) then
hToken := ParamSet.Token.Handle
else
hToken := 0; // Zero to fall back to CreateProcessW behavior
Result.Location := 'CreateProcessAsUserW';
Result.LastCall.ExpectedPrivilege := SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE;
Result.Win32Result := CreateProcessAsUserW(
hToken,
PWideChar(ParamSet.Application),
PWideChar(CommandLine),
nil,
nil,
ParamSet.Provides(ppInheritHandles) and ParamSet.InheritHandles,
Startup.CreationFlags,
Startup.Environment,
CurrentDir,
Startup.StartupInfoEx,
ProcessInfo
);
if Result.IsSuccess then
with Info, ProcessInfo do
begin
ClientId.UniqueProcess := dwProcessId;
ClientId.UniqueThread := dwThreadId;
hxProcess := TAutoHandle.Capture(hProcess);
hxThread := TAutoHandle.Capture(hThread);
end;
end;
class function TExecCreateProcessAsUser.Supports(Parameter: TExecParam):
Boolean;
begin
case Parameter of
ppParameters, ppCurrentDirectory, ppDesktop, ppToken, ppParentProcess,
ppInheritHandles, ppCreateSuspended, ppBreakaway, ppNewConsole,
ppShowWindowMode, ppRunAsInvoker, ppEnvironment:
Result := True;
else
Result := False;
end;
end;
{ TExecCreateProcessWithToken }
class function TExecCreateProcessWithToken.Execute(ParamSet: IExecProvider;
out Info: TProcessInfo): TNtxStatus;
var
hToken: THandle;
CurrentDir: PWideChar;
Startup: IStartupInfo;
ProcessInfo: TProcessInformation;
begin
if ParamSet.Provides(ppCurrentDirectory) then
CurrentDir := PWideChar(ParamSet.CurrentDircetory)
else
CurrentDir := nil;
Startup := TStartupInfoHolder.Create(ParamSet, Self);
if ParamSet.Provides(ppToken) and Assigned(ParamSet.Token) then
hToken := ParamSet.Token.Handle
else
hToken := 0;
Result.Location := 'CreateProcessWithTokenW';
Result.LastCall.ExpectedPrivilege := SE_IMPERSONATE_PRIVILEGE;
Result.Win32Result := CreateProcessWithTokenW(
hToken,
ParamSet.LogonFlags,
PWideChar(ParamSet.Application),
PWideChar(PrepareCommandLine(ParamSet)),
Startup.CreationFlags,
Startup.Environment,
CurrentDir,
Startup.StartupInfoEx,
ProcessInfo
);
if Result.IsSuccess then
with Info, ProcessInfo do
begin
ClientId.UniqueProcess := dwProcessId;
ClientId.UniqueThread := dwThreadId;
hxProcess := TAutoHandle.Capture(hProcess);
hxThread := TAutoHandle.Capture(hThread);
end;
end;
class function TExecCreateProcessWithToken.Supports(Parameter: TExecParam):
Boolean;
begin
case Parameter of
ppParameters, ppCurrentDirectory, ppDesktop, ppToken, ppLogonFlags,
ppCreateSuspended, ppBreakaway, ppShowWindowMode, ppEnvironment:
Result := True;
else
Result := False;
end;
end;
{ TRunAsInvoker }
destructor TRunAsInvoker.Destroy;
var
Environment: IEnvironment;
begin
Environment := TEnvironment.OpenCurrent;
if OldValuePresent then
Environment.SetVariable(COMPAT_NAME, OldValue)
else
Environment.DeleteVariable(COMPAT_NAME);
inherited;
end;
constructor TRunAsInvoker.SetCompatState(Enabled: Boolean);
var
Environment: IEnvironment;
Status: TNtxStatus;
begin
Environment := TEnvironment.OpenCurrent;
// Save the current state
Status := Environment.QueryVariableWithStatus(COMPAT_NAME, OldValue);
if Status.IsSuccess then
OldValuePresent := True
else if Status.Status = STATUS_VARIABLE_NOT_FOUND then
OldValuePresent := False
else
Status.RaiseOnError;
// Set the new state
if Enabled then
Environment.SetVariable(COMPAT_NAME, COMPAT_VALUE).RaiseOnError
else if OldValuePresent then
Environment.DeleteVariable(COMPAT_NAME).RaiseOnError;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.TDataDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.TDataMeta;
type
// TFDPhysTDataConnectionDefParams
// Generated for: FireDAC TData driver
TFDTDataCharacterSet = (csASCII, csUTF8, csUTF16, csLATIN1252_0A, csLATIN9_0A, csLATIN1_0A, csKANJISJIS_0S, csKANJIEUC_0U, csTCHBIG5_1R0, csSCHGB2312_1T0, csHANGULKSC5601_2R4);
/// <summary> TFDPhysTDataConnectionDefParams class implements FireDAC TData driver specific connection definition class. </summary>
TFDPhysTDataConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetODBCAdvanced: String;
procedure SetODBCAdvanced(const AValue: String);
function GetLoginTimeout: Integer;
procedure SetLoginTimeout(const AValue: Integer);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetOSAuthent: Boolean;
procedure SetOSAuthent(const AValue: Boolean);
function GetCharacterSet: TFDTDataCharacterSet;
procedure SetCharacterSet(const AValue: TFDTDataCharacterSet);
function GetSessionMode: TFDTDataSessionMode;
procedure SetSessionMode(const AValue: TFDTDataSessionMode);
function GetEncrypt: Boolean;
procedure SetEncrypt(const AValue: Boolean);
function GetExtendedMetadata: Boolean;
procedure SetExtendedMetadata(const AValue: Boolean);
function GetMetaDefSchema: String;
procedure SetMetaDefSchema(const AValue: String);
function GetMetaCurSchema: String;
procedure SetMetaCurSchema(const AValue: String);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False;
property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False;
property Server: String read GetServer write SetServer stored False;
property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False;
property CharacterSet: TFDTDataCharacterSet read GetCharacterSet write SetCharacterSet stored False default csASCII;
property SessionMode: TFDTDataSessionMode read GetSessionMode write SetSessionMode stored False default tmTeradata;
property Encrypt: Boolean read GetEncrypt write SetEncrypt stored False;
property ExtendedMetadata: Boolean read GetExtendedMetadata write SetExtendedMetadata stored False;
property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False;
property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysTDataConnectionDefParams
// Generated for: FireDAC TData driver
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetODBCAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetODBCAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetLoginTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetLoginTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetOSAuthent: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetOSAuthent(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetCharacterSet: TFDTDataCharacterSet;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if CompareText(s, 'ASCII') = 0 then
Result := csASCII
else if CompareText(s, 'UTF8') = 0 then
Result := csUTF8
else if CompareText(s, 'UTF16') = 0 then
Result := csUTF16
else if CompareText(s, 'LATIN1252_0A') = 0 then
Result := csLATIN1252_0A
else if CompareText(s, 'LATIN9_0A') = 0 then
Result := csLATIN9_0A
else if CompareText(s, 'LATIN1_0A') = 0 then
Result := csLATIN1_0A
else if CompareText(s, 'KANJISJIS_0S') = 0 then
Result := csKANJISJIS_0S
else if CompareText(s, 'KANJIEUC_0U') = 0 then
Result := csKANJIEUC_0U
else if CompareText(s, 'TCHBIG5_1R0') = 0 then
Result := csTCHBIG5_1R0
else if CompareText(s, 'SCHGB2312_1T0') = 0 then
Result := csSCHGB2312_1T0
else if CompareText(s, 'HANGULKSC5601_2R4') = 0 then
Result := csHANGULKSC5601_2R4
else
Result := csASCII;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetCharacterSet(const AValue: TFDTDataCharacterSet);
const
C_CharacterSet: array[TFDTDataCharacterSet] of String = ('ASCII', 'UTF8', 'UTF16', 'LATIN1252_0A', 'LATIN9_0A', 'LATIN1_0A', 'KANJISJIS_0S', 'KANJIEUC_0U', 'TCHBIG5_1R0', 'SCHGB2312_1T0', 'HANGULKSC5601_2R4');
begin
FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := C_CharacterSet[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetSessionMode: TFDTDataSessionMode;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_TData_SessionMode];
if CompareText(s, 'Teradata') = 0 then
Result := tmTeradata
else if CompareText(s, 'ANSI') = 0 then
Result := tmANSI
else
Result := tmTeradata;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetSessionMode(const AValue: TFDTDataSessionMode);
const
C_SessionMode: array[TFDTDataSessionMode] of String = ('Teradata', 'ANSI');
begin
FDef.AsString[S_FD_ConnParam_TData_SessionMode] := C_SessionMode[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetEncrypt: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_TData_Encrypt];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetEncrypt(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_TData_Encrypt] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetExtendedMetadata: Boolean;
begin
Result := FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetExtendedMetadata(const AValue: Boolean);
begin
FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetMetaDefSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetMetaDefSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnectionDefParams.GetMetaCurSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnectionDefParams.SetMetaCurSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue;
end;
end.
|
unit ServerHorse.Settings;
interface
uses
System.SysUtils,
System.JSON,
ServerHorse.Consts,
GBJSON.Interfaces,
GBJSON.Config,
GBJSON.Helper,
DataSet.Serialize.Config;
type
iServerHorseSettings<T> = interface
['{36434654-025F-4E2A-B54E-416B362A9B65}']
function CaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>; overload;
function CaseDefinition: TshCaseDefinition; overload;
function GBJSONCaseDefinition: TCaseDefinition;
function DSerializeCaseDefinition: TCaseNameDefinition;
function ShorseToDSSerializeCaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>;
function ShorseToGBJSONCaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>;
procedure JsonObjectToObject(aObj: TObject; aJsonObject: TJSONObject);
end;
TServerHorseSettings<T: class, constructor> = class(TInterfacedObject,
iServerHorseSettings<T>)
private
fCaseDefinition: TshCaseDefinition;
fGCaseDefinition: TCaseDefinition;
fDSCaseDefinition: TCaseNameDefinition;
public
function CaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>; overload;
function CaseDefinition: TshCaseDefinition; overload;
function GBJSONCaseDefinition: TCaseDefinition;
function ShorseToGBJSONCaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>;
function DSerializeCaseDefinition: TCaseNameDefinition;
function ShorseToDSSerializeCaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>;
procedure JsonObjectToObject(aObj: TObject; aJsonObject: TJSONObject);
constructor Create;
destructor Destroy; override;
class function New: iServerHorseSettings<T>;
end;
implementation
{ TServerHorseConfig }
function TServerHorseSettings<T>.CaseDefinition(Value: TshCaseDefinition)
: iServerHorseSettings<T>;
begin
result := Self;
fCaseDefinition := Value;
ShorseToGBJSONCaseDefinition(Value);
ShorseToDSSerializeCaseDefinition(Value);
end;
function TServerHorseSettings<T>.CaseDefinition: TshCaseDefinition;
begin
result := fCaseDefinition;
end;
constructor TServerHorseSettings<T>.Create;
begin
fCaseDefinition := shLower;
fDSCaseDefinition := cndUpperCamelCase;
fGCaseDefinition := cdLower;
end;
destructor TServerHorseSettings<T>.Destroy;
begin
inherited;
end;
procedure TServerHorseSettings<T>.JsonObjectToObject(aObj: TObject;
aJsonObject: TJSONObject);
begin
TGBJSONConfig.GetInstance.CaseDefinition(fGCaseDefinition);
TGBJSONDefault.Serializer<T>(False).JsonObjectToObject(aObj, aJsonObject);
aObj.fromJSONObject(aJsonObject);
end;
class function TServerHorseSettings<T>.New: iServerHorseSettings<T>;
begin
result := Self.Create;
end;
function TServerHorseSettings<T>.DSerializeCaseDefinition: TCaseNameDefinition;
begin
result := fDSCaseDefinition;
end;
function TServerHorseSettings<T>.GBJSONCaseDefinition: TCaseDefinition;
begin
result := fGCaseDefinition;
end;
function TServerHorseSettings<T>.ShorseToDSSerializeCaseDefinition
(Value: TshCaseDefinition): iServerHorseSettings<T>;
begin
result := Self;
fDSCaseDefinition := TCaseNameDefinition(Value);
{ fGCaseDefinition: TCaseDefinition;
fDSCaseDefinition: TCaseNameDefinition; }
{ case Value of
shNone:
fDSCaseDefinition := TCaseNameDefinition(Value); // cndNone;
shLower:
fDSCaseDefinition := cndLower;
shUpper:
fDSCaseDefinition := cndUpper;
shLowerCamelCase:
fDSCaseDefinition := cndLowerCamelCase;
shUpperCamelCase:
fDSCaseDefinition := cndUpperCamelCase;
end; }
end;
function TServerHorseSettings<T>.ShorseToGBJSONCaseDefinition
(Value: TshCaseDefinition): iServerHorseSettings<T>;
begin
result := Self;
fGCaseDefinition := TCaseDefinition(Value);
{ case Value of
shNone:
fGCaseDefinition := cdNone;
shLower:
fGCaseDefinition := cdLower;
shUpper:
fGCaseDefinition := cdUpper;
shLowerCamelCase:
fGCaseDefinition := cdLowerCamelCase;
shUpperCamelCase:
fGCaseDefinition := cdUpperCamelCase;
end; }
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* (c) Copyright 1993, Silicon Graphics, Inc.
* 1993-1995 Microsoft Corporation
* ALL RIGHTS RESERVED
*/}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormResize(Sender: TObject);
private
DC : HDC;
hrc: HGLRC;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
// Initialize material property, light source, and lighting model.
procedure MyInit;
const
// mat_specular and mat_shininess are NOT default values
mat_ambient : array[0..3] of GLfloat = ( 0.0, 0.0, 0.0, 1.0 );
mat_diffuse : array[0..3] of GLfloat = ( 0.4, 0.4, 0.4, 1.0 );
mat_specular : array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 );
mat_shininess : GLfloat = 15.0;
begin
glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, @mat_shininess);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
end;
procedure DrawPlane;
begin
glBegin (GL_QUADS);
glNormal3f (0.0, 0.0, 1.0);
glVertex3f (-1.0, -1.0, 0.0);
glVertex3f (0.0, -1.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glVertex3f (-1.0, 0.0, 0.0);
glNormal3f (0.0, 0.0, 1.0);
glVertex3f (0.0, -1.0, 0.0);
glVertex3f (1.0, -1.0, 0.0);
glVertex3f (1.0, 0.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glNormal3f (0.0, 0.0, 1.0);
glVertex3f (0.0, 0.0, 0.0);
glVertex3f (1.0, 0.0, 0.0);
glVertex3f (1.0, 1.0, 0.0);
glVertex3f (0.0, 1.0, 0.0);
glNormal3f (0.0, 0.0, 1.0);
glVertex3f (0.0, 0.0, 0.0);
glVertex3f (0.0, 1.0, 0.0);
glVertex3f (-1.0, 1.0, 0.0);
glVertex3f (-1.0, 0.0, 0.0);
glEnd;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.FormPaint(Sender: TObject);
const
infinite_light : array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 0.0 );
local_light : array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 );
begin
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glTranslatef (-1.5, 0.0, 0.0);
glLightfv (GL_LIGHT0, GL_POSITION, @infinite_light);
drawPlane;
glPopMatrix;
glPushMatrix;
glTranslatef (1.5, 0.0, 0.0);
glLightfv (GL_LIGHT0, GL_POSITION, @local_light);
drawPlane;
glPopMatrix;
SwapBuffers(DC);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat(DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
MyInit;
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.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);
InvalidateRect(Handle, nil, False);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Context.Mac;
{$I FMX.Defines.inc}
interface
procedure SelectOpenGLContext;
implementation {===============================================================}
uses
System.Classes, System.SysUtils, System.Types, System.UITypes, System.Math, FMX.Types, Macapi.CocoaTypes, Macapi.AppKit,
FMX.Types3D, FMX.Platform, Macapi.OpenGL, FMX.Filter, FMX.Context.Mac.GLSL;
type
{ TContextOpenGL }
TContextOpenGL = class(TContext3D)
private
{ buffers }
FRenderBuf: GLuint;
FFrameBuf: GLuint;
FDepthBuf: GLuint;
FColorBufTex: GLuint;
FContextObject: NSOpenGLContext;
procedure ApplyVertices(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
procedure UnApplyVertices;
protected
procedure ApplyContextState(AState: TContextState); override;
{ Bitmaps }
procedure UpdateBitmapHandle(ABitmap: TBitmap); override;
procedure DestroyBitmapHandle(ABitmap: TBitmap); override;
{ Assign }
procedure AssignToBitmap(Dest: TBitmap); override;
function GetValid: Boolean; override;
public
constructor CreateFromWindow(const AParent: TFmxHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean); override;
constructor CreateFromBitmap(const ABitmap: TBitmap; const AMultisample: TMultisample;
const ADepthStencil: Boolean); override;
destructor Destroy; override;
{ buffer }
procedure Resize; override;
{ buffer }
function DoBeginScene: Boolean; override;
procedure DoEndScene(const CopyTarget: Boolean = True); override;
{ low-level }
procedure SetTextureMatrix(const AUnit: Integer; const AMatrix: TMatrix); override;
procedure SetTextureUnit(const AUnit: Integer; const ABitmap: TBitmap); override;
procedure SetTextureUnitFromContext(const AUnit: Integer; const ARect: PRectF = nil); override;
procedure SetStencilOp(const Fail, ZFail, ZPass: TStencilOp); override;
procedure SetStencilFunc(const Func: TStencilfunc; Ref, Mask: cardinal); override;
procedure Clear(const ATarget: TClearTargets; const AColor: TAlphaColor; const ADepth: single; const AStencil: Cardinal); override;
procedure DrawTrianglesList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
procedure DrawTrianglesStrip(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
procedure DrawTrianglesFan(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
procedure DrawLinesList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
procedure DrawLinesStrip(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
procedure DrawPointsList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); override;
{ vertex shaders }
function CreateVertexShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader; override;
procedure DestroyVertexShader(const Shader: TContextShader); override;
procedure SetVertexShader(const Shader: TContextShader); override;
procedure SetVertexShaderVector(Index: Integer; const V: TVector3D); override;
procedure SetVertexShaderMatrix(Index: Integer; const M: TMatrix3D); override;
{ pixel shader }
function CreatePixelShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader; override;
procedure DestroyPixelShader(const Shader: TContextShader); override;
procedure SetPixelShader(const Shader: TContextShader); override;
procedure SetPixelShaderVector(Index: Integer; const V: TVector3D); override;
procedure SetPixelShaderMatrix(Index: Integer; const M: TMatrix3D); override;
property ContextObject: NSOpenGLContext read FContextObject;
end;
T_T2F_C4U_N3F_V3F = packed record
T: TPointF;
C: TAlphaColor;
N: TPoint3D;
V: TPoint3D;
end;
function ColorToGlColor(AColor: TAlphaColor): TVector3D;
begin
Result.X := TAlphaColorRec(AColor).R / $FF;
Result.Y := TAlphaColorRec(AColor).G / $FF;
Result.Z := TAlphaColorRec(AColor).B / $FF;
Result.W := TAlphaColorRec(AColor).A / $FF;
end;
{ TContextOpenGL }
var
FirstContext: TContextOpenGL;
const
attrs: array [0..5] of NSOpenGLPixelFormatAttribute =
(
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 24,
NSOpenGLPFAStencilSize, 8,
0
);
attrs2: array [0..11] of NSOpenGLPixelFormatAttribute =
(
NSOpenGLPFAAccelerated,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 24,
NSOpenGLPFAStencilSize, 8,
NSOpenGLPFAMultisample,
NSOpenGLPFASampleBuffers, 1,
NSOpenGLPFASamples, 2,
0
);
attrs4: array [0..11] of NSOpenGLPixelFormatAttribute =
(
NSOpenGLPFAAccelerated,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 24,
NSOpenGLPFAStencilSize, 8,
NSOpenGLPFAMultisample,
NSOpenGLPFASampleBuffers, 1,
NSOpenGLPFASamples, 4,
0
);
constructor TContextOpenGL.CreateFromWindow(const AParent: TFmxHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean);
var
PixelFormat: NSOpenGLPixelFormat;
PF: Pointer;
Ctx: NSOpenGLContext;
begin
inherited;
PF := nil;
case FMultisample of
TMultisample.ms4Samples:
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs4[0]);
if PF = nil then
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs2[0]);
end;
end;
TMultisample.ms2Samples:
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs2[0]);
end;
end;
if PF = nil then
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs[0]);
end;
PixelFormat := TNSOpenGLPixelFormat.Wrap(PF);
Ctx := TNSOpenGLContext.Create;
if FirstContext = nil then
begin
FContextObject := TNSOpenGLContext.Wrap(Ctx.initWithFormat(PixelFormat, nil));
FirstContext := Self;
end
else
FContextObject := TNSOpenGLContext.Wrap(Ctx.initWithFormat(PixelFormat, FirstContext.ContextObject));
PixelFormat.release;
// set context to the view
TNSOpenGLView.Wrap(Pointer(Platform.FindForm(Parent).ContextHandle)).setOpenGLContext(FContextObject);
FContextObject.makeCurrentContext;
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_FALSE);
CreateBuffer;
end;
constructor TContextOpenGL.CreateFromBitmap(const ABitmap: TBitmap; const AMultisample: TMultisample;
const ADepthStencil: Boolean);
var
PixelFormat: NSOpenGLPixelFormat;
SaveContext: NSOpenGLContext;
Ctx: NSOpenGLContext;
PF: Pointer;
Status: Integer;
begin
inherited;
PF := nil;
case FMultisample of
TMultisample.ms4Samples:
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs4[0]);
if PF = nil then
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs2[0]);
end;
end;
TMultisample.ms2Samples:
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs2[0]);
end;
end;
if PF = nil then
begin
PixelFormat := TNSOpenGLPixelFormat.Create;
PF := PixelFormat.initWithAttributes(@attrs[0]);
end;
Ctx := TNSOpenGLContext.Create;
if FirstContext = nil then
begin
FContextObject := TNSOpenGLContext.Wrap(Ctx.initWithFormat(PixelFormat, nil));
// FHandle := THandle(FContextObject);
FirstContext := Self;
end
else
begin
FContextObject := TNSOpenGLContext.Wrap(Ctx.initWithFormat(PixelFormat, FirstContext.ContextObject));
// FHandle := THandle(FContextObject);
end;
PixelFormat.release;
SaveContext := TNSOpenGLContext.Wrap(TNSOpenGLContext.OCClass.currentContext);
FContextObject.makeCurrentContext;
{ create buffers }
glGenFramebuffersEXT(1, @FFrameBuf);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FFrameBuf);
glGenRenderbuffersEXT(1, @FRenderBuf);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, FRenderBuf);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA, FWidth, FHeight);
glFrameBufferRenderBufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, FRenderBuf);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
if FDepthStencil then
begin
glGenRenderbuffersEXT(1, @FDepthBuf);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, FDepthBuf);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, FWidth, FHeight);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, FDepthBuf);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, FDepthBuf);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
end;
Status := glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if Status <> GL_FRAMEBUFFER_COMPLETE_EXT then
Writeln('frame buffer not complete');
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glGenTextures(1, @FColorBufTex);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_FALSE);
SaveContext.makeCurrentContext;
CreateBuffer;
end;
destructor TContextOpenGL.Destroy;
begin
if FContextObject <> nil then
FContextObject.makeCurrentContext;
if FColorBufTex <> 0 then
glDeleteTextures(1, @FColorBufTex);
if FDepthBuf <> 0 then
glDeleteRenderbuffersEXT(1, @FDepthBuf);
if FRenderBuf <> 0 then
glDeleteRenderbuffersEXT(1, @FRenderBuf);
if FFrameBuf <> 0 then
glDeleteFramebuffersEXT(1, @FFrameBuf);
glDeleteTextures(1, @FColorBufTex);
if FContextObject <> nil then
FContextObject.release;
FContextObject := nil;
inherited;
if FirstContext = Self then
FirstContext := nil;
if ShaderDevice = Self then
ShaderDevice := nil;
end;
procedure TContextOpenGL.Resize;
var
Status: Integer;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if FFrameBuf <> 0 then
begin
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FFrameBuf);
if FRenderBuf <> 0 then
begin
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, FRenderBuf);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA, FWidth, FHeight);
end;
if FDepthBuf <> 0 then
begin
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, FDepthBuf);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, FWidth, FHeight);
end;
Status := glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if Status <> GL_FRAMEBUFFER_COMPLETE_EXT then
writeln('frame buffer not complete');
end
else
FContextObject.update;
end;
end;
function TContextOpenGL.GetValid: Boolean;
begin
Result := FContextObject <> nil;
end;
function TContextOpenGL.DoBeginScene: Boolean;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if FFrameBuf <> 0 then
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FFrameBuf);
glViewport(0, 0, FWidth, FHeight);
{ Render }
Result := inherited DoBeginScene;
if FDepthStencil then
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glFrontFace(GL_CW);
glDisable(GL_LIGHT0);
glDisable(GL_LIGHT1);
glDisable(GL_LIGHT2);
glDisable(GL_LIGHT3);
glDisable(GL_LIGHT4);
glDisable(GL_LIGHT5);
glDisable(GL_LIGHT6);
glDisable(GL_LIGHT7);
glEnable(GL_NORMALIZE);
end else
Result := False;
end;
procedure TContextOpenGL.DoEndScene(const CopyTarget: Boolean = True);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if (FBitmap <> nil) and CopyTarget then
begin
glFlush();
glReadPixels(0, 0, FWidth, FHeight, GL_RGBA, GL_UNSIGNED_BYTE, FBitmap.StartLine);
FBitmap.FlipVertical;
end else
FContextObject.flushBuffer;
end;
end;
procedure TContextOpenGL.ApplyContextState(AState: TContextState);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
case AState of
TContextState.csZTestOn:
begin
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
end;
TContextState.csZTestOff: glDisable(GL_DEPTH_TEST);
TContextState.csZWriteOn: glDepthMask(1);
TContextState.csZWriteOff: glDepthMask(0);
TContextState.csAlphaTestOn: glEnable(GL_ALPHA_TEST);
TContextState.csAlphaTestOff: glDisable(GL_ALPHA_TEST);
TContextState.csAlphaBlendOn: glEnable(GL_BLEND);
TContextState.csAlphaBlendOff: glDisable(GL_BLEND);
TContextState.csStencilOn: glEnable(GL_STENCIL_TEST);
TContextState.csStencilOff: glDisable(GL_STENCIL_TEST);
TContextState.csColorWriteOn: glColorMask(1, 1, 1, 1);
TContextState.csColorWriteOff: glColorMask(0, 0, 0, 0);
TContextState.csFrontFace:
begin
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
end;
TContextState.csBackFace:
begin
glCullFace(GL_FRONT);
glEnable(GL_CULL_FACE);
end;
TContextState.csAllFace: glDisable(GL_CULL_FACE);
TContextState.csBlendAdditive: glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
TContextState.csBlendNormal: glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
TContextState.csFlat: glShadeModel(GL_FLAT);
TContextState.csGouraud: glShadeModel(GL_SMOOTH);
TContextState.csFrame: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
TContextState.csSolid: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
TContextState.csTexNearest:
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
end;
TContextState.csTexLinear:
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
end;
end;
end;
end;
procedure TContextOpenGL.Clear(const ATarget: TClearTargets; const AColor: TAlphaColor; const ADepth: single; const AStencil: Cardinal);
var
Flags: Integer;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
Flags := 0;
if FDepthStencil and (TClearTarget.ctDepth in ATarget) then
begin
Flags := Flags or GL_DEPTH_BUFFER_BIT;
glClearDepth(1.0);
end;
if FDepthStencil and (TClearTarget.ctStencil in ATarget) then
begin
Flags := Flags or GL_STENCIL_BUFFER_BIT;
glClearStencil(0);
end;
if (TClearTarget.cTColor in ATarget) then
begin
Flags := Flags or GL_COLOR_BUFFER_BIT;
glClearColor(TAlphaColorRec(AColor).R / $FF, TAlphaColorRec(AColor).G / $FF, TAlphaColorRec(AColor).B / $FF, TAlphaColorRec(AColor).A / $FF);
end;
glClear(Flags);
end;
end;
procedure TContextOpenGL.ApplyVertices(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single);
var
i: Integer;
TempVer: array of T_T2F_C4U_N3F_V3F;
C: TVector3D;
begin
FCurrentOpacity := Opacity;
FCurrentColoredVertices := TVertexFormat.vfDiffuse in Vertices.Format;
SetParams;
glGetMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, @C);
C.W := Opacity;
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, @C);
if Vertices.Format = [TVertexFormat.vfVertex, TVertexFormat.vfTexCoord0] then
glInterleavedArrays(GL_T2F_V3F, 0, Vertices.Buffer);
if Vertices.Format = [TVertexFormat.vfVertex, TVertexFormat.vfNormal, TVertexFormat.vfTexCoord0] then
glInterleavedArrays(GL_T2F_N3F_V3F, 0, Vertices.Buffer);
if Vertices.Format = [TVertexFormat.vfVertex, TVertexFormat.vfNormal, TVertexFormat.vfDiffuse, TVertexFormat.vfTexCoord0] then
begin
SetLength(TempVer, Vertices.Length);
for i := 0 to Vertices.Length - 1 do
begin
with TempVer[i] do
begin
T := Vertices.TexCoord0[i];
C := CorrectColor(Vertices.Diffuse[i]);
N := Vertices.Normals[i];
V := Vertices.Vertices[i];
end;
end;
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glTexCoordPointer(2, GL_FLOAT, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0])));
glColorPointer(4, GL_UNSIGNED_BYTE, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0]) + 2 * 4));
glNormalPointer(GL_FLOAT, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0]) + 3 * 4));
glVertexPointer(3, GL_FLOAT, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0]) + 6 * 4));
end
else
if Vertices.Format = [TVertexFormat.vfVertex, TVertexFormat.vfDiffuse] then
begin
SetLength(TempVer, Vertices.Length);
for i := 0 to Vertices.Length - 1 do
begin
with TempVer[i] do
begin
C := CorrectColor(Vertices.Diffuse[i]);
V := Vertices.Vertices[i];
end;
end;
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_UNSIGNED_BYTE, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0]) + 2 * 4));
glVertexPointer(3, GL_FLOAT, SizeOf(T_T2F_C4U_N3F_V3F), Pointer(Integer(@TempVer[0]) + 6 * 4));
end
else
begin
if TVertexFormat.vfVertex in Vertices.Format then
begin
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, Vertices.VertexSize, Vertices.Buffer);
end;
if TVertexFormat.vfNormal in Vertices.Format then
begin
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, Vertices.VertexSize, Pointer(Integer(Vertices.Buffer) + GetVertexOffset(TVertexFormat.vfNormal, Vertices.Format)));
end;
if TVertexFormat.vfTexCoord0 in Vertices.Format then
begin
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, Vertices.VertexSize, Pointer(Integer(Vertices.Buffer) + GetVertexOffset(TVertexFormat.vfTexCoord0, Vertices.Format)));
end;
end;
glEnableClientState(GL_INDEX_ARRAY);
glIndexPointer(GL_UNSIGNED_SHORT, 0, Indices.Buffer);
end;
procedure TContextOpenGL.AssignToBitmap(Dest: TBitmap);
begin
Dest.SetSize(FWidth, FHeight);
glReadPixels(0, 0, FWidth, FHeight, GL_RGBA, GL_UNSIGNED_BYTE, Dest.StartLine);
Dest.FlipVertical;
end;
procedure TContextOpenGL.UnApplyVertices;
begin
glDisableClientState(GL_INDEX_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
end;
procedure TContextOpenGL.DrawTrianglesList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_TRIANGLES, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.DrawTrianglesStrip(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_TRIANGLE_STRIP, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.DrawTrianglesFan(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_TRIANGLE_FAN, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.DrawLinesList(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_LINES, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.DrawLinesStrip(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_LINE_STRIP, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.DrawPointsList(const Vertices: TVertexBuffer;
const Indices: TIndexBuffer; const Opacity: Single);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
try
glMultMatrixf(@FCurrentMatrix);
ApplyVertices(Vertices, Indices, Opacity);
glDrawElements(GL_POINTS, Indices.Length, GL_UNSIGNED_SHORT, Indices.Buffer);
UnApplyVertices;
finally
glPopMatrix;
end;
end;
end;
procedure TContextOpenGL.SetTextureMatrix(const AUnit: Integer; const AMatrix: TMatrix);
begin
end;
procedure TContextOpenGL.SetTextureUnit(const AUnit: Integer; const ABitmap: TBitmap);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glActiveTexture(GL_TEXTURE0 + AUnit);
if ABitmap = nil then
begin
glBindTexture(GL_TEXTURE_2D, 0);
Exit;
end;
UpdateBitmapHandle(ABitmap);
glBindTexture(GL_TEXTURE_2D, Integer(ABitmap.Handles[FirstContext]));
glActiveTexture(GL_TEXTURE0);
end;
end;
procedure TContextOpenGL.SetTextureUnitFromContext(const AUnit: Integer; const ARect: PRectF = nil);
var
I: Integer;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glActiveTexture(GL_TEXTURE0 + AUnit);
if FColorBufTex = 0 then
glGenTextures(1, @FColorBufTex);
glBindTexture(GL_TEXTURE_2D, FColorBufTex);
if FCurrentStates[TContextState.csTexLinear] then
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
end
else
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
end;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (ARect <> nil) then
begin
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ARect.Truncate.Width, ARect.Truncate.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil);
for I := 0 to ARect.Truncate.Height - 1 do
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, I, 0, FHeight - I - 1, ARect.Truncate.Width, 1);
end
else
begin
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, FWidth, FHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil);
for I := 0 to FHeight - 1 do
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, FHeight - I - 1, 0, I, FWidth, 1);
end;
glActiveTexture(GL_TEXTURE0);
end;
end;
procedure TContextOpenGL.SetStencilOp(const Fail, ZFail, ZPass: TStencilOp);
var
gFail, gZFail, gZPass: GLenum;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
case Fail of
TStencilOp.soKeep: gFail := GL_KEEP;
TStencilOp.soZero: gFail := GL_ZERO;
TStencilOp.soReplace: gFail := GL_KEEP;
TStencilOp.soIncrease: gFail := GL_INCR;
TStencilOp.soDecrease: gFail := GL_DECR;
TStencilOp.soInvert: gFail := GL_INVERT;
end;
case ZFail of
TStencilOp.soKeep: gZFail := GL_KEEP;
TStencilOp.soZero: gZFail := GL_ZERO;
TStencilOp.soReplace: gZFail := GL_KEEP;
TStencilOp.soIncrease: gZFail := GL_INCR;
TStencilOp.soDecrease: gZFail := GL_DECR;
TStencilOp.soInvert: gZFail := GL_INVERT;
end;
case ZPass of
TStencilOp.soKeep: gZPass := GL_KEEP;
TStencilOp.soZero: gZPass := GL_ZERO;
TStencilOp.soReplace: gZPass := GL_KEEP;
TStencilOp.soIncrease: gZPass := GL_INCR;
TStencilOp.soDecrease: gZPass := GL_DECR;
TStencilOp.soInvert: gZPass := GL_INVERT;
end;
glStencilOp(gFail, gZFail, gZPass);
end;
end;
procedure TContextOpenGL.SetStencilFunc(const Func: TStencilfunc; Ref, Mask: cardinal);
var
gFunc: GLenum;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
case Func of
TStencilFunc.sfNever: gFunc := GL_NEVER;
TStencilFunc.sfLess: gFunc := GL_LESS;
TStencilFunc.sfLequal: gFunc := GL_LEQUAL;
TStencilFunc.sfGreater: gFunc := GL_GREATER;
TStencilFunc.fsGequal: gFunc := GL_GEQUAL;
TStencilFunc.sfEqual: gFunc := GL_EQUAL;
TStencilFunc.sfNotEqual: gFunc := GL_NOTEQUAL;
TStencilFunc.sfAlways: gFunc := GL_ALWAYS;
end;
glStencilFunc(gFunc, Ref, Mask);
end;
end;
procedure TContextOpenGL.UpdateBitmapHandle(ABitmap: TBitmap);
var
i: Integer;
Tex: THandle;
begin
if ABitmap = nil then Exit;
if ABitmap.Width * ABitmap.Height = 0 then
begin
ABitmap.HandlesNeedUpdate[FirstContext] := False;
Exit;
end;
if FContextObject = nil then
Exit;
FContextObject.makeCurrentContext;
{ create - if need }
if not ABitmap.HandleExists(FirstContext) then
begin
glGenTextures(1, @Tex);
glBindTexture(GL_TEXTURE_2D, Tex);
if FCurrentStates[TContextState.csTexLinear] then
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
end
else
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
end;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ABitmap.Width, ABitmap.Height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, ABitmap.Startline);
ABitmap.AddFreeNotify(FirstContext);
ABitmap.HandleAdd(FirstContext);
ABitmap.Handles[FirstContext] := Pointer(Tex);
ABitmap.HandlesNeedUpdate[FirstContext] := False;
FirstContext.FBitmaps.Add(ABitmap);
end
else
if ABitmap.HandlesNeedUpdate[FirstContext] then
begin
Tex := THandle(ABitmap.Handles[FirstContext]);
glBindTexture(GL_TEXTURE_2D, Tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ABitmap.Width, ABitmap.Height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, ABitmap.Startline);
ABitmap.HandlesNeedUpdate[FirstContext] := False;
end;
end;
procedure TContextOpenGL.DestroyBitmapHandle(ABitmap: TBitmap);
var
Tex: cardinal;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if (ABitmap.HandleExists(FirstContext)) then
begin
ABitmap.RemoveFreeNotify(FirstContext);
Tex := THandle(ABitmap.Handles[FirstContext]);
if Tex <> 0 then
glDeleteTextures(1, @Tex);
FirstContext.FBitmaps.Remove(ABitmap);
ABitmap.HandleRemove(FirstContext);
end;
end;
end;
{ vertex shaders }
function TContextOpenGL.CreateVertexShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader;
var
errorPos, Shader: Integer;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if ARBCode <> nil then
begin
glEnable(GL_VERTEX_PROGRAM_ARB);
try
glGenProgramsARB(1, @Shader);
if Shader <> 0 then
begin
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, Shader);
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(PAnsiChar(ARBCode)), PAnsiChar(ARBCode));
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, @errorPos);
if errorPos = -1 then
Result := TContextShader(Shader)
else
begin
Result := 0;
glDeleteProgramsARB(GL_VERTEX_PROGRAM_ARB, @Shader);
// Writeln('Vertex shader error');
end;
end
else
begin
Result := 0;
// Writeln('Vertex shader error');
end;
finally
glDisable(GL_VERTEX_PROGRAM_ARB);
end;
end;
end;
end;
procedure TContextOpenGL.DestroyVertexShader(const Shader: TContextShader);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if Shader <> 0 then
begin
glDeleteProgramsARB(1, @Shader);
// Shader := 0;
end;
end;
end;
procedure TContextOpenGL.SetVertexShader(const Shader: TContextShader);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if Shader = 0 then
glDisable(GL_VERTEX_PROGRAM_ARB)
else
begin
glEnable(GL_VERTEX_PROGRAM_ARB);
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, Integer(Shader));
end;
FCurrentVS := Shader;
end;
end;
procedure TContextOpenGL.SetVertexShaderVector(Index: Integer; const V: TVector3D);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glProgramLocalParameter4fARB(GL_VERTEX_PROGRAM_ARB, Index, V.X, V.Y, V.Z, V.W);
end;
end;
procedure TContextOpenGL.SetVertexShaderMatrix(Index: Integer; const M: TMatrix3D);
var
V: TVector3D;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
V := Vector3D(M.m11, M.m21, M.m31, M.m41);
glProgramLocalParameter4fARB(GL_VERTEX_PROGRAM_ARB, Index + 0, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m12, M.m22, M.m32, M.m42);
glProgramLocalParameter4fARB(GL_VERTEX_PROGRAM_ARB, Index + 1, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m13, M.m23, M.m33, M.m43);
glProgramLocalParameter4fARB(GL_VERTEX_PROGRAM_ARB, Index + 2, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m14, M.m24, M.m33, M.m44);
glProgramLocalParameter4fARB(GL_VERTEX_PROGRAM_ARB, Index + 3, V.X, V.Y, V.Z, V.W);
end;
end;
{ pixel shader }
function TContextOpenGL.CreatePixelShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader;
var
errorPos, Shader: Integer;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glEnable(GL_FRAGMENT_PROGRAM_ARB);
try
glGenProgramsARB(1, @Shader);
if Shader <> 0 then
begin
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, Shader);
glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(PAnsiChar(ARBCode)), PAnsiChar(ARBCode));
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, @errorPos);
if errorPos = -1 then
Result := TContextShader(Shader)
else
begin
Result := 0;
glDeleteProgramsARB(1, @Shader);
// Writeln('Pixel shader error');
end;
end else
Result := 0;
finally
glDisable(GL_FRAGMENT_PROGRAM_ARB);
end;
end;
end;
procedure TContextOpenGL.DestroyPixelShader(const Shader: TContextShader);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if Shader <> 0 then
begin
glDeleteProgramsARB(1, @Shader);
// Shader := 0;
end;
end;
end;
procedure TContextOpenGL.SetPixelShader(const Shader: TContextShader);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
if Shader = 0 then
glDisable(GL_FRAGMENT_PROGRAM_ARB)
else
begin
glEnable(GL_FRAGMENT_PROGRAM_ARB);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, Integer(Shader));
FCurrentPS := Shader;
end;
end;
end;
procedure TContextOpenGL.SetPixelShaderVector(Index: Integer; const V: TVector3D);
begin
if Valid then
begin
FContextObject.makeCurrentContext;
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, Index, V.X, V.Y, V.Z, V.W);
end;
end;
procedure TContextOpenGL.SetPixelShaderMatrix(Index: Integer; const M: TMatrix3D);
var
V: TVector3D;
begin
if Valid then
begin
FContextObject.makeCurrentContext;
V := Vector3D(M.m11, M.m21, M.m31, M.m41);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, Index + 0, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m12, M.m22, M.m32, M.m42);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, Index + 1, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m13, M.m23, M.m33, M.m43);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, Index + 2, V.X, V.Y, V.Z, V.W);
V := Vector3D(M.m14, M.m24, M.m33, M.m44);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, Index + 3, V.X, V.Y, V.Z, V.W);
end;
end;
var
OpenGLHandle: HMODULE;
procedure SelectOpenGLContext;
var
Vendor: String;
PixelFormat: NSOpenGLPixelFormat;
Ctx: NSOpenGLContext;
begin
OpenGLHandle := InitOpenGL;
PixelFormat := TNSOpenGLPixelFormat.Create;
PixelFormat := TNSOpenGLPixelFormat.Wrap(PixelFormat.initWithAttributes(@attrs[0]));
try
Ctx := TNSOpenGLContext.Create;
Ctx := TNSOpenGLContext.Wrap(Ctx.initWithFormat(PixelFormat, nil));
try
Ctx.makeCurrentContext;
Vendor := PAnsiChar(glGetString(GL_VENDOR));
if CompareText(Vendor, 'NVIDIA Corporation') = 0 then
SetOpenGLSLAsDefault
else
DefaultContextClass := TContextOpenGL;
finally
Ctx.release;
end;
finally
PixelFormat.release;
end;
end;
initialization
finalization
if FirstContext <> nil then
FirstContext.Free;
FreeLibrary(OpenGLHandle);
end.
|
{
fngdirwatch.pas
FnugryDirWatch Component
Copyright (C) 1998 Gleb Yourchenko
Version 1.0.0.1
Revision History:
1.0.0.1 EvWatchNotify modified. Record chain
processing bug fixed.
}
{$A-,B-,I-,R-,X+}
{$define PlatformCheck} // Check platform before allocating
// DirWatch instance.
unit FngDirWatch;
interface
uses
Windows, SysUtils, Classes, Messages, syncobjs;
const
FILE_ACTION_ADDED = $00000001;
FILE_ACTION_REMOVED = $00000002;
FILE_ACTION_MODIFIED = $00000003;
FILE_ACTION_RENAMED_OLD_NAME = $00000004;
FILE_ACTION_RENAMED_NEW_NAME = $00000005;
type
EDirWatchError = class(Exception);
TDirWatchOption = (
dw_file_name,
dw_dir_name,
dw_file_attr,
dw_file_size,
dw_file_write_date,
dw_file_access_date,
dw_file_creation_date,
dw_file_security
);
TDirWatchOptions = set of TDirWatchOption;
TFileChangeNotifyEvent = procedure(Sender :TObject;
Action :Integer; const FileName :string) of object;
TFnugryDirWatch = class(TComponent)
private
FWatchThread :TThread;
FOptions :TDirWatchOptions;
FWndHandle :HWND;
FErrorMsg :String;
FWatchSubtree :Boolean;
FDirectory :String;
FOnChange :TNotifyEvent;
FOnNotify :TFileChangeNotifyEvent;
function GetEnabled :Boolean;
procedure SetEnabled(const Value :Boolean);
procedure SetOptions(const Value :TDirWatchOptions);
procedure WatchWndProc(var M :TMessage);
function MakeFilter :Cardinal;
procedure SetWatchSubTree(const Value :Boolean);
function GetDirectory :String;
procedure SetDirectory(const Value :String);
procedure EvWatchNotify(Sender :TObject);
procedure EvWatchError(Sender :TObject);
protected
procedure AllocWatchThread;
procedure ReleaseWatchThread;
procedure RestartWatchThread;
procedure Change; virtual;
procedure Notify(Action :Integer; const FileName :String); virtual;
public
constructor Create(AOwner :TComponent); override;
destructor Destroy; override;
function ActionName(Action :Integer):String;
property ErrorMsg :String
read FErrorMsg;
published
property Enabled :Boolean
read GetEnabled write SetEnabled;
property Options :TDirWatchOptions
read FOptions write SetOptions;
property WatchSubTree :Boolean
read FWatchSubTree write SetWatchSubTree;
property Directory :String
read GetDirectory write SetDirectory;
property OnChange :TNotifyEvent
read FOnChange write FOnChange;
property OnNotify :TFileChangeNotifyEvent
read FOnNotify write FOnNotify;
end;
procedure Register;
implementation
uses
forms;
procedure Register;
begin
RegisterComponents('Samples', [TFnugryDirWatch]);
end;
{ Types & constants from winnt.h not
included in windows.pas: }
type
LPOVERLAPPED_COMPLETION_ROUTINE = procedure (
dwErrorCode :Longint;
dwNumberOfBytesTransfered :Longint;
lpOverlapped :POverlapped); stdcall;
TReadDirectoryChangesWProc = function(
hDirectory :THandle; lpBuffer :Pointer;
nBufferLength :Longint; bWatchSubtree :Bool;
dwNotifyFilter :Longint; var lpBytesReturned :Longint;
lpOverlapped :POVERLAPPED;
lpCompletionRoutine :LPOVERLAPPED_COMPLETION_ROUTINE):Bool; stdcall;
PFILE_NOTIFY_INFORMATION = ^TFILE_NOTIFY_INFORMATION;
TFILE_NOTIFY_INFORMATION = record
NextEntryOffset :Longint;
Action :Longint;
FileNameLength :Longint;
FileName :array[0..MAX_PATH-1] of WideChar;
end;
const
WM_DIRWATCH_ERROR = WM_USER + 137;
WM_DIRWATCH_NOTIFY = WM_USER + 138;
FILE_NOTIFY_CHANGE_FILE_NAME = $00000001;
FILE_NOTIFY_CHANGE_DIR_NAME = $00000002;
FILE_NOTIFY_CHANGE_ATTRIBUTES = $00000004;
FILE_NOTIFY_CHANGE_SIZE = $00000008;
FILE_NOTIFY_CHANGE_LAST_WRITE = $00000010;
FILE_NOTIFY_CHANGE_LAST_ACCESS = $00000020;
FILE_NOTIFY_CHANGE_CREATION = $00000040;
FILE_NOTIFY_CHANGE_SECURITY = $00000100;
FILE_LIST_DIRECTORY = $0001;
{ Error messages: }
const
m_err_platform = 'TFnugryDirWatch requires MS Windows NT Version 4 or higher';
m_err_opendir = 'Could not open directory "%s"'#13#10'Error code: %d';
m_err_link = 'Could not find procedure "%s" in module "%s"';
m_err_readchanges = 'ReadDirectoryChanges call failed.';
m_err_getresult = 'GetOverlappedResult call failed';
{ TDirWatchThread }
const
szKernel32 = 'kernel32';
szReadDirectoryChangesW = 'ReadDirectoryChangesW';
const
IO_BUFFER_LEN = 32*sizeof(TFILE_NOTIFY_INFORMATION);
type
CException = class of Exception;
TDirWatchThread = class(TThread)
private
FWatchSubTree :Bool;
FIOResult :Pointer;
FIOResultLen :Longint;
FDirHandle :THandle;
FDirectory :String;
FFilter :Cardinal;
FErrorClass :TClass;
FErrorMsg :String;
FOnError :TNotifyEvent;
FOnNotify :TNotifyEvent;
FCompletionEvent :TEvent;
FKernelHandle :Thandle;
FReadDirectoryChangesProc :TReadDirectoryChangesWProc;
protected
procedure Execute; override;
procedure DoError;
procedure DoNotify;
public
constructor Create(const aDir :String; aFilter :Cardinal;
aWatchSubTree :Bool; aNotifyProc, aErrorProc :TNotifyEvent);
destructor Destroy; override;
procedure ClearError;
property ErrorClass :TClass
read FErrorClass;
property ErrorMsg :String
read FErrorMsg;
property OnError :TNotifyEvent
read FOnError write FOnError;
property OnNotify :TNotifyEvent
read FOnNotify write FOnNotify;
property IOResult :Pointer
read FIOResult;
end;
procedure TDirWatchThread.ClearError;
begin
FErrorMsg := '';
FErrorClass := Nil;
end;
procedure TDirWatchThread.DoError;
begin
if assigned(FOnError) then
FOnError(Self);
end;
procedure TDirWatchThread.DoNotify;
begin
if assigned(FOnNotify) then
FOnNotify(Self);
end;
procedure TDirWatchThread.Execute;
var
Overlapped :TOVERLAPPED;
WaitResult :TWaitResult;
TmpFIOResultLen :Longint;
TmpBytesTransferred :DWORD;
begin
while not terminated do
try
//
// Do nothing if an error occured.
// (Waiting for owner to release the
// thread or clear error state)
//
if assigned(FErrorClass) then
begin
sleep(0);
continue;
end;
//
//
fillchar(overlapped, sizeof(overlapped), 0);
FCompletionEvent.ResetEvent;
overlapped.hEvent := FCompletionEvent.Handle;
TmpFIOResultLen := FIOResultLen;
if not FReadDirectoryChangesProc(FDirHandle,
FIOResult, IO_BUFFER_LEN, FWatchSubtree,
FFilter, TmpFIOResultLen, @Overlapped, nil) then
begin
FIOResultLen := TmpFIOResultLen;
raise EDirWatchError.Create(m_err_readchanges);
end;
repeat
WaitResult := FCompletionEvent.WaitFor(100);
if WaitResult = wrSignaled then
begin
//
// retrieve overlapped result
// and generate Notify event
//
TmpFIOResultLen := FIOResultLen;
if not GetOverlappedResult(FDirHandle,
Overlapped, TmpBytesTransferred, true) then
begin
FIOResultLen := TmpFIOResultLen;
raise EDirWatchError.Create(m_err_getresult);
end;
DoNotify;
end;
until terminated or (WaitResult <> wrTimeout);
except
on E :Exception do
begin
FErrorClass := E.ClassType;
FErrorMsg := E.Message;
DoError;
end
else
raise;
end;
end;
constructor TDirWatchThread.Create(const aDir :String;
aFilter :Cardinal; aWatchSubTree :Bool; aNotifyProc,
aErrorProc :TNotifyEvent);
begin
//
// Retrieve proc pointer, open directory to
// watch and allocate buffer for notification data.
// (note, it is done before calling inherited
// create (that calls BeginThread) so any exception
// will be still raised in caller's thread)
//
FKernelHandle := LoadLibrary(szKernel32);
assert(FKernelHandle <> 0);
FReadDirectoryChangesProc := GetProcAddress(
FKernelHandle, szReadDirectoryChangesW);
if not assigned(FReadDirectoryChangesProc) then
raise EDirWatchError.CreateFmt(m_err_link,
[szReadDirectoryChangesW, szKernel32]);
FDirHandle := CreateFile(
PChar(aDir),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ OR FILE_SHARE_DELETE OR FILE_SHARE_WRITE,
Nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS OR FILE_FLAG_OVERLAPPED,
0
);
if FDirHandle = INVALID_HANDLE_VALUE then
raise EDirWatchError.CreateFmt(
m_err_opendir, [aDir, GetLastError]);
GetMem(FIOResult, IO_BUFFER_LEN);
inherited Create(true);
FOnError := aErrorProc;
FOnNotify := aNotifyProc;
FFilter := aFilter;
FWatchSubTree := aWatchSubtree;
FDirectory := aDir;
FreeOnTerminate := false;
FCompletionEvent := TEvent.Create(nil, true, false, '');
//
// Start the thread
//
resume;
end;
destructor TDirWatchThread.Destroy;
begin
Terminate;
WaitFor;
if assigned(FCompletionEvent) then
FCompletionEvent.Free;
if FDirHandle <> INVALID_HANDLE_VALUE then
CloseHandle(FDirHandle);
if assigned(FIOResult) then
FreeMem(FIOResult);
if FKernelHandle <> 0 then
FreeLibrary(FKernelHandle);
inherited Destroy;
end;
{ TFnugryDirWatch }
procedure TFnugryDirWatch.AllocWatchThread;
begin
assert(FWatchThread = Nil);
FWatchThread := TDirWatchThread.Create(Directory,
MakeFilter, WatchSubtree, EvWatchNotify, EvWatchError);
end;
procedure TFnugryDirWatch.ReleaseWatchThread;
begin
assert(assigned(FWatchThread));
FWatchThread.Free;
FWatchThread := Nil;
end;
procedure TFnugryDirWatch.RestartWatchThread;
begin
Enabled := false;
Enabled := true;
end;
function TFnugryDirWatch.GetEnabled :Boolean;
begin
result := assigned(FWatchThread);
end;
procedure TFnugryDirWatch.SetEnabled(const Value :Boolean);
begin
if Value <> Enabled then
begin
if Value then
AllocWatchThread
else
ReleaseWatchThread;
Change;
end;
end;
destructor TFnugryDirWatch.Destroy;
begin
Enabled := false;
if FWndHandle <> 0 then
DeallocateHWnd(FWndHandle);
inherited Destroy;
end;
constructor TFnugryDirWatch.Create(AOwner :TComponent);
begin
{$ifdef PlatformCheck}
if (Win32Platform <> VER_PLATFORM_WIN32_NT) then
raise EDirWatchError.Create(m_err_platform);
{$endif}
inherited Create(AOwner);
FWndHandle := AllocateHWnd(WatchWndProc);
FOptions := [dw_file_name, dw_dir_name, dw_file_size,
dw_file_attr, dw_file_creation_date, dw_file_access_date,
dw_file_write_date, dw_file_security];
FWatchSubtree := true;
end;
procedure TFnugryDirWatch.SetOptions(const Value :TDirWatchOptions);
begin
if FOptions <> Value then
begin
FOptions := Value;
if Enabled then RestartWatchThread;
Change;
end;
end;
procedure TFnugryDirWatch.WatchWndProc(var M :TMessage);
var
ErrorClass :CException;
begin
case m.msg of
WM_DIRWATCH_NOTIFY :
//
// Retrieve notify data and forward
// the event to TFnugryDirWatch's notify
// handler. Free filename string (allocated
// in WatchThread's notify handler.)
//
begin
try
Notify(m.wParam, WideCharToString(PWideChar(m.lParam)));
finally
if m.lParam <> 0 then
FreeMem(Pointer(m.lParam));
end;
end;
WM_DIRWATCH_ERROR :
//
// Disable dir watch and re-raise
// exception on error
//
begin
ErrorClass := CException(m.lParam);
assert(assigned(ErrorClass));
Enabled := false;
raise ErrorClass.Create(ErrorMsg);
end;
end;
end;
function TFnugryDirWatch.MakeFilter :Cardinal;
const
FilterFlags :array[TDirWatchOption] of Integer = (
FILE_NOTIFY_CHANGE_FILE_NAME,
FILE_NOTIFY_CHANGE_DIR_NAME,
FILE_NOTIFY_CHANGE_ATTRIBUTES,
FILE_NOTIFY_CHANGE_SIZE,
FILE_NOTIFY_CHANGE_LAST_WRITE,
FILE_NOTIFY_CHANGE_LAST_ACCESS,
FILE_NOTIFY_CHANGE_CREATION,
FILE_NOTIFY_CHANGE_SECURITY);
var
f :TDirWatchOption;
begin
result := 0;
for f := low(TDirWatchOption) to high(TDirWatchOption) do
if f in FOptions then
result := result or FilterFlags[f];
end;
procedure TFnugryDirWatch.EvWatchNotify(Sender :TObject);
var
NotifyData :PFILE_NOTIFY_INFORMATION;
FileName :PWideChar;
NextEntry :Integer;
begin
assert(Sender is TDirWatchThread);
NotifyData := TDirWatchThread(Sender).IOResult;
repeat
FileName := nil;
if NotifyData^.FileNameLength > 0 then
begin
GetMem(FileName, NotifyData^.FileNameLength + 2);
move(NotifyData^.FileName, Pointer(FileName)^, NotifyData^.FileNameLength);
PWord(Integer(FileName)+NotifyData^.FileNameLength)^ := 0;
end;
PostMessage(FWndHandle, WM_DIRWATCH_NOTIFY, NotifyData^.Action, LPARAM(FileName));
NextEntry := NotifyData^.NextEntryOffset;
inc(longint(NotifyData), NextEntry);
until (NextEntry = 0);
end;
procedure TFnugryDirWatch.EvWatchError(Sender :TObject);
begin
assert(Sender is TDirWatchThread);
FErrorMsg := TDirWatchThread(Sender).ErrorMsg;
PostMessage(FWndHandle, WM_DIRWATCH_ERROR, 0,
LPARAM(TDirWatchThread(Sender).ErrorClass));
end;
procedure TFnugryDirWatch.SetWatchSubTree(const Value :Boolean);
begin
if Value <> FWatchSubtree then
begin
FWatchSubtree := Value;
if Enabled then RestartWatchThread;
Change;
end;
end;
function TFnugryDirWatch.GetDirectory :String;
begin
result := FDirectory;
if result = '' then result := '.\';
end;
procedure TFnugryDirWatch.SetDirectory(const Value :String);
begin
if stricomp(PChar(trim(Value)), PChar(FDirectory)) <> 0 then
begin
FDirectory := trim(Value);
if Enabled then RestartWatchThread;
Change;
end;
end;
procedure TFnugryDirWatch.Change;
begin
if assigned(FOnChange) then FOnChange(Self);
end;
procedure TFnugryDirWatch.Notify(
Action :Integer; const FileName :String);
begin
if assigned(FOnNotify) then
FOnNotify(Self, Action, FileName);
end;
function TFnugryDirWatch.ActionName(Action :Integer):String;
const
ActionNames :array[FILE_ACTION_ADDED..FILE_ACTION_RENAMED_NEW_NAME] of string = (
'FILE_ACTION_ADDED', 'FILE_ACTION_REMOVED', 'FILE_ACTION_MODIFIED',
'FILE_ACTION_RENAMED_OLD_NAME', 'FILE_ACTION_RENAMED_NEW_NAME');
begin
if Action in [FILE_ACTION_ADDED..FILE_ACTION_RENAMED_NEW_NAME] then
result := ActionNames[Action]
else
result := 'FILE_ACTION_UNKNOWN';
end;
initialization
end.
|
unit uBotGestor;
interface
uses
System.Classes, Vcl.ExtCtrls, System.Generics.Collections,
uBotConversa,
uTInject,
uTInject.classes;
type
TBotManager = class(TComponent)
private
FSenhaADM: String;
FSimultaneos: Integer;
FTempoInatividade: Integer;
FConversas: TObjectList<TBotConversa>;
FOnInteracao: TNotifyConversa;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AdministrarChatList(AInject: TInject; AChats: TChatList);
procedure ProcessarResposta(AMessagem: TMessagesClass);
function BuscarConversa(AID: String): TBotConversa;
function NovaConversa(AMessage: TMessagesClass): TBotConversa;
function BuscarConversaEmEspera: TBotConversa;
function AtenderProximoEmEspera: TBotConversa;
property SenhaADM: String read FSenhaADM write FSenhaADM;
property Simultaneos: Integer read FSimultaneos write FSimultaneos default 1;
property Conversas: TObjectList<TBotConversa> read FConversas;
property TempoInatividade: Integer read FTempoInatividade write FTempoInatividade;
//Procedures notificadoras
procedure ProcessarInteracao(Conversa: TBotConversa);
procedure ConversaSituacaoAlterada(Conversa: TBotConversa);
//Notify
property OnInteracao: TNotifyConversa read FOnInteracao write FOnInteracao;
end;
implementation
uses
System.StrUtils, System.SysUtils;
{ TBotManager }
constructor TBotManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FConversas := TObjectList<TBotConversa>.Create;
end;
destructor TBotManager.Destroy;
begin
FreeAndNil(FConversas);
inherited Destroy;
end;
procedure TBotManager.AdministrarChatList(AInject: TInject; AChats: TChatList);
var
AChat : TChatClass;
AMessage: TMessagesClass;
begin
//Loop em todos os chats
for AChat in AChats.result do
begin
//Não considerar chats de grupos
if not AChat.isGroup then
begin
//Define que a mensagem ja foi lida,
//para evitar recarrega-la novamente.
AInject.ReadMessages( AChat.id );
//Pode haver mais de uma mensagem, pego a ultima
AMessage := AChat.messages[ Low( AChat.messages ) ];
//Não considerar mensagens enviadas por mim
if not AMessage.sender.isMe then
begin
//Carregar Conversa e passar a mensagem
ProcessarResposta( AMessage );
end;
end;
end;
end;
procedure TBotManager.ProcessarResposta(AMessagem: TMessagesClass);
var
AConversa: TBotConversa;
begin
AConversa := BuscarConversa( AMessagem.sender.id );
if not Assigned(AConversa) then
AConversa := NovaConversa( AMessagem );
//Tratando a situacao em que vem a mesma mensagem.
if AConversa.IDMensagem <> AMessagem.T then
begin
AConversa.IDMensagem := AMessagem.t;
AConversa.Resposta := AMessagem.body;
AConversa.&type := AMessagem.&type;
//Tratando a situacao em que vem a localizacao.
if (AMessagem.lat <> 0) and (AMessagem.lng <> 0) then
begin
AConversa.Lat := AMessagem.lat;
AConversa.Lng := AMessagem.lng;
end;
//Houve interacao, reinicia o timer de inatividade da conversa;
AConversa.ReiniciarTimer;
//Notifica mensagem recebida
ProcessarInteracao( AConversa );
end;
end;
function TBotManager.BuscarConversa(AID: String): TBotConversa;
var
AConversa: TBotConversa;
begin
Result := nil;
for AConversa in FConversas do
begin
if AConversa.ID = AID then
begin
Result := AConversa;
Break;
end;
end;
end;
function TBotManager.NovaConversa(AMessage: TMessagesClass): TBotConversa;
var
ADisponivel: Boolean;
begin
ADisponivel := (Conversas.Count < Simultaneos);
Result := TBotConversa.Create(Self);
with Result do
begin
case AMessage.body = SenhaADM of
False : TipoUsuario := tpCliente;
True : TipoUsuario := tpAdm;
end;
TempoInatividade := Self.TempoInatividade;
ID := AMessage.Sender.id;
Telefone := Copy(AMessage.sender.id,1,Pos('@',AMessage.sender.id)-1);
//Capturar nome publico, ou formatado (numero/nome).
Nome := IfThen(AMessage.sender.PushName <> EmptyStr
,AMessage.sender.PushName
,AMessage.sender.FormattedName);
//Eventos para controle externos
OnSituacaoAlterada := ConversaSituacaoAlterada;
OnRespostaRecebida := ProcessarInteracao;
end;
FConversas.Add( Result );
//Validando a disponibilidade ou tipo adm
if (ADisponivel) or (Result.TipoUsuario = tpAdm)
then Result.Situacao := saNova
else Result.Situacao := saEmEspera;
end;
function TBotManager.BuscarConversaEmEspera: TBotConversa;
var
AConversa: TBotConversa;
begin
Result := nil;
for AConversa in FConversas do
begin
if AConversa.Situacao = saEmEspera then
begin
Result := AConversa;
Break;
end;
end;
end;
function TBotManager.AtenderProximoEmEspera: TBotConversa;
var
AConversa: TBotConversa;
begin
Result := BuscarConversaEmEspera;
if Assigned( Result ) then
begin
Result.Situacao := saNova;
Result.ReiniciarTimer;
ProcessarInteracao(Result);
end;
end;
procedure TBotManager.ProcessarInteracao(Conversa: TBotConversa);
begin
if Assigned( OnInteracao ) then
OnInteracao( Conversa );
end;
procedure TBotManager.ConversaSituacaoAlterada(Conversa: TBotConversa);
begin
//Se ficou inativo
if Conversa.Situacao in [saInativa, saFinalizada] then
begin
//Encaminha
OnInteracao(Conversa);
//Destroy
Conversas.Remove( Conversa );
//Atende proximo da fila
AtenderProximoEmEspera;
end;
end;
end.
|
unit REMain;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Menus, ComCtrls, ClipBrd,
ToolWin, ActnList, ImgList;
type
TMainForm = class(TForm)
MainMenu: TMainMenu;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
FilePrintItem: TMenuItem;
FileExitItem: TMenuItem;
EditUndoItem: TMenuItem;
EditCutItem: TMenuItem;
EditCopyItem: TMenuItem;
EditPasteItem: TMenuItem;
HelpAboutItem: TMenuItem;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
PrintDialog: TPrintDialog;
Ruler: TPanel;
FontDialog1: TFontDialog;
FirstInd: TLabel;
LeftInd: TLabel;
RulerLine: TBevel;
RightInd: TLabel;
N5: TMenuItem;
miEditFont: TMenuItem;
Editor: TRichEdit;
StatusBar: TStatusBar;
StandardToolBar: TToolBar;
OpenButton: TToolButton;
SaveButton: TToolButton;
PrintButton: TToolButton;
ToolButton5: TToolButton;
UndoButton: TToolButton;
CutButton: TToolButton;
CopyButton: TToolButton;
PasteButton: TToolButton;
ToolButton10: TToolButton;
FontName: TComboBox;
FontSize: TEdit;
ToolButton11: TToolButton;
UpDown1: TUpDown;
BoldButton: TToolButton;
ItalicButton: TToolButton;
UnderlineButton: TToolButton;
ToolButton16: TToolButton;
LeftAlign: TToolButton;
CenterAlign: TToolButton;
RightAlign: TToolButton;
ToolButton20: TToolButton;
BulletsButton: TToolButton;
ToolbarImages: TImageList;
ActionList1: TActionList;
FileNewCmd: TAction;
FileOpenCmd: TAction;
FileSaveCmd: TAction;
FilePrintCmd: TAction;
FileExitCmd: TAction;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
Bevel1: TBevel;
LanguageMenu: TMenuItem;
LanguageEnglish: TMenuItem;
LanguageGerman: TMenuItem;
EditCutCmd: TAction;
EditCopyCmd: TAction;
EditPasteCmd: TAction;
EditUndoCmd: TAction;
EditFontCmd: TAction;
FileSaveAsCmd: TAction;
LanguageFrench: TMenuItem;
procedure SelectionChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ShowHint(Sender: TObject);
procedure FileNew(Sender: TObject);
procedure FileOpen(Sender: TObject);
procedure FileSave(Sender: TObject);
procedure FileSaveAs(Sender: TObject);
procedure FilePrint(Sender: TObject);
procedure FileExit(Sender: TObject);
procedure EditUndo(Sender: TObject);
procedure EditCut(Sender: TObject);
procedure EditCopy(Sender: TObject);
procedure EditPaste(Sender: TObject);
procedure HelpAbout(Sender: TObject);
procedure SelectFont(Sender: TObject);
procedure RulerResize(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure BoldButtonClick(Sender: TObject);
procedure ItalicButtonClick(Sender: TObject);
procedure FontSizeChange(Sender: TObject);
procedure AlignButtonClick(Sender: TObject);
procedure FontNameChange(Sender: TObject);
procedure UnderlineButtonClick(Sender: TObject);
procedure BulletsButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure RulerItemMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RulerItemMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FirstIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure LeftIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RightIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormShow(Sender: TObject);
procedure RichEditChange(Sender: TObject);
procedure SwitchLanguage(Sender: TObject);
procedure ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
private
FFileName: string;
FUpdating: Boolean;
FDragOfs: Integer;
FDragging: Boolean;
function CurrText: TTextAttributes;
procedure GetFontNames;
procedure SetFileName(const FileName: String);
procedure CheckFileSave;
procedure SetupRuler;
procedure SetEditRect;
procedure UpdateCursorPos;
procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES;
procedure PerformFileOpen(const AFileName: string);
procedure SetModified(Value: Boolean);
end;
var
MainForm: TMainForm;
implementation
uses REAbout, RichEdit, ShellAPI, ReInit;
resourcestring
sSaveChanges = 'Save changes to %s?';
sOverWrite = 'OK to overwrite %s';
sUntitled = 'Untitled';
sModified = 'Modified';
sColRowInfo = 'Line: %3d Col: %3d';
const
RulerAdj = 4/3;
GutterWid = 6;
ENGLISH = (SUBLANG_ENGLISH_US shl 10) or LANG_ENGLISH;
FRENCH = (SUBLANG_FRENCH shl 10) or LANG_FRENCH;
GERMAN = (SUBLANG_GERMAN shl 10) or LANG_GERMAN;
{$R *.DFM}
procedure TMainForm.SelectionChange(Sender: TObject);
begin
with Editor.Paragraph do
try
FUpdating := True;
FirstInd.Left := Trunc(FirstIndent*RulerAdj)-4+GutterWid;
LeftInd.Left := Trunc((LeftIndent+FirstIndent)*RulerAdj)-4+GutterWid;
RightInd.Left := Ruler.ClientWidth-6-Trunc((RightIndent+GutterWid)*RulerAdj);
BoldButton.Down := fsBold in Editor.SelAttributes.Style;
ItalicButton.Down := fsItalic in Editor.SelAttributes.Style;
UnderlineButton.Down := fsUnderline in Editor.SelAttributes.Style;
BulletsButton.Down := Boolean(Numbering);
FontSize.Text := IntToStr(Editor.SelAttributes.Size);
FontName.Text := Editor.SelAttributes.Name;
case Ord(Alignment) of
0: LeftAlign.Down := True;
1: RightAlign.Down := True;
2: CenterAlign.Down := True;
end;
UpdateCursorPos;
finally
FUpdating := False;
end;
end;
function TMainForm.CurrText: TTextAttributes;
begin
if Editor.SelLength > 0 then Result := Editor.SelAttributes
else Result := Editor.DefAttributes;
end;
function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
begin
TStrings(Data).Add(LogFont.lfFaceName);
Result := 1;
end;
procedure TMainForm.GetFontNames;
var
DC: HDC;
begin
DC := GetDC(0);
EnumFonts(DC, nil, @EnumFontsProc, Pointer(FontName.Items));
ReleaseDC(0, DC);
FontName.Sorted := True;
end;
procedure TMainForm.SetFileName(const FileName: String);
begin
FFileName := FileName;
Caption := Format('%s - %s', [ExtractFileName(FileName), Application.Title]);
end;
procedure TMainForm.CheckFileSave;
var
SaveResp: Integer;
begin
if not Editor.Modified then Exit;
SaveResp := MessageDlg(Format(sSaveChanges, [FFileName]),
mtConfirmation, mbYesNoCancel, 0);
case SaveResp of
idYes: FileSave(Self);
idNo: {Nothing};
idCancel: Abort;
end;
end;
procedure TMainForm.SetupRuler;
var
I: Integer;
S: String;
begin
SetLength(S, 201);
I := 1;
while I < 200 do
begin
S[I] := #9;
S[I+1] := '|';
Inc(I, 2);
end;
Ruler.Caption := S;
end;
procedure TMainForm.SetEditRect;
var
R: TRect;
begin
with Editor do
begin
R := Rect(GutterWid, 0, ClientWidth-GutterWid, ClientHeight);
SendMessage(Handle, EM_SETRECT, 0, Longint(@R));
end;
end;
{ Event Handlers }
procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnHint := ShowHint;
OpenDialog.InitialDir := ExtractFilePath(ParamStr(0));
SaveDialog.InitialDir := OpenDialog.InitialDir;
SetFileName(sUntitled);
GetFontNames;
SetupRuler;
SelectionChange(Self);
CurrText.Name := DefFontData.Name;
CurrText.Size := -MulDiv(DefFontData.Height, 72, Screen.PixelsPerInch);
LanguageEnglish.Tag := ENGLISH;
LanguageFrench.Tag := FRENCH;
LanguageGerman.Tag := GERMAN;
case SysLocale.DefaultLCID of
ENGLISH: SwitchLanguage(LanguageEnglish);
FRENCH: SwitchLanguage(LanguageFrench);
GERMAN: SwitchLanguage(LanguageGerman);
end;
end;
procedure TMainForm.ShowHint(Sender: TObject);
begin
if Length(Application.Hint) > 0 then
begin
StatusBar.SimplePanel := True;
StatusBar.SimpleText := Application.Hint;
end
else StatusBar.SimplePanel := False;
end;
procedure TMainForm.FileNew(Sender: TObject);
begin
SetFileName(sUntitled);
Editor.Lines.Clear;
Editor.Modified := False;
SetModified(False);
end;
procedure TMainForm.PerformFileOpen(const AFileName: string);
begin
Editor.Lines.LoadFromFile(AFileName);
SetFileName(AFileName);
Editor.SetFocus;
Editor.Modified := False;
SetModified(False);
end;
procedure TMainForm.FileOpen(Sender: TObject);
begin
CheckFileSave;
if OpenDialog.Execute then
begin
PerformFileOpen(OpenDialog.FileName);
Editor.ReadOnly := ofReadOnly in OpenDialog.Options;
end;
end;
procedure TMainForm.FileSave(Sender: TObject);
begin
if FFileName = sUntitled then
FileSaveAs(Sender)
else
begin
Editor.Lines.SaveToFile(FFileName);
Editor.Modified := False;
SetModified(False);
end;
end;
procedure TMainForm.FileSaveAs(Sender: TObject);
begin
if SaveDialog.Execute then
begin
if FileExists(SaveDialog.FileName) then
if MessageDlg(Format(sOverWrite, [SaveDialog.FileName]),
mtConfirmation, mbYesNoCancel, 0) <> idYes then Exit;
Editor.Lines.SaveToFile(SaveDialog.FileName);
SetFileName(SaveDialog.FileName);
Editor.Modified := False;
SetModified(False);
end;
end;
procedure TMainForm.FilePrint(Sender: TObject);
begin
if PrintDialog.Execute then
Editor.Print(FFileName);
end;
procedure TMainForm.FileExit(Sender: TObject);
begin
Close;
end;
procedure TMainForm.EditUndo(Sender: TObject);
begin
with Editor do
if HandleAllocated then SendMessage(Handle, EM_UNDO, 0, 0);
end;
procedure TMainForm.EditCut(Sender: TObject);
begin
Editor.CutToClipboard;
end;
procedure TMainForm.EditCopy(Sender: TObject);
begin
Editor.CopyToClipboard;
end;
procedure TMainForm.EditPaste(Sender: TObject);
begin
Editor.PasteFromClipboard;
end;
procedure TMainForm.HelpAbout(Sender: TObject);
begin
with TAboutBox.Create(Self) do
try
ShowModal;
finally
Free;
end;
end;
procedure TMainForm.SelectFont(Sender: TObject);
begin
FontDialog1.Font.Assign(Editor.SelAttributes);
if FontDialog1.Execute then
CurrText.Assign(FontDialog1.Font);
SelectionChange(Self);
Editor.SetFocus;
end;
procedure TMainForm.RulerResize(Sender: TObject);
begin
RulerLine.Width := Ruler.ClientWidth - (RulerLine.Left*2);
end;
procedure TMainForm.FormResize(Sender: TObject);
begin
SetEditRect;
SelectionChange(Sender);
end;
procedure TMainForm.FormPaint(Sender: TObject);
begin
SetEditRect;
end;
procedure TMainForm.BoldButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if BoldButton.Down then
CurrText.Style := CurrText.Style + [fsBold]
else
CurrText.Style := CurrText.Style - [fsBold];
end;
procedure TMainForm.ItalicButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if ItalicButton.Down then
CurrText.Style := CurrText.Style + [fsItalic]
else
CurrText.Style := CurrText.Style - [fsItalic];
end;
procedure TMainForm.FontSizeChange(Sender: TObject);
begin
if FUpdating then Exit;
CurrText.Size := StrToInt(FontSize.Text);
end;
procedure TMainForm.AlignButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
Editor.Paragraph.Alignment := TAlignment(TControl(Sender).Tag);
end;
procedure TMainForm.FontNameChange(Sender: TObject);
begin
if FUpdating then Exit;
CurrText.Name := FontName.Items[FontName.ItemIndex];
end;
procedure TMainForm.UnderlineButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
if UnderlineButton.Down then
CurrText.Style := CurrText.Style + [fsUnderline]
else
CurrText.Style := CurrText.Style - [fsUnderline];
end;
procedure TMainForm.BulletsButtonClick(Sender: TObject);
begin
if FUpdating then Exit;
Editor.Paragraph.Numbering := TNumberingStyle(BulletsButton.Down);
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
try
CheckFileSave;
except
CanClose := False;
end;
end;
{ Ruler Indent Dragging }
procedure TMainForm.RulerItemMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragOfs := (TLabel(Sender).Width div 2);
TLabel(Sender).Left := TLabel(Sender).Left+X-FDragOfs;
FDragging := True;
end;
procedure TMainForm.RulerItemMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if FDragging then
TLabel(Sender).Left := TLabel(Sender).Left+X-FDragOfs
end;
procedure TMainForm.FirstIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.FirstIndent := Trunc((FirstInd.Left+FDragOfs-GutterWid) / RulerAdj);
LeftIndMouseUp(Sender, Button, Shift, X, Y);
end;
procedure TMainForm.LeftIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.LeftIndent := Trunc((LeftInd.Left+FDragOfs-GutterWid) / RulerAdj)-Editor.Paragraph.FirstIndent;
SelectionChange(Sender);
end;
procedure TMainForm.RightIndMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
Editor.Paragraph.RightIndent := Trunc((Ruler.ClientWidth-RightInd.Left+FDragOfs-2) / RulerAdj)-2*GutterWid;
SelectionChange(Sender);
end;
procedure TMainForm.UpdateCursorPos;
var
CharPos: TPoint;
begin
CharPos.Y := SendMessage(Editor.Handle, EM_EXLINEFROMCHAR, 0,
Editor.SelStart);
CharPos.X := (Editor.SelStart -
SendMessage(Editor.Handle, EM_LINEINDEX, CharPos.Y, 0));
Inc(CharPos.Y);
Inc(CharPos.X);
StatusBar.Panels[0].Text := Format(sColRowInfo, [CharPos.Y, CharPos.X]);
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
UpdateCursorPos;
DragAcceptFiles(Handle, True);
RichEditChange(nil);
Editor.SetFocus;
{ Check if we should load a file from the command line }
if (ParamCount > 0) and FileExists(ParamStr(1)) then
PerformFileOpen(ParamStr(1));
end;
procedure TMainForm.WMDropFiles(var Msg: TWMDropFiles);
var
CFileName: array[0..MAX_PATH] of Char;
begin
try
if DragQueryFile(Msg.Drop, 0, CFileName, MAX_PATH) > 0 then
begin
CheckFileSave;
PerformFileOpen(CFileName);
Msg.Result := 0;
end;
finally
DragFinish(Msg.Drop);
end;
end;
procedure TMainForm.RichEditChange(Sender: TObject);
begin
SetModified(Editor.Modified);
end;
procedure TMainForm.SetModified(Value: Boolean);
begin
if Value then StatusBar.Panels[1].Text := sModified
else StatusBar.Panels[1].Text := '';
end;
procedure TMainForm.SwitchLanguage(Sender: TObject);
var
Name : String;
Size : Integer;
begin
if LoadNewResourceModule(TComponent(Sender).Tag) <> 0 then
begin
Name := FontName.Text;
Size := StrToInt(FontSize.Text);
ReinitializeForms;
LanguageEnglish.Checked := LanguageEnglish = Sender;
LanguageFrench.Checked := LanguageFrench = Sender;
LanguageGerman.Checked := LanguageGerman = Sender;
CurrText.Name := Name;
CurrText.Size := Size;
SelectionChange(Self);
FontName.SelLength := 0;
SetupRuler;
if Visible then Editor.SetFocus;
end;
end;
procedure TMainForm.ActionList2Update(Action: TBasicAction;
var Handled: Boolean);
begin
{ Update the status of the edit commands }
EditCutCmd.Enabled := Editor.SelLength > 0;
EditCopyCmd.Enabled := EditCutCmd.Enabled;
if Editor.HandleAllocated then
begin
EditUndoCmd.Enabled := Editor.Perform(EM_CANUNDO, 0, 0) <> 0;
EditPasteCmd.Enabled := Editor.Perform(EM_CANPASTE, 0, 0) <> 0;
end;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourNavMeshHelper;
interface
// Undefine (or define in a build cofnig) the following line to use 64bit polyref.
// Generally not needed, useful for very large worlds.
// Note: tiles build using 32bit refs are not compatible with 64bit refs!
//#define DT_POLYREF64 1
// Note: If you want to use 64-bit refs, change the types of both dtPolyRef & dtTileRef.
// It is also recommended that you change dtHashRef() to a proper 64-bit hash.
/// A handle to a polygon within a navigation mesh tile.
/// @ingroup detour
{$ifdef DT_POLYREF64}
const
DT_SALT_BITS = 16;
DT_TILE_BITS = 28;
DT_POLY_BITS = 20;
type
TdtPolyRef = UInt64;
{$else}
type
TdtPolyRef = Cardinal;
{$endif}
PdtPolyRef = ^TdtPolyRef;
/// A handle to a tile within a navigation mesh.
/// @ingroup detour
{$ifdef DT_POLYREF64}
TdtTileRef = UInt64;
{$else}
TdtTileRef = Cardinal;
{$endif}
PdtTileRef = ^TdtTileRef;
implementation
end. |
unit printfrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, ExtCtrls, ComCtrls, IniFiles, RepDataUnit, DB;
type
ReportPanel = record
repid: integer;
caption: string;
cnt: integer;
pnl: TPanel;
upd: TUpDown;
end;
TPrintForm = class(TForm)
pnlBottom: TPanel;
btnOk: TButton;
btnCancel: TButton;
pnlTop: TPanel;
btnPreview: TCheckBox;
btnConfig: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnConfigClick(Sender: TObject);
private
panels: array of ReportPanel;
function ShowPanels(empty: boolean): boolean;
procedure ClearPanels();
procedure AddPanel(repid: integer; const caption: string);
procedure AddPanels(reps: PListReport);
public
function Execute(kind: integer; docid: integer; qryDoc, qryRec, qryCredit: TDataSet): boolean;
end;
var
PrintForm: TPrintForm;
implementation
uses config, dataunit, print;
{$R *.DFM}
procedure TPrintForm.FormCreate(Sender: TObject);
begin
btnPreview.Checked := PreviewReports;
end;
procedure TPrintForm.FormShow(Sender: TObject);
begin
Realign;
end;
procedure TPrintForm.btnConfigClick(Sender: TObject);
var all: boolean;
begin
all := ShowPanels(btnConfig.Tag <> 0);
if all then
begin
btnConfig.Tag := 0;
btnConfig.Caption := '<<';
end else begin
btnConfig.Tag := 1;
btnConfig.Caption := '>>';
end;
end;
//------------------------------------------------------------------------------
function TPrintForm.ShowPanels(empty: boolean): boolean;
var
i: integer;
begin
result := true;
for i := 0 to Length(panels) - 1 do
begin
panels[i].pnl.Visible := empty or (panels[i].upd.Position > 0);
if panels[i].pnl.Visible then panels[i].pnl.Top := pnlBottom.Top - 1
else result := false;
end;
end;
procedure TPrintForm.ClearPanels();
var
i: integer;
begin
for i := 0 to Length(panels) - 1 do
begin
if panels[i].pnl <> nil then panels[i].pnl.Free;
end;
SetLength(panels, 0);
end;
procedure TPrintForm.AddPanel(repid: integer; const caption: string);
var
i, cnt: integer;
pnl: TPanel;
lb: TLabel;
edt: TEdit;
upd: TUpDown;
begin
cnt := CurrentConfig.getInteger('forms.TPrintForm.count_' + caption, 1);
pnl := TPanel.Create(self);
pnl.Visible := false;
pnl.Height := 26;
pnl.Align := alTop;
pnl.Parent := self;
pnl.BevelInner := bvNone;
pnl.BevelOuter := bvNone;
//pnl.Top := pnlBottom.Top - 1;
edt := TEdit.Create(self);
edt.Left := 190;
edt.Top := (pnl.Height - edt.Height) div 2;
edt.Width := 30;
edt.Text := IntToStr(cnt);
edt.Parent := pnl;
upd := TUpDown.Create(self);
upd.Parent := pnl;
upd.Associate := edt;
upd.Position := cnt;
lb := TLabel.Create(pnl);
lb.Alignment := taLeftJustify;
lb.Caption := caption;
lb.Left := edt.Left - lb.Width - 10;
lb.Top := (pnl.Height - lb.Height) div 2;
lb.Parent := pnl;
i := Length(panels);
SetLength(panels, i + 1);
panels[i].repid := repid;
panels[i].caption := caption;
panels[i].cnt := cnt;
panels[i].pnl := pnl;
panels[i].upd := upd;
end;
procedure TPrintForm.AddPanels(reps: PListReport);
var i: integer;
begin
for i := 0 to Length(reps^) - 1 do begin
AddPanel(reps^[i].id, reps^[i].caption);
end;
end;
function TPrintForm.Execute(kind: integer; docid: integer; qryDoc, qryRec, qryCredit: TDataSet): boolean;
var i, params: integer;
begin
ClearPanels();
if (kind and $01) = 0 then AddPanels(@RepData.ListDocProd)
else AddPanels(@RepData.ListDocQuery);
if (kind and $10) <> 0 then AddPanel(1, 'Приходный кассовый ордер');
if (kind and $20) <> 0 then AddPanel(2, 'Расходный кассовый ордер');
if (kind and $40) <> 0 then AddPanel(4, 'Платёжное поручение');
btnConfig.Tag := 0;
btnConfigClick(btnConfig);
result := (PrintForm.ShowModal = mrOk);
if not result then exit;
result := false;
params := 0;
if btnPreview.Checked then params := params or rpPreview;
for i := 0 to Length(panels) - 1 do
begin
if panels[i].cnt <> panels[i].upd.Position then
begin
panels[i].cnt := panels[i].upd.Position;
CurrentConfig.setInteger('forms.TPrintForm.count_' + panels[i].caption, panels[i].cnt);
end;
if panels[i].cnt > 0 then
begin
case (panels[i].repid) of
1: printOrder(docid, qryCredit, panels[i].cnt);
2: printROrder(docid, qryCredit, panels[i].cnt);
4: printPlat(docid, qryCredit, panels[i].cnt);
else RepData.printDoc(panels[i].repid, params, docid, qryDoc, qryRec, panels[i].cnt);
end;
result := true;
end;
end;
end;
//------------------------------------------------------------------------------
end.
|
unit Unit1;
interface
var
A0, B0, C0, D0: Int32;
A1, B1, C1, D1: Int32;
implementation
procedure Test;
begin
A0 := 1;
B0 := 2;
C1 := 3;
D1 := 4;
A1 := A0;
B1 := B0;
C0 := C1;
D0 := D1;
end;
initialization
Test();
finalization
assert(A0 = 1, 'A0 <> 1');
assert(B0 = 2, 'B0 <> 2');
assert(C0 = 3, 'C0 <> 3');
assert(D0 = 4, 'D0 <> 4');
assert(A1 = 1, 'A1 <> 1');
assert(B1 = 2, 'A2 <> 2');
assert(C1 = 3, 'A3 <> 3');
assert(D1 = 4, 'A4 <> 4');
end. |
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/zSound * }
{ ****************************************************************************** }
(*
Optimize.Move -- optimizing System.Move routine for SIMD
instruction sets at runtime.
Copyright (C) 2008 Ciobanu Alexandru, MMX/SSE/SSE2/SSE3 versions
of Move routine originally written by Seth and taken from
YAWE project: http://code.google.com/p/yawe-mmorpg/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
unit Optimize.Move.Win32;
interface
implementation
{$IFNDEF FPC}
{$IFDEF WIN32}
uses
Windows, SysUtils;
{ SIMD Detection code }
type
TSimdInstructionSupport = (sisMMX, sisSSE, sisSSE2, sisSSE3);
TSimdInstructionSupportSet = set of TSimdInstructionSupport;
TCPUIDRegs = record
rEAX, rEBX, rECX, rEDX: Integer;
end;
var
SimdSupported: TSimdInstructionSupportSet;
CacheLimit : Integer;
NbrOfCPUs : Cardinal;
function CPUID(const FuncId: Integer): TCPUIDRegs;
var
Regs: TCPUIDRegs;
begin
{ Request the opcode support }
asm
{ Save registers }
Push eax
Push ebx
Push ecx
Push edx
{ Set the function 1 and clear others }
mov eax, [FuncId]
xor ebx, ebx
xor ecx, ecx
xor edx, edx
{ Call CPUID }
CPUID
{ Store the registers we need }
mov [Regs.rEAX], eax
mov [Regs.rEBX], ebx
mov [Regs.rECX], ecx
mov [Regs.rEDX], edx
{ Restore registers }
Pop edx
Pop ecx
Pop ebx
Pop eax
end;
Result := Regs;
end;
function CPUIIDSupports(const FuncId: Integer; const Extended: Boolean = False): Boolean;
begin
if Extended then
Result := CPUID($80000000).rEAX >= FuncId
else
Result := CPUID($00000000).rEAX >= FuncId;
end;
function GetSupportedSimdInstructionSets: TSimdInstructionSupportSet;
var
Regs: TCPUIDRegs;
begin
Result := [];
{ Check for iset support }
if not CPUIIDSupports($00000001) then
Exit;
{ Request SIMD support }
Regs := CPUID($00000001);
if ((Regs.rECX and 1) <> 0) then
Result := Result + [sisSSE3];
if ((Regs.rEDX and (1 shl 23)) <> 0) then
Result := Result + [sisMMX];
if ((Regs.rEDX and (1 shl 25)) <> 0) then
Result := Result + [sisSSE];
if ((Regs.rEDX and (1 shl 26)) <> 0) then
Result := Result + [sisSSE2];
{
Check if Windows supports XMM registers - run an instruction and check
for exceptions.
}
try
asm
ORPS XMM0, XMM0
end
except
begin
{ Exclude SSE instructions! }
Result := Result - [sisSSE, sisSSE2, sisSSE3];
end;
end;
end;
function GetL2CacheSize: Integer;
var
{ Variables used for config description }
Regs: TCPUIDRegs;
CfgD: packed array [0 .. 15] of Byte absolute Regs;
i, j : Integer;
QueryCount: Byte;
begin
{ Unknown cache size }
Result := 0;
{ Check for cache support }
if not CPUIIDSupports($00000002) then
Exit;
{ Request cache support }
Regs := CPUID($00000002);
{ Query count }
QueryCount := Regs.rEAX and $FF;
for i := 1 to QueryCount do
begin
for j := 1 to 15 do
begin
case CfgD[j] of
$39: Result := 128;
$3B: Result := 128;
$3C: Result := 256;
$41: Result := 128;
$42: Result := 256;
$43: Result := 512;
$44: Result := 1024;
$45: Result := 2048;
$78: Result := 1024;
$79: Result := 128;
$7A: Result := 256;
$7B: Result := 512;
$7C: Result := 1024;
$7D: Result := 2048;
$7F: Result := 512;
$82: Result := 256;
$83: Result := 512;
$84: Result := 1024;
$85: Result := 2048;
$86: Result := 512;
$87: Result := 1024;
end;
end;
{ Re-Request cache support }
if i < QueryCount then
Regs := CPUID($00000002);
end;
end;
function GetExtendedL2CacheSize: Integer;
var
Regs: TCPUIDRegs;
begin
Result := 0;
{ Check for cache support }
if not CPUIIDSupports($80000006, True) then
Exit;
{ CPUID: $80000005 }
Regs := CPUID($80000006);
{ L2 Cache size }
Result := Regs.rECX shr 16;
end;
procedure GetCPUInfo();
var
CacheSize1, CacheSize2: Integer;
SysInfo : TSystemInfo;
begin
{ Detect supported SIMD sets }
SimdSupported := GetSupportedSimdInstructionSets();
CacheSize1 := GetL2CacheSize();
CacheSize2 := GetExtendedL2CacheSize();
{ Get the cache limit }
if CacheSize2 > 0 then
CacheLimit := CacheSize2 * -512
else
CacheLimit := CacheSize1 * -512;
{ If the cache size is unknown use a hack }
if CacheLimit = 0 then
CacheLimit := -$7FFFFFFF;
{ Get core count }
GetSystemInfo(SysInfo);
NbrOfCPUs := SysInfo.dwNumberOfProcessors;
end;
function PatchMethod(OldMethod, NewMethod: Pointer): Boolean;
const
SizeOfJump = 5;
var
OldFlags: Cardinal;
__Jump : ^Byte;
__Addr : ^Integer;
begin
Result := False;
try
{ Change the code protection to write }
VirtualProtect(OldMethod, SizeOfJump, PAGE_READWRITE, OldFlags);
except
begin Exit;
end;
end;
try
{ Insert the jump instruction }
__Jump := OldMethod;
__Jump^ := $E9;
{ Insert the jump address = (OLD - NEW - SIZEOFJUMP) }
__Addr := PTR(Integer(OldMethod) + 1);
__Addr^ := Integer(NewMethod) - Integer(OldMethod) - SizeOfJump;
finally
{ Change the protection back to what it was }
VirtualProtect(OldMethod, SizeOfJump, OldFlags, OldFlags);
end;
{ Set status to success }
Result := True;
end;
const
TINYSIZE = 36;
procedure SmallForwardMove;
asm
jmp DWord PTR [@@FwdJumpTable+ecx*4]
Nop { Align Jump Table }
@@FwdJumpTable:
DD @@Done { Removes need to test for zero size move }
DD @@Fwd01, @@Fwd02, @@Fwd03, @@Fwd04, @@Fwd05, @@Fwd06, @@Fwd07, @@Fwd08
DD @@Fwd09, @@Fwd10, @@Fwd11, @@Fwd12, @@Fwd13, @@Fwd14, @@Fwd15, @@Fwd16
DD @@Fwd17, @@Fwd18, @@Fwd19, @@Fwd20, @@Fwd21, @@Fwd22, @@Fwd23, @@Fwd24
DD @@Fwd25, @@Fwd26, @@Fwd27, @@Fwd28, @@Fwd29, @@Fwd30, @@Fwd31, @@Fwd32
DD @@Fwd33, @@Fwd34, @@Fwd35, @@Fwd36
@@Fwd36:
mov ecx, [eax-36]
mov [edx-36], ecx
@@Fwd32:
mov ecx, [eax-32]
mov [edx-32], ecx
@@Fwd28:
mov ecx, [eax-28]
mov [edx-28], ecx
@@Fwd24:
mov ecx, [eax-24]
mov [edx-24], ecx
@@Fwd20:
mov ecx, [eax-20]
mov [edx-20], ecx
@@Fwd16:
mov ecx, [eax-16]
mov [edx-16], ecx
@@Fwd12:
mov ecx, [eax-12]
mov [edx-12], ecx
@@Fwd08:
mov ecx, [eax-8]
mov [edx-8], ecx
@@Fwd04:
mov ecx, [eax-4]
mov [edx-4], ecx
ret
Nop
@@Fwd35:
mov ecx, [eax-35]
mov [edx-35], ecx
@@Fwd31:
mov ecx, [eax-31]
mov [edx-31], ecx
@@Fwd27:
mov ecx, [eax-27]
mov [edx-27], ecx
@@Fwd23:
mov ecx, [eax-23]
mov [edx-23], ecx
@@Fwd19:
mov ecx, [eax-19]
mov [edx-19], ecx
@@Fwd15:
mov ecx, [eax-15]
mov [edx-15], ecx
@@Fwd11:
mov ecx, [eax-11]
mov [edx-11], ecx
@@Fwd07:
mov ecx, [eax-7]
mov [edx-7], ecx
mov ecx, [eax-4]
mov [edx-4], ecx
ret
Nop
@@Fwd03:
movzx ecx, Word PTR [eax-3]
mov [edx-3], Cx
movzx ecx, Byte PTR [eax-1]
mov [edx-1], cl
ret
@@Fwd34:
mov ecx, [eax-34]
mov [edx-34], ecx
@@Fwd30:
mov ecx, [eax-30]
mov [edx-30], ecx
@@Fwd26:
mov ecx, [eax-26]
mov [edx-26], ecx
@@Fwd22:
mov ecx, [eax-22]
mov [edx-22], ecx
@@Fwd18:
mov ecx, [eax-18]
mov [edx-18], ecx
@@Fwd14:
mov ecx, [eax-14]
mov [edx-14], ecx
@@Fwd10:
mov ecx, [eax-10]
mov [edx-10], ecx
@@Fwd06:
mov ecx, [eax-6]
mov [edx-6], ecx
@@Fwd02:
movzx ecx, Word PTR [eax-2]
mov [edx-2], Cx
ret
Nop
Nop
Nop
@@Fwd33:
mov ecx, [eax-33]
mov [edx-33], ecx
@@Fwd29:
mov ecx, [eax-29]
mov [edx-29], ecx
@@Fwd25:
mov ecx, [eax-25]
mov [edx-25], ecx
@@Fwd21:
mov ecx, [eax-21]
mov [edx-21], ecx
@@Fwd17:
mov ecx, [eax-17]
mov [edx-17], ecx
@@Fwd13:
mov ecx, [eax-13]
mov [edx-13], ecx
@@Fwd09:
mov ecx, [eax-9]
mov [edx-9], ecx
@@Fwd05:
mov ecx, [eax-5]
mov [edx-5], ecx
@@Fwd01:
movzx ecx, Byte PTR [eax-1]
mov [edx-1], cl
ret
@@Done:
end;
{ ------------------------------------------------------------------------- }
{ Perform Backward Move of 0..36 Bytes }
{ On Entry, ECX = Count, EAX = Source, EDX = Dest. Destroys ECX }
procedure SmallBackwardMove;
asm
jmp DWord PTR [@@BwdJumpTable+ecx*4]
Nop { Align Jump Table }
@@BwdJumpTable:
DD @@Done { Removes need to test for zero size move }
DD @@Bwd01, @@Bwd02, @@Bwd03, @@Bwd04, @@Bwd05, @@Bwd06, @@Bwd07, @@Bwd08
DD @@Bwd09, @@Bwd10, @@Bwd11, @@Bwd12, @@Bwd13, @@Bwd14, @@Bwd15, @@Bwd16
DD @@Bwd17, @@Bwd18, @@Bwd19, @@Bwd20, @@Bwd21, @@Bwd22, @@Bwd23, @@Bwd24
DD @@Bwd25, @@Bwd26, @@Bwd27, @@Bwd28, @@Bwd29, @@Bwd30, @@Bwd31, @@Bwd32
DD @@Bwd33, @@Bwd34, @@Bwd35, @@Bwd36
@@Bwd36:
mov ecx, [eax+32]
mov [edx+32], ecx
@@Bwd32:
mov ecx, [eax+28]
mov [edx+28], ecx
@@Bwd28:
mov ecx, [eax+24]
mov [edx+24], ecx
@@Bwd24:
mov ecx, [eax+20]
mov [edx+20], ecx
@@Bwd20:
mov ecx, [eax+16]
mov [edx+16], ecx
@@Bwd16:
mov ecx, [eax+12]
mov [edx+12], ecx
@@Bwd12:
mov ecx, [eax+8]
mov [edx+8], ecx
@@Bwd08:
mov ecx, [eax+4]
mov [edx+4], ecx
@@Bwd04:
mov ecx, [eax]
mov [edx], ecx
ret
Nop
Nop
Nop
@@Bwd35:
mov ecx, [eax+31]
mov [edx+31], ecx
@@Bwd31:
mov ecx, [eax+27]
mov [edx+27], ecx
@@Bwd27:
mov ecx, [eax+23]
mov [edx+23], ecx
@@Bwd23:
mov ecx, [eax+19]
mov [edx+19], ecx
@@Bwd19:
mov ecx, [eax+15]
mov [edx+15], ecx
@@Bwd15:
mov ecx, [eax+11]
mov [edx+11], ecx
@@Bwd11:
mov ecx, [eax+7]
mov [edx+7], ecx
@@Bwd07:
mov ecx, [eax+3]
mov [edx+3], ecx
mov ecx, [eax]
mov [edx], ecx
ret
Nop
Nop
Nop
@@Bwd03:
movzx ecx, Word PTR [eax+1]
mov [edx+1], Cx
movzx ecx, Byte PTR [eax]
mov [edx], cl
ret
Nop
Nop
@@Bwd34:
mov ecx, [eax+30]
mov [edx+30], ecx
@@Bwd30:
mov ecx, [eax+26]
mov [edx+26], ecx
@@Bwd26:
mov ecx, [eax+22]
mov [edx+22], ecx
@@Bwd22:
mov ecx, [eax+18]
mov [edx+18], ecx
@@Bwd18:
mov ecx, [eax+14]
mov [edx+14], ecx
@@Bwd14:
mov ecx, [eax+10]
mov [edx+10], ecx
@@Bwd10:
mov ecx, [eax+6]
mov [edx+6], ecx
@@Bwd06:
mov ecx, [eax+2]
mov [edx+2], ecx
@@Bwd02:
movzx ecx, Word PTR [eax]
mov [edx], Cx
ret
Nop
@@Bwd33:
mov ecx, [eax+29]
mov [edx+29], ecx
@@Bwd29:
mov ecx, [eax+25]
mov [edx+25], ecx
@@Bwd25:
mov ecx, [eax+21]
mov [edx+21], ecx
@@Bwd21:
mov ecx, [eax+17]
mov [edx+17], ecx
@@Bwd17:
mov ecx, [eax+13]
mov [edx+13], ecx
@@Bwd13:
mov ecx, [eax+9]
mov [edx+9], ecx
@@Bwd09:
mov ecx, [eax+5]
mov [edx+5], ecx
@@Bwd05:
mov ecx, [eax+1]
mov [edx+1], ecx
@@Bwd01:
movzx ecx, Byte PTR[eax]
mov [edx], cl
ret
@@Done:
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE) }
procedure Forwards_IA32;
asm
fild qword PTR [eax] { First 8 }
lea eax, [eax+ecx-8]
lea ecx, [edx+ecx-8]
Push edx
Push ecx
fild qword PTR [eax] { Last 8 }
Neg ecx { QWORD Align Writes }
and edx, -8
lea ecx, [ecx+edx+8]
Pop edx
@@Loop:
fild qword PTR [eax+ecx]
fistp qword PTR [edx+ecx]
Add ecx, 8
jl @@Loop
Pop eax
fistp qword PTR [edx] { Last 8 }
fistp qword PTR [eax] { First 8 }
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE) }
procedure Backwards_IA32;
asm
Sub ecx, 8
fild qword PTR [eax+ecx] { Last 8 }
fild qword PTR [eax] { First 8 }
Add ecx, edx { QWORD Align Writes }
Push ecx
and ecx, -8
Sub ecx, edx
@@Loop:
fild qword PTR [eax+ecx]
fistp qword PTR [edx+ecx]
Sub ecx, 8
jg @@Loop
Pop eax
fistp qword PTR [edx] { First 8 }
fistp qword PTR [eax] { Last 8 }
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE) }
procedure Forwards_MMX;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE { Size at which using MMX becomes worthwhile }
jl Forwards_IA32
cmp ecx, LARGESIZE
jge @@FwdLargeMove
Push ebx
mov ebx, edx
movq MM0, [eax] { First 8 Bytes }
Add eax, ecx { QWORD Align Writes }
Add ecx, edx
and edx, -8
Add edx, 40
Sub ecx, edx
Add edx, ecx
Neg ecx
Nop { Align Loop }
@@FwdLoopMMX:
movq MM1, [eax+ecx-32]
movq mm2, [eax+ecx-24]
movq mm3, [eax+ecx-16]
movq mm4, [eax+ecx- 8]
movq [edx+ecx-32], MM1
movq [edx+ecx-24], mm2
movq [edx+ecx-16], mm3
movq [edx+ecx- 8], mm4
Add ecx, 32
jle @@FwdLoopMMX
movq [ebx], MM0 { First 8 Bytes }
emms
Pop ebx
Neg ecx
Add ecx, 32
jmp SmallForwardMove
Nop { Align Loop }
Nop
@@FwdLargeMove:
Push ebx
mov ebx, ecx
test edx, 15
jz @@FwdAligned
lea ecx, [edx+15] { 16 byte Align Destination }
and ecx, -16
Sub ecx, edx
Add eax, ecx
Add edx, ecx
Sub ebx, ecx
call SmallForwardMove
@@FwdAligned:
mov ecx, ebx
and ecx, -16
Sub ebx, ecx { EBX = Remainder }
Push esi
Push edi
mov esi, eax { ESI = Source }
mov edi, edx { EDI = Dest }
mov eax, ecx { EAX = Count }
and eax, -64 { EAX = No of Bytes to Blocks Moves }
and ecx, $3F { ECX = Remaining Bytes to Move (0..63) }
Add esi, eax
Add edi, eax
Neg eax
@@MMXcopyloop:
movq MM0, [esi+eax ]
movq MM1, [esi+eax+ 8]
movq mm2, [esi+eax+16]
movq mm3, [esi+eax+24]
movq mm4, [esi+eax+32]
movq mm5, [esi+eax+40]
movq mm6, [esi+eax+48]
movq mm7, [esi+eax+56]
movq [edi+eax ], MM0
movq [edi+eax+ 8], MM1
movq [edi+eax+16], mm2
movq [edi+eax+24], mm3
movq [edi+eax+32], mm4
movq [edi+eax+40], mm5
movq [edi+eax+48], mm6
movq [edi+eax+56], mm7
Add eax, 64
jnz @@MMXcopyloop
emms { Empty MMX State }
Add ecx, ebx
shr ecx, 2
Rep movsd
mov ecx, ebx
and ecx, 3
Rep movsb
Pop edi
Pop esi
Pop ebx
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE) }
procedure Backwards_MMX;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE { Size at which using MMX becomes worthwhile }
jl Backwards_IA32
Push ebx
movq MM0, [eax+ecx-8] { Get Last QWORD }
lea ebx, [edx+ecx] { QWORD Align Writes }
and ebx, 7
Sub ecx, ebx
Add ebx, ecx
Sub ecx, 32
@@BwdLoopMMX:
movq MM1, [eax+ecx ]
movq mm2, [eax+ecx+ 8]
movq mm3, [eax+ecx+16]
movq mm4, [eax+ecx+24]
movq [edx+ecx+24], mm4
movq [edx+ecx+16], mm3
movq [edx+ecx+ 8], mm2
movq [edx+ecx ], MM1
Sub ecx, 32
jge @@BwdLoopMMX
movq [edx+ebx-8], MM0 { Last QWORD }
emms
Add ecx, 32
Pop ebx
jmp SmallBackwardMove
end;
{ ------------------------------------------------------------------------- }
procedure LargeAlignedSSEMove;
asm
@@Loop:
movaps XMM0, [eax+ecx]
movaps xmm1, [eax+ecx+16]
movaps xmm2, [eax+ecx+32]
movaps xmm3, [eax+ecx+48]
movaps [edx+ecx], XMM0
movaps [edx+ecx+16], xmm1
movaps [edx+ecx+32], xmm2
movaps [edx+ecx+48], xmm3
movaps xmm4, [eax+ecx+64]
movaps xmm5, [eax+ecx+80]
movaps xmm6, [eax+ecx+96]
movaps xmm7, [eax+ecx+112]
movaps [edx+ecx+64], xmm4
movaps [edx+ecx+80], xmm5
movaps [edx+ecx+96], xmm6
movaps [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
end;
{ ------------------------------------------------------------------------- }
procedure LargeUnalignedSSEMove;
asm
@@Loop:
movups XMM0, [eax+ecx]
movups xmm1, [eax+ecx+16]
movups xmm2, [eax+ecx+32]
movups xmm3, [eax+ecx+48]
movaps [edx+ecx], XMM0
movaps [edx+ecx+16], xmm1
movaps [edx+ecx+32], xmm2
movaps [edx+ecx+48], xmm3
movups xmm4, [eax+ecx+64]
movups xmm5, [eax+ecx+80]
movups xmm6, [eax+ecx+96]
movups xmm7, [eax+ecx+112]
movaps [edx+ecx+64], xmm4
movaps [edx+ecx+80], xmm5
movaps [edx+ecx+96], xmm6
movaps [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
end;
{ ------------------------------------------------------------------------- }
procedure HugeAlignedSSEMove;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movaps XMM0, [eax+ecx]
movaps xmm1, [eax+ecx+16]
movaps xmm2, [eax+ecx+32]
movaps xmm3, [eax+ecx+48]
movntps [edx+ecx], XMM0
movntps [edx+ecx+16], xmm1
movntps [edx+ecx+32], xmm2
movntps [edx+ecx+48], xmm3
movaps xmm4, [eax+ecx+64]
movaps xmm5, [eax+ecx+80]
movaps xmm6, [eax+ecx+96]
movaps xmm7, [eax+ecx+112]
movntps [edx+ecx+64], xmm4
movntps [edx+ecx+80], xmm5
movntps [edx+ecx+96], xmm6
movntps [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
sfence
end;
{ ------------------------------------------------------------------------- }
procedure HugeUnalignedSSEMove;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movups XMM0, [eax+ecx]
movups xmm1, [eax+ecx+16]
movups xmm2, [eax+ecx+32]
movups xmm3, [eax+ecx+48]
movntps [edx+ecx], XMM0
movntps [edx+ecx+16], xmm1
movntps [edx+ecx+32], xmm2
movntps [edx+ecx+48], xmm3
movups xmm4, [eax+ecx+64]
movups xmm5, [eax+ecx+80]
movups xmm6, [eax+ecx+96]
movups xmm7, [eax+ecx+112]
movntps [edx+ecx+64], xmm4
movntps [edx+ecx+80], xmm5
movntps [edx+ecx+96], xmm6
movntps [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
sfence
end;
{ ------------------------------------------------------------------------- }
{ Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSEMove;
asm
Push ebx
mov ebx, ecx
and ecx, -128 { No of Bytes to Block Move (Multiple of 128) }
Add eax, ecx { End of Source Blocks }
Add edx, ecx { End of Dest Blocks }
Neg ecx
cmp ecx, CacheLimit { Count > Limit - Use Prefetch }
jl @@Huge
test eax, 15 { Check if Both Source/Dest are Aligned }
jnz @@LargeUnaligned
call LargeAlignedSSEMove { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@LargeUnaligned: { Source Not 16-Byte Aligned }
call LargeUnalignedSSEMove
jmp @@Remainder
@@Huge:
test eax, 15 { Check if Both Source/Dest Aligned }
jnz @@HugeUnaligned
call HugeAlignedSSEMove { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@HugeUnaligned: { Source Not 16-Byte Aligned }
call HugeUnalignedSSEMove
@@Remainder:
and ebx, $7F { Remainder (0..112 - Multiple of 16) }
jz @@Done
Add eax, ebx
Add edx, ebx
Neg ebx
@@RemainderLoop:
movups XMM0, [eax+ebx]
movaps [edx+ebx], XMM0
Add ebx, 16
jnz @@RemainderLoop
@@Done:
Pop ebx
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE) }
procedure Forwards_SSE;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
Push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
movups XMM0, [eax] { First 16 Bytes }
mov ebx, edx
Add eax, ecx { Align Writes }
Add ecx, edx
and edx, -16
Add edx, 48
Sub ecx, edx
Add edx, ecx
Neg ecx
Nop { Align Loop }
@@FwdLoopSSE:
movups xmm1, [eax+ecx-32]
movups xmm2, [eax+ecx-16]
movaps [edx+ecx-32], xmm1
movaps [edx+ecx-16], xmm2
Add ecx, 32
jle @@FwdLoopSSE
movups [ebx], XMM0 { First 16 Bytes }
Neg ecx
Add ecx, 32
Pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] { 16 byte Align Destination }
and ecx, -16
Sub ecx, edx
Add eax, ecx
Add edx, ecx
Sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
Sub ebx, ecx { EBX = Remainder }
Push edx
Push eax
Push ecx
call LargeSSEMove
Pop ecx
Pop eax
Pop edx
Add ecx, ebx
Add eax, ecx
Add edx, ecx
mov ecx, ebx
Pop ebx
jmp SmallForwardMove
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE) }
procedure Backwards_SSE;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
Push ebx
movups XMM0, [eax+ecx-16] { Last 16 Bytes }
lea ebx, [edx+ecx] { Align Writes }
and ebx, 15
Sub ecx, ebx
Add ebx, ecx
Sub ecx, 32
@@BwdLoop:
movups xmm1, [eax+ecx]
movups xmm2, [eax+ecx+16]
movaps [edx+ecx], xmm1
movaps [edx+ecx+16], xmm2
Sub ecx, 32
jge @@BwdLoop
movups [edx+ebx-16], XMM0 { Last 16 Bytes }
Add ecx, 32
Pop ebx
jmp SmallBackwardMove
end;
{ ------------------------------------------------------------------------- }
procedure LargeAlignedSSE2Move; { Also used in SSE3 Move }
asm
@@Loop:
movdqa XMM0, [eax+ecx]
movdqa xmm1, [eax+ecx+16]
movdqa xmm2, [eax+ecx+32]
movdqa xmm3, [eax+ecx+48]
movdqa [edx+ecx], XMM0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
movdqa xmm4, [eax+ecx+64]
movdqa xmm5, [eax+ecx+80]
movdqa xmm6, [eax+ecx+96]
movdqa xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
end;
{ ------------------------------------------------------------------------- }
procedure LargeUnalignedSSE2Move;
asm
@@Loop:
movdqu XMM0, [eax+ecx]
movdqu xmm1, [eax+ecx+16]
movdqu xmm2, [eax+ecx+32]
movdqu xmm3, [eax+ecx+48]
movdqa [edx+ecx], XMM0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
movdqu xmm4, [eax+ecx+64]
movdqu xmm5, [eax+ecx+80]
movdqu xmm6, [eax+ecx+96]
movdqu xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
end;
{ ------------------------------------------------------------------------- }
procedure HugeAlignedSSE2Move; { Also used in SSE3 Move }
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movdqa XMM0, [eax+ecx]
movdqa xmm1, [eax+ecx+16]
movdqa xmm2, [eax+ecx+32]
movdqa xmm3, [eax+ecx+48]
movntdq [edx+ecx], XMM0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
movdqa xmm4, [eax+ecx+64]
movdqa xmm5, [eax+ecx+80]
movdqa xmm6, [eax+ecx+96]
movdqa xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
sfence
end;
{ ------------------------------------------------------------------------- }
procedure HugeUnalignedSSE2Move;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movdqu XMM0, [eax+ecx]
movdqu xmm1, [eax+ecx+16]
movdqu xmm2, [eax+ecx+32]
movdqu xmm3, [eax+ecx+48]
movntdq [edx+ecx], XMM0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
movdqu xmm4, [eax+ecx+64]
movdqu xmm5, [eax+ecx+80]
movdqu xmm6, [eax+ecx+96]
movdqu xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
sfence
end; { HugeUnalignedSSE2Move }
{ ------------------------------------------------------------------------- }
{ Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSE2Move;
asm
Push ebx
mov ebx, ecx
and ecx, -128 { No of Bytes to Block Move (Multiple of 128) }
Add eax, ecx { End of Source Blocks }
Add edx, ecx { End of Dest Blocks }
Neg ecx
cmp ecx, CacheLimit { Count > Limit - Use Prefetch }
jl @@Huge
test eax, 15 { Check if Both Source/Dest are Aligned }
jnz @@LargeUnaligned
call LargeAlignedSSE2Move { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@LargeUnaligned: { Source Not 16-Byte Aligned }
call LargeUnalignedSSE2Move
jmp @@Remainder
@@Huge:
test eax, 15 { Check if Both Source/Dest Aligned }
jnz @@HugeUnaligned
call HugeAlignedSSE2Move { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@HugeUnaligned: { Source Not 16-Byte Aligned }
call HugeUnalignedSSE2Move
@@Remainder:
and ebx, $7F { Remainder (0..112 - Multiple of 16) }
jz @@Done
Add eax, ebx
Add edx, ebx
Neg ebx
@@RemainderLoop:
movdqu XMM0, [eax+ebx]
movdqa [edx+ebx], XMM0
Add ebx, 16
jnz @@RemainderLoop
@@Done:
Pop ebx
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE) }
procedure Forwards_SSE2;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
Push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
movdqu XMM0, [eax] { First 16 Bytes }
mov ebx, edx
Add eax, ecx { Align Writes }
Add ecx, edx
and edx, -16
Add edx, 48
Sub ecx, edx
Add edx, ecx
Neg ecx
@@FwdLoopSSE2:
movdqu xmm1, [eax+ecx-32]
movdqu xmm2, [eax+ecx-16]
movdqa [edx+ecx-32], xmm1
movdqa [edx+ecx-16], xmm2
Add ecx, 32
jle @@FwdLoopSSE2
movdqu [ebx], XMM0 { First 16 Bytes }
Neg ecx
Add ecx, 32
Pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] { 16 byte Align Destination }
and ecx, -16
Sub ecx, edx
Add eax, ecx
Add edx, ecx
Sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
Sub ebx, ecx { EBX = Remainder }
Push edx
Push eax
Push ecx
call LargeSSE2Move
Pop ecx
Pop eax
Pop edx
Add ecx, ebx
Add eax, ecx
Add edx, ecx
mov ecx, ebx
Pop ebx
jmp SmallForwardMove
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE) }
procedure Backwards_SSE2;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
Push ebx
movdqu XMM0, [eax+ecx-16] { Last 16 Bytes }
lea ebx, [edx+ecx] { Align Writes }
and ebx, 15
Sub ecx, ebx
Add ebx, ecx
Sub ecx, 32
Add edi, 0 { 3-Byte NOP Equivalent to Align Loop }
@@BwdLoop:
movdqu xmm1, [eax+ecx]
movdqu xmm2, [eax+ecx+16]
movdqa [edx+ecx], xmm1
movdqa [edx+ecx+16], xmm2
Sub ecx, 32
jge @@BwdLoop
movdqu [edx+ebx-16], XMM0 { Last 16 Bytes }
Add ecx, 32
Pop ebx
jmp SmallBackwardMove
end;
{ ------------------------------------------------------------------------- }
procedure LargeUnalignedSSE3Move;
asm
@@Loop:
lddqu XMM0, [eax+ecx]
lddqu xmm1, [eax+ecx+16]
lddqu xmm2, [eax+ecx+32]
lddqu xmm3, [eax+ecx+48]
movdqa [edx+ecx], XMM0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
lddqu xmm4, [eax+ecx+64]
lddqu xmm5, [eax+ecx+80]
lddqu xmm6, [eax+ecx+96]
lddqu xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
end;
{ ------------------------------------------------------------------------- }
procedure HugeUnalignedSSE3Move;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
lddqu XMM0, [eax+ecx]
lddqu xmm1, [eax+ecx+16]
lddqu xmm2, [eax+ecx+32]
lddqu xmm3, [eax+ecx+48]
movntdq [edx+ecx], XMM0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
lddqu xmm4, [eax+ecx+64]
lddqu xmm5, [eax+ecx+80]
lddqu xmm6, [eax+ecx+96]
lddqu xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
Add ecx, 128
js @@Loop
sfence
end;
{ ------------------------------------------------------------------------- }
{ Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSE3Move(const Source; var dest; Count: Integer);
asm
Push ebx
mov ebx, ecx
and ecx, -128 { No of Bytes to Block Move (Multiple of 128) }
Add eax, ecx { End of Source Blocks }
Add edx, ecx { End of Dest Blocks }
Neg ecx
cmp ecx, CacheLimit { Count > Limit - Use Prefetch }
jl @@Huge
test eax, 15 { Check if Both Source/Dest are Aligned }
jnz @@LargeUnaligned
call LargeAlignedSSE2Move { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@LargeUnaligned: { Source Not 16-Byte Aligned }
call LargeUnalignedSSE3Move
jmp @@Remainder
@@Huge:
test eax, 15 { Check if Both Source/Dest Aligned }
jnz @@HugeUnaligned
call HugeAlignedSSE2Move { Both Source and Dest 16-Byte Aligned }
jmp @@Remainder
@@HugeUnaligned: { Source Not 16-Byte Aligned }
call HugeUnalignedSSE3Move
@@Remainder:
and ebx, $7F { Remainder (0..112 - Multiple of 16) }
jz @@Done
Add eax, ebx
Add edx, ebx
Neg ebx
@@RemainderLoop:
lddqu XMM0, [eax+ebx]
movdqa [edx+ebx], XMM0
Add ebx, 16
jnz @@RemainderLoop
@@Done:
Pop ebx
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE) }
procedure Forwards_SSE3;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
Push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
lddqu XMM0, [eax] { First 16 Bytes }
mov ebx, edx
Add eax, ecx { Align Writes }
Add ecx, edx
and edx, -16
Add edx, 48
Sub ecx, edx
Add edx, ecx
Neg ecx
@@FwdLoopSSE3:
lddqu xmm1, [eax+ecx-32]
lddqu xmm2, [eax+ecx-16]
movdqa [edx+ecx-32], xmm1
movdqa [edx+ecx-16], xmm2
Add ecx, 32
jle @@FwdLoopSSE3
movdqu [ebx], XMM0 { First 16 Bytes }
Neg ecx
Add ecx, 32
Pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] { 16 byte Align Destination }
and ecx, -16
Sub ecx, edx
Add eax, ecx
Add edx, ecx
Sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
Sub ebx, ecx { EBX = Remainder }
Push edx
Push eax
Push ecx
call LargeSSE3Move
Pop ecx
Pop eax
Pop edx
Add ecx, ebx
Add eax, ecx
Add edx, ecx
mov ecx, ebx
Pop ebx
jmp SmallForwardMove
end;
{ ------------------------------------------------------------------------- }
{ Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE) }
procedure Backwards_SSE3;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
Push ebx
lddqu XMM0, [eax+ecx-16] { Last 16 Bytes }
lea ebx, [edx+ecx] { Align Writes }
and ebx, 15
Sub ecx, ebx
Add ebx, ecx
Sub ecx, 32
Add edi, 0 { 3-Byte NOP Equivalent to Align Loop }
@@BwdLoop:
lddqu xmm1, [eax+ecx]
lddqu xmm2, [eax+ecx+16]
movdqa [edx+ecx], xmm1
movdqa [edx+ecx+16], xmm2
Sub ecx, 32
jge @@BwdLoop
movdqu [edx+ebx-16], XMM0 { Last 16 Bytes }
Add ecx, 32
Pop ebx
jmp SmallBackwardMove
end;
procedure MoveMMX(const Source; var dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
Add eax, ecx
Add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_MMX
JE @@Done { For Compatibility with Delphi's move for Source = Dest }
Sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_MMX
jmp Backwards_MMX { Source/Dest Overlap }
@@Done:
end;
procedure MoveSSE(const Source; var dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
Add eax, ecx
Add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_SSE
JE @@Done { For Compatibility with Delphi's move for Source = Dest }
Sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE
jmp Backwards_SSE { Source/Dest Overlap }
@@Done:
end;
procedure MoveSSE2(const Source; var dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
Add eax, ecx
Add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_SSE2
JE @@Done { For Compatibility with Delphi's move for Source = Dest }
Sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE2
jmp Backwards_SSE2 { Source/Dest Overlap }
@@Done:
end;
procedure MoveSSE3(const Source; var dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
Add eax, ecx
Add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_SSE3
JE @@Done { For Compatibility with Delphi's move for Source = Dest }
Sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE3
jmp Backwards_SSE3 { Source/Dest Overlap }
@@Done:
end;
initialization
{ Initialize internals }
GetCPUInfo();
{ Patch the RTL Move method }
if sisSSE3 in SimdSupported then
PatchMethod(@System.Move, @MoveSSE3) { SSE3 version }
else if sisSSE2 in SimdSupported then
PatchMethod(@System.Move, @MoveSSE2) { SSE2 version }
else if sisSSE in SimdSupported then
PatchMethod(@System.Move, @MoveSSE) { SSE version }
else if sisMMX in SimdSupported then
PatchMethod(@System.Move, @MoveMMX); { MMX version }
{$ENDIF}
{$ENDIF FPC}
end.
|
{*
FrameChartBase.pas/dfm
----------------------
Begin: 2005/08/04
Last revision: $Date: 2010-11-02 18:16:23 $ $Author: rhupalo $
Version number: $Revision: 1.21 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2010 Animal Population Health Institute, Colorado State University
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 unit defines a base class frame used by forms providing charts showing graphical summaries of
various outputs - cost relationships and epicurves, and disease, detection, and control status, etc.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
*)
unit FrameChartBase;
interface
uses
Windows,
Messages,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Chart
;
type
/// Base class, inheriting from TFrame, for many of the graphical output summary frames and forms
TFrameChartBase = class( TFrame )
protected
/// the chart that the public methods of this class operate on
_chart: TChart;
/// whether to throw an exception if an instance of a derived class is created with more than one chart
_ignoreCharts: boolean;
function getChartWidth(): integer; virtual;
function getChartHeight(): integer; virtual;
public
constructor create( AOwner: TComponent ); override;
destructor destroy(); override;
function createMetafile(): TMetaFile; virtual;
function saveChartToFile( fileName: string ): boolean;
function copyChartToClipboard(): boolean;
function printChart(): boolean; virtual;
/// read-only property providing the width of _chart
property chartWidth: integer read getChartWidth;
/// read-only property providing the height of _chart
property chartHeight: integer read getChartHeight;
/// read-only access to _ignoreCharts
property ignoreCharts: boolean read _ignoreCharts default false;
end
;
implementation
{$R *.dfm}
uses
SysUtils,
ClipBrd,
MyStrUtils,
DebugWindow
;
const
DBSHOWMSG: boolean = false; /// Set to true to enable debugging messages for this unit
//-----------------------------------------------------------------------------
// Construction/destruction
//-----------------------------------------------------------------------------
{*
Creates the ChartBase object and ensures the frame only contains one
chart unless ignoreCharts is true.
@param AOwner the form that owns this instance of the frame
@throws An exception is raised if ignoreCharts is not true and the
frame (including child controls contains more than one chart.
}
constructor TFrameChartBase.create( AOwner: TComponent );
var
chartCount: integer;
// recursively examines controls of self to count the number of Chart objects
procedure lookForChart( cntnr: TWinControl );
var
i: integer;
begin
for i := 0 to cntnr.ControlCount - 1 do
begin
if( cntnr.Controls[i] is TChart ) then
begin
inc( chartCount );
_chart := cntnr.Controls[i] as TChart;
end
;
if( cntnr.Controls[i] is TWinControl ) then
begin
if( 0 < (cntnr.Controls[i] as TWinControl).controlCount ) then
lookForChart( cntnr.Controls[i] as TWinControl )
;
end
;
end
;
end
;
begin
inherited create( AOwner );
chartCount := 0;
_chart := nil;
lookForChart( self );
if( ( 1 <> chartCount ) AND (not ignoreCharts ) ) then
begin
raise exception.Create( 'Wrong number of main charts (' + intToStr(chartCount) + ') in TFrameChartBase' );
_chart := nil;
end
;
end
;
/// destroys the object and frees memory
destructor TFrameChartBase.destroy();
begin
inherited destroy();
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Meta file creation
//-----------------------------------------------------------------------------
{*
Helper function that creates a graphical image of _chart formatted as a metafile
@return graphic of chart as an un-enhanced metafile - a .WMF (Windows 3.1 Metafile, with Aldus header)
@comment Called by saveChartToFile()
}
function TFrameChartBase.createMetafile(): TMetaFile;
begin
dbcout( '_chart is nil: ' + uiBoolToText( nil = _chart ), true );
if( nil <> _chart ) then
//rbh20101102 Fix Me - does this work? TeeCreateMetafile is defined in TEEPROCS.pas, which is not on my system...
result := _chart.TeeCreateMetafile( False, Rect(0, 0, _chart.Width, _chart.Height ) )
else
result := nil
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Chart handling
//-----------------------------------------------------------------------------
{*
Saves the chart image as a graphic and writes it to filename
@param fileName full path for image file to be created
@comment file format is an un-enhanced metafile - a .WMF (Windows 3.1 Metafile, with Aldus header)
}
function TFrameChartBase.saveChartToFile( fileName: string ): boolean;
Var
m: TMetafile;
begin
m := nil;
try
try
m := createMetaFile();
m.SaveToFile( fileName );
result := true;
except
result := false;
end;
finally
freeAndNil( m );
end;
end
;
{*
Saves an image of _chart to the Windows clipboard
@return true if successful, else false
}
function TFrameChartBase.copyChartToClipboard(): boolean;
var
m: TMetafile;
AFormat: word;
AData: Cardinal;
APalette: HPALETTE;
begin
m := nil;
try
try
m := createMetaFile();
m.SaveToClipboardFormat( AFormat, AData, aPalette );
ClipBoard.SetAsHandle( AFormat, AData );
result := true;
except
result := false;
end;
finally
freeAndNil( m );
end;
end
;
{*
Attempts to print an image of _chart to the default printer in landscape mode
@return false if an exception occurs, else true
}
function TFrameChartBase.printChart(): boolean;
begin
try
try
Screen.Cursor := crHourGlass;
_chart.PrintLandscape();
result := true;
except
result := false;
end;
finally
Screen.Cursor := crDefault;
end;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Chart properties
//-----------------------------------------------------------------------------
/// Get function for property chartWidth, returning the width of _chart
function TFrameChartBase.getChartWidth(): integer;
begin
if( nil <> _chart ) then
result := _chart.Width
else
result := -1
;
end
;
/// Get function for property chartHeight, returning the height of _chart
function TFrameChartBase.getChartHeight(): integer;
begin
if( nil <> _chart ) then
result := _chart.height
else
result := -1
;
end
;
//-----------------------------------------------------------------------------
end.
|
unit Monsters;
interface
uses
Points, Collisions, EngineTypes;
procedure CreateMonster (M: PMonster; S: PSector; Model : PItemModel);
procedure TraceMonster (var M: Monster);
procedure PushMonster (var M: Monster);
procedure MoveMonster (M: PMonster; dt: float);
function CenterMonster (const M: Monster): Point;
function Live (const M: Monster): boolean;
implementation
uses
Geometry, Items, Bullets, Sounds;
procedure TraceMonster (var M: Monster);
var
ml,mh : Point;
begin
ml := M.DeltaPos;
mh := M.DeltaPos;
if Live(M) then begin
if M.Controls.Sit then ml.z := ml.z-0.064 else ml.z := ml.z+0.064;
if M.Controls.Sit then mh.z := mh.z+0.036 else mh.z := mh.z-0.036;
end else begin
mh.z := mh.z + 0.1;
end;
Trace(M.Head^, mh);
Trace(M.Body^, mh);
Trace(M.Legs^, ml);
end;
function CenterMonster (const M: Monster): Point;
begin
Result := Add(Add(Scale(M.Head.P,0.28), Scale(M.Body.P,0.36)), Scale(M.Legs.P,0.36));
end;
procedure PushMonster (var M: Monster);
var
x,y,zh,zb,zl,dz : float;
begin
with M, Item.Model^ do begin
// теперь костыльно шарики приводим друг к другу
x := Body.P.x*0.36 + Legs.P.x*0.36 + Head.P.x*0.28;
y := Body.P.y*0.36 + Legs.P.y*0.36 + Head.P.y*0.28;
zh := Head.P.z;
zl := Legs.P.z;
dz := zl - (zh+(HB+MaxBL));
if dz>0 then begin
zh := zh + dz*0.36;
zl := zl - dz*0.64;
end;
dz := (zh+(HB+MinBL)) - zl;
if dz>0 then begin
zh := zh - dz*0.36;
zl := zl + dz*0.64;
end;
zb := zh + HB;
Trace(Head^, Sub(ToPoint(x,y,zh), Head.P));
Trace(Body^, Sub(ToPoint(x,y,zb), Body.P));
Trace(Legs^, Sub(ToPoint(x,y,zl), Legs.P));
PushConvex(Item.Convexes[0]);
PushConvex(Item.Convexes[1]);
PushConvex(Item.Convexes[2]);
end;
end;
procedure DoShot (M: PMonster);
procedure CreateSound;
begin
with M.Weapons[M.CurrentWeapon].Item.Model^ do if Instrument<128 then begin
SetChanel(0);
NoSound;
SetVolume(127);
SetStyle(Instrument);
Sound(Nota);
end;
end;
begin
with M.Weapons[M.CurrentWeapon] do if isWeapon then begin
if Item.Model.Sabre then begin
if ReloadLeft<=0 then begin
ReloadLeft := Item.Model.ReloadTime;
CreateSound;
end;
Shot(M, Item.Model, (ReloadLeft/Item.Model.ReloadTime)-1/2); // Item.Monster вместо M, потому что так корректнее брать указатель
end else begin
if ReloadLeft<=0 then begin
CreateSound;
ReloadLeft := Item.Model.ReloadTime;
Shot(M, Item.Model, 0);
end;
end;
end;
end;
function Live (const M: Monster): boolean;
begin
Result := M.DeathStage<0;
end;
procedure MoveMonster (M: PMonster; dt : float);
var
Move : Point;
l,c,s : float;
st : float;
BefT, BefP, AftP, dP : Point;
NewM : Monster;
NewC : array [0..2] of Convex;
i : integer;
begin
with M^, Item.Model^ do begin
// контролы
if Live(M^) then begin
anglex := anglex + Controls.dax*dt;
if anglex<0 then anglex := 0;
if anglex>Pi then anglex := Pi;
anglez := anglez + Controls.daz*dt;
while anglez<0 do anglez := anglez + 2*Pi;
while anglex>2*Pi do anglez := anglez - 2*Pi;
end;
c := cos(anglez);
s := sin(anglez);
Move := ToPoint(0,0,0);
if Live(M^) then begin
if Controls.Forw then Move := Add(Move, ToPoint( s, c,0));
if Controls.Back then Move := Add(Move, ToPoint(-s,-c,0));
if Controls.StrL then Move := Add(Move, ToPoint(-c, s,0));
if Controls.StrR then Move := Add(Move, ToPoint( c,-s,0));
if Controls.Jump then Move := Add(Move, ToPoint(0,0,-Lightness));
if Controls.Sit then Move := Add(Move, ToPoint(0,0, Lightness));
end else begin
DeathStage := DeathStage - dt;
if DeathStage<0 then DeathStage := 0;
end;
// сдвинуть с учётом трения
l := LengthP(Move);
if l>0 then Move := Scale(Move, 0.03/l);
st := (Legs.P.z-Body.P.z+0.4)/(MaxBL+0.4);
Move := Scale(Move, (Fr*0.95+0.05));
if Live(M^) then begin
if Controls.Jump then Move := Add(Move, ToPoint(0,0,-Spring*dt*st*Fr));
end;
// применить ускорение
DeltaPos := Add(DeltaPos, Move);
DeltaPos := Add(DeltaPos, ToPoint(0, 0, Legs.S.Gravity*(1-Lightness)));
// вычислить сдвиг
// создаём фальшивую копию монстра
NewM := M^;
for i := 0 to 2 do begin
NewC[i] := Item.Convexes[i];
NewC[i].Mass := 0;
NewM.Item.Convexes := PAConvex(@NewC);
end;
NewM.Head := @NewC[0].Center;
NewM.Body := @NewC[1].Center;
NewM.Legs := @NewC[2].Center;
BefT := CenterMonster(NewM);
TraceMonster(NewM);
BefP := CenterMonster(NewM);
PushMonster(NewM);
AftP := CenterMonster(NewM);
DeltaPos := Sub(AftP, BefT);
// пересчитать силу трения
dP := Sub(BefP, AftP);
Fr := (dp.z - sqrt(sqr(dp.x)+sqr(dp.y))*0.3)*1000;
if Fr<0 then Fr := 0;
if Fr>1 then Fr := 1;
Fr := Fr*(1-Lightness)+Lightness;
// применить силу трения
l := LengthP(DeltaPos);
s := l-(Speed*dt+(1-Fr))*st; // превышение скорости
if s<0 then s:=0;
s := Fr*0.01+s;
if l>s then DeltaPos := Scale(DeltaPos, 1-s/l) else DeltaPos := ToPoint(0,0,0);
for i := 0 to 9 do with Weapons[i] do begin
ReloadLeft := ReloadLeft-dt;
if ReloadLeft<0 then ReloadLeft:=0;
end;
if Live(M^) then begin
LastDamage := LastDamage+dt;
if LastDamage>1 then LastDamage := 1;
if (Controls.WeaponNumber>=0) and (Controls.WeaponNumber<=9)
and (Weapons[Controls.WeaponNumber].IsWeapon) then
CurrentWeapon := Controls.WeaponNumber;
if Fr>0 then StepStage := StepStage + LengthP(DeltaPos);
if Controls.Shot then
DoShot(M);
end;
if PrevShot and not Controls.Shot then begin
SetChanel(0);
NoSound;
end;
PrevShot := Controls.Shot;
end;
TraceMonster(M^);
PushMonster(M^);
end;
procedure CreateMonster (M: PMonster; S: PSector; Model : PItemModel);
var
i : integer;
begin
FillChar(M^, sizeof(M^), 0);
M.AngleX := Pi/2;
M.AngleZ := Pi;
M.StepStage := 0;
M.Item.Monster := M;
M.DeathStage := -1;
M.Health := Model.InitialHealths;
M.Armor := 0;
M.CurrentWeapon := 0;
M.LastDamage := 1;
M.PrevShot := False;
CreateItem(@M.Item, S, Model);
M.Item.Convexes[0].R := Model.HeadR;
M.Item.Convexes[1].R := Model.BodyR;
M.Item.Convexes[2].R := Model.LegsR;
for i := 0 to 9 do begin
M.Weapons[i].IsWeapon := (Model.DefaultHasWeapon[i]) and (Model.WeaponModels[i]<>nil);
if Model.WeaponModels[i]<>nil then
CreateWeapon(@M.Weapons[i], Model.WeaponModels[i], M);
end;
end;
end.
|
unit oPKIEncryptionSignature;
interface
uses
System.Classes,
oPKIEncryption;
type
TPKIEncryptionSignature = class(TInterfacedObject, IPKIEncryptionSignature)
private
fHashText: string;
fDateTimeSigned: string;
fSignature: string;
function getHashText: string; virtual; final;
function getDateTimeSigned: string; virtual; final;
function getSignature: string; virtual;
procedure setHashText(const aValue: string); virtual; final;
procedure setDateTimeSigned(const aValue: string); virtual; final;
procedure setSignature(const aValue: string); virtual; final;
protected
procedure LoadSignature(const aValue: TStringList); virtual; final;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TPKIEncryptionSignature }
constructor TPKIEncryptionSignature.Create;
begin
inherited;
end;
destructor TPKIEncryptionSignature.Destroy;
begin
inherited;
end;
function TPKIEncryptionSignature.getDateTimeSigned: string;
begin
Result := fDateTimeSigned;
end;
function TPKIEncryptionSignature.getHashText: string;
begin
Result := fHashText;
end;
function TPKIEncryptionSignature.getSignature: string;
begin
Result := fSignature;
end;
procedure TPKIEncryptionSignature.LoadSignature(const aValue: TStringList);
begin
fSignature := '';
with aValue.GetEnumerator do
while MoveNext do
fSignature := fSignature + Current;
end;
procedure TPKIEncryptionSignature.setDateTimeSigned(const aValue: string);
begin
fDateTimeSigned := aValue;
end;
procedure TPKIEncryptionSignature.setHashText(const aValue: string);
begin
fHashText := aValue;
end;
procedure TPKIEncryptionSignature.setSignature(const aValue: string);
begin
fSignature := aValue;
end;
end.
|
unit MagicBrush;
interface
uses Graphics;
{* Магические кисти Версия 1.0 реализация различных кистей с помощью
базового абстарктного класса обернутого в фабрику *}
type
TMagicBrush = class
FCurrentValue: TColor;
private
FPenWidth: Integer;
FBrushIcon: TIcon;
FName: string;
FCanvas: TCanvas;
FColor: TColor;
FIsFirstCall: Boolean;
procedure SetPenWidth(const Value: Integer);
procedure SetBrushIcon(const Value: TIcon);
procedure SetName(const Value: string);
procedure SetColor(const Value: TColor);
public
constructor Create(aCanvas: TCanvas); virtual;
// Рисовать у каждого класс она будет своя
procedure Draw(X, Y: Integer); virtual; abstract;
procedure RefreshBrush(); virtual; abstract;
// Ширина пера
property Width: Integer read FPenWidth write SetPenWidth;
// Получить иконку
property Icon: TIcon read FBrushIcon write SetBrushIcon;
// Получить имя
property Name: string read FName write SetName;
// Активный цвет
property ActiveColor: TColor read FColor write SetColor;
// Канва рисовани
property Canvas: Tcanvas read FCanvas write FCanvas;
// Если первфый вызов функции
property ISFirstCall: Boolean read FIsFirstCall write FIsFirstCall;
end;
implementation
{ TMagicBrush }
constructor TMagicBrush.Create(aCanvas: TCanvas);
begin
FCanvas := aCanvas;
FIsFirstCall := true;
end;
procedure TMagicBrush.SetBrushIcon(const Value: TIcon);
begin
FBrushIcon := Value;
end;
procedure TMagicBrush.SetColor(const Value: TColor);
begin
FColor := Value;
FCanvas.Pen.Color := Value;
FCurrentValue := FColor;
end;
procedure TMagicBrush.SetName(const Value: string);
begin
FName := Value;
end;
procedure TMagicBrush.SetPenWidth(const Value: Integer);
begin
FPenWidth := Value;
end;
end.
|
namespace ComplexNumbers;
interface
type
Complex = public class
private
property Size: Double read Real*Imaginary;
protected
public
constructor; empty;
constructor (aReal, aImaginary: Double);
property Real: Double;
property Imaginary: Double;
method ToString: String; override;
class operator Add(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Subtract(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Multiply(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Divide(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Equal(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Less(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator LessOrEqual(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Greater(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator GreaterOrEqual(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Minus(aOperand: Complex): Complex;
class operator Plus(aOperand: Complex) : Complex;
class operator Explicit(aValue: Complex): Double;
class operator Implicit(aValue: Double): Complex;
class operator Implicit(aValue: Int32): Complex;
end;
implementation
constructor Complex(aReal, aImaginary: Double);
begin
Real := aReal;
Imaginary := aImaginary;
end;
class operator Complex.Add(aOperand1 : Complex; aOperand2 : Complex) : Complex;
begin
result := new Complex(aOperand1.Real+aOperand2.Real, aOperand1.Imaginary+aOperand2.Imaginary);
end;
class operator Complex.Subtract(aOperand1 : Complex; aOperand2 : Complex) : Complex;
begin
result := new Complex(aOperand1.Real-aOperand2.Real, aOperand1.Imaginary-aOperand2.Imaginary);
end;
class operator Complex.Multiply(aOperand1 : Complex; aOperand2 : Complex) : Complex;
var
lReal, lImaginary: Double;
begin
//
// (a + ib)(c + id) = (ac - bd) + i(bc + ad)
//
lReal := aOperand1.Real*aOperand2.Real - aOperand1.Imaginary*aOperand2.Imaginary;
lImaginary := aOperand1.Imaginary*aOperand2.Real + aOperand1.Real*aOperand2.Imaginary;
result := new Complex(lReal, lImaginary);
end;
class operator Complex.Divide(aOperand1 : Complex; aOperand2 : Complex) : Complex;
var
lReal, lImaginary, lDivisor: Double;
begin
//
// (a + ib)(c + id) = (ac + bd)/(c�+d�) + i(bc - ad)/(c�+d�)
//
lDivisor := (aOperand2.Real*aOperand2.Real + aOperand2.Imaginary*aOperand2.Imaginary);
lReal := (aOperand1.Real*aOperand2.Real + aOperand1.Imaginary*aOperand2.Imaginary) / lDivisor;
lImaginary := (aOperand1.Imaginary*aOperand2.Real - aOperand1.Real*aOperand2.Imaginary) / lDivisor;
result := new Complex(lReal, lImaginary);
end;
{ Unary Operators }
class operator Complex.Minus(aOperand: Complex): Complex;
begin
result := new Complex(-aOperand.Real, -aOperand.Imaginary);
end;
class operator Complex.Plus(aOperand: Complex) : Complex;
begin
result := aOperand;
end;
{ Comparison operators }
class operator Complex.Equal(aOperand1 : Complex; aOperand2 : Complex): boolean;
begin
result := (aOperand1.Real = aOperand2.Real) and (aOperand1.Imaginary = aOperand2.Imaginary);
end;
class operator Complex.Less(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size < aOperand2.Size;
end;
class operator Complex.LessOrEqual(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size <= aOperand2.Size;
end;
class operator Complex.Greater(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size > aOperand2.Size;
end;
class operator Complex.GreaterOrEqual(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size >= aOperand2.Size;
end;
{ Cast Operators }
class operator Complex.Explicit(aValue: Complex): Double;
begin
result := aValue.Real;
end;
class operator Complex.Implicit(aValue: Double): Complex;
begin
result := new Complex(aValue, 0)
end;
class operator Complex.Implicit(aValue: Int32): Complex;
begin
result := new Complex(aValue, 0)
end;
method Complex.ToString: string;
begin
if (Real = 0) and (Imaginary = 0) then
result := '0'//'.ToString
else if (Imaginary = 0) then
result := Real.ToString
else if (Real = 0) then
result := Imaginary.ToString+'i'
else if (Imaginary < 0) then
result := Real.ToString+Imaginary.ToString+'i'
else
result := Real.ToString+'+'+Imaginary.ToString+'i';
end;
end. |
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
SysUtils, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
private
DC: HDC;
hrc: HGLRC;
qObj : GLUquadricObj;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
fRot : Boolean = True;
theta : Integer;
implementation
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
light_diffuse : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
light_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
mat_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
mat_shininess : GLfloat = 50.0;
begin
glLightfv(GL_LIGHT0, GL_DIFFUSE, @light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, @light_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, @mat_shininess);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
// объект
qObj := gluNewQuadric;
// операции с трафаретом
glStencilFunc(GL_EQUAL, 0, 1);
glStencilOp(GL_INCR, GL_INCR, GL_INCR);
glEnable(GL_STENCIL_TEST);
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint (Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_STENCIL_BUFFER_BIT);
glPushMatrix;
glPushMatrix;
glColor3f(1.0, 0.0, 0.0);
glTranslatef (45.0, 40.0, -150.0);
gluSphere (qObj, 50.0, 20, 20);
glPopMatrix;
If fRot then glRotatef(theta, 1.0, 1.0, 0.0);
glColorMask(False, False, False, False);
glPushMatrix;
// первая дырка
glTranslatef(45.0,45.0,0.0);
gluDisk(qObj,15.0,20.0,20,20);
// вторая дырка
glTranslatef(20.0,20.0,0.0);
gluDisk(qObj,15.0,20.0,20,20);
glPopMatrix;
glColorMask(True, True, True, True);
glColor3f(1.0, 1.0, 0.0);
// площадка
glBegin(GL_QUADS);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(100.0, 0.0, 0.0);
glVertex3f(100.0, 100.0, 0.0);
glVertex3f(0.0, 100.0, 0.0);
glEnd;
glPopMatrix;
SwapBuffers (DC);
EndPaint (Handle, ps);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = VK_SPACE then fRot := not fRot;
end;
{=======================================================================
Обработка таймера}
procedure TfrmGL.Timer1Timer(Sender: TObject);
begin
theta := (theta + 5) mod 360;
InvalidateRect(Handle, nil, False);
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;
gluPerspective(50.0, 1.0, 50.0, 400.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef (-50.0, -50.0, -200.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
gluDeleteQuadric (qObj);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
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.
|
unit uLocation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ActnList, ExtCtrls, Buttons, DbCtrls, DBGrids, PopupNotifier, uBaseDbForm, db,
ZAbstractDataset, ZDataset, ZSequence, ZSqlUpdate;
type
{ TfrmLocation }
TfrmLocation = class(TbaseDbForm)
actCharFilter: TAction;
actClearFilter: TAction;
actLocation: TActionList;
btnCharFilter: TSpeedButton;
btnShowAll: TSpeedButton;
cmbCharFilter: TComboBox;
cmbFieldArg: TComboBox;
dbCode: TDBEdit;
dbgLocation: TDBGrid;
dbName: TDBEdit;
dsLocation: TDataSource;
edtLocate: TEdit;
groupBoxEdit: TGroupBox;
Label1: TLabel;
Label2: TLabel;
panelParams: TPanel;
pupNotiferLocation: TPopupNotifier;
zqLocation: TZQuery;
zqLocationL_CODE: TStringField;
zqLocationL_ID: TLongintField;
zqLocationL_NAME: TStringField;
zseqLocation: TZSequence;
zupdLocation: TZUpdateSQL;
procedure actCharFilterExecute(Sender: TObject);
procedure actClearFilterExecute(Sender: TObject);
procedure cmbFieldArgChange(Sender: TObject);
procedure dbgLocationMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure dbgLocationTitleClick(Column: TColumn);
procedure edtLocateEnter(Sender: TObject);
procedure edtLocateExit(Sender: TObject);
procedure edtLocateKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState
);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure zqLocationAfterDelete(DataSet: TDataSet);
procedure zqLocationAfterOpen(DataSet: TDataSet);
procedure zqLocationAfterPost(DataSet: TDataSet);
procedure zqLocationAfterScroll(DataSet: TDataSet);
private
{ private declarations }
charArg : String; {name-start with this char}
fieldArg : String; {locate text from field}
procedure saveBeforeClose;
public
{ public declarations }
procedure onActFirst; override;
procedure onActPrior; override;
procedure onActNext; override;
procedure onActLast; override;
procedure onActInsert; override;
procedure onActDelete; override;
procedure onActEdit; override;
procedure onActSave; override;
procedure onActCancel; override;
{open dataSet using charArg}
procedure applyCharFilter;
end;
var
frmLocation: TfrmLocation;
const
{fields of tbl location}
FIELD_ID : String = 'L_ID';
FIELD_CODE : String = 'L_CODE';
FIELD_NAME : String = 'L_NAME';
{params}
PARAM_NAME : String = 'L_NAME'; {:L_NAME}
implementation
uses
uDModule, uConfirm;
{$R *.lfm}
{ TfrmLocation }
procedure TfrmLocation.FormCreate(Sender: TObject);
begin
{default args}
charArg:= 'A%';
fieldArg:= PARAM_NAME; {locate using field_name}
end;
procedure TfrmLocation.FormShow(Sender: TObject);
var
helpMsg : String = 'Izaberite početna slova';
x, y : Longint;
begin
{gubi poziciju nije ispravno}
end;
procedure TfrmLocation.actCharFilterExecute(Sender: TObject);
begin
{set filter}
charArg:= cmbCharFilter.Text + '%';
{apply filter}
applyCharFilter;
end;
procedure TfrmLocation.actClearFilterExecute(Sender: TObject);
begin
{set char-argument}
charArg:= '%'; {show all}
applyCharFilter;
{set cmbCharFilter index}
cmbCharFilter.Text:= 'Mesta na slovo ...'; {message like text}
end;
procedure TfrmLocation.cmbFieldArgChange(Sender: TObject);
begin
{set field-filter}
case cmbFieldArg.ItemIndex of
1: fieldArg:= FIELD_NAME;
2: fieldArg:= FIELD_CODE;
else
fieldArg:= FIELD_NAME;
end;
{set focus}
edtLocate.SetFocus;
end;
procedure TfrmLocation.dbgLocationMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
{set cursor again}
dbgLocation.Cursor:= crHandPoint;
end;
procedure TfrmLocation.dbgLocationTitleClick(Column: TColumn);
var
recCount, recNo : String;
recMsg : String = '0 od 0'; {find again recNo}
begin
{sort}
doSortDbGrid(TZAbstractDataset(zqLocation), Column);
{refresh after sort}
dbgLocation.Refresh;
{ find recNo}
recCount:= IntToStr(TZAbstractDataset(zqLocation).RecordCount);
recNo:= IntToStr(TZAbstractDataset(zqLocation).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmLocation.edtLocateEnter(Sender: TObject);
begin
{clear text and set font-color}
edtLocate.Text:= '';
edtLocate.Font.Color:= clBlack;
end;
procedure TfrmLocation.edtLocateExit(Sender: TObject);
begin
{set text and font-color}
edtLocate.Text:= 'Pronadji ...';
edtLocate.Font.Color:= clGray;
end;
procedure TfrmLocation.edtLocateKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{try to locate}
if(not TZAbstractDataset(zqLocation).Locate(fieldArg, edtLocate.Text, [loCaseInsensitive, loPartialKey])) then
begin
Beep;
edtLocate.SelectAll;
end;
end;
procedure TfrmLocation.FormClose(Sender: TObject; var CloseAction: TCloseAction
);
begin
{check for unsaved changes}
saveBeforeClose;
inherited;
end;
procedure TfrmLocation.zqLocationAfterDelete(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{upply updates}
TZAbstractDataset(DataSet).ApplyUpdates;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmLocation.zqLocationAfterOpen(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{set btns cheking recCount}
doAfterOpenDataSet(TZAbstractDataset(DataSet));
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmLocation.zqLocationAfterPost(DataSet: TDataSet);
var
currId : Longint;
firstChar : String = '';
currText : String;
{calc records(recNo and countRec)}
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{upply updates}
TZAbstractDataset(DataSet).ApplyUpdates;
{rtefresh current row}
TZAbstractDataset(DataSet).RefreshCurrentRow(True);
{find currText}
currText:= TZAbstractDataset(DataSet).FieldByName(FIELD_NAME).AsString;
{first char to firstChar-var}
firstChar:= LeftStr(currText, 1);
firstChar:= firstChar + '%';
{compare current charFilter}
if(charArg <> firstChar) then
begin
{save position}
currId:= TZAbstractDataset(DataSet).FieldByName(FIELD_ID).AsInteger;
charArg:= firstChar;
applyCharFilter;
{locate}
TZAbstractDataset(DataSet).Locate(FIELD_ID, currId, []);
end;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then {*** never ***}
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmLocation.zqLocationAfterScroll(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{set btns cheking recCount}
if(TZAbstractDataset(DataSet).State in [dsEdit, dsInsert]) then
Exit;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmLocation.saveBeforeClose;
var
newDlg : TdlgConfirm;
confirmMsg : String = 'Postoje izmene koje nisu sačuvane!';
saveAll : Boolean = False;
begin
{set confirm msg}
confirmMsg:= confirmMsg + #13#10;
confirmMsg:= confirmMsg + 'Želite da sačuvamo izmene?';
if(TZAbstractDataset(zqLocation).State in [dsEdit, dsInsert]) then
begin
{ask user to confirm}
newDlg:= TdlgConfirm.Create(nil);
newDlg.memoMsg.Lines.Text:= confirmMsg;
if(newDlg.ShowModal = mrOK) then
saveAll:= True;
{free dialog}
newDlg.Free;
end;
{check all}
if saveAll then
doSaveRec(TZAbstractDataset(zqLocation)); {in this case just one dataSet}
end;
procedure TfrmLocation.onActFirst;
begin
{jump to first rec}
doFirstRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActPrior;
begin
{jump to prior rec}
doPriorRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActNext;
begin
{jump to next rec}
doNextRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActLast;
begin
{jump to last rec}
doLastRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActInsert;
begin
{set focus and insert new rec}
dbCode.SetFocus;
doInsertRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActDelete;
begin
{delete rec}
doDeleteRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActEdit;
begin
{set focus and edit rec}
dbCode.SetFocus;
doEditRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActSave;
begin
{save rec}
doSaveRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.onActCancel;
begin
{cancel rec}
doCancelRec(TZAbstractDataset(zqLocation));
end;
procedure TfrmLocation.applyCharFilter;
begin
TZAbstractDataset(zqLocation).DisableControls;
TZAbstractDataset(zqLocation).Close;
try
TZAbstractDataset(zqLocation).ParamByName(PARAM_NAME).AsString:= charArg;
TZAbstractDataset(zqLocation).Open;
TZAbstractDataset(zqLocation).EnableControls;
{show arg in cmbChar}
//cmbCharFilter.ItemIndex:= cmbCharFilter.Items.IndexOf(LeftStr(charArg, 1)); {without '%'}
except
on e : Exception do
begin
dModule.zdbh.Rollback;
TZAbstractDataset(zqLocation).EnableControls;
ShowMessage(e.Message);
end;
end;
end;
end.
|
unit authconfigdialogunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ZentaoUnit, langunit;
type
{ TAuthConfigDialogForm }
TAuthConfigDialogForm = class(TForm)
AccountLabel: TLabel;
authAccountInput: TEdit;
authPasswordInput: TEdit;
ConfirmButton: TButton;
PasswordLabel: TLabel;
procedure ConfirmButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
AuthConfigDialogForm: TAuthConfigDialogForm;
implementation
{$R *.lfm}
{ TAuthConfigDialogForm }
procedure TAuthConfigDialogForm.FormCreate(Sender: TObject);
begin
authAccountInput.Text := userconfig.ApacheAuthAccount;
authPasswordInput.Text := userconfig.ApacheAuthPassword;
end;
procedure TAuthConfigDialogForm.FormShow(Sender: TObject);
begin
Caption := GetLang('menu/configAuthAcount', '配置访问验证账号');
AccountLabel.Caption := GetLang('ui/account', '用户名');
PasswordLabel.Caption := GetLang('ui/password', '密码');
ConfirmButton.Caption := GetLang('ui/confirm', '确定');
end;
procedure TAuthConfigDialogForm.ConfirmButtonClick(Sender: TObject);
begin
if (authAccountInput.Text = '') or (authPasswordInput.Text = '') then begin
ShowMessage(GetLang('message/accountAndPasswordRequired', '用户名或密码不能为空。'));
end else begin
userconfig.ApacheAuthAccount := authAccountInput.Text;
userconfig.ApacheAuthPassword := authPasswordInput.Text;
SaveConfig();
resetAuthConfig;
Close();
end;
end;
end.
|
unit uGenericCommands;
interface
uses SysUtils, uBase, uBaseCommand, uEnvironment, uExceptions, uExceptionCodes,
uEventModel, Forms, uRootForm, uStrings;
type
TLaunchCommand = class( TBaseCommand )
public
procedure Execute; override;
procedure UnExecute; override;
end;
implementation
{ TLaunchCommand }
procedure TLaunchCommand.Execute;
begin
if Assigned( Env ) then begin
RaiseFatalException( SYS_EXCEPT );
end;
Env := TEnvironment.Create;
Env.EventModel := TEventModel.Create;
Env.RootForm := TfmRoot.Create( Application );
with Env.RootForm do begin
Visible := false;
Caption := APP_TITLE;
end;
end;
procedure TLaunchCommand.UnExecute;
begin
FreeAndNil( Env.RootForm );
FreeAndNil( Env.EventModel );
FreeANdNil( Env );
inherited;
end;
end.
|
unit DMCustomerTreeU;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Provider, BdeProv, Db, DBTables, DBClient;
type
TDMCustomerTree = class(TDataModule)
CustomerQuery: TQuery;
CustomerOrdersTable: TTable;
CustomerQuerySource: TDataSource;
CustomerTreeProvider: TProvider;
CustomerOrderItemsTable: TTable;
CustomerOrdersSource: TDataSource;
CustomerOrderItemsTableOrderNo: TFloatField;
CustomerOrderItemsTableItemNo: TFloatField;
CustomerOrderItemsTablePartNo: TFloatField;
CustomerOrderItemsTableQty: TIntegerField;
CustomerOrderItemsTableDiscount: TFloatField;
NextOrderTable: TTable;
CustomerQueryCustNo: TFloatField;
CustomerQueryCompany: TStringField;
CustomerQueryAddr1: TStringField;
CustomerQueryAddr2: TStringField;
CustomerQueryCity: TStringField;
CustomerQueryState: TStringField;
CustomerQueryZip: TStringField;
CustomerQueryCountry: TStringField;
CustomerQueryPhone: TStringField;
CustomerQueryFAX: TStringField;
CustomerQueryTaxRate: TFloatField;
CustomerQueryContact: TStringField;
CustomerQueryLastInvoiceDate: TDateTimeField;
NextCustomerTable: TTable;
NextItemTable: TTable;
CustomerListQuery: TQuery;
CustomerListQueryCustNo: TFloatField;
CustomerListQueryCompany: TStringField;
CustomerListProvider: TDataSetProvider;
EmployeesTable: TTable;
PartsProvider: TProvider;
PartsQuery: TQuery;
Session1: TSession;
Database1: TDatabase;
procedure DMCustomerTreeCreate(Sender: TObject);
procedure CustomerTreeProviderUpdateData(Sender: TObject;
DataSet: TClientDataSet);
procedure CustomerTreeProviderBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
private
FCanEditCustomer: Boolean;
{ Private declarations }
public
{ Public declarations }
property CanEditCustomer: Boolean read FCanEditCustomer write FCanEditCustomer;
function GetCustomerOrdersTree(CustNo: Integer;
MetaData: WordBool): OleVariant;
function ApplyCustomerTree(Delta: OleVariant;
out ErrorCount: Integer): OleVariant;
function GetCustomersList: OleVariant;
procedure ValidateEmpNo(AEmpNo: Integer);
function GetPartsList: OleVariant;
end;
implementation
{$R *.DFM}
function TDMCustomerTree.GetCustomerOrdersTree(CustNo: Integer;
MetaData: WordBool): OleVariant;
var
RecsOut: Integer;
begin
with CustomerQuery do
begin
Close;
Params[0].AsInteger := CustNo;
Open;
end;
with CustomerTreeProvider do
begin
if CanEditCustomer then
Options := Options - [poReadOnly]
else
Options := Options + [poReadOnly];
Reset(MetaData);
Result := GetRecords(-1, RecsOut);
end;
end;
function TDMCustomerTree.ApplyCustomerTree(Delta: OleVariant;
out ErrorCount: Integer): OleVariant;
begin
with CustomerTreeProvider do
begin
Result := ApplyUpdates(Delta, -1, ErrorCount);
end;
end;
procedure TDMCustomerTree.DMCustomerTreeCreate(Sender: TObject);
begin
FCanEditCustomer := True;
end;
procedure TDMCustomerTree.CustomerTreeProviderUpdateData(Sender: TObject;
DataSet: TClientDataSet);
procedure UpdateItems(Items: TDataSet);
begin
end;
procedure UpdateOrders(Orders: TDataSet);
begin
with DataSet do
while not EOF do
begin
if UpdateStatus = usInserted then
;
// Provide unique customer number
//UpdateItems((FieldByName('CustomerOrderItemsTable') as TDataSetField).NestedDataSet);
Next;
end;
end;
begin
with DataSet do
while not EOF do
begin
if UpdateStatus = usInserted then
;
// Provide unique customer number
//UpdateOrders((FieldByName('CustomerOrdersTable') as TDataSetField).NestedDataSet);
Next;
end;
end;
procedure TDMCustomerTree.CustomerTreeProviderBeforeUpdateRecord(
Sender: TObject; SourceDS: TDataSet; DeltaDS: TClientDataSet;
UpdateKind: TUpdateKind; var Applied: Boolean);
function NewKey(KeyTable: TTable): Integer;
begin
with KeyTable do
begin
Active := True;
Edit;
with Fields[0] do
begin
Result := AsInteger;
AsInteger := Result + 1;
end;
Post;
end;
end;
begin
// Update records here
// provide new key values, etc.
if SourceDS = CustomerQuery then
begin
case UpdateKind of
ukInsert:
with DeltaDS do
begin
Edit;
FieldByName('CustNo').AsInteger := NewKey(NextCustomerTable);
Post;
end;
ukDelete: ; // Cascade deletes
end;
end
else if SourceDS = CustomerOrdersTable then
begin
case UpdateKind of
ukInsert:
with DeltaDS do
begin
Edit;
FieldByName('OrderNo').AsInteger := NewKey(NextOrderTable);
Post;
end;
ukDelete: ; // Cascade deletes
end;
end
else if SourceDS = CustomerOrderItemsTable then
begin
case UpdateKind of
ukInsert:
with DeltaDS do
begin
Edit;
FieldByName('ItemNo').AsInteger := NewKey(NextItemTable);
Post;
end;
end
end;
end;
function TDMCustomerTree.GetCustomersList: OleVariant;
begin
with CustomerListQuery do
begin
Close;
Open;
end;
with CustomerListProvider do
begin
Reset(True);
Result := Data;
end;
end;
procedure TDMCustomerTree.ValidateEmpNo(AEmpNo: Integer);
begin
EmployeesTable.Active := True;
if not EmployeesTable.Locate('EmpNo', AEmpNo, []) then
raise Exception.CreateFmt('EmpNo %d not found.', [AEmpNo]);
end;
function TDMCustomerTree.GetPartsList: OleVariant;
begin
with PartsQuery do
begin
Close;
Open;
end;
with PartsProvider do
begin
Reset(True);
Result := Data;
end;
end;
end.
|
unit uDMConexao;
interface
uses
SysUtils, Classes, DBXpress, DB, SqlExpr, Forms, IniFiles, Dialogs,
FMTBcd;
type
TDMConection = class(TDataModule)
scoDados: TSQLConnection;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
function Fnc_ArquivoConfiguracao: string;
public
{ Public declarations }
end;
var
DMConection: TDMConection;
implementation
{$R *.dfm}
const
cArquivoConfiguracao = 'Parceiro.ini';
function TDMConection.Fnc_ArquivoConfiguracao: string;
begin
Result := ExtractFilePath(Application.ExeName) + cArquivoConfiguracao;
end;
procedure TDMConection.DataModuleCreate(Sender: TObject);
var
Config: TIniFile;
vTexto: String;
begin
scoDados.Connected := False;
scoDados.KeepConnection := True;
vTexto := Fnc_ArquivoConfiguracao;
if not FileExists(Fnc_ArquivoConfiguracao) then
begin
MessageDlg(' Arquivo Parceiro.ini não Configurado!',mtInformation,[mbOk],0);
Exit;
end;
Config := TIniFile.Create(Fnc_ArquivoConfiguracao);
scoDados.LoadParamsFromIniFile(Fnc_ArquivoConfiguracao);
try
try
scoDados.Params.Values['DRIVERNAME'] := 'INTERBASE';
scoDados.Params.Values['SQLDIALECT'] := '3';
scoDados.Params.Values['DATABASE'] := Config.ReadString('Automafour', 'DATABASE', '');
scoDados.Params.Values['USER_NAME'] := Config.ReadString('Automafour', 'USERNAME', '');
scoDados.Params.Values['PASSWORD'] := Config.ReadString('Automafour', 'PASSWORD', '');
scoDados.Connected := True;
except
on E: exception do
begin
raise Exception.Create('Erro ao conectar ao banco de dados:' + #13 +
'Mensagem: ' + E.Message + #13 +
'Classe: ' + E.ClassName + #13 + #13 +
'Dados da Conexao ' + #13 +
'Banco de Dados: ' + scoDados.Params.Values['Database'] + #13 +
'Usuário: ' + scoDados.Params.Values['User_Name']);
end;
end;
finally
FreeAndNil(Config);
end;
end;
end.
|
unit xVectorArc;
interface
uses Classes, SysUtils, Math, System.Types, System.UITypes, FMX.Controls,
FMX.StdCtrls, FMX.Objects, FMX.Graphics, xVectorType, xVectorLine, FMX.Types;
type
/// <summary>
/// 向量弧线
/// </summary>
TVectorArc = class
private
FArcR: Single;
FEndVector: TVectorLineInfo;
FVID: Integer;
FStartVector: TVectorLineInfo;
FVName: string;
FCanvas: TControl;
FCenterPoint: TPointF;
FIsSelected: Boolean;
FOnMouseDown: TMouseEvent;
procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure MouseLeave(Sender: TObject);
procedure DblClick(Sender: TObject);
procedure MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure SetIsSelected(const Value: Boolean);
public
FArc : TArc;
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TVectorArc);
/// <summary>
/// 向量ID
/// </summary>
property VID : Integer read FVID write FVID;
/// <summary>
/// 向量名称
/// </summary>
property VName : string read FVName write FVName;
/// <summary>
/// 起始向量
/// </summary>
property StartVector : TVectorLineInfo read FStartVector write FStartVector;
/// <summary>
/// 终止向量
/// </summary>
property EndVector : TVectorLineInfo read FEndVector write FEndVector;
/// <summary>
/// 圆弧半径长度
/// </summary>
property ArcR : Single read FArcR write FArcR;
/// <summary>
/// 原点
/// </summary>
property CenterPoint : TPointF read FCenterPoint write FCenterPoint;
/// <summary>
/// 画布
/// </summary>
property Canvas : TControl read FCanvas write FCanvas;
/// <summary>
/// 画图
/// </summary>
procedure Draw;
/// <summary>
/// 是否被选中
/// </summary>
property IsSelected : Boolean read FIsSelected write SetIsSelected;
/// <summary>
/// 鼠标按下事件
/// </summary>
property OnMouseDown : TMouseEvent read FOnMouseDown write FOnMouseDown;
end;
implementation
{ TVectorArc }
procedure TVectorArc.Assign(Source: TVectorArc);
begin
if Assigned(Source) then
begin
FArcR := Source.ArcR;
FEndVector := Source.EndVector;
FVID := Source.VID;
FStartVector:= Source.StartVector;
FVName := Source.VName;
end;
end;
constructor TVectorArc.Create;
begin
FArcR := 15;
FIsSelected := False;
end;
procedure TVectorArc.DblClick(Sender: TObject);
begin
end;
destructor TVectorArc.Destroy;
begin
if Assigned(FArc) then
FArc.Free;
inherited;
end;
procedure TVectorArc.Draw;
function AdjustAngle(dAngle : Double) : Double;
var
dTemp : Integer;
begin
dTemp := Round(dAngle*1000);
dTemp := dTemp mod 360000;
Result := dTemp / 1000;
if Result < 0 then
Result := 360 + Result;
end;
begin
if Assigned(FStartVector) and Assigned(FEndVector) then
begin
if not Assigned(FArc) then
FArc := TArc.Create(FCanvas);
FArc.Parent := FCanvas;
FArc.Position.X := FCenterPoint.X - FArcR;
FArc.Position.Y := FCenterPoint.Y - FArcR;
FArc.Width := FArcR*2;
FArc.Height := FArcR*2;
FArc.Stroke.Color := FStartVector.VColor;
FArc.Cursor := crHandPoint;
FArc.StartAngle := -FStartVector.VAngle;
FArc.EndAngle := AdjustAngle(FStartVector.VAngle-FEndVector.VAngle);
FArc.OnMouseMove := MouseMove;
FArc.OnMouseLeave := MouseLeave;
FArc.OnDblClick := DblClick;
FArc.OnMouseDown := MouseDown;
end;
end;
procedure TVectorArc.MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if Assigned(FOnMouseDown) then
begin
FOnMouseDown(Self, Button, Shift, X, Y);
end;
end;
procedure TVectorArc.MouseLeave(Sender: TObject);
begin
if FIsSelected then
begin
FArc.Stroke.Color := C_COLOR_SELECT;
end
else
begin
FArc.Stroke.Color := FStartVector.VColor;
end;
end;
procedure TVectorArc.MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
begin
FArc.Stroke.Color := C_COLOR_SELECT;
end;
procedure TVectorArc.SetIsSelected(const Value: Boolean);
begin
FIsSelected := Value;
end;
end.
|
unit ThreadUnit;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.ActnList;
type
TSimpleThread = class;
TThreadExecObject = class
private
FName: string;
FDescription: string;
FErrMessage: string;
FWinHandle: THandle;
FMsg: UINT;
FOnBeforeAction: TAction;
FOnAfterAction: TAction;
FUserObject: TPersistent;
FUserTree: TPersistent;
FUserTag: NativeInt;
procedure SendNotification;
protected
FThread: TSimpleThread;
procedure Execute; virtual; abstract;
public
constructor Create;
procedure Start;
procedure Finish;
property UserTree: TPersistent read FUserTree write FUserTree;
property UserObject: TPersistent read FUserObject write FUserObject;
property UserTag: NativeInt read FUserTag write FUserTag;
property ErrMessage: string read FErrMessage write FErrMessage;
property Name: string read FName write FName;
property WinHandle: THandle read FWinHandle write FWinHandle;
property Description: string read FDescription write FDescription;
property Msg: UINT read FMsg write FMsg;
property OnBeforeAction: TAction read FOnBeforeAction write FOnBeforeAction;
property OnAfterAction: TAction read FOnAfterAction write FOnAfterAction;
end;
TExecObject = TThreadExecObject;
TSimpleThread = class(TThread)
private
{ Private declarations }
FExecObject: TThreadExecObject;
protected
procedure Execute; override;
public
{ Public declarations }
property ExecObject: TThreadExecObject read FExecObject write FExecObject;
property Terminated;
end;
implementation
uses Winapi.ActiveX, plugin;
{ TSimpleThread }
procedure TSimpleThread.Execute;
begin
Priority := tpLower;
CoInitialize(nil);
try
if not Terminated then
try
FExecObject.Execute;
except
on E: Exception do
FExecObject.ErrMessage := E.Message;
end;
finally
Terminate;
FExecObject.SendNotification;
CoUnInitialize;
end;
end;
{ TThreadExecObject }
constructor TThreadExecObject.Create;
begin
inherited;
FMsg := WM_USER_MESSAGE_FROM_THREAD;
end;
procedure TThreadExecObject.Finish;
begin
if Assigned(FOnAfterAction) then
begin
FOnAfterAction.Tag := NativeInt(Self);
FOnAfterAction.Execute;
end;
end;
procedure TThreadExecObject.SendNotification;
begin
SendMessage(FWinHandle,FMsg,0,LPARAM(Self));
end;
procedure TThreadExecObject.Start;
begin
if Assigned(FOnBeforeAction) then
begin
FOnBeforeAction.Tag := NativeInt(Self);
FOnBeforeAction.Execute;
end;
FThread := TSimpleThread.Create(True);
FThread.FreeOnTerminate := True;
with TSimpleThread(FThread) do
begin
ExecObject := Self;
FThread.Start;
end;
end;
end.
|
unit Controller.ContatoController;
interface
uses
System.SysUtils, System.Classes, Datasnap.DSServer,
Datasnap.DSAuth, Datasnap.DSProviderDataModuleAdapter, uDMServer,
Datasnap.DSCommonServer, Rest.JSON, System.JSON, 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;
type
TContatoController = class(TDSServerModule)
ContatoTable: TFDQuery;
Contato_emailTable: TFDQuery;
Contato_telefoneTable: TFDQuery;
private
function Validar: string;
{ Private declarations }
public
{ Public declarations }
function Contatos: TJSONValue;
function Contato(ID: Integer): TJSONValue;
function updateContatos(Contatos:TJSONValue):TJSONValue;
function acceptContatos(Contatos:TJSONValue):TJSONValue;
function cancelContatos(Contatos:TJSONValue):TJSONValue;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TContatoController }
function TContatoController.acceptContatos(Contatos: TJSONValue): TJSONValue;
begin
end;
function TContatoController.cancelContatos(Contatos: TJSONValue): TJSONValue;
begin
end;
function TContatoController.Contato(ID: Integer): TJSONValue;
begin
//
end;
function TContatoController.Contatos: TJSONValue;
var
Arr: TJSONArray;
Obj: TJSONObject;
I: Integer;
begin
Arr := TJSONArray.Create;
ContatoTable.Open();
ContatoTable.First;
while not ContatoTable.Eof do
begin
Obj := TJSONObject.Create;
for I := 0 to ContatoTable.FieldCount-1 do
begin
Obj.AddPair(ContatoTable.Fields[I].FieldName, ContatoTable.Fields[I].AsString);
end;
Arr.Add(Obj);
ContatoTable.Next;
end;
Result := Arr;
end;
function TContatoController.updateContatos(Contatos: TJSONValue): TJSONValue;
begin
end;
function TContatoController.Validar: string;
begin
Result := 'funcionando!';
end;
end.
|
{**********************************************}
{ TeeChart Formatting Editor }
{ Copyright (c) 2001-2004 by David Berneda }
{ All Rights Reserved. }
{**********************************************}
unit TeeFormatting;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
SysUtils, Classes, TeCanvas, TeeProcs, TeEngine, Chart, TeePenDlg;
type
TFormatEditor = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
GroupBox1: TGroupBox;
CBCustom: TComboFlat;
CBDate: TComboFlat;
RBDate: TRadioButton;
RBCustom: TRadioButton;
RBGeo: TRadioButton;
CBGeo: TComboFlat;
Panel2: TPanel;
RBInteger: TRadioButton;
CBPercent: TCheckBox;
CBThousands: TCheckBox;
CBCurrency: TCheckBox;
CBFixedDecimals: TCheckBox;
UpDown1: TUpDown;
Edit1: TEdit;
Label1: TLabel;
Label2: TLabel;
Edit2: TEdit;
UpDown2: TUpDown;
procedure RadioGroup1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CBDateChange(Sender: TObject);
procedure CBCustomChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBPercentClick(Sender: TObject);
procedure CBThousandsClick(Sender: TObject);
procedure CBGeoChange(Sender: TObject);
procedure RBIntegerClick(Sender: TObject);
private
{ Private declarations }
tmpChanging : Boolean;
Procedure AddDate(Const S:String);
Procedure AddGeo(Const S:String);
public
{ Public declarations }
Format : String;
IsDate : Boolean;
IsGeo : Boolean;
Function TheFormat:String;
class Function Change(AOwner:TComponent; const AFormat:String; AllowDates:Boolean=True):String;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
{$IFDEF D6}
uses
StrUtils;
{$ENDIF}
{$IFNDEF D6} // From Borland's Delphi 6 StrUtils unit, for Delphi 4,5.
function DupeString(const AText: string; ACount: Integer): string;
var
P: PChar;
C: Integer;
begin
C := Length(AText);
SetLength(Result, C * ACount);
P := Pointer(Result);
if P = nil then Exit;
while ACount > 0 do
begin
Move(Pointer(AText)^, P^, C);
Inc(P, C);
Dec(ACount);
end;
end;
{$ENDIF}
procedure TFormatEditor.RadioGroup1Click(Sender: TObject);
begin
if tmpChanging then exit;
IsDate:=RBDate.Checked;
IsGeo:=RBGeo.Checked;
if RBDate.Checked or RBGeo.Checked or RBCustom.Checked then
RBInteger.Checked:=False;
CBDate.Enabled:=IsDate;
CBGeo.Enabled:=RBGeo.Checked;
CBCustom.Enabled:=RBCustom.Checked;
if RBDate.Checked then
begin
EnableControls(False,[Edit1,UpDown1]);
if CBDate.Text='' then CBDate.Text:=ShortDateFormat;
CBDate.SetFocus;
end
else
if RBGeo.Checked then
begin
EnableControls(False,[Edit1,UpDown1]);
if CBGeo.Text='' then CBGeo.Text:=CBGeo.Items[0];
CBGeo.SetFocus;
end
else
begin
CBPercent.Enabled:=not CBCustom.Enabled;
if CBCustom.Enabled then
begin
if CBCustom.Text='' then CBCustom.Text:=TheFormat;
CBCustom.SetFocus;
end;
end;
end;
function TFormatEditor.TheFormat: String;
var t : Integer;
begin
if CBCustom.Enabled then
result:=CBCustom.Text
else
if RBInteger.Checked then
begin
if CBCurrency.Checked then result:=CurrencyString
else result:='';
if UpDown2.Position=0 then
if CBThousands.Checked then result:=result+'#,###'
else result:=result+'#'
else
begin
if CBThousands.Checked then
begin
if UpDown2.Position>3 then
result:=result+DupeString('0',UpDown2.Position-3)+',000'
else
result:=result+'#,'+DupeString('#',3-UpDown2.Position)+DupeString('0',UpDown2.Position);
end
else
for t:=1 to UpDown2.Position do
result:=result+'0';
end;
if UpDown1.Position>0 then
if CBFixedDecimals.Checked then
result:=result+'.'+DupeString('0',UpDown1.Position)
else
result:=result+'.'+DupeString('#',UpDown1.Position);
if CBPercent.Checked then result:=result+'%';
end
else
if RBDate.Checked then
result:=CBDate.Text
else
if RBGeo.Checked then
result:=CBGeo.Text
else
result:='';
end;
procedure TFormatEditor.FormShow(Sender: TObject);
procedure SetIntegerRB;
begin
tmpChanging:=True;
try
RBInteger.Checked:=True;
finally
tmpChanging:=False;
end;
end;
var i : Integer;
t : Integer;
tmp : Integer;
IsCustom : Boolean;
OldFormat : String;
begin
OldFormat:=Format;
CBCustom.Items.Clear;
CBCustom.Items.Add('#.#');
CBCustom.Items.Add('0.0%');
CBGeo.Items.Clear;
CBGeo.Items.Add('ddd° mm'' ss".zzz');
CBGeo.Items.Add('ddd mm'' ss".zzz');
CBGeo.Items.Add('ddd deg mm'' ss".zzz');
CBGeo.Items.Add('ddd mm'' ss".zzz');
CBGeo.Items.Add('ddd mm ss.zzz');
CBGeo.Items.Add('ddd mm ss');
CBGeo.Items.Add('ddd mm');
CBGeo.Items.Add('ddd°');
CBGeo.Items.Add('ddd');
if IsDate or (CBDate.Items.IndexOf(Format)<>-1) then
begin
CBDate.Enabled:=True;
AddDate(Format);
CBDate.Text:=Format;
CBDate.SetFocus;
tmpChanging:=True;
try
RBDate.Checked:=True;
finally
tmpChanging:=False;
end;
end
else
if IsGeo or (CBGeo.Items.IndexOf(Format)<>-1) then
begin
CBGeo.Enabled:=True;
AddGeo(Format);
CBGeo.Text:=Format;
CBGeo.SetFocus;
tmpChanging:=True;
try
RBGeo.Checked:=True;
finally
tmpChanging:=False;
end;
end
else
begin
i:=Pos('%',Format);
CBPercent.Checked:=i>0;
CBPercentClick(Self);
if i>0 then Delete(Format,i,1);
i:=Pos(CurrencyString,Format);
CBCurrency.Checked:=i>0;
if i>0 then Delete(Format,i,Length(CurrencyString));
i:=Pos(',',Format);
CBThousands.Checked:=i>0;
if i>0 then Delete(Format,i,1);
i:=Pos('.',Format);
if i>0 then
begin
SetIntegerRB;
tmp:=0;
while (Copy(Format,i+tmp+1,1)='#') or (Copy(Format,i+tmp+1,1)='0') do
Inc(tmp);
UpDown1.Position:=tmp;
CBFixedDecimals.Checked:=(tmp>0) and (Copy(Format,i+1,1)='0');
Delete(Format,i,tmp+1);
end;
IsCustom:=False;
for t:=1 to Length(Format) do
if (Format[t]<>'#') and (Format[t]<>'0') then
begin
IsCustom:=True;
Format:=OldFormat;
break;
end;
tmp:=0;
if not IsCustom then
begin
SetIntegerRB;
for t:=1 to Length(Format) do
if Format[t]='0' then Inc(tmp);
UpDown2.Position:=tmp;
end
else
begin
tmpChanging:=True;
try
RBCustom.Checked:=True;
finally
tmpChanging:=False;
end;
CBCustom.Enabled:=True;
if CBCustom.Items.IndexOf(Format)=0 then
CBCustom.Items.Add(Format);
CBCustom.Text:=Format;
CBCustom.SetFocus;
end;
end;
TeeTranslateControl(Self);
end;
procedure TFormatEditor.CBDateChange(Sender: TObject);
begin
Format:=CBDate.Text;
end;
procedure TFormatEditor.CBCustomChange(Sender: TObject);
begin
Format:=CBCustom.Text;
end;
Procedure TFormatEditor.AddDate(Const S:String);
begin
if CBDate.Items.IndexOf(S)=-1 then CBDate.Items.Add(S);
end;
Procedure TFormatEditor.AddGeo(Const S:String);
begin
if CBGeo.Items.IndexOf(S)=-1 then CBGeo.Items.Add(S);
end;
procedure TFormatEditor.FormCreate(Sender: TObject);
begin
AddDate(ShortDateFormat);
AddDate(ShortTimeFormat);
end;
procedure TFormatEditor.CBPercentClick(Sender: TObject);
begin
CBThousands.Enabled:=not CBPercent.Checked;
CBCurrency.Enabled:=not CBPercent.Checked;
if CBPercent.Checked then
begin
CBThousands.Checked:=False;
CBCurrency.Checked:=False;
end;
end;
procedure TFormatEditor.CBThousandsClick(Sender: TObject);
begin
RadioGroup1Click(Sender);
end;
procedure TFormatEditor.CBGeoChange(Sender: TObject);
begin
Format:=CBGeo.Text;
end;
procedure TFormatEditor.RBIntegerClick(Sender: TObject);
begin
if RBInteger.Checked then
begin
RBDate.Checked:=False;
RBGeo.Checked:=False;
RBCustom.Checked:=False;
end;
RadioGroup1Click(Self);
end;
class function TFormatEditor.Change(AOwner:TComponent; const AFormat: String; AllowDates:Boolean=True): String;
begin
with TFormatEditor.Create(AOwner) do
try
Format:=AFormat;
Panel1.Visible:=AllowDates;
AddDefaultValueFormats(CBCustom.Items);
if ShowModal=mrOk then result:=TheFormat
else result:=AFormat;
finally
Free;
end;
end;
end.
|
unit _frSetup;
interface
uses
FrameBase, JsonData,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TfrSetup = class(TFrame)
Label1: TLabel;
cbYouTube: TCheckBox;
edStreamKey: TEdit;
Bevel1: TBevel;
cbMinimize: TCheckBox;
procedure edStreamKeyKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbYouTubeClick(Sender: TObject);
procedure cbMinimizeClick(Sender: TObject);
private
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
procedure rp_ShowOptionControl(AParams:TJsonData);
end;
implementation
uses
Core, Options;
{$R *.dfm}
{ TfrSetup }
procedure TfrSetup.cbMinimizeClick(Sender: TObject);
begin
TOptions.Obj.MinimizeOnRecording := cbMinimize.Checked;
end;
procedure TfrSetup.cbYouTubeClick(Sender: TObject);
begin
TOptions.Obj.YouTubeOption.OnAir := cbYouTube.Checked;
end;
constructor TfrSetup.Create(AOwner: TComponent);
begin
inherited;
TCore.Obj.View.Add(Self);
end;
destructor TfrSetup.Destroy;
begin
TCore.Obj.View.Remove(Self);
inherited;
end;
procedure TfrSetup.edStreamKeyKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
TOptions.Obj.YouTubeOption.StreamKey := edStreamKey.Text;
end;
procedure TfrSetup.rp_ShowOptionControl(AParams: TJsonData);
begin
Visible := AParams.Values['Target'] = HelpKeyword;
end;
end. |
(**
This module contains the interfaces for creating meuns in the IDEs project manager.
There are two interfaces, one for D2005 to 2009 and another for D2010 onwards.
@Author David Hoyle
@Version 1.0
@Date 30 Dec 2017
**)
Unit ITHelper.ProjectManagerMenuInterface;
Interface
{$INCLUDE 'CompilerDefinitions.inc'}
{$IFDEF D2005}
Uses
ToolsAPI,
ITHelper.Wizard,
Classes,
Menus;
Type
(** A class to handle the creation of a menu for the project manager. **)
TITHProjectManagerMenu = Class(TNotifierObject, IOTANotifier,
{$IFNDEF D2010} INTAProjectMenuCreatorNotifier {$ELSE} IOTAProjectMenuItemCreatorNotifier {$ENDIF})
Strict Private
FWizard: TITHWizard;
Strict Protected
// IOTANotifier
Procedure AfterSave;
Procedure BeforeSave;
Procedure Destroyed;
Procedure Modified;
{$IFNDEF D2010}
// INTAProjectMenuCreatorNotifier
Function AddMenu(Const Ident: String): TMenuItem;
Function CanHandle(Const Ident: String): Boolean;
{$ENDIF}
{$IFDEF D2010}
// IOTAProjectMenuItemCreatorNotifier
Procedure AddMenu(Const Project: IOTAProject; Const IdentList: TStrings;
Const ProjectManagerMenuList: IInterfaceList; IsMultiSelect: Boolean);
{$ENDIF}
// General Methods
Procedure OptionsClick(Sender: TObject);
Public
Constructor Create(Const Wizard: TITHWizard);
End;
{$IFDEF D2010}
(** A class to define a Delphi 2010 Project Menu Item. **)
TITHelperProjectMenu = Class(TNotifierObject, IOTALocalMenu, IOTAProjectManagerMenu)
Strict Private
FWizard : TITHWizard;
FProject : IOTAProject;
FPosition: Integer;
FCaption : String;
FName : String;
FVerb : String;
FParent : String;
FSetting : TSetting;
Strict Protected
// IOTALocalMenu
Function GetCaption: String;
Function GetChecked: Boolean;
Function GetEnabled: Boolean;
Function GetHelpContext: Integer;
Function GetName: String;
Function GetParent: String;
Function GetPosition: Integer;
Function GetVerb: String;
Procedure SetCaption(Const Value: String);
Procedure SetChecked(Value: Boolean);
Procedure SetEnabled(Value: Boolean);
Procedure SetHelpContext(Value: Integer);
Procedure SetName(Const Value: String);
Procedure SetParent(Const Value: String);
Procedure SetPosition(Value: Integer);
Procedure SetVerb(Const Value: String);
// IOTAProjectManagerMenu
Function GetIsMultiSelectable: Boolean;
Procedure SetIsMultiSelectable(Value: Boolean);
Procedure Execute(Const MenuContextList: IInterfaceList); Overload;
Function PreExecute(Const MenuContextList: IInterfaceList): Boolean;
Function PostExecute(Const MenuContextList: IInterfaceList): Boolean;
// General Methods
Public
Constructor Create(Const Wizard: TITHWizard; Const Project: IOTAProject; Const strCaption, strName,
strVerb, strParent: String; Const iPosition: Integer; Const Setting: TSetting);
End;
{$ENDIF}
{$ENDIF}
Implementation
{$IFDEF D2005}
Uses
SysUtils,
ITHelper.TestingHelperUtils;
ResourceString
(** A resource string for plug-ins main menu. **)
strMainCaption = 'Integrated Testing Helper';
(** A resource string for Project options menu. **)
strProjectCaption = 'Project Options';
(** A resource string for Before Compilation menu. **)
strBeforeCaption = 'Before Compilation';
(** A resource string for After Compilation Menu. **)
strAfterCaption = 'After Compilation';
(** A resource string for ZIP Options menu. **)
strZIPCaption = 'ZIP Options';
Const
(** A constant string identifier for the main menu. **)
strMainName = 'ITHelperMainMenu';
(** A constant string identifier for Project Options. **)
strProjectName = 'ITHProjMgrProjectOptions';
(** A constant string identifier for Before Options. **)
strBeforeName = 'ITHProjMgrBefore';
(** A constant string identifier for After Options. **)
strAfterName = 'ITHProjMgrAfter';
(** A constant string identifier for ZIP Options. **)
strZIPName = 'ITHProjMgrZIPOptions';
{ TProjectManagerMenu }
{$IFNDEF D2010}
(**
This method create a menu to be displayed in the project manager for handling
the configuration of Integrated Testing Helper Options.
@precon None.
@postcon Create a menu to be displayed in the project manager for handling
the configuration of Integrated Testing Helper Options.
@param Ident as a string as a constant
@return a TMenuItem
**)
Function TProjectManagerMenu.AddMenu(Const Ident: String): TMenuItem;
Var
SM: TMenuItem;
Begin
Result := Nil;
If Like(sProjectContainer, Ident) Then
Begin
Result := TMenuItem.Create(Nil);
Result.Caption := strMainCaption;
SM := TMenuItem.Create(Nil);
SM.Caption := strProjectCaption;
SM.Name := strProjectName;
SM.OnClick := OptionsClick;
Result.Add(SM);
SM := TMenuItem.Create(Nil);
SM.Caption := strBeforeCaption;
SM.Name := strBeforeName;
SM.OnClick := OptionsClick;
Result.Add(SM);
SM := TMenuItem.Create(Nil);
SM.Caption := strAfterCaption;
SM.Name := strAfterName;
SM.OnClick := OptionsClick;
Result.Add(SM);
SM := TMenuItem.Create(Nil);
SM.Caption := strZIPCaption;
SM.Name := strZIPName;
SM.OnClick := OptionsClick;
Result.Add(SM);
End;
End;
{$ELSE}
(**
This method create a menu to be displayed in the project manager for handling the configuration of
Integrated Testing Helper Options.
@precon None.
@postcon Create a menu to be displayed in the project manager for handling the configuration of
Integrated Testing Helper Options.
@nocheck MissingCONSTInParam
@nohints
@param Project as an IOTAProject as a constant
@param IdentList as a TStrings as a constant
@param ProjectManagerMenuList as an IInterfaceList as a constant
@param IsMultiSelect as a Boolean
**)
Procedure TITHProjectManagerMenu.AddMenu(Const Project: IOTAProject; Const IdentList: TStrings;
Const ProjectManagerMenuList: IInterfaceList; IsMultiSelect: Boolean);
Const
strOptions = 'Options';
Var
i, j : Integer;
iPosition: Integer;
M : IOTAProjectManagerMenu;
Begin
For i := 0 To IdentList.Count - 1 Do
If sProjectContainer = IdentList[i] Then
Begin
iPosition := 0;
For j := 0 To ProjectManagerMenuList.Count - 1 Do
Begin
M := ProjectManagerMenuList.Items[j] As IOTAProjectManagerMenu;
If CompareText(M.Verb, strOptions) = 0 Then
Begin
iPosition := M.Position + 1;
Break;
End;
End;
ProjectManagerMenuList.Add(TITHelperProjectMenu.Create(FWizard, Project,
strMainCaption, strMainName, strMainName, '', iPosition, seProject));
ProjectManagerMenuList.Add(TITHelperProjectMenu.Create(FWizard, Project,
strProjectCaption, strProjectName, strProjectName, strMainName, iPosition + 1,
seProject));
ProjectManagerMenuList.Add(TITHelperProjectMenu.Create(FWizard, Project,
strBeforeCaption, strBeforeName, strBeforeName, strMainName, iPosition + 2,
seBefore));
ProjectManagerMenuList.Add(TITHelperProjectMenu.Create(FWizard, Project,
strAfterCaption, strAfterName, strAfterName, strMainName, iPosition + 3,
seAfter));
ProjectManagerMenuList.Add(TITHelperProjectMenu.Create(FWizard, Project,
strZIPCaption, strZIPName, strZIPName, strMainName, iPosition + 4, seZIP));
End;
End;
{$ENDIF}
(**
This method is not implemented.
@precon None.
@postcon None.
@nocheck EmptyMethod
**)
Procedure TITHProjectManagerMenu.AfterSave;
Begin
End;
(**
This method is not implemented.
@precon None.
@postcon None.
@nocheck EmptyMethod
**)
Procedure TITHProjectManagerMenu.BeforeSave;
Begin
End;
{$IFNDEF D2010}
(**
This method is called for the selected node in the project manager asking if
a menu should be created for the given ID. We return true for the ident
"ProjectContainer".
@precon None.
@postcon Returns true for the ident "ProjectContainer".
@param Ident as a string as a constant
@return a Boolean
**)
Function TITHProjectManagerMenu.CanHandle(Const Ident: String): Boolean;
Begin
Result := sProjectContainer = Ident;
End;
{$ENDIF}
(**
This is a constructor for the TProjectManagerMenu class.
@precon None.
@postcon Holds a reference to the main wizard for configuring options.
@param Wizard as a TITHWizard as a constant
**)
Constructor TITHProjectManagerMenu.Create(Const Wizard: TITHWizard);
Begin
FWizard := Wizard;
End;
(**
This method is not implemented.
@precon None.
@postcon None.
@nocheck EmptyMethod
**)
Procedure TITHProjectManagerMenu.Destroyed;
Begin
End;
(**
This method is not implemented.
@precon None.
@postcon None.
@nocheck EmptyMethod
**)
Procedure TITHProjectManagerMenu.Modified;
Begin
End;
(**
This is an on click event handler for the project manager menu items.
@precon None.
@postcon Invokes the main wizards various option dialogues for the selected project.
@param Sender as a TObject
**)
Procedure TITHProjectManagerMenu.OptionsClick(Sender: TObject);
Var
Project : IOTAProject;
strIdent: String;
Begin
Project := (BorlandIDEServices As IOTAProjectManager).GetCurrentSelection(strIdent);
If Sender Is TMenuItem Then
If (Sender As TMenuItem).Name = strProjectName Then
FWizard.ConfigureOptions(Project, seProject)
Else If (Sender As TMenuItem).Name = strBeforeName Then
FWizard.ConfigureOptions(Project, seBefore)
Else If (Sender As TMenuItem).Name = strAfterName Then
FWizard.ConfigureOptions(Project, seAfter)
Else If (Sender As TMenuItem).Name = strZIPName Then
FWizard.ConfigureOptions(Project, seZIP);
End;
{ TITHelperProjectMenu }
{$IFDEF D2010}
(**
This is a constructor method for the TITHelperProjectMenu class.
@precon None.
@postcon Initialises the class with reference to the project and the wizard.
@param Wizard as a TITHWizard as a constant
@param Project as an IOTAProject as a constant
@param strCaption as a String as a constant
@param strName as a String as a constant
@param strVerb as a String as a constant
@param strParent as a String as a constant
@param iPosition as an Integer as a constant
@param Setting as a TSetting as a constant
**)
Constructor TITHelperProjectMenu.Create(Const Wizard: TITHWizard; Const Project: IOTAProject;
Const strCaption, strName, strVerb, strParent: String; Const iPosition: Integer;
Const Setting: TSetting);
Begin
FWizard := Wizard;
FProject := Project;
FPosition := iPosition;
FCaption := strCaption;
FName := strName;
FVerb := strVerb;
FParent := strParent;
FSetting := Setting;
End;
(**
This is an execute method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Displays the Configuation Options dialogue for the current project.
@nohints
@param MenuContextList as an IInterfaceList as a constant
**)
Procedure TITHelperProjectMenu.Execute(Const MenuContextList: IInterfaceList);
Begin
FWizard.ConfigureOptions(FProject, FSetting);
End;
(**
This is an GetCaption method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns the menu caption to be displayed.
@return a String
**)
Function TITHelperProjectMenu.GetCaption: String;
Begin
Result := FCaption;
End;
(**
This is an GetChecked method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns false for the menu item to not be checked.
@return a Boolean
**)
Function TITHelperProjectMenu.GetChecked: Boolean;
Begin
Result := False;
End;
(**
This is an GetEnabled method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns true for the menu item to tbe enabled.
@return a Boolean
**)
Function TITHelperProjectMenu.GetEnabled: Boolean;
Begin
Result := True;
End;
(**
This is an GetHelpContext method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns zero for no context help.
@return a Integer
**)
Function TITHelperProjectMenu.GetHelpContext: Integer;
Begin
Result := 0;
End;
(**
This is an GetIsMultiSelectable method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Returns false for not being a multi-selectable menu item.
@return a Boolean
**)
Function TITHelperProjectMenu.GetIsMultiSelectable: Boolean;
Begin
Result := False;
End;
(**
This is an GetName method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns a name for the menu item.
@return a String
**)
Function TITHelperProjectMenu.GetName: String;
Begin
Result := FName;
End;
(**
This is an GetParent method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns an empty string since this menu item does not have a parent menu.
@return a String
**)
Function TITHelperProjectMenu.GetParent: String;
Begin
Result := FParent;
End;
(**
This is an GetPosition method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns the position passed to the menu items constructor.
@return a Integer
**)
Function TITHelperProjectMenu.GetPosition: Integer;
Begin
Result := FPosition;
End;
(**
This is an GetVerb method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Returns an identifier for the menu item.
@return a String
**)
Function TITHelperProjectMenu.GetVerb: String;
Begin
Result := FVerb;
End;
(**
This is a post execute method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Does nothing and returns false.
@nohints
@param MenuContextList as an IInterfaceList as a constant
@return a Boolean
**)
Function TITHelperProjectMenu.PostExecute(Const MenuContextList: IInterfaceList): Boolean;
Begin
Result := False;
End;
(**
This is a pre execute method implementation for the IOTAProjectManageMenu interface.
@precon None.
@postcon Does nothing and returns false.
@nohints
@param MenuContextList as an IInterfaceList as a constant
@return a Boolean
**)
Function TITHelperProjectMenu.PreExecute(Const MenuContextList: IInterfaceList): Boolean;
Begin
Result := False;
End;
(**
This is an SetCaption method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck EmptyMethod
@nohints
@param Value as a String as a Constant
**)
Procedure TITHelperProjectMenu.SetCaption(Const Value: String);
Begin
// Do nothing.
End;
(**
This is an SetChecked method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck MissingCONSTInParam EmptyMethod
@nohints
@param Value as a Boolean
**)
Procedure TITHelperProjectMenu.SetChecked(Value: Boolean);
Begin
// Do nothing.
End;
(**
This is an SetEnabled method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck MissingCONSTInParam EmptyMethod
@nohints
@param Value as a Boolean
**)
Procedure TITHelperProjectMenu.SetEnabled(Value: Boolean);
Begin
// Do nothing.
End;
(**
This is an SetHelpContext method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck MissingCONSTInParam EmptyMethod
@nohints
@param Value as a Integer
**)
Procedure TITHelperProjectMenu.SetHelpContext(Value: Integer);
Begin
// Do nothing.
End;
(**
This is an SetIsMultiSelectable method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck MissingCONSTInParam EmptyMethod
@nohints
@param Value as a Boolean
**)
Procedure TITHelperProjectMenu.SetIsMultiSelectable(Value: Boolean);
Begin
// Do nothing.
End;
(**
This is an SetName method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck EmptyMethod
@nohints
@param Value as a String as a Constant
**)
Procedure TITHelperProjectMenu.SetName(Const Value: String);
Begin
// Do nothing.
End;
(**
This is an SetParent method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck EmptyMethod
@nohints
@param Value as a String as a Constant
**)
Procedure TITHelperProjectMenu.SetParent(Const Value: String);
Begin
// Do nothing.
End;
(**
This is an SetPosition method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck MissingCONSTInParam EmptyMethod
@nohints
@param Value as a Integer
**)
Procedure TITHelperProjectMenu.SetPosition(Value: Integer);
Begin
// Do nothing.
End;
(**
This is an SetVerb method implementation for the IOTAProjectManageMenu
interface.
@precon None.
@postcon Does nothing.
@nocheck EmptyMethod
@nohints
@param Value as a String as a Constant
**)
Procedure TITHelperProjectMenu.SetVerb(Const Value: String);
Begin
// Do nothing.
End;
{$ENDIF}
{$ENDIF}
End.
|
{ *********************************************************************** }
{ }
{ Delphi Runtime Library }
{ }
{ Copyright (c) 1999-2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
{ ***************************************************** }
{ COM+ Administration Interface Unit }
{ ***************************************************** }
unit COMAdmin;
interface
uses Windows, ActiveX;
const
COMAdminMajorVersion = 1;
COMAdminMinorVersion = 0;
LIBID_COMAdmin: TGUID = '{F618C513-DFB8-11D1-A2CF-00805FC79235}';
IID_ICOMAdminCatalog: TGUID = '{DD662187-DFC2-11D1-A2CF-00805FC79235}';
CLASS_COMAdminCatalog: TGUID = '{F618C514-DFB8-11D1-A2CF-00805FC79235}';
IID_ICatalogObject: TGUID = '{6EB22871-8A19-11D0-81B6-00A0C9231C29}';
CLASS_COMAdminCatalogObject: TGUID = '{F618C515-DFB8-11D1-A2CF-00805FC79235}';
IID_ICatalogCollection: TGUID = '{6EB22872-8A19-11D0-81B6-00A0C9231C29}';
CLASS_COMAdminCatalogCollection: TGUID = '{F618C516-DFB8-11D1-A2CF-00805FC79235}';
type
COMAdminApplicationInstallOptions = TOleEnum;
const
COMAdminInstallNoUsers = $00000000;
COMAdminInstallUsers = $00000001;
COMAdminInstallForceOverwriteOfFiles = $00000002;
type
COMAdminApplicationExportOptions = TOleEnum;
const
COMAdminExportNoUsers = $00000000;
COMAdminExportUsers = $00000001;
COMAdminExportApplicationProxy = $00000002;
COMAdminExportForceOverwriteOfFiles = $00000004;
type
COMAdminThreadingModels = TOleEnum;
const
COMAdminThreadingModelApartment = $00000000;
COMAdminThreadingModelFree = $00000001;
COMAdminThreadingModelMain = $00000002;
COMAdminThreadingModelBoth = $00000003;
COMAdminThreadingModelNeutral = $00000004;
COMAdminThreadingModelNotSpecified = $00000005;
type
COMAdminTransactionOptions = TOleEnum;
const
COMAdminTransactionIgnored = $00000000;
COMAdminTransactionNone = $00000001;
COMAdminTransactionSupported = $00000002;
COMAdminTransactionRequired = $00000003;
COMAdminTransactionRequiresNew = $00000004;
type
COMAdminSynchronizationOptions = TOleEnum;
const
COMAdminSynchronizationIgnored = $00000000;
COMAdminSynchronizationNone = $00000001;
COMAdminSynchronizationSupported = $00000002;
COMAdminSynchronizationRequired = $00000003;
COMAdminSynchronizationRequiresNew = $00000004;
type
COMAdminActivationOptions = TOleEnum;
const
COMAdminActivationInproc = $00000000;
COMAdminActivationLocal = $00000001;
type
COMAdminAccessChecksLevelOptions = TOleEnum;
const
COMAdminAccessChecksApplicationLevel = $00000000;
COMAdminAccessChecksApplicationComponentLevel = $00000001;
type
COMAdminAuthenticationLevelOptions = TOleEnum;
const
COMAdminAuthenticationDefault = $00000000;
COMAdminAuthenticationNone = $00000001;
COMAdminAuthenticationConnect = $00000002;
COMAdminAuthenticationCall = $00000003;
COMAdminAuthenticationPacket = $00000004;
COMAdminAuthenticationIntegrity = $00000005;
COMAdminAuthenticationPrivacy = $00000006;
type
COMAdminImpersonationLevelOptions = TOleEnum;
const
COMAdminImpersonationAnonymous = $00000001;
COMAdminImpersonationIdentify = $00000002;
COMAdminImpersonationImpersonate = $00000003;
COMAdminImpersonationDelegate = $00000004;
type
COMAdminAuthenticationCapabilitiesOptions = TOleEnum;
const
COMAdminAuthenticationCapabilitiesNone = $00000000;
COMAdminAuthenticationCapabilitiesStaticCloaking = $00000020;
COMAdminAuthenticationCapabilitiesDynamicCloaking = $00000040;
COMAdminAuthenticationCapabilitiesSecureReference = $00000002;
type
COMAdminOS = TOleEnum;
const
COMAdminOSWindows3_1 = $00000001;
COMAdminOSWindows9x = $00000002;
COMAdminOSWindowsNT = $00000003;
COMAdminOSWindowsNTEnterprise = $00000004;
type
COMAdminServiceOptions = TOleEnum;
const
COMAdminServiceLoadBalanceRouter = $00000001;
COMAdminServiceIMDB = $00000002;
type
COMAdminServiceStatusOptions = TOleEnum;
const
COMAdminServiceStopped = $00000000;
COMAdminServiceStartPending = $00000001;
COMAdminServiceStopPending = $00000002;
COMAdminServiceRunning = $00000003;
COMAdminServiceContinuePending = $00000004;
COMAdminServicePausePending = $00000005;
COMAdminServicePaused = $00000006;
COMAdminServiceUnknownState = $00000007;
type
COMAdminFileFlags = TOleEnum;
const
COMAdminFileFlagLoadable = $00000001;
COMAdminFileFlagCOM = $00000002;
COMAdminFileFlagContainsPS = $00000004;
COMAdminFileFlagContainsComp = $00000008;
COMAdminFileFlagContainsTLB = $00000010;
COMAdminFileFlagSelfReg = $00000020;
COMAdminFileFlagSelfUnReg = $00000040;
COMAdminFileFlagUnloadableDLL = $00000080;
COMAdminFileFlagDoesNotExist = $00000100;
COMAdminFileFlagAlreadyInstalled = $00000200;
COMAdminFileFlagBadTLB = $00000400;
COMAdminFileFlagGetClassObjFailed = $00000800;
COMAdminFileFlagClassNotAvailable = $00001000;
COMAdminFileFlagRegistrar = $00002000;
COMAdminFileFlagNoRegistrar = $00004000;
COMAdminFileFlagDLLRegsvrFailed = $00008000;
COMAdminFileFlagRegTLBFailed = $00010000;
COMAdminFileFlagRegistrarFailed = $00020000;
COMAdminFileFlagError = $00040000;
type
COMAdminComponentFlags = TOleEnum;
const
COMAdminCompFlagTypeInfoFound = $00000001;
COMAdminCompFlagCOMPlusPropertiesFound = $00000002;
COMAdminCompFlagProxyFound = $00000004;
COMAdminCompFlagInterfacesFound = $00000008;
COMAdminCompFlagAlreadyInstalled = $00000010;
COMAdminCompFlagNotInApplication = $00000020;
type
COMAdminErrorCodes = TOleEnum;
const
COMAdminErrObjectErrors = $80110401;
COMAdminErrObjectInvalid = $80110402;
COMAdminErrKeyMissing = $80110403;
COMAdminErrAlreadyInstalled = $80110404;
COMAdminErrAppFileWriteFail = $80110407;
COMAdminErrAppFileReadFail = $80110408;
COMAdminErrAppFileVersion = $80110409;
COMAdminErrBadPath = $8011040A;
COMAdminErrApplicationExists = $8011040B;
COMAdminErrRoleExists = $8011040C;
COMAdminErrCantCopyFile = $8011040D;
COMAdminErrNoUser = $8011040F;
COMAdminErrInvalidUserids = $80110410;
COMAdminErrNoRegistryCLSID = $80110411;
COMAdminErrBadRegistryProgID = $80110412;
COMAdminErrAuthenticationLevel = $80110413;
COMAdminErrUserPasswdNotValid = $80110414;
COMAdminErrCLSIDOrIIDMismatch = $80110418;
COMAdminErrRemoteInterface = $80110419;
COMAdminErrDllRegisterServer = $8011041A;
COMAdminErrNoServerShare = $8011041B;
COMAdminErrDllLoadFailed = $8011041D;
COMAdminErrBadRegistryLibID = $8011041E;
COMAdminErrAppDirNotFound = $8011041F;
COMAdminErrRegistrarFailed = $80110423;
COMAdminErrCompFileDoesNotExist = $80110424;
COMAdminErrCompFileLoadDLLFail = $80110425;
COMAdminErrCompFileGetClassObj = $80110426;
COMAdminErrCompFileClassNotAvail = $80110427;
COMAdminErrCompFileBadTLB = $80110428;
COMAdminErrCompFileNotInstallable = $80110429;
COMAdminErrNotChangeable = $8011042A;
COMAdminErrNotDeletable = $8011042B;
COMAdminErrSession = $8011042C;
COMAdminErrCompMoveLocked = $8011042D;
COMAdminErrCompMoveBadDest = $8011042E;
COMAdminErrRegisterTLB = $80110430;
COMAdminErrSystemApp = $80110433;
COMAdminErrCompFileNoRegistrar = $80110434;
COMAdminErrCoReqCompInstalled = $80110435;
COMAdminErrServiceNotInstalled = $80110436;
COMAdminErrPropertySaveFailed = $80110437;
COMAdminErrObjectExists = $80110438;
COMAdminErrRegFileCorrupt = $8011043B;
COMAdminErrPropertyOverflow = $8011043C;
COMAdminErrNotInRegistry = $8011043E;
COMAdminErrObjectNotPoolable = $8011043F;
COMAdminErrApplidMatchesClsid = $80110446;
COMAdminErrRoleDoesNotExist = $80110447;
COMAdminErrStartAppNeedsComponents = $80110448;
COMAdminErrRequiresDifferentPlatform = $80110449;
COMAdminErrQueuingServiceNotAvailable = $80110602;
COMAdminErrObjectParentMissing = $80110808;
COMAdminErrObjectDoesNotExist = $80110809;
COMAdminErrCanNotExportAppProxy = $8011044A;
COMAdminErrCanNotStartApp = $8011044B;
COMAdminErrCanNotExportSystemApp = $8011044C;
COMAdminErrCanNotSubscribeToComponent = $8011044D;
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
ICOMAdminCatalog = interface;
ICOMAdminCatalogDisp = dispinterface;
ICatalogObject = interface;
ICatalogObjectDisp = dispinterface;
ICatalogCollection = interface;
ICatalogCollectionDisp = dispinterface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// *********************************************************************//
COMAdminCatalog = ICOMAdminCatalog;
COMAdminCatalogObject = ICatalogObject;
COMAdminCatalogCollection = ICatalogCollection;
// *********************************************************************//
// Declaration of structures, unions and aliases.
// *********************************************************************//
PPSafeArray1 = ^PSafeArray; {*}
ICOMAdminCatalog = interface(IDispatch)
['{DD662187-DFC2-11D1-A2CF-00805FC79235}']
function GetCollection(const bstrCollName: WideString): IDispatch; safecall;
function Connect(const bstrConnectString: WideString): IDispatch; safecall;
function Get_MajorVersion: Integer; safecall;
function Get_MinorVersion: Integer; safecall;
function GetCollectionByQuery(const bstrCollName: WideString; var aQuery: PSafeArray): IDispatch; safecall;
procedure ImportComponent(const bstrApplIdOrName: WideString;
const bstrCLSIDOrProgId: WideString); safecall;
procedure InstallComponent(const bstrApplIdOrName: WideString; const bstrDLL: WideString;
const bstrTLB: WideString; const bstrPSDLL: WideString); safecall;
procedure ShutdownApplication(const bstrApplIdOrName: WideString); safecall;
procedure ExportApplication(const bstrApplIdOrName: WideString;
const bstrApplicationFile: WideString; lOptions: Integer); safecall;
procedure InstallApplication(const bstrApplicationFile: WideString;
const bstrDestinationDirectory: WideString; lOptions: Integer;
const bstrUserId: WideString; const bstrPassword: WideString;
const bstrRSN: WideString); safecall;
procedure StopRouter; safecall;
procedure RefreshRouter; safecall;
procedure StartRouter; safecall;
procedure Reserved1; safecall;
procedure Reserved2; safecall;
procedure InstallMultipleComponents(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray; var varCLSIDS: PSafeArray); safecall;
procedure GetMultipleComponentsInfo(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray; out varCLSIDS: PSafeArray;
out varClassNames: PSafeArray;
out varFileFlags: PSafeArray;
out varComponentFlags: PSafeArray); safecall;
procedure RefreshComponents; safecall;
procedure BackupREGDB(const bstrBackupFilePath: WideString); safecall;
procedure RestoreREGDB(const bstrBackupFilePath: WideString); safecall;
procedure QueryApplicationFile(const bstrApplicationFile: WideString;
out bstrApplicationName: WideString;
out bstrApplicationDescription: WideString;
out bHasUsers: WordBool; out bIsProxy: WordBool;
out varFileNames: PSafeArray); safecall;
procedure StartApplication(const bstrApplIdOrName: WideString); safecall;
function ServiceCheck(lService: Integer): Integer; safecall;
procedure InstallMultipleEventClasses(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray; var varCLSIDS: PSafeArray); safecall;
procedure InstallEventClass(const bstrApplIdOrName: WideString; const bstrDLL: WideString;
const bstrTLB: WideString; const bstrPSDLL: WideString); safecall;
procedure GetEventClassesForIID(const bstrIID: WideString; out varCLSIDS: PSafeArray;
out varProgIDs: PSafeArray; out varDescriptions: PSafeArray); safecall;
property MajorVersion: Integer read Get_MajorVersion;
property MinorVersion: Integer read Get_MinorVersion;
end;
ICOMAdminCatalogDisp = dispinterface
['{DD662187-DFC2-11D1-A2CF-00805FC79235}']
function GetCollection(const bstrCollName: WideString): IDispatch; dispid 1;
function Connect(const bstrConnectString: WideString): IDispatch; dispid 2;
property MajorVersion: Integer readonly dispid 3;
property MinorVersion: Integer readonly dispid 4;
function GetCollectionByQuery(const bstrCollName: WideString;
var aQuery: {??PSafeArray} OleVariant): IDispatch; dispid 5;
procedure ImportComponent(const bstrApplIdOrName: WideString;
const bstrCLSIDOrProgId: WideString); dispid 6;
procedure InstallComponent(const bstrApplIdOrName: WideString; const bstrDLL: WideString;
const bstrTLB: WideString; const bstrPSDLL: WideString); dispid 7;
procedure ShutdownApplication(const bstrApplIdOrName: WideString); dispid 8;
procedure ExportApplication(const bstrApplIdOrName: WideString;
const bstrApplicationFile: WideString; lOptions: Integer); dispid 9;
procedure InstallApplication(const bstrApplicationFile: WideString;
const bstrDestinationDirectory: WideString; lOptions: Integer;
const bstrUserId: WideString; const bstrPassword: WideString;
const bstrRSN: WideString); dispid 10;
procedure StopRouter; dispid 11;
procedure RefreshRouter; dispid 12;
procedure StartRouter; dispid 13;
procedure Reserved1; dispid 14;
procedure Reserved2; dispid 15;
procedure InstallMultipleComponents(const bstrApplIdOrName: WideString;
var varFileNames: {??PSafeArray} OleVariant;
var varCLSIDS: {??PSafeArray} OleVariant); dispid 16;
procedure GetMultipleComponentsInfo(const bstrApplIdOrName: WideString;
var varFileNames: {??PSafeArray} OleVariant;
out varCLSIDS: {??PSafeArray} OleVariant;
out varClassNames: {??PSafeArray} OleVariant;
out varFileFlags: {??PSafeArray} OleVariant;
out varComponentFlags: {??PSafeArray} OleVariant); dispid 17;
procedure RefreshComponents; dispid 18;
procedure BackupREGDB(const bstrBackupFilePath: WideString); dispid 19;
procedure RestoreREGDB(const bstrBackupFilePath: WideString); dispid 20;
procedure QueryApplicationFile(const bstrApplicationFile: WideString;
out bstrApplicationName: WideString;
out bstrApplicationDescription: WideString;
out bHasUsers: WordBool; out bIsProxy: WordBool;
out varFileNames: {??PSafeArray} OleVariant); dispid 21;
procedure StartApplication(const bstrApplIdOrName: WideString); dispid 22;
function ServiceCheck(lService: Integer): Integer; dispid 23;
procedure InstallMultipleEventClasses(const bstrApplIdOrName: WideString;
var varFileNames: {??PSafeArray} OleVariant;
var varCLSIDS: {??PSafeArray} OleVariant); dispid 24;
procedure InstallEventClass(const bstrApplIdOrName: WideString; const bstrDLL: WideString;
const bstrTLB: WideString; const bstrPSDLL: WideString); dispid 25;
procedure GetEventClassesForIID(const bstrIID: WideString;
out varCLSIDS: {??PSafeArray} OleVariant;
out varProgIDs: {??PSafeArray} OleVariant;
out varDescriptions: {??PSafeArray} OleVariant); dispid 26;
end;
ICatalogObject = interface(IDispatch)
['{6EB22871-8A19-11D0-81B6-00A0C9231C29}']
function Get_Value(const bstrPropName: WideString): OleVariant; safecall;
procedure Set_Value(const bstrPropName: WideString; retval: OleVariant); safecall;
function Get_Key: OleVariant; safecall;
function Get_Name: OleVariant; safecall;
function IsPropertyReadOnly(const bstrPropName: WideString): WordBool; safecall;
function Get_Valid: WordBool; safecall;
function IsPropertyWriteOnly(const bstrPropName: WideString): WordBool; safecall;
property Value[const bstrPropName: WideString]: OleVariant read Get_Value write Set_Value;
property Key: OleVariant read Get_Key;
property Name: OleVariant read Get_Name;
property Valid: WordBool read Get_Valid;
end;
ICatalogObjectDisp = dispinterface
['{6EB22871-8A19-11D0-81B6-00A0C9231C29}']
property Value[const bstrPropName: WideString]: OleVariant dispid 1;
property Key: OleVariant readonly dispid 2;
property Name: OleVariant readonly dispid 3;
function IsPropertyReadOnly(const bstrPropName: WideString): WordBool; dispid 4;
property Valid: WordBool readonly dispid 5;
function IsPropertyWriteOnly(const bstrPropName: WideString): WordBool; dispid 6;
end;
ICatalogCollection = interface(IDispatch)
['{6EB22872-8A19-11D0-81B6-00A0C9231C29}']
function Get__NewEnum: IUnknown; safecall;
function Get_Item(lIndex: Integer): IDispatch; safecall;
function Get_Count: Integer; safecall;
procedure Remove(lIndex: Integer); safecall;
function Add: IDispatch; safecall;
procedure Populate; safecall;
function SaveChanges: Integer; safecall;
function GetCollection(const bstrCollName: WideString; varObjectKey: OleVariant): IDispatch; safecall;
function Get_Name: OleVariant; safecall;
function Get_AddEnabled: WordBool; safecall;
function Get_RemoveEnabled: WordBool; safecall;
function GetUtilInterface: IDispatch; safecall;
function Get_DataStoreMajorVersion: Integer; safecall;
function Get_DataStoreMinorVersion: Integer; safecall;
procedure PopulateByKey(aKeys: PSafeArray); safecall;
procedure PopulateByQuery(const bstrQueryString: WideString; lQueryType: Integer); safecall;
property _NewEnum: IUnknown read Get__NewEnum;
property Item[lIndex: Integer]: IDispatch read Get_Item;
property Count: Integer read Get_Count;
property Name: OleVariant read Get_Name;
property AddEnabled: WordBool read Get_AddEnabled;
property RemoveEnabled: WordBool read Get_RemoveEnabled;
property DataStoreMajorVersion: Integer read Get_DataStoreMajorVersion;
property DataStoreMinorVersion: Integer read Get_DataStoreMinorVersion;
end;
ICatalogCollectionDisp = dispinterface
['{6EB22872-8A19-11D0-81B6-00A0C9231C29}']
property _NewEnum: IUnknown readonly dispid -4;
property Item[lIndex: Integer]: IDispatch readonly dispid 1;
property Count: Integer readonly dispid 1610743810;
procedure Remove(lIndex: Integer); dispid 1610743811;
function Add: IDispatch; dispid 1610743812;
procedure Populate; dispid 2;
function SaveChanges: Integer; dispid 3;
function GetCollection(const bstrCollName: WideString; varObjectKey: OleVariant): IDispatch; dispid 4;
property Name: OleVariant readonly dispid 6;
property AddEnabled: WordBool readonly dispid 7;
property RemoveEnabled: WordBool readonly dispid 8;
function GetUtilInterface: IDispatch; dispid 9;
property DataStoreMajorVersion: Integer readonly dispid 10;
property DataStoreMinorVersion: Integer readonly dispid 11;
procedure PopulateByKey(aKeys: {??PSafeArray} OleVariant); dispid 12;
procedure PopulateByQuery(const bstrQueryString: WideString; lQueryType: Integer); dispid 13;
end;
implementation
end.
|
{$A8} {$R-}
{*************************************************************}
{ }
{ Embarcadero Delphi Visual Component Library }
{ InterBase Express core components }
{ }
{ Copyright (c) 1998-2017 Embarcadero Technologies, Inc.}
{ All rights reserved }
{ }
{ Additional code created by Jeff Overcash and used }
{ with permission. }
{*************************************************************}
unit IBX.IBBatchUpdate;
interface
uses System.Classes, IBX.IBDatabase, IBX.IBSQL, IBX.IBExternals,
System.Generics.Collections, IBX.IBHeader;
type
TIBBatchErrors = array of ISC_STATUS;
TIBBatchError = class
public
Index : Integer;
ErrorCode : ISC_Status;
end;
TIBBatchErrorList = TList<TIBBatchError>;
TIBBatchErrorsEnumerator = class
private
FIndex : Integer;
FErrors : TIBBatchErrorList;
public
constructor Create(Errors: TIBBatchErrorList);
function GetCurrent: TIBBatchError; inline;
function MoveNext: Boolean;
property Current: TIBBatchError read GetCurrent;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TIBBatchUpdate = class(TComponent)
private
FBatchSize : Integer;
FBase : TIBBase;
FBatchSQL : TIBSQL;
FIBBatchErrorList : TIBBatchErrorList;
FPrepared : Boolean;
function GetSQLParams: TIBXSQLDA;
procedure SetBatchSize(const Value: Integer);
function GetHasErrors: Boolean;
procedure SetDatabase(const Value: TIBDatabase);
procedure SetTransaction(const Value: TIBTransaction);
function GetSQL: TStrings;
procedure SetSQL(const Value: TStrings);
function GetDatabase: TIBDatabase;
function GetTransaction: TIBTransaction;
function GetDBHandle: PISC_DB_HANDLE;
function GetTRHandle: PISC_TR_HANDLE;
protected
FSQL: TStrings; { SQL Query (by user) }
FProcessedSQL: TStrings; { SQL Query (pre-processed for param labels) }
FHandle: TISC_STMT_HANDLE; { Once prepared, this accesses the SQL Query }
FSQLParams : TIBXSQLDA; { Any parameters to the query }
FSQLType: TIBSQLTypes; { Select, update, delete, insert, create, alter, etc...}
procedure PreprocessSQL;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function Execute : Boolean;
procedure Prepare;
procedure Unprepare;
procedure First;
procedure Next;
procedure Prior;
procedure Insert;
procedure Post;
procedure Clear;
function Call(ErrCode: ISC_STATUS; RaiseError: Boolean): ISC_STATUS;
function GetEnumerator: TIBBatchErrorsEnumerator;
property Params: TIBXSQLDA read GetSQLParams;
property HasErrors : Boolean read GetHasErrors;
property Prepared: Boolean read FPrepared;
property DBHandle: PISC_DB_HANDLE read GetDBHandle;
property TRHandle: PISC_TR_HANDLE read GetTRHandle;
published
property SQL : TStrings read GetSQL write SetSQL;
property Database : TIBDatabase read GetDatabase write SetDatabase;
property Transaction : TIBTransaction read GetTransaction write SetTransaction;
[ default(1000)]
property BatchSize : Integer read FBatchSize write SetBatchSize;
end;
implementation
uses IBX.IBIntf, IBX.IB, System.SysUtils, IBX.IBSQLMonitor, IBX.IBXConst,
System.Character, IBX.IBErrorCodes;
{ TIBBatchUpdate }
function TIBBatchUpdate.Call(ErrCode: ISC_STATUS;
RaiseError: Boolean): ISC_STATUS;
begin
result := 0;
if Transaction <> nil then
result := Transaction.Call(ErrCode, RaiseError)
else
if RaiseError and (ErrCode > 0) then
IBDataBaseError(Database.GDSLibrary);
end;
procedure TIBBatchUpdate.Clear;
begin
end;
constructor TIBBatchUpdate.Create(AOwner: TComponent);
begin
inherited;
FBatchSQL := TIBSQL.Create(Self);
FBatchSize := 1000;
FBase := TIBBase.Create(self);
FPrepared := false;
FIBBatchErrorList := TIBBatchErrorList.Create;
end;
destructor TIBBatchUpdate.Destroy;
begin
FBatchSQL.Free;
FIBBatchErrorList.Free;
FBase.Free;
inherited;
end;
function TIBBatchUpdate.Execute: Boolean;
begin
Result := false;
end;
procedure TIBBatchUpdate.First;
begin
end;
function TIBBatchUpdate.GetDatabase: TIBDatabase;
begin
Result := FBase.Database;
end;
function TIBBatchUpdate.GetDBHandle: PISC_DB_HANDLE;
begin
Result := FBase.DBHandle;
end;
function TIBBatchUpdate.GetEnumerator: TIBBatchErrorsEnumerator;
begin
Result := TIBBatchErrorsEnumerator.Create(FIBBatchErrorList);
end;
function TIBBatchUpdate.GetHasErrors: Boolean;
begin
Result := FIBBatchErrorList.Count > 0;
end;
function TIBBatchUpdate.GetSQL: TStrings;
begin
Result := FBatchSQL.SQL;
end;
function TIBBatchUpdate.GetSQLParams: TIBXSQLDA;
begin
Result := FBatchSQL.Params;
end;
function TIBBatchUpdate.GetTransaction: TIBTransaction;
begin
Result := FBase.Transaction;
end;
function TIBBatchUpdate.GetTRHandle: PISC_TR_HANDLE;
begin
Result := FBase.TRHandle;
end;
procedure TIBBatchUpdate.Insert;
begin
end;
procedure TIBBatchUpdate.Next;
begin
end;
procedure TIBBatchUpdate.Post;
begin
end;
procedure TIBBatchUpdate.Prepare;
var
stmt_len: Integer;
res_buffer: array[0..7] of Byte;
type_item: Byte;
bt : TBytes;
FGDSLibrary : IGDSLibrary;
begin
FBase.CheckDatabase;
FBase.CheckTransaction;
if FPrepared then
exit;
FGDSLibrary := Database.GDSLibrary;
if (FSQL.Text = '') then
IBError(ibxeEmptyQuery, [nil]);
PreprocessSQL;
if (FProcessedSQL.Text = '') then
IBError(ibxeEmptyQuery, [nil]);
try
Call(FGDSLibrary.isc_dsql_alloc_statement2(StatusVector, DBHandle,
@FHandle), True);
bt := Database.Encoding.GetBytes(FProcessedSQL.Text + #0);
try
Call(FGDSLibrary.isc_dsql_prepare(StatusVector, TRHandle, @FHandle, 0,
PByte(bt), Database.SQLDialect, nil), True);
except
SetLength(bt, 0);
raise;
end;
{ After preparing the statement, query the stmt type and possibly
create a FSQLRecord "holder" }
{ Get the type of the statement }
type_item := Byte(isc_info_sql_stmt_type);
Call(FGDSLibrary.isc_dsql_sql_info(StatusVector, @FHandle, 1, @type_item,
SizeOf(res_buffer), @res_buffer), True);
if (res_buffer[0] <> Byte(isc_info_sql_stmt_type)) then
IBError(ibxeUnknownError, [nil]);
stmt_len := FGDSLibrary.isc_vax_integer(@res_buffer[1], 2);
FSQLType := TIBSQLTypes(FGDSLibrary.isc_vax_integer(@res_buffer[3], stmt_len));
case FSQLType of
SQLGetSegment,
SQLPutSegment,
SQLStartTransaction:
begin
Unprepare;
IBError(ibxeNotPermitted, [nil]);
end;
SQLCommit,
SQLRollback,
SQLDDL, SQLSetGenerator,
SQLInsert, SQLUpdate, SQLDelete, SQLSelect, SQLSelectForUpdate,
SQLExecProcedure:
begin
{ We already know how many inputs there are, so... }
if (FSQLParams.AsXSQLDA <> nil) and
(Call(FGDSLibrary.isc_dsql_describe_bind(StatusVector, @FHandle, Database.SQLDialect,
FSQLParams.AsXSQLDA), False) > 0) then
IBDataBaseError(FGDSLibrary);
if (FSQLParams.AsXSQLDA <> nil) and
(FSQLParams.Count <> FSQLParams.AsXSQLDA^.sqld) then
begin
FSQLParams.Count := FSQLParams.AsXSQLDA^.sqld;
Call(FGDSLibrary.isc_dsql_describe_bind(StatusVector, @FHandle, Database.SQLDialect,
FSQLParams.AsXSQLDA), False);
end;
// FSQLParams.Initialize;
end;
end;
FPrepared := True;
except
on E: Exception do
begin
if (FHandle <> nil) then
Unprepare;
raise;
end;
end;
end;
procedure TIBBatchUpdate.PreprocessSQL;
var
cCurChar, cNextChar, cQuoteChar: Char;
sSQL, sProcessedSQL, sParamName: String;
i, iLenSQL, iSQLPos: Integer;
iCurState, iCurParamState: Integer;
slNames: TStrings;
const
DefaultState = 0;
CommentState = 1;
QuoteState = 2;
ParamState = 3;
ParamDefaultState = 0;
ParamQuoteState = 1;
procedure AddToProcessedSQL(cChar: Char);
begin
sProcessedSQL[iSQLPos] := cChar;
Inc(iSQLPos);
end;
begin
slNames := TStringList.Create;
try
{ Do some initializations of variables }
cQuoteChar := '''';
sSQL := FSQL.Text;
iLenSQL := Length(sSQL);
SetString(sProcessedSQL, nil, iLenSQL + 1);
i := low(sSQL);
iSQLPos := i;
iCurState := DefaultState;
iCurParamState := ParamDefaultState;
{ Now, traverse through the SQL string, character by character,
picking out the parameters and formatting correctly for InterBase }
while (i <= iLenSQL) do begin
{ Get the current token and a look-ahead }
cCurChar := sSQL[i];
if i = iLenSQL then
cNextChar := #0
else
cNextChar := sSQL[i + 1];
{ Now act based on the current state }
case iCurState of
DefaultState: begin
case cCurChar of
'''', '"': begin
cQuoteChar := cCurChar;
iCurState := QuoteState;
end;
'?', ':': begin
iCurState := ParamState;
AddToProcessedSQL('?');
end;
'/': if (cNextChar = '*') then begin
AddToProcessedSQL(cCurChar);
Inc(i);
iCurState := CommentState;
end;
end;
end;
CommentState: begin
if (cNextChar = #0) then
IBError(ibxeSQLParseError, [SEOFInComment])
else if (cCurChar = '*') then begin
if (cNextChar = '/') then
iCurState := DefaultState;
end;
end;
QuoteState: begin
if cNextChar = #0 then
IBError(ibxeSQLParseError, [SEOFInString])
else if (cCurChar = cQuoteChar) then begin
if (cNextChar = cQuoteChar) then begin
AddToProcessedSQL(cCurChar);
Inc(i);
end else
iCurState := DefaultState;
end;
end;
ParamState:
begin
{ collect the name of the parameter }
if iCurParamState = ParamDefaultState then
begin
if cCurChar = '"' then
iCurParamState := ParamQuoteState
else
if cCurChar.IsInArray(['_', '$']) or
cCurChar.IsLetterOrDigit then {do not localize}
sParamName := sParamName + cCurChar
else
IBError(ibxeSQLParseError, [SParamNameExpected]);
end
else begin
{ determine if Quoted parameter name is finished }
if cCurChar = '"' then
begin
Inc(i);
slNames.Add(sParamName);
SParamName := '';
iCurParamState := ParamDefaultState;
iCurState := DefaultState;
end
else
sParamName := sParamName + cCurChar
end;
{ determine if the unquoted parameter name is finished }
if (iCurParamState <> ParamQuoteState) and
(iCurState <> DefaultState) then
begin
if not (cNextChar.IsInArray(['_', '$']) or
cNextChar.IsLetterOrDigit) then {do not localize}
begin
Inc(i);
iCurState := DefaultState;
slNames.Add(sParamName);
sParamName := '';
end;
end;
end;
end;
if iCurState <> ParamState then
AddToProcessedSQL(sSQL[i]);
Inc(i);
end;
AddToProcessedSQL(#0);
FSQLParams.Count := slNames.Count;
for i := 0 to slNames.Count - 1 do
FSQLParams.AddName(slNames[i], i);
FProcessedSQL.Text := sProcessedSQL;
finally
slNames.Free;
end;
end;
procedure TIBBatchUpdate.Prior;
begin
end;
procedure TIBBatchUpdate.SetBatchSize(const Value: Integer);
begin
FBatchSize := Value;
end;
procedure TIBBatchUpdate.SetDatabase(const Value: TIBDatabase);
begin
if (FBase <> nil) and (FBase.Database <> Value) then
FBase.Database := Value;
end;
procedure TIBBatchUpdate.SetSQL(const Value: TStrings);
begin
if FBatchSQL.SQL.Text <> Value.Text then
begin
FBatchSQL.SQL.Assign(Value);
end;
end;
procedure TIBBatchUpdate.SetTransaction(const Value: TIBTransaction);
begin
if Assigned(FBase) and (FBase.Transaction <> Value) then
begin
if Prepared then
Unprepare;
FBase.Transaction := Value;
end;
end;
procedure TIBBatchUpdate.Unprepare;
var
isc_res: ISC_STATUS;
begin
try
{ The following two lines merely set the SQLDA count
variable FCount to 0, but do not deallocate
That way the allocations can be reused for
a new query sring in the same SQL instance }
// FSQLRecord.Count := 0;
// FSQLParams.Count := 0;
if (FHandle <> nil) and Database.Connected then
begin
isc_res := Call(Database.GDSLibrary.isc_dsql_free_statement(StatusVector, @FHandle, DSQL_drop), False);
if (StatusVector^ = 1) and (isc_res > 0) and (isc_res <> isc_bad_stmt_handle)
and (isc_res <> isc_lost_db_connection) then
IBDataBaseError(Database.GDSLibrary);
end;
finally
FPrepared := False;
FHandle := nil;
end;
end;
{ TIBBatchErrorsEnumerator }
constructor TIBBatchErrorsEnumerator.Create(Errors: TIBBatchErrorList);
begin
inherited Create;
FIndex := -1;
FErrors := Errors;
end;
function TIBBatchErrorsEnumerator.GetCurrent: TIBBatchError;
begin
Result := FErrors.Items[FIndex];
end;
function TIBBatchErrorsEnumerator.MoveNext: Boolean;
begin
Result := FIndex < FErrors.Count - 1;
if Result then
Inc(FIndex);
end;
end.
|
unit uVersion;
interface
uses
Classes, Types, Forms, Windows, SysUtils, IPInfo;
const
InfoNum = 10;
InfoStr: array[1..InfoNum] of string = ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFileName', 'ProductName', 'ProductVersion', 'Comments');
PROCESSOR_INTEL_386 = 386;
PROCESSOR_INTEL_486 = 486;
PROCESSOR_INTEL_PENTIUM = 586;
PROCESSOR_MIPS_R4000 = 4000;
PROCESSOR_ALPHA_21064 = 21064;
PROCESSOR_ARCHITECTURE_INTEL = 0;
PROCESSOR_ARCHITECTURE_MIPS = 1;
PROCESSOR_ARCHITECTURE_ALPHA = 2;
PROCESSOR_ARCHITECTURE_PPC = 3;
PROCESSOR_ARCHITECTURE_UNKNOWN = $FFFF;
MIB_IF_TYPE_OTHER = 1;
MIB_IF_TYPE_ETHERNET = 6;
MIB_IF_TYPE_TOKENRING = 9;
MIB_IF_TYPE_FDDI = 15;
MIB_IF_TYPE_PPP = 23;
MIB_IF_TYPE_LOOPBACK = 24;
MIB_IF_TYPE_SLIP = 28;
type
// Major Version
// MinorVersion
// Release
// Build
TVerInfo = array[1..4] of word;
TVersionInfoItem = record
Name : string;
Str : string;
end;
TVersionInfoArr = array[1..InfoNum] of TVersionInfoItem;
TProcessorInfo = class (TObject)
private
procedure GetProcessorInfo;
public
MySysInfo :TSystemInfo; // holds the system information
model : word;
stepping : word;
ProcessorLevel : word;
ProcessorType :string;
Architecture :string;
NumberOfProcessors :Integer;
HasCPUID : boolean;
CPUID : string;
Vendor : string;
function AsString : string;
constructor create;
end;
TWindowsInfo = class (TObject)
private
procedure GetWindowsVersion;
public
Version : TVerInfo;
VersionStr : string;
windows : string;
CSDVersion : string;
IsServer : boolean;
PlatformId : integer;
function AsString : string;
constructor create;
end;
TNetworkInfo = class (TObject)
private
procedure GetNetworkInfo;
public
Adaptadores : integer;
NetAdapter1Name : string;
NetAdapter1Description : string;
NetAdapter1MACNumbers : string;
NetAdapter1MAC : string;
NetAdaptersMAC : TStringList;
IPAssigned : boolean;
function AsString : string;
constructor create;
destructor destroy; override;
end;
TVersionInfo = class (TObject)
private
FVersinIntoExists : boolean;
FVersionInfoArr : TVersionInfoArr;
public
WindowsInfo : TWindowsInfo;
ProcessorInfo : TProcessorInfo;
NetWorkInfo : TNetWorkInfo;
FileVersion : TVerInfo;
ProductVersion : TVerInfo;
ExeName, ExePath : string;
procedure add(Name,str:string);
function AsString : string;
function StringByName (s:string) : string;
function ProgramDisplayShortVersion : string;
function ProgramDisplayLongVersion : string;
procedure LoadVersionInfo;
function LoadFilesInDirVersionInfo(dir,namemask:string):TStringList;
function VersionOfFile(fn:string):String;
constructor create;
destructor destroy; override;
end;
function StrToVerInfo(s: string):TVerInfo;
function VerInfoToStrLong(vi: TVerInfo):string;
function VerInfoToStrShort(vi: TVerInfo):string;
function CompareLongVersion (s1, s2:string ) : integer;
function NetworkHasIPAssigned : boolean;
function WaitForNetworkIPAssignment(aSecs:integer) : boolean;
var
VersionInfo : TVersionInfo;
implementation
const
ID_BIT = $200000; // EFLAGS ID bit
type
TCPUID = array[1..4] of Longint;
TVendor = array [0..11] of char;
function IsCPUID_Available : Boolean; register;
asm
PUSHFD {direct access to flags no possible, only via stack}
POP EAX {flags to EAX}
MOV EDX,EAX {save current flags}
XOR EAX,ID_BIT {not ID bit}
PUSH EAX {onto stack}
POPFD {from stack to flags, with not ID bit}
PUSHFD {back to stack}
POP EAX {get back to EAX}
XOR EAX,EDX {check if ID bit affected}
JZ @exit {no, CPUID not availavle}
MOV AL,True {Result=True}
@exit:
end;
function GetCPUID : TCPUID; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Resukt}
MOV EAX,1
DW $A20F {CPUID Command}
STOSD {CPUID[1]}
MOV EAX,EBX
STOSD {CPUID[2]}
MOV EAX,ECX
STOSD {CPUID[3]}
MOV EAX,EDX
STOSD {CPUID[4]}
POP EDI {Restore registers}
POP EBX
end;
function GetCPUVendor : TVendor; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;
constructor TVersionInfo.create;
var
i : integer;
begin
inherited;
for i:=1 to InfoNum do
FVersionInfoArr[i].Name := InfoStr[i];
WindowsInfo := TWindowsInfo.create;
ProcessorInfo := TProcessorInfo.create;
NetWorkInfo := TNetWorkInfo.create;
end;
destructor TVersionInfo.destroy;
begin
inherited;
ProcessorInfo.Free;
WindowsInfo.Free;
NetWorkInfo.Free;
end;
procedure TVersionInfo.LoadVersionInfo;
var
S: string;
n, Len, i: DWORD;
Buf: PChar;
Value: PChar;
begin
S := Application.ExeName;
ExeName := ExtractFileName(s);
ExePath := ExtractFilePath(s);
n := GetFileVersionInfoSize(PChar(S), n);
FVersinIntoExists := n > 0;
if FVersinIntoExists then begin
Buf := AllocMem(n);
GetFileVersionInfo(PChar(S), 0, n, Buf);
for i := 1 to InfoNum do
if VerQueryValue(Buf, PChar('\StringFileInfo\041604E4\' + InfoStr[i]), Pointer(Value), Len) then
if trim(value)<>'' then
VersionInfo.Add(InfoStr[i],Value);
FreeMem(Buf, n);
end;
end;
procedure TVersionInfo.add(Name, str:string);
var
i : integer;
begin
for i:=1 to InfoNum do
if comparetext(FVersionInfoArr[i].Name,Name)=0 then begin
FVersionInfoArr[i].Str := Str;
if name = 'FileVersion' then
FileVersion := StrToVerInfo(Str);
if name = 'ProductVersion' then
ProductVersion := StrToVerInfo(Str);
break;
end;
end;
function TVersionInfo.StringByName (s:string) : string;
var
i : integer;
begin
result := '';
for i:=1 to InfoNum do
if comparetext(FVersionInfoArr[i].Name,s)=0 then begin
result := FVersionInfoArr[i].Str;
break;
end;
end;
function TVersionInfo.AsString : string;
var
i : integer;
begin
if FVersinIntoExists then begin
result := '';
for i:=1 to InfoNum do
if comparetext( FVersionInfoArr[i].Str, '' ) <> 0 then
result := result + FVersionInfoArr[i].Name + ' = ' + FVersionInfoArr[i].Str + #13#10 ;
end else
result := 'Não há informações de versão disponíveis.';
end;
function StrToVerInfo(s: string):TVerInfo;
var
i : integer;
v : integer;
dws : string;
begin
if trim(s)='' then begin
result[1] := 0;
result[2] := 0;
result[3] := 0;
result[4] := 0;
exit;
end;
v := 0;
for i:=1 to length(s) do begin
if s[i]='.' then begin
inc(v);
result[v] := strtoint(dws);
dws := '';
end;
if s[i] in ['0'..'9'] then
dws := dws+s[i];
end;
inc(v);
result[v] := strtoint(dws);
end;
function VerInfoToStrLong(vi: TVerInfo):string;
begin
// min = 0.0.0.0 = char(7)
// max = 65535.65535.65535.65535 = char(23)
result := IntTostr(vi[1]) + '.' +
IntTostr(vi[2]) + '.' +
IntTostr(vi[3]) + '.' +
IntTostr(vi[4]);
end;
function VerInfoToStrShort(vi: TVerInfo):string;
begin
// min = 0.0 = char(3)
// max = 65535.65535 = char(11)
result := IntTostr(vi[1]) + '.' +
IntTostr(vi[2]);
end;
function TVersionInfo.ProgramDisplayLongVersion : string;
begin
result := VersionInfo.StringByName('FileVersion');
end;
function TVersionInfo.ProgramDisplayShortVersion : string;
var
i,c : integer;
s : string;
begin
s := VersionInfo.StringByName('FileVersion');
result := ''; c:=0;
for i := 1 to length(s) do begin
if s[i]='.' then inc(c);
if c=2 then break;
result := result + s[i];
end;
end;
function TVersionInfo.VersionOfFile(fn:string):String;
var
n, Len: DWORD;
Buf: PChar;
Value: PChar;
begin
result :='';
n := GetFileVersionInfoSize(PChar(fn), n);
if n > 0 then
begin
Buf := AllocMem(n);
GetFileVersionInfo(PChar(fn), 0, n, Buf);
if VerQueryValue(Buf, PChar('\StringFileInfo\041604E4\FileVersion'), Pointer(Value), Len) then
if trim(value)<>'' then
result := Value;
FreeMem(Buf, n);
end
end;
function TVersionInfo.LoadFilesInDirVersionInfo(dir,namemask:string):TStringList;
var
sr: TSearchRec;
begin
result := TStringList.Create;
if FindFirst(dir + '*.exe"', faAnyFile , sr) = 0 then begin
repeat
if pos(namemask, sr.Name)=1 then begin
result.add(sr.Name + '=' + VersionOfFile(dir+sr.Name));
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
function CompareLongVersion (s1, s2:string ) : integer;
var
v1, v2 :TVerInfo;
begin
v1 := StrToVerInfo(s1);
v2 := StrToVerInfo(s2);
if v1[1]>v2[1] then begin
result := 1;
exit;
end;
if v1[1]<v2[1] then begin
result := -1;
exit;
end;
if v1[2]>v2[2] then begin
result := 1;
exit;
end;
if v1[2]<v2[2] then begin
result := -1;
exit;
end;
if v1[3]>v2[3] then begin
result := 1;
exit;
end;
if v1[3]<v2[3] then begin
result := -1;
exit;
end;
if v1[4]>v2[4] then begin
result := 1;
exit;
end;
if v1[4]<v2[4] then
result := -1
else
result := 0;
end;
// -----------------------------------------------------------------------------
constructor TWindowsInfo.create;
begin
inherited;
GetWindowsVersion;
end;
function TWindowsInfo.AsString: string;
begin
result := windows + ' ';
if CSDVersion <> '' then
result := result + CSDVersion + ' ';
result := result + 'Version ' + VersionStr;
end;
procedure TWindowsInfo.GetWindowsVersion;
var
VerInfo: TOSVersionInfo;
begin
VerInfo.dwOSVersionInfoSize := SizeOf(VerInfo);
GetVersionEx(VerInfo);
case VerInfo.dwMajorVersion of
2 : case VerInfo.dwMinorVersion of
0 : windows := 'Win 95';
10 : windows := 'Win 98';
90 : windows := 'Win ME';
end;
3 : case VerInfo.dwMinorVersion of
51 : windows := 'NT 3.51';
end;
4 : case VerInfo.dwMinorVersion of
0 : windows := 'NT 4';
end;
5 : case VerInfo.dwMinorVersion of
0 : windows := 'Win 2000';
1 : windows := 'Win XP';
2 : windows := 'Win 2003';
end;
end;
IsServer := false;
case VerInfo.dwMajorVersion of
3, 4 : IsServer := true;
5 : case VerInfo.dwMinorVersion of
0, 2 : IsServer := true;
end;
end;
CSDVersion := VerInfo.szCSDVersion;
PlatformId := VerInfo.dwPlatformId;
Version[1] := VerInfo.dwMajorVersion;
Version[2] := VerInfo.dwMinorVersion;
Version[3] := 0;
Version[4] := VerInfo.dwBuildNumber;
VersionStr := inttostr(Version[1]) + '.' + inttostr(Version[2]) + '.0.' + inttostr(Version[4]);
{
Druga okresla numer wersji:
dla Win 95, 98 i ME jest to 4
dla Win NT 3.x jest to 3
dla Win NT 4 jest to 4
dla Win 2000, XP, 2003 jest to 5
Trzecia okresla numer podwersji:
dla Win 95 jest to 0
dla Win 98 jest to 10
dla Win ME jest to 90
dla Win NT 3.51 jest to 51
dla Win NT 4 jest to 0
dla Win 2000 jest to 0
dla Win XP jest to 1
dla Win 2003 jest to 2
}
end;
// -----------------------------------------------------------------------------
constructor TProcessorInfo.create;
begin
inherited;
GetProcessorInfo;
end;
function TProcessorInfo.AsString: string;
begin
result := 'Processador: ' + Vendor + #13#10;
if HasCPUID then
result := result + 'CPUID: '+ CPUID
else
result := result + 'Sem CPUID';
result := result + #13#10 + inttostr(NumberOfProcessors) + ' ' +Architecture + #13#10 +
'Type: ' + ProcessorType +
' Model: ' + inttostr(model) +
' Stepping: ' + inttostr(Stepping) +
' Level: ' + inttostr(ProcessorLevel) ;
end;
procedure TProcessorInfo.GetProcessorInfo;
var
_CPUID : TCPUID;
I : Integer;
begin
for I := Low(_CPUID) to High(_CPUID) do _CPUID[I] := -1;
HasCPUID := IsCPUID_Available;
if HasCPUID then begin
_CPUID:= GetCPUID;
CPUID := IntToHex(_CPUID[1],8) + '-' +
IntToHex(_CPUID[2],8) + '-' +
IntToHex(_CPUID[3],8) + '-' +
IntToHex(_CPUID[4],8);
Vendor := GetCPUVendor;
end else begin
CPUID := '';
end;
GetSystemInfo(MySysInfo);
case MySysInfo.wProcessorArchitecture of
PROCESSOR_ARCHITECTURE_INTEL: begin
Architecture := 'Intel Processor Architecture';
end;
PROCESSOR_ARCHITECTURE_MIPS:
Architecture := 'MIPS Processor Architecture';
PROCESSOR_ARCHITECTURE_ALPHA:
Architecture := 'DEC ALPHA Processor Architecture';
PROCESSOR_ARCHITECTURE_PPC:
Architecture := 'PPC Processor Architecture';
PROCESSOR_ARCHITECTURE_UNKNOWN:
Architecture := 'Unknown Processor Architecture';
end;
NumberOfProcessors := MySysInfo.dwNumberOfProcessors;
ProcessorType := inttostr(MySysInfo.dwProcessorType);
model := (MySysInfo.wProcessorRevision and $FF00) shr 8;
stepping := MySysInfo.wProcessorRevision and $00FF;
ProcessorLevel := MySysInfo.wProcessorLevel
end;
// -------------------------------------- T N e t W o r k I n f o
function NetworkHasIPAssigned : boolean;
var
IPnfo: TIPInfo;
i, j : integer;
qAdaptadores : integer;
begin
Result := false;
try
IPnfo := TIPInfo.Create;
try
qAdaptadores := IPnfo.MaxAdapters;
if qAdaptadores>0 then begin
for i:=0 to qAdaptadores-1 do begin
for j:=0 to IPnfo.Adapters[i].MaxIPAddresses-1 do begin
if IPnfo.Adapters[i].IPAddresses[j].Address<>'0.0.0.0' then begin
result := true;
exit;
end;
end;
end;
end;
finally
IPnfo.Free;
end;
except
on e:exception do
end;
end;
// aSecs Segundos para Timeout
// result = timeout
function WaitForNetworkIPAssignment(aSecs:integer) : boolean;
var
fim : boolean;
seg : integer;
begin
seg := 0;
result := false;
repeat
fim := NetworkHasIPAssigned;
if not fim then begin
result := seg>aSecs;
sleep(1000);
inc(seg);
end;
until fim or result;
if fim then result := false;
end;
constructor TNetworkInfo.create;
begin
inherited;
NetAdaptersMAC := TStringList.create;
GetNetworkInfo;
end;
destructor TNetworkInfo.destroy;
begin
NetAdaptersMAC.free;
inherited;
end;
procedure TNetworkInfo.GetNetworkInfo;
var
IPnfo: TIPInfo;
i, j : integer;
begin
try
IPnfo := TIPInfo.Create;
NetAdaptersMAC.Clear;
try
Adaptadores := IPnfo.MaxAdapters;
if Adaptadores>0 then begin
IPAssigned := false;
for i:=0 to Adaptadores-1 do begin
for j:=0 to IPnfo.Adapters[i].MaxIPAddresses-1 do begin
NetAdaptersMAC.Add(IPnfo.Adapters[i].HWAddress);
if IPnfo.Adapters[i].IPAddresses[j].Address <> '0.0.0.0' then begin
IPAssigned := true;
break;
end;
end;
end;
NetAdapter1Name := IPnfo.Adapters[0].Name;
NetAdapter1Description := IPnfo.Adapters[0].Description;
NetAdapter1MAC := IPnfo.Adapters[0].HWAddress;
NetAdapter1MACNumbers := copy(NetAdapter1MAC, 1,2) +
copy(NetAdapter1MAC, 4,2) +
copy(NetAdapter1MAC, 7,2) +
copy(NetAdapter1MAC, 10,2) +
copy(NetAdapter1MAC, 13,2) +
copy(NetAdapter1MAC, 16,2) ;
end;
finally
IPnfo.Free;
end;
except
end;
end;
function TNetworkInfo.AsString : string;
var
IPnfo: TIPInfo;
i, j : integer;
SType : string;
begin
try
IPnfo := TIPInfo.Create;
try
Result := 'Adaptadores : ' + inttostr(Adaptadores) + #13#10;
if Adaptadores>0 then begin
for i:=0 to Adaptadores-1 do begin
Result := Result + 'Adaptador '+inttostr(i+1) + ': ' +
IPnfo.Adapters[i].Name + #13#10;
case IPnfo.Adapters[i].AType of
MIB_IF_TYPE_OTHER : SType := 'OTHER';
MIB_IF_TYPE_ETHERNET : SType := 'ETHERNET';
MIB_IF_TYPE_TOKENRING : SType := 'TOKENRING';
MIB_IF_TYPE_FDDI : SType := 'FDDI';
MIB_IF_TYPE_PPP : SType := 'PPP';
MIB_IF_TYPE_LOOPBACK : SType := 'LOOPBACK';
MIB_IF_TYPE_SLIP : SType := 'SLIP';
end;
Result := Result + 'Tipo: '+SType + #13#10;
if trim(IPnfo.Adapters[i].Description) <> '' then
Result := Result + 'Descrição: ' + IPnfo.Adapters[i].Description + #13#10;
Result := Result + 'Endereço MAC: '+IPnfo.Adapters[i].HWAddress + #13#10;
for j:=0 to IPnfo.Adapters[i].MaxIPAddresses-1 do begin
Result := Result + ' Endereço IP ' + inttostr(j+1) + ': ' +
IPnfo.Adapters[i].IPAddresses[j].Address + #13#10;
Result := Result + ' Máscara IP ' + inttostr(j+1) + ': ' +
IPnfo.Adapters[i].IPAddresses[j].Netmask + #13#10;
end;
if IPnfo.Adapters[i].DHCPServer.Address <> '' then
Result := Result + 'DHCPServer: '+ IPnfo.Adapters[i].DHCPServer.Address + #13#10;
if IPnfo.Adapters[i].HaveWINS then begin
Result := Result + 'PrimaryWINSServer: '+ IPnfo.Adapters[i].PrimaryWINSServer.Address + #13#10;
Result := Result + 'SecondaryWINSServer: '+ IPnfo.Adapters[i].SecondaryWINSServer.Address + #13#10;
end;
end;
end;
finally
IPnfo.Free;
end;
except
Result := 'Não há adaptadores de rede presentes.';
end;
end;
initialization
VersionInfo := TVersionInfo.create;
finalization
VersionInfo.free;
end.
|
unit editscript;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons, ComCtrls, ExtCtrls, SynMemo, SynHighlighterPas, uPSComponent,
uPSComponent_Default, uPSC_StrUtils, rxspin;
type
{ TfrmScriptEditor }
TfrmScriptEditor = class(TForm)
btnHelp: TBitBtn;
btnLoadScript: TBitBtn;
btnSaveScript: TBitBtn;
btnOK: TBitBtn;
btnCancel: TBitBtn;
cbScriptCategory: TComboBox;
edScriptName: TEdit;
edDescription: TEdit;
lblScriptName: TLabel;
lblDescription: TLabel;
lblScriptCategory: TLabel;
lblSelectedScript: TLabel;
dlgOpen: TOpenDialog;
pascalSyntaxHighlighter: TSynPasSyn;
PSImport_Classes1: TPSImport_Classes;
PSImport_StrUtils1: TPSImport_StrUtils;
dlgSave: TSaveDialog;
TestScript: TPSScript;
PSImport_DateUtils1: TPSImport_DateUtils;
cbScriptType: TComboBox;
lblScriptType: TLabel;
pnlScriptAndTestArea: TPanel;
synmemCodeEditor: TSynMemo;
Splitter2: TSplitter;
pnlTestArea: TPanel;
pnlTestPanels: TPanel;
memoSource: TMemo;
memoTarget: TMemo;
pnlTestButton: TPanel;
spdbtnTest: TSpeedButton;
pnlTestAreaLabels: TPanel;
lblInputData: TLabel;
lblOutput: TLabel;
Splitter1: TSplitter;
sbar: TStatusBar;
procedure btnHelpClick(Sender: TObject);
procedure btnLoadScriptClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnSaveScriptClick(Sender: TObject);
procedure spdbtnTestClick(Sender: TObject);
procedure TestScriptAfterExecute(Sender: TPSScript);
procedure TestScriptCompile(Sender: TPSScript);
procedure TestScriptExecute(Sender: TPSScript);
function ShowSaveDialog:string;
function ShowOpenDialog:string;
function IfFileExists(Filename:string):boolean;
procedure ShowMessageDialog(Msg:String);
procedure ErrorMessageDialog(Msg:string);
function ConfirmationDialog(Msg:string):boolean;
function InputBoxDialog(Title, Msg, DefaultText :String):string;
procedure SetupSourceTestAreas;
procedure SetupTargetTestAreas;
procedure SetupScriptArea;
procedure synmemCodeEditorClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
Clippy:TStringList;
ScriptID:Integer;
end;
var
frmScriptEditor: TfrmScriptEditor;
implementation
uses main, db, options, EngLangRes;
{$R *.lfm}
{ TfrmScriptEditor }
procedure TfrmScriptEditor.TestScriptAfterExecute(Sender: TPSScript);
begin
memoTarget.Text := Clippy.Text;
Clippy.Free;
end;
procedure TfrmScriptEditor.spdbtnTestClick(Sender: TObject);
var idx:integer;
Compiled:boolean;
X:Integer;
Y:Integer;
begin
TestScript.Script.Text := synmemCodeEditor.Text;
Compiled := TestScript.Compile;
if Compiled then begin
if not TestScript.Execute
then MessageDlg(msgExecutionError, mtError, [mbOK], 0);
end else begin
for idx := 0 to TestScript.CompilerMessageCount-1
do begin
MessageDlg(msgErrorCompiling+':'+TestScript.CompilerMessages[idx].MessageToString, mtError, [mbOK], 0);
X := TestScript.CompilerMessages[0].Col;
Y := TestScript.CompilerMessages[0].Row;
synmemCodeEditor.CaretX:=X;
synmemCodeEditor.CaretY:=Y;
end;
end;
end;
procedure TfrmScriptEditor.btnOKClick(Sender: TObject);
begin
ModalResult := mrNone;
if (frmMain.Scripts.Locate('ScriptName',edScriptName.Text,[locaseinsensitive])) then begin
//got one with the same name but it maybe the one we're editing in which case we're ok!
if frmMain.Scripts.FieldByName('ScriptIndex').asInteger = ScriptID then begin
ModalResult := mrOK;
end else begin
MessageDlg(msgScriptAlreadyExists, mtError, [mbOK], 0);
end;
end else begin
ModalResult := mrOK;
end;
end;
procedure TfrmScriptEditor.SetupScriptArea;
begin
synmemCodeEditor.Lines.Assign(frmOptions.memoInitScript.Lines);
end;
procedure TfrmScriptEditor.synmemCodeEditorClick(Sender: TObject);
begin
sbar.Panels[1].Text:= '['+IntToStr( synmemCodeEditor.CaretY )+':'+ IntToStr( synmemCodeEditor.CaretX )+']';
end;
procedure TfrmScriptEditor.SetupSourceTestAreas;
begin
memoSource.Lines.Assign(frmOptions.memoInitData.Lines);
end;
procedure TfrmScriptEditor.SetupTargetTestAreas;
begin
memoTarget.Lines.Clear;
end;
procedure TfrmScriptEditor.btnSaveScriptClick(Sender: TObject);
begin
dlgSave.Filter := msgAllFiles;
if dlgSave.Execute then begin
synmemCodeEditor.Lines.SaveToFile(dlgOpen.Filename);
end;
end;
procedure TfrmScriptEditor.btnLoadScriptClick(Sender: TObject);
begin
dlgOpen.Filter := msgAllFiles;
if dlgOpen.Execute then begin
synmemCodeEditor.Lines.LoadFromFile(dlgOpen.Filename);
end;
end;
procedure TfrmScriptEditor.btnHelpClick(Sender: TObject);
begin
frmMain.btnHelpClick(Self);
end;
procedure TfrmScriptEditor.TestScriptCompile(Sender: TPSScript);
begin
Clippy := TStringList.Create;
Clippy.Text := memoSource.Text;
Sender.AddRegisteredPTRVariable('Clippy','TStringList');
Sender.AddMethod(Self, @TfrmScriptEditor.ShowSaveDialog, 'function ShowSaveDialog:string;');
Sender.AddMethod(Self, @TfrmScriptEditor.ShowOpenDialog, 'function ShowOpenDialog:string;');
Sender.AddMethod(Self, @TfrmScriptEditor.IfFileExists, 'function IfFileExists(Filename:String):boolean;');
Sender.AddMethod(Self, @TfrmScriptEditor.ShowMessageDialog, 'procedure ShowMessage(Msg:string)');
Sender.AddMethod(Self, @TfrmScriptEditor.ErrorMessageDialog, 'procedure ErrorMessage(Msg:string)');
Sender.AddMethod(Self, @TfrmScriptEditor.ConfirmationDialog, 'function IsConfirmed(Msg:string):boolean;');
Sender.AddMethod(Self, @TfrmScriptEditor.InputBoxDialog, 'function InputBox(Title, Msg, DefaultText :String):string;');
end;
procedure TfrmScriptEditor.TestScriptExecute(Sender: TPSScript);
begin
Sender.SetPointerToData('Clippy',@Clippy, Sender.FindNamedType('TStringList'));
end;
function TfrmScriptEditor.ShowSaveDialog:string;
begin
Result := '';
dlgSave.Filter := msgAllFiles;
if dlgSave.Execute then begin
Result := dlgSave.FileName;
end;
end;
function TfrmScriptEditor.ShowOpenDialog: string;
begin
Result := '';
dlgOpen.Filter := msgAllFiles;
if dlgOpen.Execute then begin
Result := dlgOpen.FileName;
end;
end;
function TfrmScriptEditor.IfFileExists(Filename:string):boolean;
begin
Result := FileExists(Filename);
end;
procedure TfrmScriptEditor.ShowMessageDialog(Msg:string);
begin
MessageDlg(Msg, mtInformation, [mbOK], 0);
end;
procedure TfrmScriptEditor.ErrorMessageDialog(Msg:string);
begin
MessageDlg(Msg, mtError, [mbOK], 0);
end;
function TfrmScriptEditor.ConfirmationDialog(Msg:string):boolean;
begin
Result := MessageDlg(Msg, mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
function TfrmScriptEditor.InputBoxDialog(Title, Msg, DefaultText :String):string;
begin
Result := InputBox(Title, Msg, DefaultText);
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ComCtrls, uClient;
type
TClientForm = class(TForm)
labelUniqueName: TLabel;
editUniqueName: TEdit;
gbClient: TGroupBox;
labelFileName: TLabel;
editFileName: TEdit;
btnFileName: TButton;
pbProgress: TProgressBar;
mLog: TMemo;
btnSend: TButton;
btnClose: TButton;
dlgFileName: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnFileNameClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
Client: TSharedMemoryClient;
procedure ClientCallback(const Msg: String; Percents: Integer;
IsError: Boolean);
public
{ Public declarations }
destructor Destroy(); override;
end;
var
ClientForm: TClientForm;
implementation
{$R *.dfm}
uses System.UITypes;
destructor TClientForm.Destroy();
begin
if Assigned(Client) then
FreeAndNil(Client);
inherited Destroy();
end;
procedure TClientForm.FormCreate(Sender: TObject);
begin
try
Client := TSharedMemoryClient.Create();
editUniqueName.Text := Client.SharedMemoryName;
editFileName.Text := Client.FileName;
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOk], 0);
Application.Terminate()
end;
end;
end;
procedure TClientForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Client.Terminated();
end;
procedure TClientForm.btnFileNameClick(Sender: TObject);
begin
if dlgFileName.Execute() then
editFileName.Text := dlgFileName.FileName;
end;
procedure TClientForm.btnSendClick(Sender: TObject);
begin
btnFileName.Enabled := False;
btnSend.Enabled := False;
try
try
Client.Send(editFileName.Text, ClientCallback);
except
on E: Exception do
MessageDlg(E.Message, mtError, [mbOk], 0);
end;
finally
btnFileName.Enabled := True;
btnSend.Enabled := True;
end;
end;
procedure TClientForm.btnCloseClick(Sender: TObject);
begin
Close();
end;
procedure TClientForm.ClientCallback(const Msg: String; Percents: Integer;
IsError: Boolean);
begin
if IsError then
begin
MessageDlg(Format('Приложение будет завершено,' +
' так как произошла критическая ошибка: "%s"',
[Msg]), mtError, [mbOk], 0);
Close();
end else
begin
pbProgress.Position := Percents;
if Msg <> '' then
mLog.Lines.Add(Msg);
end;
Application.ProcessMessages();
end;
end.
|
unit uOptionen_form;
{$mode delphi}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,uturtlemanager;
type
{ TTOptionen }
TTOptionen = class(TForm)
BT_fertig: TButton;
BT_zuruecksetzen: TButton;
ED_stringlaenge: TEdit;
Label1: TLabel;
procedure BT_fertigClick(Sender: TObject);
procedure BT_zuruecksetzenClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
procedure update_bt();
procedure turtles_neuzeichnen(turtlemanager:TTurtlemanager;maximaleStringLaenge:CARDINAL);
end;
var
Optionen_Form: TTOptionen;
implementation
{$R *.lfm}
uses uForm;
{ TTOptionen }
procedure TTOptionen.BT_fertigClick(Sender: TObject);
VAR maximaleStringLaenge:QWord;turtlemanager:TTurtlemanager;i:CARDINAL;
begin
maximaleStringLaenge:=strtoint(ED_stringlaenge.text); //Aufpassen mit der Größe
if maximaleStringLaenge > 18446744073709 then
begin
SHOWMESSAGE('Die maximale Stringlänge darf maximal 1.8446.744.073.709 sein.');
BT_zuruecksetzenClick(self);
end
else
begin
turtlemanager:=Hauptform.o.copy();
// wenn kleiner als vorher neuzeichnen, wenn größer -> egal
if maximaleStringLaenge < Hauptform.maximaleStringLaenge then
begin
turtles_neuzeichnen(turtlemanager,maximaleStringLaenge);
end
else
begin
Hauptform.maximaleStringLaenge:=maximaleStringLaenge;
//alle maximalenStringLaengen anpassen
if not (turtlemanager.turtleListe.Count=0) then
begin
for i:=0 to turtlemanager.turtleListe.Count-1 do
begin
turtlemanager.turtleListe[i].maximaleStringLaenge:=maximaleStringLaenge;
turtlemanager.turtleListe[i].zeichnen();
end;
end;
Hauptform.push_neue_instanz(turtlemanager);
end;
Visible:=False;
Hauptform.zeichnen;
end;
//wieder unsichtbar machen
end;
function neuzeichnen(turtlemanager:TTurtlemanager;maximaleStringLaenge:CARDINAL):Boolean;
var i:CARDINAL;
begin
for i:=0 to turtlemanager.turtleListe.Count-1 do
begin
turtlemanager.turtleListe[i].maximaleStringLaenge:=maximaleStringLaenge;
if not turtlemanager.turtleListe[i].zeichnen then result:=True;
end;
result:=False;
end;
function neu_machen(turtlemanager:TTurtlemanager;maximaleStringLaenge:CARDINAL): TTurtlemanager;
VAR i,rek:CARDINAL;
begin
for i:=0 to turtlemanager.turtleListe.Count-1 do
begin
turtlemanager.turtleListe[i].maximaleStringLaenge:=maximaleStringLaenge;
while not turtlemanager.turtleListe[i].zeichnen do
begin
rek:= turtlemanager.turtleListe[i].rekursionsTiefe;
turtlemanager.turtleListe[i].rekursionsTiefe:=rek-1;
end;
end;
result:= turtlemanager;
end;
procedure TTOptionen.turtles_neuzeichnen(turtlemanager:TTurtlemanager;maximaleStringLaenge:CARDINAL);
VAR str_1,str_2,str_3,str:string; bt_selected:Integer;kopie:TTurtlemanager;
begin
//neuzeichen mit fehler handeling
//mehrere optionen: rekursionstiefe runter machen (automatisch oder löschen)
if neuzeichnen(turtlemanager,maximaleStringLaenge) then
begin
Hauptform.maximaleStringLaenge:=maximaleStringLaenge;
Hauptform.push_neue_instanz(turtlemanager); //testen
end
else
begin
str_1:='Es gab einen Fehler beim Neuzeichen der Turtles!';
str_2:='Dies liegt daran, das eine oder mehrere Turtles zu lang für die neue Maximallänge sind.';
str_3:='Soll die Rekursiontiefe automatisch angepasst werden, da es passt?';
str:= str_1+sLineBreak+str_2+ sLineBreak + str_3;
bt_selected:=MessageDlg(str,mtCustom,[mbYes,mbCancel],0);
if bt_selected=mrYes then
begin
turtlemanager:= neu_machen(turtlemanager,maximaleStringLaenge);
Hauptform.maximaleStringLaenge:=maximaleStringLaenge;
Hauptform.push_neue_instanz(turtlemanager);
end
else
begin
//Abruch
end;
end;
end;
procedure TTOptionen.BT_zuruecksetzenClick(Sender: TObject);
begin
update_bt();
end;
procedure TTOptionen.FormShow(Sender: TObject);
begin
//WindowState := wsFullScreen;
end;
procedure TTOptionen.update_bt();
begin
ED_stringlaenge.text:=inttostr(Hauptform.maximaleStringLaenge);
end;
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2004 by vtkTools }
{ }
{******************************************}
{Contains the TvgrMultiPageButton component that represents a button that lets users select a range of pages in preview.
Use the TvgrMultiPageButton component to provide the user with a button with drop-down panel
from which he can select a pages' range.
The pages' range is specified by two parameters:
<ul>
<li>Count of pages per width</li>
<li>Count of pages per height</li>
</ul>
See also:
TvgrMultiPageButton}
unit vgr_MultiPageButton;
{$I vtk.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
stdctrls, Buttons, math, vgr_Button;
const
{Default value for caption displaying at the bottom of drop-down panel, when user
can cancel selecting of pages' range.}
DefaultCloseCaption = 'Close';
{Default value for caption displaying at the bottom of drop-down panel, when user
can select the pages' range.}
DefaultPagesCaption = 'Pages %d x %d';
{Specifies the default value for minimum amount of pages per width of drop-down panel.
Syntax:
DefaultMinPagesPerX = 3;}
DefaultMinPagesPerX = 3;
{Specifies the default value for maximum amount of pages per width of drop-down panel.
Syntax:
DefaultMaxPagesPerX = 10;}
DefaultMaxPagesPerX = 10;
{Specifies the default value for minimum amount of pages per height of drop-down panel.
Syntax:
DefaultMinPagesPerY = 2;}
DefaultMinPagesPerY = 2;
{Specifies the default value for maximum amount of pages per height of drop-down panel.
Syntax:
DefaultMaxPagesPerY = 4;}
DefaultMaxPagesPerY = 4;
{Width of page button.
Syntax:
ColorBoxWidth = 24;}
ColorBoxWidth = 24;
{Height of page button.
Syntax:
ColorBoxHeight = 24;}
ColorBoxHeight = 24;
type
TvgrMultiPageButton = class;
{TvgrPagesRangeSelectedEvent is the type for TvgrMultiPageButton.OnPagesRangeSelectedEvent event.
This event occurs when user selects a pages' range.
Parameters:
Sender - The TvgrMultiPageButton object.
APagesRange - Specifies a selected pages' range.}
TvgrPagesRangeSelectedEvent = procedure (Sender: TObject; const APagesRange: TPoint) of object;
/////////////////////////////////////////////////
//
// TvgrMultiPagePaletteForm
//
/////////////////////////////////////////////////
{TvgrMultiPagePaletteForm implements drop down panel, which are showing when user click on TvgrMultiPageButton.
Also this form can be shown separately, with use of a PopupPaletteForm method.}
TvgrMultiPagePaletteForm = class(TvgrDropDownForm)
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FCloseCaption: String;
FPagesCaption: String;
FSelectedPagesRange: TPoint;
FOnPagesRangeSelected: TvgrPagesRangeSelectedEvent;
FButtonsRect: TRect;
FCaptionRect: TRect;
FImmediateDropDown: Boolean;
FMinPagesPerX: Integer;
FMaxPagesPerX: Integer;
FMinPagesPerY: Integer;
FMaxPagesPerY: Integer;
FPagesPerX: Integer;
FPagesPerY: Integer;
FDisablePaint: Boolean;
procedure SetImmediateDropDown(Value: Boolean);
function GetSelectedPagesRange: TPoint;
function GetMultiPageButtonRect(const AMultiPageButtonPos: TPoint): TRect;
procedure SetSelectedPagesRange(Value: TPoint);
procedure GetPointInfoAt(const APos: TPoint; var APagesRange: TPoint);
procedure DrawButton(ACanvas: TCanvas; const AMultiPageButtonPos: TPoint; Highlighted: Boolean);
function GetButton: TvgrMultiPageButton;
protected
procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
procedure CloseUp(X, Y: Integer);
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function GetFormSize: TSize;
property Button: TvgrMultiPageButton read GetButton;
public
{Creates an instance of the TvgrMultiPagePaletteForm class.
Parameters:
AOwner - The component - owner.}
constructor Create(AOwner: TComponent); override;
{Frees an intance of the TvgrMultiPagePaletteForm class.}
destructor Destroy; override;
{Specifies the minimum amount of pages per width of drop-down panel.}
property MinPagesPerX: Integer read FMinPagesPerX write FMinPagesPerX;
{Specifies the minimum amount of pages per height of drop-down panel.}
property MinPagesPerY: Integer read FMinPagesPerY write FMinPagesPerY;
{Specifies the maximum amount of pages per width of drop-down panel.}
property MaxPagesPerX: Integer read FMaxPagesPerX write FMaxPagesPerX;
{Specifies the maximum amount of pages per height of drop-down panel.}
property MaxPagesPerY: Integer read FMaxPagesPerY write FMaxPagesPerY;
{Specifies the current amount of pages per width of drop-down panel.}
property PagesPerX: Integer read FPagesPerX write FPagesPerX;
{Specifies the current amount of pages per height of drop-down panel.}
property PagesPerY: Integer read FPagesPerY write FPagesPerY;
{Specifies the selected pages' range.}
property SelectedPagesRange: TPoint read GetSelectedPagesRange write SetSelectedPagesRange;
{Specifies the value indicating whether the drop-down panel must be opened immediate after
the left mouse down.}
property ImmediateDropDown: Boolean read FImmediateDropDown write SetImmediateDropDown;
{Specifies the caption displaying at the bottom of drop-down panel, when user
can cancel selecting of pages' range.}
property CloseCaption: string read FCloseCaption write FCloseCaption;
{Specifies the caption displaying at the bottom of drop-down panel, when user
can select the pages' range.}
property PagesCaption: string read FPagesCaption write FPagesCaption;
{Occurs when the user selects the pages' range.
See also:
TvgrPageSelectedEvent}
property OnPagesRangeSelected: TvgrPagesRangeSelectedEvent read FOnPagesRangeSelected write FOnPagesRangeSelected;
end;
/////////////////////////////////////////////////
//
// TvgrMultiPageButton
//
/////////////////////////////////////////////////
{TvgrMultiPageButton represents a button that lets users select the pages' range.
Use the TvgrMultiPageButton component to provide the user with a button with drop-down panel
from which he can select a pages' range.
The pages' range is specified by two parameters:
<ul>
<li>Count of pages per width</li>
<li>Count of pages per height</li>
</ul>
Use the SelectedPagesRange property to access the currently selected range of pages.}
TvgrMultiPageButton = class(TvgrBaseButton)
private
FImmediateDropDown: Boolean;
FSelectedPagesRange: TPoint;
FOnPagesRangeSelected: TvgrPagesRangeSelectedEvent;
FCloseCaption: String;
FPagesCaption: String;
FMinPagesPerX: Integer;
FMaxPagesPerX: Integer;
FMinPagesPerY: Integer;
FMaxPagesPerY: Integer;
procedure DoOnPagesRangeSelected(Sender: TObject; const APagesRange: TPoint);
procedure SetSelectedPagesRange(Value: TPoint);
procedure SetImmediateDropDown(Value: Boolean);
function IsCloseCaptionStored: Boolean;
function IsPagesCaptionStored: Boolean;
function GetDropDownForm: TvgrMultiPagePaletteForm;
protected
procedure CNCommand(var Msg: TWMCommand); message CN_COMMAND;
function GetDropDownFormClass: TvgrDropDownFormClass; override;
function GetDrawFocusRect: Boolean; override;
procedure ShowDropDownForm; override;
procedure DrawButton(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean); override;
procedure DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
property DropDownForm: TvgrMultiPagePaletteForm read GetDropDownForm;
public
{Creates an instance of the TvgrMultiPageButton class.
Parameters:
AOwner - Component that is responsible for freeing the button.
It becomes the value of the Owner property.}
constructor Create(AOwner: TComponent); override;
{Frees an instance of the TvgrMultiPageButton class.}
destructor Destroy; override;
{Simulates a mouse click, as if the user had clicked the button.}
procedure Click; override;
{Specifies the current pages' range.}
property SelectedPagesRange: TPoint read FSelectedPagesRange write SetSelectedPagesRange;
published
property Action;
property Anchors;
property BiDiMode;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentBiDiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
{$IFDEF VGR_D5}
property OnContextPopup;
{$ENDIF}
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
{Set Flat to true to remove the raised border when the button is unselected and the lowered border when the button is clicked or selected.}
property Flat default True;
{Specifies the value indicating whether the drop-down panel must be opened immediate after
the left mouse down.}
property ImmediateDropDown: Boolean read FImmediateDropDown write SetImmediateDropDown default true;
{Specifies the minimum amount of pages per width of drop-down panel.}
property MinPagesPerX: Integer read FMinPagesPerX write FMinPagesPerX default DefaultMinPagesPerX;
{Specifies the minimum amount of pages per height of drop-down panel.}
property MinPagesPerY: Integer read FMinPagesPerY write FMinPagesPerY default DefaultMinPagesPerY;
{Specifies the maximum amount of pages per width of drop-down panel.}
property MaxPagesPerX: Integer read FMaxPagesPerX write FMaxPagesPerX default DefaultMaxPagesPerX;
{Specifies the maximum amount of pages per height of drop-down panel.}
property MaxPagesPerY: Integer read FMaxPagesPerY write FMaxPagesPerY default DefaultMaxPagesPerY;
{Specifies the caption displaying at the bottom of drop-down panel, when user
can cancel selecting of pages' range.}
property CloseCaption: string read FCloseCaption write FCloseCaption stored IsCloseCaptionStored;
{Specifies the caption displaying at the bottom of drop-down panel, when user
can select the pages' range.}
property PagesCaption: string read FPagesCaption write FPagesCaption stored IsPagesCaptionStored;
{Occurs when the user selects the pages' range.
See also:
TvgrPagesRangeSelectedEvent}
property OnPagesRangeSelected: TvgrPagesRangeSelectedEvent read FOnPagesRangeSelected write FOnPagesRangeSelected;
end;
{Use this metod to create and show TvgrMultiPagePaletteForm at specified position.
Parameters:
AOwner - Specifies an owner for the created form.
X, Y - Coordinates of the created form this values is relative to the screen in pixels.
OnPagesRangeSelected - Specifies an event procedure, which is called when user selects the pages' range.
Return value:
Returns a reference to the created form.}
function PopupPaletteForm(AOwner: TComponent;
X, Y: integer;
OnPagesRangeSelected: TvgrPagesRangeSelectedEvent): TvgrMultiPagePaletteForm;
implementation
uses
vgr_GUIFunctions, vgr_Functions;
{$R vgrMultiPageButton.res}
{$R *.DFM}
const
LeftOffset = 3;
RightOffset = 3;
TopOffset = 3;
BottomOffset = 3;
DeltaXOffset = 2;
DeltaYOffset = 2;
var
FButtonImage: TBitmap;
FPageImage: TBitmap;
function PopupPaletteForm(AOwner: TComponent;
X, Y: integer;
OnPagesRangeSelected: TvgrPagesRangeSelectedEvent): TvgrMultiPagePaletteForm;
var
R: TRect;
begin
Result := TvgrMultiPagePaletteForm.Create(AOwner);
Result.OnPagesRangeSelected := OnPagesRangeSelected;
SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
if X + Result.Width > r.Right then
X := X - Result.Width;
if Y + Result.Height > r.Bottom then
Y := Y - Result.Height;
Result.Left := X;
Result.Top := Y;
Result.Show;
end;
/////////////////////////////////////////////////
//
// TvgrMultiPageButton
//
/////////////////////////////////////////////////
constructor TvgrMultiPageButton.Create(AOwner: TComponent);
begin
inherited;
FImmediateDropDown := True;
FCloseCaption := DefaultCloseCaption;
FPagesCaption := DefaultPagesCaption;
FMinPagesPerX := DefaultMinPagesPerX;
FMinPagesPerY := DefaultMinPagesPerY;
FMaxPagesPerX := DefaultMaxPagesPerX;
FMaxPagesPerY := DefaultMaxPagesPerY;
Flat := True;
Width := 23;
Height := 22;
end;
destructor TvgrMultiPageButton.Destroy;
begin
inherited;
end;
function TvgrMultiPageButton.IsCloseCaptionStored: Boolean;
begin
Result := FCloseCaption <> DefaultCloseCaption;
end;
function TvgrMultiPageButton.IsPagesCaptionStored: Boolean;
begin
Result := FPagesCaption <> DefaultPagesCaption;
end;
function TvgrMultiPageButton.GetDropDownForm: TvgrMultiPagePaletteForm;
begin
Result := TvgrMultiPagePaletteForm(inherited DropDownForm);
end;
function TvgrMultiPageButton.GetDropDownFormClass: TvgrDropDownFormClass;
begin
Result := TvgrMultiPagePaletteForm;
end;
procedure TvgrMultiPageButton.ShowDropDownForm;
begin
inherited;
DropDownForm.SelectedPagesRange := Point(0, 0);
DropDownForm.OnPagesRangeSelected := DoOnPagesRangeSelected;
DropDownForm.PagesCaption := PagesCaption;
DropDownForm.CloseCaption := CloseCaption;
DropDownForm.MinPagesPerX := MinPagesPerX;
DropDownForm.MinPagesPerY := MinPagesPerY;
DropDownForm.MaxPagesPerX := MaxPagesPerX;
DropDownForm.MaxPagesPerY := MaxPagesPerY;
end;
function TvgrMultiPageButton.GetDrawFocusRect: Boolean;
begin
Result := false;
end;
procedure TvgrMultiPageButton.DrawButton(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean);
begin
if (DropDownForm <> nil) and (DropDownForm.ImmediateDropDown) then
begin
inherited DrawButton(ADC, ADisabled, True, AFocused, AUnderMouse);
end
else
begin
inherited;
end;
end;
procedure TvgrMultiPageButton.DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect);
var
R: TRect;
ATempCanvas: TCanvas;
begin
r := AInternalRect;
// draw image
ATempCanvas := TCanvas.Create;
ATempCanvas.Handle := ADC;
try
with r do
ATempCanvas.Draw(r.Left + (r.Right - r.Left - FButtonImage.Width) div 2,
r.Top + (r.Bottom - r.Top - FButtonImage.Height) div 2, FButtonImage);
finally
ATempCanvas.Free;
end;
end;
procedure TvgrMultiPageButton.CNCommand(var Msg: TWMCommand);
begin
if Msg.NotifyCode = BN_CLICKED then
begin
if ImmediateDropDown then
begin
Msg.Result := 1;
exit;
end;
end;
inherited;
end;
procedure TvgrMultiPageButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if DropDownForm <> nil then
begin
DropDownForm.ImmediateDropDown := False;
Invalidate;
end;
inherited;
end;
procedure TvgrMultiPageButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ImmediateDropDown then
begin
if DropDownForm = nil then
begin
ShowDropDownForm;
DropDownForm.ImmediateDropDown := True;
end;
Invalidate;
end;
end;
procedure TvgrMultiPageButton.Click;
begin
if (DropDownForm = nil) and not ImmediateDropDown then
ShowDropDownForm;
inherited;
end;
procedure TvgrMultiPageButton.SetSelectedPagesRange(Value: TPoint);
begin
FSelectedPagesRange := Value;
Invalidate;
end;
procedure TvgrMultiPageButton.SetImmediateDropDown(Value: Boolean);
begin
FImmediateDropDown := Value;
end;
procedure TvgrMultiPageButton.DoOnPagesRangeSelected(Sender: TObject; const APagesRange: TPoint);
begin
SelectedPagesRange := APagesRange;
if Assigned(OnPagesRangeSelected) then
OnPagesRangeSelected(Self, SelectedPagesRange);
end;
/////////////////////////////////
//
// TprMultiPagePaletteForm
//
/////////////////////////////////
constructor TvgrMultiPagePaletteForm.Create(AOwner: TComponent);
begin
inherited;
BorderStyle := bsNone;
FMinPagesPerX := DefaultMinPagesPerX;
FMinPagesPerY := DefaultMinPagesPerY;
FMaxPagesPerX := DefaultMaxPagesPerX;
FMaxPagesPerY := DefaultMaxPagesPerY;
FPagesPerX := FMinPagesPerX;
FPagesPerY := FMinPagesPerY;
FCloseCaption := DefaultCloseCaption;
FPagesCaption := DefaultPagesCaption;
FSelectedPagesRange.X := 0;
FSelectedPagesRange.Y := 0;
end;
destructor TvgrMultiPagePaletteForm.Destroy;
begin
inherited;
end;
procedure TvgrMultiPagePaletteForm.CMMouseLeave(var Msg: TMessage);
begin
if not ImmediateDropDown then
SelectedPagesRange := Point(0, 0);
inherited;
end;
procedure TvgrMultiPagePaletteForm.SetImmediateDropDown(Value: Boolean);
begin
FImmediateDropDown := Value;
if FImmediateDropDown then
SetCaptureControl(Self);
end;
function TvgrMultiPagePaletteForm.GetSelectedPagesRange;
begin
Result := FSelectedPagesRange;
end;
function TvgrMultiPagePaletteForm.GetMultiPageButtonRect(const AMultiPageButtonPos: TPoint): TRect;
begin
Result.Left := LeftOffset + AMultiPageButtonPos.X * (ColorBoxWidth + DeltaXOffset);
Result.Top := TopOffset + AMultiPageButtonPos.Y * (ColorBoxHeight + DeltaYOffset);
Result.Right := Result.Left + ColorBoxWidth;
Result.Bottom := Result.Top + ColorBoxHeight;
end;
procedure TvgrMultiPagePaletteForm.SetSelectedPagesRange(Value: TPoint);
begin
FSelectedPagesRange := Value;
Invalidate;
end;
procedure TvgrMultiPagePaletteForm.GetPointInfoAt(const APos: TPoint; var APagesRange: TPoint);
begin
if APos.X < FButtonsRect.Left then
APagesRange.X := 0
else
APagesRange.X := Max(0, (APos.X - LeftOffset) div (ColorBoxWidth + DeltaXOffset) + 1);
if APos.Y < FButtonsRect.Top then
APagesRange.Y := 0
else
APagesRange.Y := Max(0, (APos.Y - TopOffset) div (ColorBoxHeight + DeltaYOffset) + 1);
if ImmediateDropDown then
begin
APagesRange.X := Min(APagesRange.X, MaxPagesPerX);
APagesRange.Y := Min(APagesRange.Y, MaxPagesPerY);
end
else
begin
if PtInRect(FButtonsRect, APos) then
begin
APagesRange.X := Min(APagesRange.X, MaxPagesPerX);
APagesRange.Y := Min(APagesRange.Y, MaxPagesPerY);
end
else
begin
APagesRange.X := 0;
APagesRange.Y := 0;
end;
end;
end;
function TvgrMultiPagePaletteForm.GetButton: TvgrMultiPageButton;
begin
Result := TvgrMultiPageButton(inherited Button);
end;
procedure TvgrMultiPagePaletteForm.DrawButton(ACanvas: TCanvas; const AMultiPageButtonPos: TPoint; Highlighted: Boolean);
var
R, R2, R_BAK: TRect;
begin
R := GetMultiPageButtonRect(AMultiPageButtonPos);
R_BAK := R;
R2 := R;
// Icon
R2.Left := R2.Left + (R2.Right - R2.Left - FPageImage.Width) div 2;
R2.Top := R2.Top + (R2.Bottom - R2.Top - FPageImage.Height) div 2;
R2.Right := R2.Left + FPageImage.Width;
R2.Bottom := R2.Top + FPageImage.Height;
Canvas.StretchDraw(R2, FPageImage);
ExcludeClipRect(Canvas, R2);
// Shadow for page icon
Canvas.Brush.Color := clGray;
R := R2;
R2.Left := R2.Right;
R2.Right := R2.Right + 1;
R2.Top := R2.Top + 1;
R2.Bottom := R2.Bottom + 1;
Canvas.FillRect(R2);
ExcludeClipRect(Canvas, R2);
R2 := R;
R2.Left := R2.Left + 1;
R2.Right := R2.Right + 1;
R2.Top := R2.Bottom;
R2.Bottom := R2.Bottom + 1;
Canvas.FillRect(R2);
ExcludeClipRect(Canvas, R2);
// inner area
R := R_BAK;
InflateRect(R, -1, -1);
if Highlighted then
Canvas.Brush.Color := clHighlight
else
Canvas.Brush.Color := clWindow;
Canvas.FillRect(R);
ExcludeClipRect(ACanvas, R);
// border
Canvas.Brush.Color := clBtnShadow;
Canvas.FillRect(R_BAK);
ExcludeClipRect(ACanvas, R_BAK);
end;
procedure TvgrMultiPagePaletteForm.FormPaint(Sender: TObject);
var
R: TRect;
I, J: integer;
ACaption: string;
begin
if FDisablePaint then
exit;
// Buttons
for I := 0 to PagesPerX - 1 do
for J := 0 to PagesPerY - 1 do
DrawButton(Canvas, Point(I, J), (J < SelectedPagesRange.Y) and (I < SelectedPagesRange.X));
// Bottom caption
Canvas.Brush.Color := clWindow;
Canvas.Font.Color := clWindowText;
Canvas.FillRect(FCaptionRect);
Canvas.Brush.Style := bsClear;
if (SelectedPagesRange.Y = 0) or (SelectedPagesRange.X = 0) then
ACaption := CloseCaption
else
ACaption := Format(PagesCaption, [SelectedPagesRange.Y, SelectedPagesRange.X]);
with FCaptionRect, Canvas.TextExtent(ACaption) do
Canvas.TextOut(Left + (Right - Left - cx) div 2,
Top + (Bottom - Top - cy) div 2,
ACaption);
ExcludeClipRect(Canvas, FCaptionRect);
Canvas.Brush.Style := bsSolid;
//
R := ClientRect;
InflateRect(R, -1, -1);
Canvas.Brush.Color := clWindow;
Canvas.FillRect(R);
ExcludeClipRect(Canvas, R);
// Form's borders
Canvas.Brush.Color := clBtnShadow;
Canvas.FillRect(ClientRect);
end;
function TvgrMultiPagePaletteForm.GetFormSize: TSize;
begin
// buttons' area
FButtonsRect := Rect(LeftOffset,
TopOffset,
LeftOffset + PagesPerX * ColorBoxWidth + (PagesPerX - 1) * DeltaXOffset,
TopOffset + PagesPerY * ColorBoxHeight+ (PagesPerY - 1) * DeltaYOffset);
// caption's area
FCaptionRect.Left := FButtonsRect.Left;
FCaptionRect.Top := FButtonsRect.Bottom;
FCaptionRect.Right := FButtonsRect.Right;
FCaptionRect.Bottom := FCaptionRect.Top + MulDiv(GetFontHeight(Canvas.Font), 3, 2);
// form's size
Result.cx := FButtonsRect.Right + RightOffset;
Result.cy := FCaptionRect.Bottom + BottomOffset;
end;
procedure TvgrMultiPagePaletteForm.FormCreate(Sender: TObject);
begin
with GetFormSize do
begin
ClientWidth := cx;
ClientHeight := cy;
end;
end;
procedure TvgrMultiPagePaletteForm.MouseMove(Shift: TShiftState; X, Y: Integer);
var
ANewPagesRange: TPoint;
begin
GetPointInfoAt(Point(X, Y), ANewPagesRange);
if (ANewPagesRange.X <> SelectedPagesRange.X) or (ANewPagesRange.Y <> SelectedPagesRange.Y) then
begin
if (ANewPagesRange.X > PagesPerX) or (ANewPagesRange.Y > PagesPerY) then
begin
PagesPerY := Max(ANewPagesRange.Y, PagesPerY);
PagesPerX := Max(ANewPagesRange.X, PagesPerX);
with GetFormSize do
SetBounds(Left, Top, cx, cy);
end;
FSelectedPagesRange := ANewPagesRange;
Invalidate;
end;
end;
procedure TvgrMultiPagePaletteForm.CloseUp(X, Y: Integer);
begin
if (SelectedPagesRange.X > 0) or (SelectedPagesRange.Y > 0) then
begin
if Assigned(FOnPagesRangeSelected) then
FOnPagesRangeSelected(Self, SelectedPagesRange);
end;
Close;
end;
procedure TvgrMultiPagePaletteForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
CloseUp(X, Y);
end;
procedure TvgrMultiPagePaletteForm.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
P: TPoint;
begin
if ImmediateDropDown then
begin
SetCaptureControl(nil);
if Self.Button <> nil then
begin
P := ClientToScreen(Point(X, Y));
P := Self.Button.ScreenToClient(P);
if PtInRect(Rect(0, 0, Self.Button.Width, Self.Button.Height), P) then
begin
Self.Button.MouseUp(Button, Shift, P.X, P.Y);
exit;
end
else
Self.Button.MouseInControl := False;
end;
CloseUp(X, Y);
end;
end;
initialization
FButtonImage := TBitmap.Create;
FButtonImage.LoadFromResourceName(hInstance, 'VGR_MULTIPAGEICON');
FButtonImage.Transparent := True;
FPageImage := TBitmap.Create;
FPageImage.LoadFromResourceName(hInstance,'VGR_PAGEICON');
finalization
FButtonImage.Free;
FPageImage.Free;
end.
|
unit SSPHelper;
interface uses
{$ifdef unix}
DynLibs,
{$else}
Windows,
{$endif}
Types, SysUtils, Classes,
SSPTypes;
const
//SIMPLE SERIALIZATION PROTOCOL
//
SSP_TYPE_OBJECT = 0; // objectType intType COUNT (stringType FIELD_NAME valueType FIELD_VALUE)*
SSP_TYPE_ARRAY = 1; // arrayType intType COUNT ( valueType FIELD_VALUE)*
SSP_TYPE_STRING = 2; // stringType intType COUNT ( BYTE_VALUE)*
SSP_TYPE_DECIMAL = 4; // decimalType intType COUNT ( BYTE_VALUE)*
SSP_TYPE_INT_8 =10; // int8Type BYTE_VALUE
SSP_TYPE_INT_16 =11; // int16Type BYTE_VALUES hi-lo 2
SSP_TYPE_INT_32 =12; // int32Type BYTE_VALUE0 hi-lo 4
SSP_TYPE_INT_64 =13; // int64Type BYTE_VALUE0 hi-lo 8
SSP_TYPE_FLOAT_32 =15; // floatSingleType BYTE_VALUE0 hi-lo 4
SSP_TYPE_FLOAT_64 =16; // floatDoubleType BYTE_VALUE0 hi-lo 8
SSP_TYPE_BYTE_ARRAY =20; // byteArrayType intType COUNT ( BYTE_VALUE)*
type
ESSPInvalidData = class(Exception)
end;
TSSPHelper = class
public
class function getTypeOf(value: int64 ): shortint; overload;
class function getTypeOf(value: double): shortint; overload;
class procedure writeType (dest: TStream; value: shortint );
class procedure writeByteArray(dest: TStream; size: integer; buffer: pointer); overload;
class procedure writeByteArray(dest: TStream; const buffer: TByteArray); overload;
class procedure writeObject(dest: TStream; fieldCount: integer );
class procedure writeField (dest: TStream; fieldName : WideString);
class procedure writeArray (dest: TStream; itemCount : integer );
class procedure writeUTF8String (dest: TStream; value: AnsiString);
class procedure writeString (dest: TStream; value: WideString);
class procedure writeInt (dest: TStream; value: int64 );
class procedure writeInt8 (dest: TStream; value: shortint );
class procedure writeInt16 (dest: TStream; value: smallint );
class procedure writeInt32 (dest: TStream; value: longint );
class procedure writeInt64 (dest: TStream; value: int64 );
class procedure writeFloat (dest: TStream; value: double );
class procedure writeFloat32 (dest: TStream; value: single );
class procedure writeFloat64 (dest: TStream; value: double );
class procedure writeDecimalString(dest: TStream; value: AnsiString);
class function checkType (actual, required: shortint): shortint;
class function readType (src: TStream): shortint;
class function readByteArrayData (src: TStream; type_: shortint): TByteDynArray;
class function readUTF8StringData (src: TStream; type_: shortint): AnsiString ;
class function readStringData (src: TStream; type_: shortint): WideString ;
class function readIntData (src: TStream; type_: shortint): int64 ;
class function readInt8Data (src: TStream; type_: shortint): shortint ;
class function readInt16Data (src: TStream; type_: shortint): smallint ;
class function readInt32Data (src: TStream; type_: shortint): longint ;
class function readInt64Data (src: TStream; type_: shortint): int64 ;
class function readFloatData (src: TStream; type_: shortint): double ;
class function readFloat32Data (src: TStream; type_: shortint): single ;
class function readFloat64Data (src: TStream; type_: shortint): double ;
class function readDecimalStringData(src: TStream; type_: shortint): AnsiString ;
class function readAnyData (src: TStream; type_: shortint): ISSPAny ;
class function readObjectData (src: TStream; type_: shortint): ISSPAny ;
class function readArrayData (src: TStream; type_: shortint): ISSPAny ;
class function readByteArray (src: TStream): TByteDynArray;
class function readUTF8String (src: TStream): AnsiString ;
class function readString (src: TStream): WideString ;
class function readInt (src: TStream): int64 ;
class function readInt8 (src: TStream): shortint ;
class function readInt16 (src: TStream): smallint ;
class function readInt32 (src: TStream): longint ;
class function readInt64 (src: TStream): int64 ;
class function readFloat (src: TStream): double ;
class function readFloat32 (src: TStream): single ;
class function readFloat64 (src: TStream): double ;
class function readDecimalString(src: TStream): AnsiString ;
class function readAny (src: TStream): ISSPAny ;
class function readObject (src: TStream): ISSPAny ;
class function readArray (src: TStream): ISSPAny ;
end;
{
TSSPWriter = class
protected
_origin: TStream;
_owned : boolean;
public
constructor create(origin: TStream; owned: boolean);
destructor destroy; override;
procedure beginObject(fieldCount: integer);
procedure endObject();
procedure beginField(fieldName: WideString);
procedure endField();
procedure beginArray(itemCount: integer);
procedure endArray();
procedure writeByteArray(size: integer; buffer: pointer);
procedure writeObject(fieldCount: integer );
procedure writeField (fieldName : WideString);
procedure writeArray (itemCount : integer );
procedure writeUTF8String (value: AnsiString);
procedure writeString (value: WideString);
procedure writeInt (value: int64 );
procedure writeInt8 (value: shortint );
procedure writeInt16 (value: smallint );
procedure writeInt32 (value: longint );
procedure writeInt64 (value: int64 );
procedure writeFloat (value: double );
procedure writeSingle (value: single );
procedure writeDouble (value: double );
procedure writeDecimal (value: double );
procedure writeDecimalString(value: AnsiString);
end;
TSSPReader = class
protected
_origin: TStream;
_owned : boolean;
public
constructor create(origin: TStream; owned: boolean);
destructor destroy; override;
function readType (): shortint ;
function readUTF8String (): AnsiString;
function readString (): WideString;
function readInt (): int64 ;
function readInt8 (): shortint ;
function readInt16 (): smallint ;
function readInt32 (): longint ;
function readInt64 (): int64 ;
function readFloat (): double ;
function readSingle (): single ;
function readDouble (): double ;
function readDecimal (): double ;
function readDecimalString(): AnsiString;
function readAny (): ISSPAny;
end;
}
function getNormalFormatSettings(): TFormatSettings;
function normalFloatToStr (const format: String; value: extended): String;
function normalStrToFloat (const value: String): extended;
function normalStrToFloatDef(const value: String; defaultValue: extended): extended;
implementation uses Math,
SFPHelper;
type
TByteArray2 = packed array[0..(2-1)] of byte;
TByteArray4 = packed array[0..(4-1)] of byte;
TByteArray8 = packed array[0..(8-1)] of byte;
class function TSSPHelper.getTypeOf(value: int64): shortint;
begin
if value < low (longint ) then result:= SSP_TYPE_INT_64
else if value < low (smallint) then result:= SSP_TYPE_INT_32
else if value < low (shortint) then result:= SSP_TYPE_INT_16
else if value <= high(shortint) then result:= SSP_TYPE_INT_8
else if value <= high(smallint) then result:= SSP_TYPE_INT_16
else if value <= high(longint ) then result:= SSP_TYPE_INT_32
else result:= SSP_TYPE_INT_64;
end;
class function TSSPHelper.getTypeOf(value: double): shortint;
var tempSingle: single;
begin
tempSingle:= value;
if isNAN(tempSingle) or (tempSingle = value) then
result:= SSP_TYPE_FLOAT_32 else
result:= SSP_TYPE_FLOAT_64;
end;
class procedure TSSPHelper.writeType (dest: TStream; value: shortint );
begin
TSFPHelper.internalWrite(dest, 1, @value);
end;
class procedure TSSPHelper.writeByteArray(dest: TStream; size: integer; buffer: pointer);
begin
TSSPHelper.writeType (dest, SSP_TYPE_BYTE_ARRAY);
TSSPHelper.writeInt (dest, size);
TSFPHelper.internalWrite(dest, size, buffer);
end;
class procedure TSSPHelper.writeByteArray(dest: TStream; const buffer: TByteArray);
begin
TSSPHelper.writeType (dest, SSP_TYPE_BYTE_ARRAY);
TSSPHelper.writeInt (dest, length(buffer));
if 0 < length(buffer) then
TSFPHelper.internalWrite(dest, length(buffer), @buffer[0]);
end;
class procedure TSSPHelper.writeObject(dest: TStream; fieldCount: integer );
begin
TSSPHelper.writeType(dest, SSP_TYPE_OBJECT);
TSSPHelper.writeInt(dest, fieldCount);
end;
class procedure TSSPHelper.writeField (dest: TStream; fieldName : WideString);
begin
TSSPHelper.writeString(dest, fieldName);
end;
class procedure TSSPHelper.writeArray (dest: TStream; itemCount : integer );
begin
TSSPHelper.writeType(dest, SSP_TYPE_ARRAY);
TSSPHelper.writeInt(dest, itemCount);
end;
class procedure TSSPHelper.writeUTF8String (dest: TStream; value: AnsiString);
begin
TSSPHelper.writeType(dest, SSP_TYPE_STRING);
TSSPHelper.writeInt (dest, length(value));
TSFPHelper.internalWrite(dest, length(value), pansichar(value));
end;
class procedure TSSPHelper.writeString (dest: TStream; value: WideString);
begin
writeUTF8String(dest, utf8encode(value));
end;
class procedure TSSPHelper.writeInt (dest: TStream; value: int64 );
var type_: shortint;
begin
type_:= getTypeOf(value);
case type_ of
SSP_TYPE_INT_8 : writeInt8 (dest, value);
SSP_TYPE_INT_16: writeInt16(dest, value);
SSP_TYPE_INT_32: writeInt32(dest, value);
else writeInt64(dest, value);
end;
end;
{
function reverse32(value: integer): integer; overload;
begin
result:= swap(value) shl (8 * 2) or (swap(value shr (8 * 2)) and $FFFF);
end;
function reverse64(value: int64): int64; overload;
begin
result:= int64(reverse32(integer(value))) shl (8 * 4) or (reverse32(integer(value shr (8 * 4))) and $FFFFFFFF);
end;
class procedure TSSPHelper.writeInt8 (dest: TStream; value: shortint ); begin writeType(dest, SSP_TYPE_INT_8 ); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
class procedure TSSPHelper.writeInt16 (dest: TStream; value: smallint ); begin value:= swap(value); writeType(dest, SSP_TYPE_INT_16); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
class procedure TSSPHelper.writeInt32 (dest: TStream; value: longint ); begin value:= reverse32(value); writeType(dest, SSP_TYPE_INT_32); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
class procedure TSSPHelper.writeInt64 (dest: TStream; value: int64 ); begin value:= reverse64(value); writeType(dest, SSP_TYPE_INT_64); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
}
function storeInt16(value: smallint): TByteArray2;
begin
result[1]:= value and $ff; value:= value shr 8;
result[0]:= value and $ff;
end;
function storeInt32(value: longint ): TByteArray4;
begin
result[3]:= value and $ff; value:= value shr 8;
result[2]:= value and $ff; value:= value shr 8;
result[1]:= value and $ff; value:= value shr 8;
result[0]:= value and $ff;
end;
function storeInt64(value: int64 ): TByteArray8;
begin
result[7]:= value and $ff; value:= value shr 8;
result[6]:= value and $ff; value:= value shr 8;
result[5]:= value and $ff; value:= value shr 8;
result[4]:= value and $ff; value:= value shr 8;
result[3]:= value and $ff; value:= value shr 8;
result[2]:= value and $ff; value:= value shr 8;
result[1]:= value and $ff; value:= value shr 8;
result[0]:= value and $ff;
end;
function loadInt16(value: TByteArray2): smallint;
begin
result:= ((0
or (value[0] and $ff)) shl 8)
or (value[1] and $ff);
end;
function loadInt32(value: TByteArray4): longint ;
begin
result:= (longint( (longint( (longint(0
or (value[0] and $ff)) shl 8)
or (value[1] and $ff)) shl 8)
or (value[2] and $ff)) shl 8)
or (value[3] and $ff);
end;
function loadInt64(value: TByteArray8): int64 ;
begin
result:= (( (( (( (( (( (( ((0
or (value[0] and $ff)) shl 8)
or (value[1] and $ff)) shl 8)
or (value[2] and $ff)) shl 8)
or (value[3] and $ff)) shl 8)
or (value[4] and $ff)) shl 8)
or (value[5] and $ff)) shl 8)
or (value[6] and $ff)) shl 8)
or (value[7] and $ff);
end;
class procedure TSSPHelper.writeInt8 (dest: TStream; value: shortint );
begin
writeType(dest, SSP_TYPE_INT_8 );
TSFPHelper.internalWrite(dest, sizeof(value), @value);
end;
class procedure TSSPHelper.writeInt16 (dest: TStream; value: smallint );
var temp: TByteArray2;
begin
temp:= storeInt16(value);
writeType(dest, SSP_TYPE_INT_16);
TSFPHelper.internalWrite(dest, sizeof(temp), @temp[0]);
end;
class procedure TSSPHelper.writeInt32 (dest: TStream; value: longint );
var temp: TByteArray4;
begin
temp:= storeInt32(value);
writeType(dest, SSP_TYPE_INT_32);
TSFPHelper.internalWrite(dest, sizeof(temp), @temp[0]);
end;
class procedure TSSPHelper.writeInt64 (dest: TStream; value: int64 );
var temp: TByteArray8;
begin
temp:= storeInt64(value);
writeType(dest, SSP_TYPE_INT_64);
TSFPHelper.internalWrite(dest, sizeof(temp), @temp[0]);
end;
class procedure TSSPHelper.writeFloat (dest: TStream; value: double );
var type_: shortint;
begin
type_:= getTypeOf(value);
if type_ = SSP_TYPE_FLOAT_32 then
writeFloat32(dest, value) else
writeFloat64(dest, value);
end;
{
class procedure TSSPHelper.writeFloat32 (dest: TStream; value: single ); begin pinteger(@value)^:= reverse(pinteger(@value)^); writeType(dest, SSP_TYPE_FLOAT_32); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
class procedure TSSPHelper.writeFloat64 (dest: TStream; value: double ); begin pint64 (@value)^:= reverse(pint64 (@value)^); writeType(dest, SSP_TYPE_FLOAT_64); TSFPHelper.internalWrite(dest, sizeof(value), @value); end;
}
class procedure TSSPHelper.writeFloat32 (dest: TStream; value: single );
var temp: TByteArray4;
begin
temp:= storeInt32(plongint(@value)^);
writeType(dest, SSP_TYPE_FLOAT_32);
TSFPHelper.internalWrite(dest, sizeof(temp), @temp[0]);
end;
class procedure TSSPHelper.writeFloat64 (dest: TStream; value: double );
var temp: TByteArray8;
begin
temp:= storeInt64(pint64(@value)^);
writeType(dest, SSP_TYPE_FLOAT_64);
TSFPHelper.internalWrite(dest, sizeof(temp), @temp[0]);
end;
class procedure TSSPHelper.writeDecimalString(dest: TStream; value: AnsiString);
begin
TSSPHelper.writeType (dest, SSP_TYPE_DECIMAL);
TSSPHelper.writeInt (dest, length(value));
TSFPHelper.internalWrite(dest, length(value), pansichar(value));
end;
class function TSSPHelper.checkType(actual, required: shortint): shortint;
begin
result:= actual;
if actual <> required then
raise ESSPInvalidData.create('Illegal type: ' + intToStr(actual) + '. Required type: ' + intToStr(required) + '.');
end;
class function TSSPHelper.readType(src: TStream): shortint ;
var temp: byte;
begin
TSFPHelper.internalRead(src, 1, @temp);
result:= word(temp);
end;
class function TSSPHelper.readByteArrayData (src: TStream; type_: shortint): TByteDynArray;
begin
checkType(type_, SSP_TYPE_BYTE_ARRAY);
setLength(result, readInt(src));
if 0 < length(result) then
TSFPHelper.internalRead(src, length(result), @result[0]);
end;
class function TSSPHelper.readUTF8StringData (src: TStream; type_: shortint): AnsiString;
begin
checkType(type_, SSP_TYPE_STRING);
setLength(result, readInt(src));
TSFPHelper.internalRead(src, length(result), pansichar(result));
end;
class function TSSPHelper.readStringData (src: TStream; type_: shortint): WideString;
begin
result:= utf8decode(readUTF8StringData(src, type_));
end;
class function TSSPHelper.readIntData (src: TStream; type_: shortint): int64 ;
begin
case type_ of
SSP_TYPE_INT_8 : result:= readInt8Data (src, type_);
SSP_TYPE_INT_16: result:= readInt16Data(src, type_);
SSP_TYPE_INT_32: result:= readInt32Data(src, type_);
SSP_TYPE_INT_64: result:= readInt64Data(src, type_);
else
raise ESSPInvalidData.create('Illegal type: ' + intToStr(type_) + '. Required types: ('
+ intToStr(SSP_TYPE_INT_8 ) + ','
+ intToStr(SSP_TYPE_INT_16) + ','
+ intToStr(SSP_TYPE_INT_32) + ','
+ intToStr(SSP_TYPE_INT_64) + ').'
);
end;
end;
class function TSSPHelper.readInt8Data (src: TStream; type_: shortint): shortint ;
begin
checkType(type_, SSP_TYPE_INT_8 );
TSFPHelper.internalRead(src, sizeof(result), @result);
end;
class function TSSPHelper.readInt16Data (src: TStream; type_: shortint): smallint ;
var temp: TByteArray2;
begin
checkType(type_, SSP_TYPE_INT_16);
TSFPHelper.internalRead(src, sizeof(temp), @temp[0]);
result:= loadInt16(temp);
end;
class function TSSPHelper.readInt32Data (src: TStream; type_: shortint): longint ;
var temp: TByteArray4;
begin
checkType(type_, SSP_TYPE_INT_32);
TSFPHelper.internalRead(src, sizeof(temp), @temp[0]);
result:= loadInt32(temp);
end;
class function TSSPHelper.readInt64Data (src: TStream; type_: shortint): int64 ;
var temp: TByteArray8;
begin
checkType(type_, SSP_TYPE_INT_64);
TSFPHelper.internalRead(src, sizeof(temp), @temp[0]);
result:= loadInt64(temp);
end;
{
class function TSSPHelper.readInt8Data (src: TStream; type_: shortint): shortint ;
begin
checkType(type_, SSP_TYPE_INT_8 );
TSFPHelper.internalRead(src, sizeof(result), @result);
end;
class function TSSPHelper.readInt16Data (src: TStream; type_: shortint): smallint ;
var temp: TByteArray2;
begin
checkType(type_, SSP_TYPE_INT_16);
TSFPHelper.internalRead(src, sizeof(result), @result); result:= swap(result);
end;
class function TSSPHelper.readInt32Data (src: TStream; type_: shortint): longint ;
var temp: TByteArray4;
begin
checkType(type_, SSP_TYPE_INT_32);
TSFPHelper.internalRead(src, sizeof(result), @result); result:= reverse32(result);
end;
class function TSSPHelper.readInt64Data (src: TStream; type_: shortint): int64 ;
var temp: TByteArray8;
begin
checkType(type_, SSP_TYPE_INT_64); TSFPHelper.internalRead(src, sizeof(result), @result); result:= reverse64(result);
end;
}
class function TSSPHelper.readFloatData (src: TStream; type_: shortint): double ;
begin
case type_ of
SSP_TYPE_FLOAT_32: result:= readFloat32Data(src, type_);
SSP_TYPE_FLOAT_64: result:= readFloat64Data(src, type_);
else
raise ESSPInvalidData.create('Illegal type: ' + intToStr(type_) + '. Required types: ('
+ intToStr(SSP_TYPE_FLOAT_32) + ','
+ intToStr(SSP_TYPE_FLOAT_64) + ').'
);
end;
end;
class function TSSPHelper.readFloat32Data (src: TStream; type_: shortint): single ;
begin
checkType(type_, SSP_TYPE_FLOAT_32); pinteger(@result)^:= readInt32Data(src, SSP_TYPE_INT_32);
end;
class function TSSPHelper.readFloat64Data (src: TStream; type_: shortint): double ;
begin
checkType(type_, SSP_TYPE_FLOAT_64); pint64 (@result)^:= readInt64Data(src, SSP_TYPE_INT_64);
end;
class function TSSPHelper.readDecimalStringData(src: TStream; type_: shortint): AnsiString;
begin
checkType(type_, SSP_TYPE_DECIMAL);
setLength(result, readInt(src));
TSFPHelper.internalRead(src, length(result), pansichar(result));
end;
class function TSSPHelper.readAnyData (src: TStream; type_: shortint): ISSPAny ;
begin
case type_ of
SSP_TYPE_OBJECT : result:= readObjectData (src, type_) ;
SSP_TYPE_ARRAY : result:= readArrayData (src, type_) ;
SSP_TYPE_STRING : result:= TSSPString .create( readStringData (src, type_));
SSP_TYPE_BYTE_ARRAY: result:= TSSPByteArray.create( readByteArrayData (src, type_));
SSP_TYPE_DECIMAL : result:= TSSPDecimal .create( readDecimalStringData(src, type_));
SSP_TYPE_INT_8 : result:= TSSPInt .create(type_, readInt8Data (src, type_));
SSP_TYPE_INT_16 : result:= TSSPInt .create(type_, readInt16Data (src, type_));
SSP_TYPE_INT_32 : result:= TSSPInt .create(type_, readInt32Data (src, type_));
SSP_TYPE_INT_64 : result:= TSSPInt .create(type_, readInt64Data (src, type_));
SSP_TYPE_FLOAT_32 : result:= TSSPFloat .create(type_, readFloat32Data (src, type_));
SSP_TYPE_FLOAT_64 : result:= TSSPFloat .create(type_, readFloat64Data (src, type_));
else
raise ESSPInvalidData.create('Illegal type: ' + intToStr(type_) + '.');
end;
end;
class function TSSPHelper.readObjectData (src: TStream; type_: shortint): ISSPAny ;
var size: integer;
var i: integer;
var name: WideString;
begin
checkType(type_, SSP_TYPE_OBJECT);
size:= readInt(src);
result:= TSSPObject.create();
for i:= 0 to size - 1 do
begin
name:= readString(src);
result.add(name, readAny(src));
end;
end;
class function TSSPHelper.readArrayData (src: TStream; type_: shortint): ISSPAny ;
var size: integer;
var list: IInterfaceList;
var i: integer;
begin
checkType(type_, SSP_TYPE_ARRAY);
size:= readInt(src);
list:= TInterfaceList.create();
list.capacity:= size;
for i:= 0 to size - 1 do
list.add(readAny(src));
result:= TSSPArray.create(list);
end;
class function TSSPHelper.readByteArray (src: TStream): TByteDynArray;
begin result:= readByteArrayData (src, readType(src)); end;
class function TSSPHelper.readUTF8String (src: TStream): AnsiString ;
begin result:= readUTF8StringData (src, readType(src)); end;
class function TSSPHelper.readString (src: TStream): WideString ;
begin result:= readStringData (src, readType(src)); end;
class function TSSPHelper.readInt (src: TStream): int64 ;
begin result:= readIntData (src, readType(src)); end;
class function TSSPHelper.readInt8 (src: TStream): shortint ;
begin result:= readInt8Data (src, readType(src)); end;
class function TSSPHelper.readInt16 (src: TStream): smallint ;
begin result:= readInt16Data (src, readType(src)); end;
class function TSSPHelper.readInt32 (src: TStream): integer ;
begin result:= readInt32Data (src, readType(src)); end;
class function TSSPHelper.readInt64 (src: TStream): int64 ;
begin result:= readInt64Data (src, readType(src)); end;
class function TSSPHelper.readFloat (src: TStream): double ;
begin result:= readFloatData (src, readType(src)); end;
class function TSSPHelper.readFloat32 (src: TStream): single ;
begin result:= readFloat32Data (src, readType(src)); end;
class function TSSPHelper.readFloat64 (src: TStream): double ;
begin result:= readFloat64Data (src, readType(src)); end;
class function TSSPHelper.readDecimalString(src: TStream): AnsiString ;
begin result:= readDecimalStringData(src, readType(src)); end;
class function TSSPHelper.readAny (src: TStream): ISSPAny ;
begin result:= readAnyData (src, readType(src)); end;
class function TSSPHelper.readObject (src: TStream): ISSPAny ;
begin result:= readObjectData (src, readType(src)); end;
class function TSSPHelper.readArray (src: TStream): ISSPAny ;
begin result:= readArrayData (src, readType(src)); end;
{
TSSPWriter = class
protected
_origin: TStream;
_owned : boolean;
public
constructor create(origin: TStream; owned: boolean);
destructor destroy; override;
procedure beginObject(fieldCount: integer);
procedure endObject();
procedure beginField(fieldName: WideString);
procedure endField();
procedure beginArray(itemCount: integer);
procedure endArray();
procedure writeByteArray(size: integer; buffer: pointer);
procedure writeObject(fieldCount: integer );
procedure writeField (fieldName : WideString);
procedure writeArray (itemCount : integer );
procedure writeUTF8String (value: AnsiString);
procedure writeString (value: WideString);
procedure writeInt (value: int64 );
procedure writeInt8 (value: shortint );
procedure writeInt16 (value: smallint );
procedure writeInt32 (value: integer );
procedure writeInt64 (value: int64 );
procedure writeFloat (value: double );
procedure writeSingle (value: single );
procedure writeDouble (value: double );
procedure writeDecimal (value: double );
procedure writeDecimalString(value: AnsiString);
end;
TSSPReader = class
protected
_origin: TStream;
_owned : boolean;
public
constructor create(origin: TStream; owned: boolean);
destructor destroy; override;
function readType (): shortint ;
function readUTF8String (): AnsiString;
function readString (): WideString;
function readInt (): int64 ;
function readInt8 (): shortint ;
function readInt16 (): smallint ;
function readInt32 (): integer ;
function readInt64 (): int64 ;
function readFloat (): double ;
function readSingle (): single ;
function readDouble (): double ;
function readDecimal (): double ;
function readDecimalString(): AnsiString;
function readAny (): ISSPAny;
end;
}
function normalStrToFloat(const value: String): extended;
begin
result:= strToFloat(value, getNormalFormatSettings());
end;
function normalFloatToStr (const format: String; value: extended): String;
begin
result:= formatFloat(format, value, getNormalFormatSettings());
end;
function normalStrToFloatDef(const value: String; defaultValue: extended): extended;
begin
result:= strToFloatDef(value, defaultValue, getNormalFormatSettings());
end;
var __normalFormatSettings: TFormatSettings;
function getNormalFormatSettings(): TFormatSettings;
begin result:= __normalFormatSettings; end;
initialization
{$ifdef unix}
__normalFormatSettings:= defaultFormatSettings;
{$else}
getLocaleFormatSettings(LOCALE_USER_DEFAULT, __normalFormatSettings);
{$endif}
__normalFormatSettings.DecimalSeparator := '.';
__normalFormatSettings.ThousandSeparator:= #0;
__normalFormatSettings.DateSeparator:= '-';
__normalFormatSettings.TimeSeparator:= ':';
__normalFormatSettings.LongDateFormat:= 'yyyy-mm-dd';
__normalFormatSettings.ShortDateFormat:= 'yyyy-mm-dd';
__normalFormatSettings.LongTimeFormat:= 'hh:nn:ss.zzz';
end.
|
//******************************************************************************
//*** LUA SCRIPT FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2005 ***
//*** ***
//*** ***
//******************************************************************************
// File : Lua_Assert.pas
//
// Description : Access from Lua scripts to RunTime Debug.
//
//******************************************************************************
unit Lua_Assert;
interface
uses Lua, Classes;
procedure RegisterFunctions(L: Plua_State);
implementation
uses LuaUtils, RTDebug, SysUtils;
function LuaRTAssert(L: Plua_State): Integer; cdecl;
Var
Condition :Boolean;
TrueStr,
FalseStr :String;
NParams :Integer;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=3)
then begin
try
Condition := LuaToBoolean(L, 1);
TrueStr := LuaToString(L, 2);
FalseStr := LuaToString(L, 3);
RTAssert(0, Condition, 'Lua : '+TrueStr, 'Lua : '+FalseStr, 0);
except
On E:Exception do Result :=0;
end;
end;
end;
procedure RegisterFunctions(L: Plua_State);
begin
LuaRegister(L, 'RTAssert', LuaRTAssert);
end;
end.
|
unit NtUtils.WinUser.WinstaLock;
interface
uses
Winapi.WinNt, NtUtils.Exceptions;
// Lock/unlock current session's window station
function UsrxLockWindowStation(Lock: Boolean; Timeout: Int64 = 15000 * MILLISEC)
: TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntdef, Winapi.WinUser, Ntapi.ntldr, Ntapi.ntpebteb,
NtUtils.Ldr, NtUtils.Processes.Snapshots, NtUtils.Processes, NtUtils.Objects,
NtUtils.Shellcode, NtUtils.Threads, NtUtils.Processes.Memory;
// User32.dll has a pair of functions called LockWindowStation and
// UnlockWindowStation. Although any application can call them, only calls
// issued by a registered instance of winlogon.exe will succeed.
// So, we inject a thread to winlogon to execute this call in its context.
type
TGetProcessWindowStation = function: HWINSTA; stdcall;
TLockWindowStation = function (hWinStation: HWINSTA): LongBool; stdcall;
TRtlGetLastWin32Error = function: Cardinal; stdcall;
TUsrxLockerParam = record
GetProcessWindowStation: TGetProcessWindowStation;
LockWindowStation: TLockWindowStation;
RtlGetLastWin32Error: TRtlGetLastWin32Error;
end;
PWinStaPayload = ^TUsrxLockerParam;
// We are going to execute the following function inside winlogon, so make sure
// to use only functions and variables referenced through the Data parameter.
// Note: be consistent with the raw assembly below (the one we actually use).
function UsrxLockerPayload(Data: PWinStaPayload): NTSTATUS; stdcall;
begin
if Data.LockWindowStation(Data.GetProcessWindowStation) then
Result := STATUS_SUCCESS
else
Result := NTSTATUS_FROM_WIN32(Data.RtlGetLastWin32Error);
end;
const
// Be consistent with function code above
{$IFDEF WIN64}
UsrxLockerAsm: array [0..77] of Byte = ($55, $48, $83, $EC, $30, $48, $8B,
$EC, $48, $89, $4D, $40, $48, $8B, $45, $40, $FF, $10, $48, $89, $C1, $48,
$8B, $45, $40, $FF, $50, $08, $85, $C0, $74, $09, $C7, $45, $2C, $00, $00,
$00, $00, $EB, $1C, $48, $8B, $45, $40, $FF, $50, $10, $89, $45, $28, $8B,
$45, $28, $81, $E0, $FF, $FF, $00, $00, $81, $C8, $00, $00, $07, $C0, $89,
$45, $2C, $8B, $45, $2C, $48, $8D, $65, $30, $5D, $C3);
{$ENDIF}
{$IFDEF WIN32}
UsrxLockerAsm: array [0..62] of Byte = ($55, $8B, $EC, $83, $C4, $F8, $8B,
$45, $08, $FF, $10, $50, $8B, $45, $08, $FF, $50, $04, $85, $C0, $74, $07,
$33, $C0, $89, $45, $FC, $EB, $19, $8B, $45, $08, $FF, $50, $08, $89, $45,
$F8, $8B, $45, $F8, $25, $FF, $FF, $00, $00, $0D, $00, $00, $07, $C0, $89,
$45, $FC, $8B, $45, $FC, $59, $59, $5D, $C2, $04, $00);
{$ENDIF}
function GetLockerFunctionName(Lock: Boolean): String;
begin
if Lock then
Result := 'LockWindowStation'
else
Result := 'UnlockWindowStation';
end;
function UsrxLockerPrepare(var Data: TUsrxLockerParam; Lock: Boolean)
: TNtxStatus;
var
hUser32: HMODULE;
begin
// Winlogon always loads user32.dll, so we don't need to check it
Result := LdrxGetDllHandle(user32, hUser32);
if not Result.IsSuccess then
Exit;
Data.GetProcessWindowStation := LdrxGetProcedureAddress(hUser32,
'GetProcessWindowStation', Result);
if not Result.IsSuccess then
Exit;
Data.LockWindowStation := LdrxGetProcedureAddress(hUser32,
AnsiString(GetLockerFunctionName(Lock)), Result);
if not Result.IsSuccess then
Exit;
Data.RtlGetLastWin32Error := LdrxGetProcedureAddress(hNtdll,
'RtlGetLastWin32Error', Result);
end;
function UsrxLockWindowStation(Lock: Boolean; Timeout: Int64): TNtxStatus;
var
Param: TUsrxLockerParam;
Processes: TArray<TProcessEntry>;
hxProcess, hxThread: IHandle;
i, ind: Integer;
RemoteCode, RemoteContext: TMemory;
begin
{$IFDEF Win32}
// Winlogon always has the same bitness as the OS. So should we.
if RtlxAssertNotWoW64(Result) then
Exit;
{$ENDIF}
// Prepare the thread parameter
Result := UsrxLockerPrepare(Param, Lock);
if not Result.IsSuccess then
Exit;
// We need to find current session's winlogon
Result := NtxEnumerateProcesses(Processes);
if not Result.IsSuccess then
Exit;
NtxFilterProcessessByImage(Processes, 'winlogon.exe');
ind := -1;
for i := 0 to High(Processes) do
if Processes[i].Process.SessionId = RtlGetCurrentPeb.SessionId then
begin
ind := i;
Break;
end;
if ind = -1 then
begin
Result.Location := '[Searching for winlogon.exe]';
Result.Status := STATUS_NOT_FOUND;
Exit;
end;
// Open it
Result := NtxOpenProcess(hxProcess, Processes[ind].Process.ProcessId,
PROCESS_INJECT_CODE);
if not Result.IsSuccess then
Exit;
// Write the assembly and its context into winlogon's memory
Result := RtlxAllocWriteDataCodeProcess(hxProcess.Handle, @Param,
SizeOf(Param), RemoteContext, @UsrxLockerAsm,
SizeOf(UsrxLockerAsm), RemoteCode);
if not Result.IsSuccess then
Exit;
// Create a thread
Result := RtlxCreateThread(hxThread, hxProcess.Handle, RemoteCode.Address,
RemoteContext.Address);
if not Result.IsSuccess then
begin
NtxFreeMemoryProcess(hxProcess.Handle, RemoteCode.Address, RemoteCode.Size);
NtxFreeMemoryProcess(hxProcess.Handle, RemoteContext.Address,
RemoteContext.Size);
Exit;
end;
// Sychronize with it
Result := RtlxSyncThreadProcess(hxProcess.Handle, hxThread.Handle,
'Winlogon::' + GetLockerFunctionName(Lock), Timeout);
// Undo memory allocation
if not Result.Matches(STATUS_WAIT_TIMEOUT, 'NtWaitForSingleObject') then
begin
NtxFreeMemoryProcess(hxProcess.Handle, RemoteCode.Address, RemoteCode.Size);
NtxFreeMemoryProcess(hxProcess.Handle, RemoteContext.Address,
RemoteContext.Size);
end;
end;
end.
|
// -------------------------------------------------------------------------------
// Descrição: Soma de todos numeros inteiros no intervalo de 0-20
// -------------------------------------------------------------------------------
// Autor : Fernando Gomes
// Data : 28/08/2021
// -------------------------------------------------------------------------------
Program Soma_de_0_ate_20 ;
var
soma, i: integer;
Begin
soma :=0;
for i:=1 to 20 do
soma := soma + i;
write(soma)
End. |
unit View.List.Base;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.Base, Vcl.StdCtrls, Vcl.ExtCtrls,
Data.DB, Vcl.Grids, Vcl.DBGrids, Methods.Anonymous, System.Actions,
Vcl.ActnList, System.ImageList, Vcl.ImgList;
type
TNewRegister = procedure of object;
TEditIRegister = procedure of object;
TIndexFilter = procedure(AField: string) of object;
TFilterList = procedure(AField, AValue: string) of object;
TFillInField = procedure(AProc: TProc<string, string>) of object;
type
TEditHelper = class helper for TEdit
public
function TextLength: Integer;
end;
type
TfrmList = class(TfrmBase)
pnlFilter: TPanel;
pnlField: TPanel;
lblField: TLabel;
cbbFilterField: TComboBox;
pnlValue: TPanel;
lblVAlue: TLabel;
edtValue: TEdit;
dbgrdList: TDBGrid;
actNewItem: TAction;
actEditItem: TAction;
btnNewItem: TButton;
btnEditItem: TButton;
procedure edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actNewItemExecute(Sender: TObject);
procedure actEditItemExecute(Sender: TObject);
procedure dbgrdListDblClick(Sender: TObject);
procedure dbgrdListTitleClick(Column: TColumn);
private
FOnIndexFilter: TIndexFilter;
FOnFilterList: TFilterList;
FOnFillInField: TFillInField;
FOnNewRegister: TNewRegister;
FOnEditRegister: TEditIRegister;
procedure SetOnFilterList(const Value: TFilterList);
procedure SetOnIndexFilter(const Value: TIndexFilter);
procedure SetOnFillInField(const Value: TFillInField);
procedure SetOnEditRegister(const Value: TEditIRegister);
procedure SetOnNewRegister(const Value: TNewRegister);
protected
FFilterField: TStringList;
public
property OnNewRegister: TNewRegister read FOnNewRegister
write SetOnNewRegister;
property OnEditRegister: TEditIRegister read FOnEditRegister
write SetOnEditRegister;
property OnIndexFilter: TIndexFilter read FOnIndexFilter
write SetOnIndexFilter;
property OnFilterList: TFilterList read FOnFilterList write SetOnFilterList;
property OnFillInField: TFillInField read FOnFillInField
write SetOnFillInField;
end;
implementation
{$R *.dfm}
{ TfrmList }
procedure TfrmList.actEditItemExecute(Sender: TObject);
begin
inherited;
OnEditRegister;
end;
procedure TfrmList.actNewItemExecute(Sender: TObject);
begin
inherited;
OnNewRegister;
end;
procedure TfrmList.dbgrdListDblClick(Sender: TObject);
begin
inherited;
if actEditItem.Visible then
actEditItem.Execute;
end;
procedure TfrmList.dbgrdListTitleClick(Column: TColumn);
begin
inherited;
OnIndexFilter(Column.FieldName);
end;
procedure TfrmList.edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
if edtValue.TextLength < 1 then
begin
MessageDlg('Enter at least 1 characters', TMsgDlgType.mtInformation,
[mbYes], 0);
Exit;
end;
OnFilterList(FFilterField[cbbFilterField.ItemIndex], edtValue.Text);
end;
end;
procedure TfrmList.FormCreate(Sender: TObject);
begin
inherited;
FFilterField := TStringList.Create;
end;
procedure TfrmList.FormDestroy(Sender: TObject);
begin
inherited;
FFilterField.DisposeOf;
end;
procedure TfrmList.FormShow(Sender: TObject);
begin
inherited;
cbbFilterField.Clear;
OnFillInField(
procedure(AField, ADisplayer: string)
begin
FFilterField.Add(AField);
cbbFilterField.Items.Add(ADisplayer);
end);
cbbFilterField.ItemIndex := 0;
end;
procedure TfrmList.SetOnEditRegister(const Value: TEditIRegister);
begin
FOnEditRegister := Value;
end;
procedure TfrmList.SetOnFillInField(const Value: TFillInField);
begin
FOnFillInField := Value;
end;
procedure TfrmList.SetOnFilterList(const Value: TFilterList);
begin
FOnFilterList := Value;
end;
procedure TfrmList.SetOnIndexFilter(const Value: TIndexFilter);
begin
FOnIndexFilter := Value;
end;
procedure TfrmList.SetOnNewRegister(const Value: TNewRegister);
begin
FOnNewRegister := Value;
end;
{ TEditHelper }
function TEditHelper.TextLength: Integer;
begin
Result := Length(Text);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.Helpers;
interface
uses
System.Messaging, System.SysUtils, System.UITypes,
Androidapi.JNIBridge, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.JNI.Util, Androidapi.JNI.Os;
function JObjectToID(const AObject: JObject): Pointer; inline; deprecated 'Use TAndroidHelper.JObjectToID';
{ TBytes conversions }
/// <summary>Copy a TBytes into a new TJavaArray<Byte></summary>
function TBytesToTJavaArray(const ABytes: TBytes): TJavaArray<Byte>; inline;
/// <summary>Copy a TJavaArray<Byte> into a new TBytes</summary>
function TJavaArrayToTBytes(const AJArray: TJavaArray<Byte>): TBytes; inline;
{ Integer conversions }
function Int64ToJLong(const AValue: Int64): JLong;
{ String conversions }
/// <summary>Convert a JString into a string</summary>
function JStringToString(const JStr: JString): string; inline;
/// <summary>Convert a string into a JString</summary>
function StringToJString(const Str: string): JString; inline;
/// <summary>Convert a string into a JCharSequence</summary>
function StrToJCharSequence(const ASource: string): JCharSequence; inline;
/// <summary>Convert a JCharSequence into a string</summary>
function JCharSequenceToStr(const ASource: JCharSequence): string; inline;
/// <summary>Convert a string into a Jnet_Uri</summary>
function StrToJURI(const ASource: string): Jnet_Uri; inline;
/// <summary>Convert a Jnet_Uri into a string</summary>
function JURIToStr(const ASource: Jnet_Uri): string; inline;
/// <summary>Convert a JFile into a Jnet_Uri</summary>
/// <remarks>On Android 7.0 (Nougat) or later this requires the use of a file provider,
/// which will be available if the Secure File Sharing entitlement has been enabled</remarks>
function JFileToJURI(const AFile: JFile): Jnet_Uri; inline;
{ Shared instances }
/// <summary>Returns Java Application Context</summary>
function SharedActivityContext: JContext; inline; deprecated 'Use TAndroidHelper.Context';
/// <summary>Returns Java Application Activity</summary>
function SharedActivity: JActivity; inline; deprecated 'Use TAndroidHelper.Activity';
/// <summary>Returns Java Application Info</summary>
function SharedApplicationInfo: JApplicationInfo; inline; deprecated 'Use TAndroidHelper.Context.getApplicationInfo';
/// <summary>Returns Java Application AlarmManager</summary>
function SharedAlarmManager: JAlarmManager; inline; deprecated 'Use TAndroidHelper.AlarmManager';
/// <summary>Returns Java Application PrivatePreferences</summary>
function SharedPrivatePreferences: JSharedPreferences; inline; deprecated 'Use TAndroidHelper.PrivatePreferences';
/// <summary>Returns Java Application Title</summary>
function GetApplicationTitle: string; inline; deprecated 'Use TAndroidHelper.ApplicationTitle';
/// <summary>Returns Java Package Path</summary>
function GetPackagePath: string; inline; deprecated 'Use TAndroidHelper.PackagePath';
{ Check Available services }
/// <summary>Returns true if a given feature exists as a System Service</summary>
function HasSystemService(const AFeatureName: JString): Boolean; inline; deprecated 'Use TAndroidHelper.HasSystemService';
{ Working with Resources }
/// <summary>Returns the ID of a given resource name</summary>
function GetResourceID(const ResourceName: string): Integer; inline; deprecated 'Use TAndroidHelper.GetResourceID';
/// <summary>Returns the name of a given resource ID</summary>
function GetResourceString(const ResourceID: Integer): string; inline; deprecated 'Use TAndroidHelper.GetResourceString';
{ Display }
/// <summary>Returns the Display</summary>
function GetJDisplay: JDisplay; inline; deprecated 'Use TAndroidHelper.Display';
/// <summary>Returns the Display Metrics. The size is adjusted based on the current rotation of the display.</summary>
function GetJDisplayMetrics: JDisplayMetrics; inline; deprecated 'Use TAndroidHelper.DisplayMetrics';
type
TAndroidHelper = class
private
class var FJContext: JContext;
class var FJActivity: JActivity;
class var FJAlarmManager: JAlarmManager;
class var FJDisplay: JDisplay;
class var FJContentResolver: JContentResolver;
class var FMainHandler: JHandler;
class constructor Create;
class function GetPrivatePreferences: JSharedPreferences; static; inline;
class function GetJActivity: JActivity; static; inline;
class function GetPackagePath: string; static; inline;
class function GetApplicationTitle: string; static; inline;
class function GetMainHandler: JHandler; static; inline;
public
{ Check Available services }
class function HasSystemService(const AFeatureName: JString): Boolean; static; inline;
{ Working with Resources }
/// <summary>Returns the ID of a given resource name</summary>
class function GetResourceID(const AResourceName: string): Integer; overload; static; inline;
/// <summary>Returns the ID of a given resource name</summary>
class function GetResourceID(const AResourceName: string; const AResourceType: string): Integer; overload; static; inline;
/// <summary>Returns the name of a given resource ID</summary>
class function GetResourceString(AResourceID: Integer): string; static; inline;
{ Instances }
/// <summary>Returns Java Application Context</summary>
class property Context: JContext read FJContext;
/// <summary>Returns Java Content Resolver object of Context</summary>
class property ContentResolver: JContentResolver read FJContentResolver;
/// <summary>Returns Java Application Activity</summary>
/// <remarks>An exception will be launched if there is no activity, for example a Service</remarks>
class property Activity: JActivity read GetJActivity;
/// <summary>Returns Java Application Title</summary>
class property ApplicationTitle: string read GetApplicationTitle;
/// <summary>Returns Java Application AlarmManager</summary>
class property AlarmManager: JAlarmManager read FJAlarmManager;
/// <summary>Returns Java Application PrivatePreferences</summary>
class property PrivatePreferences: JSharedPreferences read GetPrivatePreferences;
/// <summary>Returns Java Package Path</summary>
class property PackagePath: string read GetPackagePath;
/// <summary>Returns main thread Handler</summary>
class property MainHandler: JHandler read GetMainHandler;
{ Display }
/// <summary>Returns the Display</summary>
class property Display: JDisplay read FJDisplay;
/// <summary>Returns the Display Metrics. The size is adjusted based on the current rotation of the display.</summary>
class function DisplayMetrics: JDisplayMetrics; static; inline;
{ JObject conversions }
/// <summary>Returns pointer on native Java object</summary>
class function JObjectToID(const AObject: JObject): Pointer; inline;
{ TBytes conversions }
/// <summary>Copy a TBytes into a new TJavaArray<Byte></summary>
class function TBytesToTJavaArray(const ABytes: TBytes): TJavaArray<Byte>; static; inline;
/// <summary>Copy a TJavaArray<Byte> into a new TBytes</summary>
class function TJavaArrayToTBytes(const AJArray: TJavaArray<Byte>): TBytes; static; inline;
{ String conversions }
/// <summary>Convert a JString into a string</summary>
class function JStringToString(const JStr: JString): string; static; inline;
/// <summary>Convert a string into a JString</summary>
class function StringToJString(const Str: string): JString; static;
/// <summary>Convert a string into a JCharSequence</summary>
class function StrToJCharSequence(const ASource: string): JCharSequence; static; inline;
/// <summary>Convert a JCharSequence into a string</summary>
class function JCharSequenceToStr(const ASource: JCharSequence): string; static; inline;
/// <summary>Convert a string into a Jnet_Uri</summary>
class function StrToJURI(const ASource: string): Jnet_Uri; static; inline;
/// <summary>Convert a Jnet_Uri into a string</summary>
class function JURIToStr(const ASource: Jnet_Uri): string; static; inline;
{ Files }
/// <summary>Convert a JFile into a Jnet_Uri</summary>
/// <remarks>On Android 7.0 (Nougat) or later this requires the use of a file provider,
/// which will be available if the Secure File Sharing entitlement has been enabled</remarks>
class function JFileToJURI(const AFile: JFile): Jnet_Uri; static; inline;
{ Colors }
/// <summary>Converts TAlphaColor to android color</summary>
class function AlphaColorToJColor(const AColor: TAlphaColor): Integer; static; inline;
end;
type
TMessageResultNotification = class(TMessage<JIntent>)
public
RequestCode: Integer;
ResultCode: Integer;
end;
TPermissionsRequestResultData = record
public
RequestCode: Integer;
Permissions: TJavaObjectArray<JString>;
GrantResults: TJavaArray<Integer>;
end;
TPermissionsRequestResultMessage = class(TMessage<TPermissionsRequestResultData>);
implementation
uses
System.Classes, Androidapi.Jni, Androidapi.NativeActivity, Androidapi.JNI.Support;
function JObjectToID(const AObject: JObject): Pointer; inline;
begin
Result := TJNIResolver.JavaInstanceToID(AObject);
end;
{ TBytes conversions }
function TJavaArrayToTBytes(const AJArray: TJavaArray<Byte>): TBytes;
begin
Result := TAndroidHelper.TJavaArrayToTBytes(AJArray);
end;
function TBytesToTJavaArray(const ABytes: TBytes): TJavaArray<Byte>;
begin
Result := TAndroidHelper.TBytesToTJavaArray(ABytes);
end;
{ Integer conversions }
function Int64ToJLong(const AValue: Int64): JLong;
begin
Result := TJLong.JavaClass.init(AValue);
end;
{ String conversions }
function JStringToString(const JStr: JString): string;
begin
Result := TAndroidHelper.JStringToString(JStr);
end;
function StringToJString(const Str: string): JString;
begin
Result := TAndroidHelper.StringToJString(Str);
end;
function StrToJCharSequence(const ASource: string): JCharSequence;
begin
Result := TAndroidHelper.StrToJCharSequence(ASource);
end;
function JCharSequenceToStr(const ASource: JCharSequence): string;
begin
Result := TAndroidHelper.JCharSequenceToStr(ASource);
end;
function StrToJURI(const ASource: string): Jnet_Uri;
begin
Result := TAndroidHelper.StrToJURI(ASource);
end;
function JURIToStr(const ASource: Jnet_Uri): string;
begin
Result := TAndroidHelper.JURIToStr(ASource);
end;
function JFileToJURI(const AFile: JFile): Jnet_Uri; inline;
begin
Result := TAndroidHelper.JFileToJURI(AFile);
end;
function SharedActivityContext: JContext;
begin
Result := TAndroidHelper.Context;
end;
function SharedActivity: JActivity;
begin
Result := TAndroidHelper.Activity;
end;
function SharedApplicationInfo: JApplicationInfo;
begin
Result := TAndroidHelper.Context.getApplicationInfo;
end;
function SharedAlarmManager: JAlarmManager;
begin
Result := TAndroidHelper.AlarmManager;
end;
function SharedPrivatePreferences: JSharedPreferences;
begin
Result := TAndroidHelper.PrivatePreferences;
end;
function GetApplicationTitle: string;
begin
Result := TAndroidHelper.ApplicationTitle;
end;
function GetPackagePath: string;
begin
Result := TAndroidHelper.PackagePath;
end;
function HasSystemService(const AFeatureName: JString): Boolean;
begin
Result := TAndroidHelper.HasSystemService(AFeatureName);
end;
function GetResourceID(const ResourceName: string): Integer;
begin
Result := TAndroidHelper.GetResourceID(ResourceName);
end;
function GetResourceString(const ResourceID: Integer): string;
begin
Result := TAndroidHelper.GetResourceString(ResourceID);
end;
function GetJDisplay: JDisplay;
begin
Result := TAndroidHelper.Display;
end;
function GetJDisplayMetrics: JDisplayMetrics;
begin
Result := TAndroidHelper.DisplayMetrics;
end;
{ TAndroidHelper }
class function TAndroidHelper.AlphaColorToJColor(const AColor: TAlphaColor): Integer;
begin
Result := TJColor.JavaClass.argb(TAlphaColorRec(AColor).A, TAlphaColorRec(AColor).R,
TAlphaColorRec(AColor).G, TAlphaColorRec(AColor).B);
end;
class constructor TAndroidHelper.Create;
var
WinManager: JWindowManager;
begin
FJContext := TJContext.Wrap(System.JavaContext);
if System.DelphiActivity <> nil then
begin
FJActivity := TJNativeActivity.Wrap(System.JavaContext);
WinManager := FJActivity.getWindowManager;
if WinManager <> nil then
FJDisplay := WinManager.getDefaultDisplay;
end;
FJAlarmManager := TJAlarmManager.Wrap(FJContext.getSystemService(TJContext.JavaClass.ALARM_SERVICE));
FJContentResolver := FJContext.getContentResolver;
end;
class function TAndroidHelper.DisplayMetrics: JDisplayMetrics;
begin
if Display <> nil then
begin
Result := TJDisplayMetrics.Create;
Display.getMetrics(Result);
end
else
Result := nil;
end;
class function TAndroidHelper.GetApplicationTitle: string;
begin
Result := JCharSequenceToStr(FJContext.getPackageManager.getApplicationLabel(FJContext.getApplicationInfo));
end;
class function TAndroidHelper.GetJActivity: JActivity;
begin
if System.DelphiActivity = nil then
raise Exception.Create('Activity not found, maybe you are in a service.')
else
Result := FJActivity;
end;
class function TAndroidHelper.GetMainHandler: JHandler;
begin
if FMainHandler = nil then
FMainHandler := TJHandler.JavaClass.init(TJLooper.JavaClass.getMainLooper);
Result := FMainHandler;
end;
class function TAndroidHelper.GetPackagePath: string;
begin
Result := JStringToString(FJContext.getApplicationInfo.nativeLibraryDir);
end;
class function TAndroidHelper.GetPrivatePreferences: JSharedPreferences;
begin
Result := Activity.getPreferences(TJActivity.JavaClass.MODE_PRIVATE);
end;
class function TAndroidHelper.GetResourceID(const AResourceName: string): Integer;
begin
Result := Activity.getResources.getIdentifier(StringToJString(AResourceName), nil, Activity.getPackageName);
end;
class function TAndroidHelper.GetResourceID(const AResourceName, AResourceType: string): Integer;
begin
Result := Activity.getResources.getIdentifier(StringToJString(AResourceName), StringToJString(AResourceType), Activity.getPackageName);
end;
class function TAndroidHelper.GetResourceString(AResourceID: Integer): string;
begin
Result := JStringToString(Activity.getResources.getString(AResourceID));
end;
class function TAndroidHelper.HasSystemService(const AFeatureName: JString): Boolean;
begin
Result := Context.getPackageManager.hasSystemFeature(AFeatureName);
end;
class function TAndroidHelper.JCharSequenceToStr(const ASource: JCharSequence): string;
begin
if ASource = nil then
Result := ''
else
Result := JStringToString(ASource.toString);
end;
class function TAndroidHelper.JFileToJURI(const AFile: JFile): Jnet_Uri;
var
LAuthority: JString;
begin
// If running on Android Nougat (7.0) or later, use a file provider to turn the file into a URI.
// This relies on enabling the Secure File Sharing entitlement in order to get the file provider.
if TOSVersion.Check(7) then
begin
LAuthority := Context.getApplicationContext.getPackageName.concat(StringToJString('.fileprovider'));
Result := TJFileProvider.JavaClass.getUriForFile(Context, LAuthority, AFile);
end
else
Result := TJnet_uri.JavaClass.fromFile(AFile);
end;
class function TAndroidHelper.JObjectToID(const AObject: JObject): Pointer;
begin
Result := TJNIResolver.JavaInstanceToID(AObject);
end;
class function TAndroidHelper.JStringToString(const JStr: JString): string;
begin
if JStr = nil then
Result := ''
else
Result := JNIStringToString(TJNIResolver.GetJNIEnv, JNIString((JStr as ILocalObject).GetObjectID));
end;
class function TAndroidHelper.JURIToStr(const ASource: Jnet_Uri): string;
begin
if ASource = nil then
Result := ''
else
Result := JStringToString(ASource.toString);
end;
class function TAndroidHelper.StringToJString(const Str: string): JString;
var
LocalRef: JNIObject;
PEnv: PJNIEnv;
begin
PEnv := TJNIResolver.GetJNIEnv;
LocalRef := StringToJNIString(PEnv, Str);
Result := TJString.Wrap(LocalRef);
PEnv^.DeleteLocalRef(PEnv, LocalRef);
end;
class function TAndroidHelper.StrToJCharSequence(const ASource: string): JCharSequence;
begin
Result := TJCharSequence.Wrap(StringToJString(ASource));
end;
class function TAndroidHelper.StrToJURI(const ASource: string): Jnet_Uri;
begin
Result := TJnet_Uri.JavaClass.parse(StringToJString(ASource));
end;
class function TAndroidHelper.TBytesToTJavaArray(const ABytes: TBytes): TJavaArray<Byte>;
var
LLength: Integer;
begin
LLength := Length(ABytes);
Result := TJavaArray<System.Byte>.Create(LLength);
if LLength > 0 then
Move(ABytes[0], PByte(Result.Data)^, LLength);
end;
class function TAndroidHelper.TJavaArrayToTBytes(const AJArray: TJavaArray<Byte>): TBytes;
var
LLength: Integer;
begin
if AJArray <> nil then
begin
LLength := AJArray.Length;
SetLength(Result, LLength);
if LLength > 0 then
Move(PByte(AJArray.Data)^, Result[0], LLength);
end
else
Result := nil;
end;
end.
|
unit IEC_2061107;
interface
uses Windows, GMGlobals, SysUtils;
function Iso1155LRC_CalcEx(buf: array of Byte; First, Last: int; bInvert: bool): byte;
function Iso1155LRC_Calc(buf: array of Byte; len: int): byte;
procedure IEC2061107_CRC(var buf: array of Byte; Len: int);
function IEC2061107_CheckCRC(buf: array of Byte; Len: int): bool;
const
strIEC_SOH = ' 01 ';
strIEC_ISI = ' 1F ';
strIEC_STX = ' 02 ';
strIEC_ETX = ' 03 ';
strIEC_DLE = ' 10 ';
strIEC_HT = ' 09 ';
strIEC_FF = ' 0C ';
IEC_SOH = $01;
IEC_ISI = $1F;
IEC_STX = $02;
IEC_ETX = $03;
IEC_DLE = $10;
IEC_HT = $09;
IEC_FF = $0C;
implementation
function Iso1155LRC_Calc(buf: array of Byte; len: int): byte;
begin
Result := Iso1155LRC_CalcEx(buf, 0, len - 1, true);
end;
function Iso1155LRC_CalcEx(buf: array of Byte; First, Last: int; bInvert: bool): byte;
var i: int;
begin
Result := 0;
if (First >= Length(buf)) or (Last >= Length(buf)) or (First < 0) or (Last < 0) then
begin
raise Exception.Create('Iso1155LRC_Calc - Range Check error');
end;
for i := First to Last do
Result := (Result + buf[i]) and $FF;
if bInvert then
Result := ((Result xor $FF) + 1) and $FF; // в стандарте есть. В реале почему-то не всегда требуется.
end;
procedure IEC2061107_FindCRCLimits(buf: array of Byte; len: int; var first, last: int);
var i: int;
begin
first := 0;
last := len - 1;
for i := len - 1 downto 0 do
if buf[i] = IEC_ETX then
begin
last := i;
break;
end;
for i := 0 to last - 1 do
if buf[i] in [IEC_STX, IEC_SOH] then
begin
first := i + 1;
break;
end;
end;
procedure IEC2061107_CRC(var buf: array of Byte; Len: int);
var first, last: int;
begin
if Len > Length(buf) then
begin
raise Exception.Create('IEC2061107_CRC - Range Check error');
end;
IEC2061107_FindCRCLimits(buf, Len, first, last);
buf[Len] := Iso1155LRC_CalcEx(buf, first, last, false);
end;
function IEC2061107_CheckCRC(buf: array of Byte; Len: int): bool;
var first, last: int;
begin
Result := false;
if len < 2 then Exit;
if Len > Length(buf) then
begin
raise Exception.Create('IEC2061107_CheckCRC - Range Check error');
end;
IEC2061107_FindCRCLimits(buf, Len - 1, first, last);
Result := buf[Len - 1] = Iso1155LRC_CalcEx(buf, first, last, false);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 149 O(N2) Dynamic Method
}
program
Paragraph;
uses
Graph;
const
MaxN=200;
type
List = array [1 .. MaxN + 1] of Extended;
List2 = array [1 .. MaxN + 1] of Integer;
var
Word, P : List;
Count : List2;
N, I, J, Lines : Integer;
L, S, Sigma : Extended;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(N);
Readln(L);
Readln(S);
Readln(Sigma);
for I := 1 to N do
Readln(Word[I]);
Close(Input);
Assign(Input, '');
Reset(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln(P[1] : 0 : 4);
Writeln(Lines);
Close(Output);
end;
procedure Paragraf (N2 : Integer);
function M (const N2 : Integer) : Integer;
var
I : Integer;
T : Extended;
begin
I := 1;
T := Word[N2];
while (T <= L) and (I + N2 - 1 <= N) do
begin
T := T + Sigma + Word[N2 + I];
Inc(I);
end;
Dec(I);
M := I;
end;
function Min (const A, B : Extended; var C, D, E : Integer) : Extended;
begin
if A <= B then
begin
Min := A;
E := C;
end
else
begin
Min := B;
E := D;
end;
end;
function P2 (const A, B : Integer) : Extended;
var
I : Integer;
T : Extended;
begin
T := L;
for I := A to A + B - 1 do
T := T - Word[I];
P2 := (B - 1) * Sqr(T / (B - 1) - S);
if A + B - 1 = N then
begin
T := Word[A];
for I := A + 1 to A + B - 1 do
T := T + Word[I] + S;
if T < L then
P2 := 0;
end;
end;
begin
P[N + 1] := 0;
Count[N + 1] := 0;
P[N] := 0;
Count[N] := 1;
for I := N - 1 downto 1 do
begin
P[I] := N * L;
for J := 2 to M(I) do
P[I] := Min(P[I], P[I + J] + P2(I,J), Count[I], J, Count[I]);
end;
end;
procedure Calculate;
var
grDriver, grMode: Integer;
Ss, T : Extended;
begin
grDriver := Detect;
InitGraph(grDriver, grMode,'');
SetLineStyle(0, 0, ThickWidth);
I := 1;
Lines := 0;
while I <= N do
begin
inc(Lines);
T := 0;
for J := 1 to Count[I] do
T := T + Word[I + J - 1];
if Count[I] <> 1 then Ss := (L - T) / (Count[I] - 1);
if (I + Count[I] > N) and (Ss > S) then Ss := S;
T := 0;
for J := 1 to Count[I] do
begin
line(20 + trunc(T),20 + Lines * 10,20 + trunc(T + Word[I + J - 1] - 1),20 + Lines * 10);
T := T + Word[I + J - 1] + Ss;
end;
I := I + Count[I];
end;
SetLineStyle(0, 0, NormWidth);
Setcolor(12);
Rectangle(17,21,trunc(L+24),25 + Lines * 10);
Readln;
Closegraph;
end;
begin
ReadInput;
Paragraf(1);
Calculate;
WriteOutput;
end. |
unit UnClienteListaRegistrosModelo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UnModelo, FMTBcd, DB, DBClient, Provider, SqlExpr,
{ Fluente }
Util, DataUtil, Dominio;
type
TClienteListaRegistrosModelo = class(TModelo)
protected
function GetSql: TSql; override;
public
function OrdernarPor(const Campo: string): TModelo; override;
end;
implementation
{$R *.dfm}
{ TClienteListaRegistrosModelo }
function TClienteListaRegistrosModelo.GetSql: TSql;
var
_exibirRegistrosExcluidos: Boolean;
_configuracao: string;
begin
_exibirRegistrosExcluidos := False;
_configuracao := Self.FConfiguracoes.Ler('ExibirRegistrosExcluidos');
if _configuracao = '1' then
_exibirRegistrosExcluidos := True;
if Self.FDominio = nil then
begin
Self.FDominio := TDominio.Create('ClienteListaRegistrosModelo');
Self.FDominio.Sql
.Select('CL_OID, CL_COD, CL_NOME, CL_FONE, CL_ENDER')
.From('CL')
.Where(Self.FUtil
.iff(not _exibirRegistrosExcluidos, Format('REC_STT = %s', [IntToStr(Ord(srAtivo))]), ''))
.Order('CL_OID')
.MetaDados('CL_OID IS NULL');
Self.FDominio.Campos
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CL_COD', 'Código', 15))
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CL_NOME', 'Cliente', 30))
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CL_FONE', 'Telefone', 20))
.Adicionar(TFabricaDeCampos.ObterCampoVisivel('CL_ENDER', 'Endereço', 30));
end;
Result := Self.FDominio.Sql;
end;
function TClienteListaRegistrosModelo.OrdernarPor(const Campo: string): TModelo;
begin
if Campo = 'Codigo' then
Self.cds.IndexName := 'codigo'
else
if Campo = 'Nome' then
Self.cds.IndexName := 'nome'
else
Self.cds.IndexName := '';
Result := Self;
end;
initialization
RegisterClass(TClienteListaRegistrosModelo);
end.
|
unit uMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ComCtrls,
ExtCtrls, StdCtrls, ActnList, Buttons;
type
{ TMainForm }
TMainForm = class(TForm)
ActAudioEngineDelete: TAction;
ActGenerateSubtitles: TAction;
ActionList1: TActionList;
ActTranslateEngineDelete: TAction;
BtnDelAudioEngine: TButton;
BtnDelTranslateEngine: TButton;
Button1: TSpeedButton;
CbbAudioEngines: TComboBox;
CbbInputLang: TComboBox;
CbbOutputAudioTrack: TComboBox;
CbbOutputEncoding: TComboBox;
CbbOutputLang: TComboBox;
CbbTranslateEngines: TComboBox;
ChkDoubleSubtitle: TCheckBox;
ChkEnabledTranslate: TCheckBox;
ChkMainSubtitle: TCheckBox;
ChkOutputLRCFile: TCheckBox;
ChkOutputSRTFile: TCheckBox;
ChkOutputTxtFile: TCheckBox;
ImageList1: TImageList;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
MiAppSettings: TMenuItem;
MiGitee: TMenuItem;
MiGithub: TMenuItem;
MiHelpText: TMenuItem;
MiNewAliyunAudoEngine: TMenuItem;
MiNewBaiduTranslateEngine: TMenuItem;
MiNewTencentTranslateEngine: TMenuItem;
MiOpenMediaFile: TMenuItem;
MiOSSSaveSettings: TMenuItem;
MiQQGroup: TMenuItem;
MiSponsor: TMenuItem;
MmoInpuFiles: TMemo;
MmoOutputLog: TMemo;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
Panel7: TPanel;
PmOpen: TPopupMenu;
PmNew: TPopupMenu;
PmSettings: TPopupMenu;
PmHelp: TPopupMenu;
Splitter1: TSplitter;
StatusBar1: TStatusBar;
ToolBar1: TToolBar;
TBtnOpen: TToolButton;
TBtnNew: TToolButton;
TBtnSettings: TToolButton;
TBtnHelp: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
procedure FormCreate(Sender: TObject);
procedure FormDropFiles(Sender: TObject; const FileNames: array of String);
procedure MiAppSettingsClick(Sender: TObject);
procedure MiGiteeClick(Sender: TObject);
procedure MiGithubClick(Sender: TObject);
procedure MiHelpTextClick(Sender: TObject);
procedure MiNewAliyunAudoEngineClick(Sender: TObject);
procedure MiNewBaiduTranslateEngineClick(Sender: TObject);
procedure MiNewTencentTranslateEngineClick(Sender: TObject);
procedure MiOpenMediaFileClick(Sender: TObject);
procedure MiOSSSaveSettingsClick(Sender: TObject);
procedure MiQQGroupClick(Sender: TObject);
procedure MiSponsorClick(Sender: TObject);
procedure TBtnHelpClick(Sender: TObject);
procedure TBtnNewClick(Sender: TObject);
procedure TBtnOpenClick(Sender: TObject);
procedure TBtnSettingsClick(Sender: TObject);
private
public
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.FormDropFiles(Sender: TObject;
const FileNames: array of String);
begin
end;
procedure TMainForm.MiAppSettingsClick(Sender: TObject);
begin
end;
procedure TMainForm.MiGiteeClick(Sender: TObject);
begin
//
end;
procedure TMainForm.MiGithubClick(Sender: TObject);
begin
//
end;
procedure TMainForm.MiHelpTextClick(Sender: TObject);
begin
//
end;
procedure TMainForm.MiNewAliyunAudoEngineClick(Sender: TObject);
begin
//
end;
procedure TMainForm.MiNewBaiduTranslateEngineClick(Sender: TObject);
begin
end;
procedure TMainForm.MiNewTencentTranslateEngineClick(Sender: TObject);
begin
end;
procedure TMainForm.MiOpenMediaFileClick(Sender: TObject);
begin
end;
procedure TMainForm.MiOSSSaveSettingsClick(Sender: TObject);
begin
end;
procedure TMainForm.MiQQGroupClick(Sender: TObject);
begin
end;
procedure TMainForm.MiSponsorClick(Sender: TObject);
begin
end;
procedure TMainForm.TBtnHelpClick(Sender: TObject);
begin
end;
procedure TMainForm.TBtnNewClick(Sender: TObject);
begin
end;
procedure TMainForm.TBtnOpenClick(Sender: TObject);
begin
end;
procedure TMainForm.TBtnSettingsClick(Sender: TObject);
begin
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
TBtnSettings.Click;
end;
end.
|
unit Unit1;
{
TreeView with check boxes and radio buttons.
http://delphi.about.com/library/weekly/aa092104a.htm
Here's how to add check boxes and radio buttons to a
TTreeView Delphi component. Give your applications a
more professional and smoother look.
..............................................
Zarko Gajic, BSCS
About Guide to Delphi Programming
http://delphi.about.com
how to advertise: http://delphi.about.com/library/bladvertise.htm
free newsletter: http://delphi.about.com/library/blnewsletter.htm
forum: http://forums.about.com/ab-delphi/start/
..............................................
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, StdCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeView;
ImageList1: TImageList;
Button1: TButton;
Memo1: TMemo;
tv1: TTreeView;
procedure TreeView1Click(Sender: TObject);
procedure TreeView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure TreeView1Collapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
procedure Button1Click(Sender: TObject);
procedure tv1Click(Sender: TObject);
procedure tv1Collapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
procedure tv1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
const
//ImageList.StateIndex=0 has some bugs, so we add one dummy image to position 0
cFlatUnCheck = 1;
cFlatChecked = 2;
cFlatRadioUnCheck = 3;
cFlatRadioChecked = 4;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure ToggleTreeViewCheckBoxes(Node:TTreeNode; cUnChecked, cChecked, cRadioUnchecked, cRadioChecked:integer);
var
tmp:TTreeNode;
begin
if Assigned(Node) then
begin
if Node.StateIndex = cUnChecked then
Node.StateIndex := cChecked
else if Node.StateIndex = cChecked then
Node.StateIndex := cUnChecked
else if Node.StateIndex = cRadioUnChecked then
begin
tmp := Node.Parent;
if not Assigned(tmp) then
tmp := TTreeView(Node.TreeView).Items.getFirstNode
else
tmp := tmp.getFirstChild;
while Assigned(tmp) do
begin
if (tmp.StateIndex in [cRadioUnChecked,cRadioChecked]) then
tmp.StateIndex := cRadioUnChecked;
tmp := tmp.getNextSibling;
end;
Node.StateIndex := cRadioChecked;
end; // if StateIndex = cRadioUnChecked
end; // if Assigned(Node)
end; (*ToggleTreeViewCheckBoxes*)
procedure TForm1.TreeView1Click(Sender: TObject);
var
P:TPoint;
begin
GetCursorPos(P);
P := TreeView1.ScreenToClient(P);
if (htOnStateIcon in TreeView1.GetHitTestInfoAt(P.X,P.Y)) then
ToggleTreeViewCheckBoxes(
TreeView1.Selected,
cFlatUnCheck,
cFlatChecked,
cFlatRadioUnCheck,
cFlatRadioChecked);
end;
procedure TForm1.TreeView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_SPACE) and Assigned(TreeView1.Selected) then
ToggleTreeViewCheckBoxes(TreeView1.Selected,cFlatUnCheck,cFlatChecked,cFlatRadioUnCheck,cFlatRadioChecked);
end; (*TreeView1KeyDown*)
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
begin
TreeView1.FullExpand;
TV1.FullExpand;
end; (*FormCreate*)
procedure TForm1.TreeView1Collapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
begin
AllowCollapse := false;
end; (*TreeView1Collapsing*)
procedure TForm1.Button1Click(Sender: TObject);
var
BoolResult:boolean;
tn : TTreeNode;
begin
if Assigned(TreeView1.Selected) then
begin
tn := TreeView1.Selected;
BoolResult := tn.StateIndex in [cFlatChecked,cFlatRadioChecked];
Memo1.Text := tn.Text + #13#10 + 'Selected: ' + BoolToStr(BoolResult, True);
end;
end; (*Button1Click*)
procedure TForm1.tv1Click(Sender: TObject);
var
P:TPoint;
begin
GetCursorPos(P);
P := TV1.ScreenToClient(P);
if (htOnStateIcon in TV1.GetHitTestInfoAt(P.X,P.Y)) then
ToggleTreeViewCheckBoxes(
TV1.Selected,
cFlatUnCheck,
cFlatChecked,
cFlatRadioUnCheck,
cFlatRadioChecked);
end;
procedure TForm1.tv1Collapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
begin
AllowCollapse := false;
end;
procedure TForm1.tv1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_SPACE) and Assigned(TV1.Selected) then
ToggleTreeViewCheckBoxes(TV1.Selected,cFlatUnCheck,cFlatChecked,cFlatRadioUnCheck,cFlatRadioChecked);
end; (*TreeView1KeyDown*)
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Joel Ivey
Description: Contains TRPCBroker and related components.
Unit: fDebugInfo displays information for debug mode.
Current Release: Version 1.1 Patch 65
*************************************************************** }
{ **************************************************
Changes in v1.1.65 (HGW 09/05/2015) XWB*1.1*65
1. None.
Changes in v1.1.60 (HGW 09/01/2013) XWB*1.1*60
1. None.
Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50
1. None.
************************************************** }
unit fDebugInfo;
interface
uses
{System}
SysUtils, Classes,
{WinApi}
Windows, Messages,
{Vcl}
Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TfrmDebugInfo = class(TForm)
lblDebugInfo: TLabel;
btnOK: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmDebugInfo: TfrmDebugInfo;
implementation
{$R *.DFM}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC high-level components }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Comp.Client;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.Classes, System.SysUtils, Data.DB, System.Generics.Collections, System.SyncObjs,
FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Stan.Util, FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.DApt.Column, FireDAC.DApt.Intf,
FireDAC.Comp.DataSet, FireDAC.Comp.UI, FireDAC.Stan.Option;
type
TFDCustomManager = class;
TFDCustomManagerClass = class of TFDCustomManager;
TFDCustomConnection = class;
TFDCustomConnectionClass = class of TFDCustomConnection;
TFDCustomTransaction = class;
TFDCustomEventAlerter = class;
TFDCustomCommand = class;
TFDCustomTableAdapter = class;
TFDCustomSchemaAdapter = class;
TFDCustomUpdateObject = class;
TFDLocalSQLDataSet = class;
TFDLocalSQLDataSets = class;
TFDCustomLocalSQL = class;
TFDAdaptedDataSet = class;
TFDCustomMemTable = class;
TFDRdbmsDataSet = class;
TFDCustomQuery = class;
TFDCustomStoredProc = class;
TFDManager = class;
TFDConnection = class;
TFDTransaction = class;
TFDEventAlerter = class;
TFDCommand = class;
TFDTableAdapter = class;
TFDSchemaAdapter = class;
TFDMetaInfoCommand = class;
TFDMemTable = class;
TFDQuery = class;
TFDTable = class;
TFDStoredProc = class;
TFDMetaInfoQuery = class;
TFDUpdateSQL = class;
TFDConnectionLoginEvent = procedure (AConnection: TFDCustomConnection;
AParams: TFDConnectionDefParams) of object;
TFDReconcileRowEvent = procedure (ASender: TObject; ARow: TFDDatSRow;
var Action: TFDDAptReconcileAction) of object;
TFDUpdateRowEvent = procedure (ASender: TObject; ARow: TFDDatSRow;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
var AAction: TFDErrorAction) of object;
TFDExecuteErrorEvent = procedure (ASender: TObject; ATimes, AOffset: LongInt;
AError: EFDDBEngineException; var AAction: TFDErrorAction) of object;
TFDConnectionRecoverEvent = procedure (ASender, AInitiator: TObject;
AException: Exception; var AAction: TFDPhysConnectionRecoverAction) of object;
TFDEventAlerterEvent = procedure (ASender: TFDCustomEventAlerter;
const AEventName: String; const AArgument: Variant) of object;
TFDOperationFinishedEvent = procedure (ASander: TObject; AState: TFDStanAsyncState;
AException: Exception) of object;
TFDGetDatasetEvent = procedure (ASender: TObject; const ASchemaName, AName: String;
var ADataSet: TDataSet; var AOwned: Boolean) of object;
TFDOpenDatasetEvent = procedure (ASender: TObject; const ASchemaName, AName: String;
const ADataSet: TDataSet) of object;
TFDCommandFlags = set of (ckMacros, ckLockParse, ckPrepare,
ckCreateIntfDontPrepare);
TFDBindedBy = (bbNone, bbName, bbObject);
TFDReleaseClientMode = (rmFetchAll, rmClose, rmOffline, rmDisconnect);
TFDInfoReportItems = set of (riConnDef, riFireDAC, riClientLog, riClient,
riSessionHints, riSession, riTryConnect, riKeepConnected);
TFDInfoReportStatus = set of (rsClientError, rsSessionError, rsClientWarning,
rsSessionWarning);
PFDTableBookmarkData = ^TFDTableBookmarkData;
TFDTableBookmarkData = record
FDatasetData: TFDBookmarkData;
FValuesBuffer: array of Byte;
end;
TFDCustomManager = class(TFDComponent, IFDStanOptions, IFDStanObject)
private class var
FSingletonLock: TCriticalSection;
FSingletonClass: TFDCustomManagerClass;
FSingleton: TFDCustomManager;
FSingletonOptsIntf: IFDStanOptions;
FConnectionClass: TFDCustomConnectionClass;
class constructor Create;
class destructor Destroy;
class function GetSingleton: TFDCustomManager; static;
class function GetSingletonOptsIntf: IFDStanOptions; static; inline;
private
FAutoCreated: Boolean;
FStreamedActive: Boolean;
FConnections: TFDObjList;
FBeforeStartup: TNotifyEvent;
FAfterStartup: TNotifyEvent;
FBeforeShutdown: TNotifyEvent;
FAfterShutdown: TNotifyEvent;
FLock: TMultiReadExclusiveWriteSynchronizer;
FOptionsIntf: IFDStanOptions;
FCachedConnection: TFDCustomConnection;
FActiveStoredUsage: TFDStoredActivationUsage;
function GetActive: Boolean;
function GetConnectionDefFileName: String;
function GetConnection(AIndex: Integer): TFDCustomConnection;
function GetConnectionCount: Integer;
function GetSilentMode: Boolean;
function GetWaitCursor: TFDGUIxScreenCursor;
procedure SetActive(const AValue: Boolean);
procedure SetConnectionDefFileName(const AValue: String);
procedure SetSilentMode(const AValue: Boolean);
procedure SetWaitCursor(const AValue: TFDGUIxScreenCursor);
procedure AddConnection(AConn: TFDCustomConnection);
procedure RemoveConnection(AConn: TFDCustomConnection);
procedure SetOptionsIntf(const AValue: IFDStanOptions);
function GetFetchOptions: TFDFetchOptions;
function GetFormatOptions: TFDFormatOptions;
function GetResourceOptions: TFDTopResourceOptions;
function GetUpdateOptions: TFDUpdateOptions;
procedure SetFetchOptions(const AValue: TFDFetchOptions);
procedure SetFormatOptions(const AValue: TFDFormatOptions);
procedure SetUpdateOptions(const AValue: TFDUpdateOptions);
procedure SetResourceOptions(const AValue: TFDTopResourceOptions);
function GetConnectionDefs: IFDStanConnectionDefs;
function GetState: TFDPhysManagerState;
function GetAfterLoadConnectionDefFile: TNotifyEvent;
function GetBeforeLoadConnectionDefFile: TNotifyEvent;
function GetConnectionDefAutoLoad: Boolean;
function GetConnectionDefsLoaded: Boolean;
procedure SetAfterLoadConnectionDefFile(const AValue: TNotifyEvent);
procedure SetBeforeLoadConnectionDefFile(const AValue: TNotifyEvent);
procedure SetConnectionDefAutoLoad(const AValue: Boolean);
function GetDriverDefAutoLoad: Boolean;
function GetDriverDefFileName: String;
procedure SetDriverDefAutoLoad(const AValue: Boolean);
procedure SetDriverDefFileName(const AValue: String);
function GetDriverDefs: IFDStanDefinitions;
function GetActualConnectionDefFileName: String;
function GetActualDriverDefFileName: String;
protected
// other
procedure InternalClose; virtual;
procedure InternalOpen; virtual;
function InternalAcquireConnection(AConnection: TFDCustomConnection;
const AConnectionName, AObjName: String): TFDCustomConnection; virtual;
function InternalAcquireTemporaryConnection(const AConnectionName: string): TFDCustomConnection; virtual;
procedure InternalReleaseConnection(var AConnection: TFDCustomConnection); virtual;
function InternalFindConnection(const AConnectionName: string): TFDCustomConnection; virtual;
procedure DoBeforeStartup; virtual;
procedure DoAfterStartup; virtual;
procedure DoBeforeShutdown; virtual;
procedure DoAfterShutdown; virtual;
procedure Loaded; override;
procedure CheckActive;
procedure CheckInactive;
{ IFDStanObject }
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanOptions
property OptionsIntfImpl: IFDStanOptions read FOptionsIntf implements IFDStanOptions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open;
procedure Close;
function AcquireConnection(const AConnectionName,
AObjName: String): TFDCustomConnection; overload;
function AcquireConnection(AConnection: TFDCustomConnection;
const AObjName: String): TFDCustomConnection; overload;
procedure ReleaseConnection(var AConnection: TFDCustomConnection);
procedure DropConnections;
function FindConnection(const AConnectionName: string): TFDCustomConnection;
procedure GetConnectionNames(AList: TStrings); overload;
procedure GetConnectionNames(AList: TStrings; ADriverName: string); overload;
procedure GetConnectionDefNames(AList: TStrings);
procedure GetDriverNames(AList: TStrings; AValidate: Boolean = False;
ABaseOnly: Boolean = False);
procedure GetCatalogNames(const AConnectionName, APattern: string; AList: TStrings);
procedure GetSchemaNames(const AConnectionName, ACatalogName, APattern: string;
AList: TStrings);
procedure GetTableNames(const AConnectionName, ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AFullName: Boolean = True);
procedure GetFieldNames(const AConnectionName, ACatalogName, ASchemaName,
ATableName, APattern: string; AList: TStrings);
procedure GetKeyFieldNames(const AConnectionName, ACatalogName, ASchemaName,
ATableName, APattern: string; AList: TStrings);
/// <summary> The GetIndexNames method returns list of the database table
/// indexes. AConnectionName specifies FireDAC connection definition name.
/// ACatalogName and ASchemaName specify optional database table catalog
/// and/or schema names. ATableName specifies the database table name.
/// APattern specifies optional table search pattern, which uses SQL LIKE
/// rules. After the call the AList will be filled by the database table
/// index names. </summary>
procedure GetIndexNames(const AConnectionName, ACatalogName, ASchemaName,
ATableName, APattern: string; AList: TStrings);
procedure GetPackageNames(const AConnectionName, ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AFullName: Boolean = True);
procedure GetStoredProcNames(const AConnectionName, ACatalogName, ASchemaName,
APackage, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AFullName: Boolean = True);
procedure GetGeneratorNames(const AConnectionName, ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AFullName: Boolean = True);
function IsConnectionDef(const AName: String): Boolean;
procedure AddConnectionDef(const AName, ADriver: string; AList: TStrings = nil;
APersistent: Boolean = False);
procedure DeleteConnectionDef(const AName: string);
procedure ModifyConnectionDef(const AName: string; AList: TStrings);
/// <summary> The RenameConnectionDef method renames existing AOldName
/// connection definition to ANewName. </summary>
procedure RenameConnectionDef(const AOldName, ANewName: string);
procedure GetConnectionDefParams(const AName: string; AList: TStrings);
procedure CloseConnectionDef(const AName: string);
procedure SaveConnectionDefFile;
procedure LoadConnectionDefFile;
procedure RefreshMetadataCache;
procedure RefreshConnectionDefFile;
function GetBaseDriverID(const ADriverID: String): String;
function GetBaseDriverDesc(const ADriverID: String): String;
function GetRDBMSKind(const ADriverID: String): TFDRDBMSKind;
// RO
property State: TFDPhysManagerState read GetState;
property AutoCreated: Boolean read FAutoCreated;
property ConnectionCount: Integer read GetConnectionCount;
property Connections[Index: Integer]: TFDCustomConnection read GetConnection;
property ConnectionDefs: IFDStanConnectionDefs read GetConnectionDefs;
property DriverDefs: IFDStanDefinitions read GetDriverDefs;
property ConnectionDefFileLoaded: Boolean read GetConnectionDefsLoaded;
property ActualDriverDefFileName: String read GetActualDriverDefFileName;
property ActualConnectionDefFileName: String read GetActualConnectionDefFileName;
// RW
property DriverDefFileAutoLoad: Boolean read GetDriverDefAutoLoad
write SetDriverDefAutoLoad default True;
property DriverDefFileName: String read GetDriverDefFileName
write SetDriverDefFileName;
property ConnectionDefFileAutoLoad: Boolean read GetConnectionDefAutoLoad
write SetConnectionDefAutoLoad default True;
property ConnectionDefFileName: String read GetConnectionDefFileName
write SetConnectionDefFileName;
property WaitCursor: TFDGUIxScreenCursor read GetWaitCursor
write SetWaitCursor default gcrSQLWait;
property SilentMode: Boolean read GetSilentMode write SetSilentMode default False;
property OptionsIntf: IFDStanOptions read FOptionsIntf write SetOptionsIntf;
property FetchOptions: TFDFetchOptions read GetFetchOptions write SetFetchOptions;
property FormatOptions: TFDFormatOptions read GetFormatOptions write SetFormatOptions;
property UpdateOptions: TFDUpdateOptions read GetUpdateOptions write SetUpdateOptions;
property ResourceOptions: TFDTopResourceOptions read GetResourceOptions write SetResourceOptions;
property Active: Boolean read GetActive write SetActive default False;
property ActiveStoredUsage: TFDStoredActivationUsage read FActiveStoredUsage
write FActiveStoredUsage default [auDesignTime, auRunTime];
property BeforeStartup: TNotifyEvent read FBeforeStartup write FBeforeStartup;
property AfterStartup: TNotifyEvent read FAfterStartup write FAfterStartup;
property BeforeShutdown: TNotifyEvent read FBeforeShutdown write FBeforeShutdown;
property AfterShutdown: TNotifyEvent read FAfterShutdown write FAfterShutdown;
property BeforeLoadConnectionDefFile: TNotifyEvent
read GetBeforeLoadConnectionDefFile write SetBeforeLoadConnectionDefFile;
property AfterLoadConnectionDefFile: TNotifyEvent
read GetAfterLoadConnectionDefFile write SetAfterLoadConnectionDefFile;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDManager = class(TFDCustomManager)
published
property DriverDefFileAutoLoad;
property DriverDefFileName;
property ConnectionDefFileAutoLoad;
property ConnectionDefFileName;
property WaitCursor;
property SilentMode;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property ActiveStoredUsage;
property Active;
property BeforeStartup;
property AfterStartup;
property BeforeShutdown;
property AfterShutdown;
property BeforeLoadConnectionDefFile;
property AfterLoadConnectionDefFile;
end;
TFDCustomConnection = class(TCustomConnection,
IFDStanOptions, IFDStanErrorHandler, IFDStanObject, IFDPhysConnectionRecoveryHandler,
IFDPhysTransactionStateHandler)
private
FConnectionIntf: IFDPhysConnection;
FTmpConnectionIntf: IFDPhysConnection;
FConnectionName: String;
FParams: IFDStanConnectionDef;
FRefCount: Integer;
FTemporary: Boolean;
FOnLogin: TFDConnectionLoginEvent;
FOptionsIntf: IFDStanOptions;
FTxOptions: TFDTxOptions;
FCommands: TFDObjList;
FOnError: TFDErrorEvent;
FLoginDialog: TFDGUIxLoginDialog;
FSharedCliHandle: Pointer;
FOfflined: Boolean;
FOnLost: TNotifyEvent;
FOnRestored: TNotifyEvent;
FOnRecover: TFDConnectionRecoverEvent;
[Weak] FUpdateTransaction: TFDCustomTransaction;
[Weak] FTransaction: TFDCustomTransaction;
FLastUsed: TDateTime;
FConnectedStoredUsage: TFDStoredActivationUsage;
FExecSQLCommand: IFDPhysCommand;
FExecSQLTab: TFDDatSTable;
FDisconnecting: Boolean;
FDeferredUnregs: TFDObjList;
FBeforeStartTransaction: TNotifyEvent;
FAfterStartTransaction: TNotifyEvent;
FBeforeCommit: TNotifyEvent;
FAfterCommit: TNotifyEvent;
FBeforeRollback: TNotifyEvent;
FAfterRollback: TNotifyEvent;
function GetParams: TFDConnectionDefParams;
procedure SetConnectionName(const AValue: String);
procedure SetParams(const AValue: TFDConnectionDefParams);
procedure ParamsChanging(ASender: TObject);
function GetConnectionDefName: string;
procedure SetConnectionDefName(const AValue: string);
function GetDriverName: string;
procedure SetDriverName(const AValue: string);
function GetInTransaction: Boolean;
function GetSQLBased: Boolean;
function GetCommandCount: Integer;
function GetCommands(AIndex: Integer): TFDCustomCommand;
procedure GetParentOptions(var AOpts: IFDStanOptions);
procedure SetOptionsIntf(const AValue: IFDStanOptions);
function GetFetchOptions: TFDFetchOptions;
function GetFormatOptions: TFDFormatOptions;
function GetUpdateOptions: TFDUpdateOptions;
function GetResourceOptions: TFDTopResourceOptions;
procedure SetFetchOptions(const AValue: TFDFetchOptions);
procedure SetFormatOptions(const AValue: TFDFormatOptions);
procedure SetUpdateOptions(const AValue: TFDUpdateOptions);
procedure SetResourceOptions(const AValue: TFDTopResourceOptions);
procedure SetTxOptions(const AValue: TFDTxOptions);
function GetRDBMSKind: TFDRDBMSKind;
function CnvMetaValue(const AStr: Variant; const ADefault: String = ''): String;
procedure DoInternalLogin;
function GetConnectionMetadata(AOpen: Boolean = False): IFDPhysConnectionMetadata;
procedure SetLoginDialog(const AValue: TFDGUIxLoginDialog);
function GetCliObj: Pointer;
function GetCliHandle: Pointer;
procedure SetOfflined(AValue: Boolean);
procedure AcquireDefaultTransaction(const AConnIntf: IFDPhysConnection);
procedure AcquireConnectionIntf(out AConnIntf: IFDPhysConnection);
procedure ReleaseDefaultTransaction(const AConnIntf: IFDPhysConnection);
procedure ReleaseConnectionIntf(var AConnIntf: IFDPhysConnection);
function GetMessages: EFDDBEngineException;
function BaseCreateSQL: IFDPhysCommand;
function BasePrepareSQL(const ACommand: IFDPhysCommand; const ASQL: String;
const AParams: array of Variant; const ATypes: array of TFieldType;
ABindMode: TFDParamBindMode): Boolean;
function GetConnectionMetadataIntf: IFDPhysConnectionMetadata;
function GetConnectionString: String;
procedure SetConnectionString(const AConnectionString: String);
procedure SetUserNamePassword(const AUserName, APassword: String);
function GetActualDriverID: String;
procedure PrepareConnectionDef(ACheckDef: Boolean);
procedure SetSharedCliHandle(const AValue: Pointer);
function EncodeListName(const ACatalogName, ASchemaName: String;
const ABaseField, AObjField: String; ARow: TFDDatSRow; AList: TStrings;
AFullName: Boolean): String;
function GetCurrentCatalog: String;
function GetCurrentSchema: String;
function GetState: TFDPhysConnectionState;
protected
{ IFDStanObject }
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
{ IFDStanErrorHandler }
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception); virtual;
{ IFDPhysConnectionRecoveryHandler }
procedure HandleConnectionRecover(const AInitiator: IFDStanObject;
AException: Exception; var AAction: TFDPhysConnectionRecoverAction);
procedure HandleConnectionRestored;
procedure HandleConnectionLost;
{ IFDPhysTransactionStateHandler }
procedure HandleDisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
procedure HandleTxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
// other
/// <summary> AttachClient is used internally to associate objects with
/// the connection component. Datasets call this method when they start
/// using the connection component. </summary>
procedure AttachClient(AClient: TObject);
/// <summary> DetachClient is used internally to remove objects from the
/// internal list of objects that are informed when a connection is
/// created or terminated. AClient should be an object that was previously
/// associated by a call to AttachClient. Datasets call this method when
/// they stop using the connection component. </summary>
procedure DetachClient(AClient: TObject);
procedure UnRegisterClient(AClient: TObject); override;
procedure DoConnect; override;
procedure DoDisconnect; override;
procedure DoValidateName(const AName: string); virtual;
function GetConnected: Boolean; override;
procedure SetConnected(AValue: Boolean); override;
procedure DoLogin(const AConnectionDef: IFDStanConnectionDef); virtual;
procedure DoRecover(const AInitiator: IFDStanObject; AException: Exception;
var AAction: TFDPhysConnectionRecoverAction); virtual;
procedure DoRestored; virtual;
procedure DoLost; virtual;
function GetADDataSet(AIndex: Integer): TFDDataSet;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetTransaction(const AValue: TFDCustomTransaction); virtual;
procedure SetUpdateTransaction(const AValue: TFDCustomTransaction); virtual;
// IFDStanOptions
property OptionsIntfImpl: IFDStanOptions read FOptionsIntf implements IFDStanOptions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
/// <summary> The CloneConnection method creates a clone of this connection
/// object and assigns most property values of this connection to the cloned
/// connection object. </summary>
function CloneConnection: TFDCustomConnection;
procedure Commit;
procedure CommitRetaining;
procedure Rollback;
procedure RollbackRetaining;
procedure StartTransaction;
procedure Open(const AConnectionString: String); overload;
procedure Open(const AConnectionString: String;
const AUserName: String; const APassword: String); overload;
procedure Open(const AUserName: String; const APassword: String); overload;
procedure Offline;
procedure Online;
procedure CheckOnline;
procedure CheckActive;
procedure CheckInactive;
function Ping: Boolean;
procedure AbortJob(AWait: Boolean = False);
{$IFDEF FireDAC_MONITOR_Comp}
procedure Trace(AStep: TFDMoniEventStep; ASender: TObject;
const AMsg: String; const AArgs: array of const);
{$ENDIF}
function GetInfoReport(AList: TStrings;
AItems: TFDInfoReportItems = [riConnDef .. riKeepConnected]): TFDInfoReportStatus;
procedure GetCatalogNames(const APattern: string; AList: TStrings);
procedure GetSchemaNames(const ACatalogName, APattern: string; AList: TStrings);
procedure GetTableNames(const ACatalogName, ASchemaName, APattern: string;
AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AKinds: TFDPhysTableKinds = [tkSynonym, tkTable, tkView];
AFullName: Boolean = True);
procedure GetFieldNames(const ACatalogName, ASchemaName, ATableName, APattern: string;
AList: TStrings);
procedure GetKeyFieldNames(const ACatalogName, ASchemaName, ATableName, APattern: string;
AList: TStrings);
/// <summary> The GetIndexNames method returns list of the database table
/// indexes. ACatalogName and ASchemaName specify optional database table
/// catalog and/or schema names. ATableName specifies the database table name.
/// APattern specifies optional table search pattern, which uses SQL LIKE
/// rules. After the call the AList will be filled by the database table
/// index names. </summary>
procedure GetIndexNames(const ACatalogName, ASchemaName, ATableName, APattern: string;
AList: TStrings);
procedure GetPackageNames(const ACatalogName, ASchemaName, APattern: string;
AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy];
AFullName: Boolean = True);
procedure GetStoredProcNames(const ACatalogName, ASchemaName, APackage, APattern: string;
AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy]; AFullName: Boolean = True);
procedure GetGeneratorNames(const ACatalogName, ASchemaName, APattern: string;
AList: TStrings; AScopes: TFDPhysObjectScopes = [osMy]; AFullName: Boolean = True);
procedure RefreshMetadataCache(const AObjName: String = '');
function EncodeObjectName(const ACatalogName, ASchemaName, ABaseObjectName,
AObjectName: String): String;
procedure DecodeObjectName(const AFullName: String; var ACatalogName,
ASchemaName, ABaseObjectName, AObjectName: String);
procedure CheckConnectionDef; virtual;
procedure ApplyUpdates(const ADataSets: array of TFDDataSet);
deprecated 'Use Centralized Cached Updates and TFDSchemaAdapter instead';
procedure ReleaseClients(AMode: TFDReleaseClientMode = rmDisconnect);
function GetLastAutoGenValue(const AName: String): Variant;
function ExecSQL(const ASQL: String; AIgnoreObjNotExists: Boolean = False): LongInt; overload;
function ExecSQL(const ASQL: String; const AParams: array of Variant): LongInt; overload;
function ExecSQL(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt; overload;
/// <summary> The ExecSQL method executes the specified ASQL command using
/// AParams parameter values. The method bind parameters to the SQL command
/// parameter markers by position. The method returns the number of affected
/// records. </summary>
function ExecSQL(const ASQL: String; AParams: TFDParams): LongInt; overload;
/// <summary> The ExecSQL method executes the specified ASQL command using
/// AParams parameter values. The method bind parameters to the SQL command
/// parameter markers by position. When SQL command returns a result set,
/// then AResultSet will be assigned to a dataset with the result set.
/// The method returns the number of affected records. </summary>
function ExecSQL(const ASQL: String; AParams: TFDParams; var AResultSet: TDataSet): LongInt; overload;
function ExecSQL(const ASQL: String; var AResultSet: TDataSet): LongInt; overload;
function ExecSQLScalar(const ASQL: String): Variant; overload;
function ExecSQLScalar(const ASQL: String; const AParams: array of Variant): Variant; overload;
function ExecSQLScalar(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): Variant; overload;
property IsSQLBased: Boolean read GetSQLBased;
property RDBMSKind: TFDRDBMSKind read GetRDBMSKind;
property ActualDriverID: String read GetActualDriverID;
property InTransaction: Boolean read GetInTransaction;
property DataSets[AIndex: Integer]: TFDDataSet read GetADDataSet;
property CommandCount: Integer read GetCommandCount;
property Commands[AIndex: Integer]: TFDCustomCommand read GetCommands;
property LastUsed: TDateTime read FLastUsed;
property RefCount: Integer read FRefCount;
property Messages: EFDDBEngineException read GetMessages;
/// <summary> The CurrentCatalog property returns the database session
/// current catalog. </summary>
property CurrentCatalog: String read GetCurrentCatalog;
/// <summary> The CurrentSchema property returns the database session
/// current schema. </summary>
property CurrentSchema: String read GetCurrentSchema;
/// <summary> The State property returns the current state of this
/// connection object. </summary>
property State: TFDPhysConnectionState read GetState;
property ConnectionIntf: IFDPhysConnection read FConnectionIntf;
property ConnectionMetaDataIntf: IFDPhysConnectionMetadata read GetConnectionMetadataIntf;
property CliObj: Pointer read GetCliObj;
property CliHandle: Pointer read GetCliHandle;
property SharedCliHandle: Pointer read FSharedCliHandle write SetSharedCliHandle;
property ConnectionName: String read FConnectionName write SetConnectionName;
property ConnectionDefName: String read GetConnectionDefName write SetConnectionDefName stored False;
property ConnectionString: String read GetConnectionString write SetConnectionString;
property DriverName: String read GetDriverName write SetDriverName stored False;
property Params: TFDConnectionDefParams read GetParams write SetParams;
property ResultConnectionDef: IFDStanConnectionDef read FParams;
property OptionsIntf: IFDStanOptions read FOptionsIntf write SetOptionsIntf;
property FetchOptions: TFDFetchOptions read GetFetchOptions write SetFetchOptions;
property FormatOptions: TFDFormatOptions read GetFormatOptions write SetFormatOptions;
property UpdateOptions: TFDUpdateOptions read GetUpdateOptions write SetUpdateOptions;
property ResourceOptions: TFDTopResourceOptions read GetResourceOptions write SetResourceOptions;
property TxOptions: TFDTxOptions read FTxOptions write SetTxOptions;
property Temporary: Boolean read FTemporary write FTemporary default False;
[Default(False)]
// include Connected into public section, so DOM will allow to document this property
property Connected default False;
property ConnectedStoredUsage: TFDStoredActivationUsage read FConnectedStoredUsage
write FConnectedStoredUsage default [auDesignTime, auRunTime];
property Offlined: Boolean read FOfflined write SetOfflined default False;
[Default(True)]
property LoginPrompt default True;
property LoginDialog: TFDGUIxLoginDialog read FLoginDialog write SetLoginDialog;
property Transaction: TFDCustomTransaction read FTransaction
write SetTransaction;
property UpdateTransaction: TFDCustomTransaction read FUpdateTransaction
write SetUpdateTransaction;
property OnLogin: TFDConnectionLoginEvent read FOnLogin write FOnLogin;
property OnError: TFDErrorEvent read FOnError write FOnError;
property OnLost: TNotifyEvent read FOnLost write FOnLost;
property OnRestored: TNotifyEvent read FOnRestored write FOnRestored;
property OnRecover: TFDConnectionRecoverEvent read FOnRecover write FOnRecover;
property BeforeStartTransaction: TNotifyEvent read FBeforeStartTransaction
write FBeforeStartTransaction;
property AfterStartTransaction: TNotifyEvent read FAfterStartTransaction
write FAfterStartTransaction;
property BeforeCommit: TNotifyEvent read FBeforeCommit write FBeforeCommit;
property AfterCommit: TNotifyEvent read FAfterCommit write FAfterCommit;
property BeforeRollback: TNotifyEvent read FBeforeRollback write FBeforeRollback;
property AfterRollback: TNotifyEvent read FAfterRollback write FAfterRollback;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDConnection = class(TFDCustomConnection)
published
property ConnectionDefName;
property DriverName;
property ConnectionName;
property Params;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property TxOptions;
property ConnectedStoredUsage;
property Connected;
property LoginDialog;
property LoginPrompt;
property Transaction;
property UpdateTransaction;
property OnLogin;
property OnError;
property OnLost;
property OnRestored;
property OnRecover;
property AfterConnect;
property BeforeConnect;
property AfterDisconnect;
property BeforeDisconnect;
property BeforeStartTransaction;
property AfterStartTransaction;
property BeforeCommit;
property AfterCommit;
property BeforeRollback;
property AfterRollback;
end;
TFDCustomTransaction = class(TFDComponent, IFDPhysTransactionStateHandler)
private
FTransactionIntf: IFDPhysTransaction;
FConnection: TFDCustomConnection;
FOptionsIntf: TFDTxOptions;
FDataSets: TFDObjList;
FNestingLevel: LongWord;
FSerialID: LongWord;
FBeforeStartTransaction: TNotifyEvent;
FAfterStartTransaction: TNotifyEvent;
FBeforeCommit: TNotifyEvent;
FAfterCommit: TNotifyEvent;
FBeforeRollback: TNotifyEvent;
FAfterRollback: TNotifyEvent;
function GetActive: Boolean;
function GetDataSetCount: Integer;
function GetDataSets(AIndex: Integer): TFDDataSet;
procedure SetConnection(const AValue: TFDCustomConnection);
procedure SetOptions(const AValue: TFDTxOptions);
procedure DoConnectChanged(Sender: TObject; Connecting: Boolean);
procedure InternalCreateTxIntf;
procedure InternalDeleteTxIntf;
procedure CheckReleased(ARetaining, AMyTrans: Boolean);
protected
procedure CheckConnected;
function CheckActive: Boolean;
// IFDPhysTransactionStateHandler
procedure HandleDisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
procedure HandleTxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
// other
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure StartTransaction;
procedure Commit;
procedure CommitRetaining;
procedure Rollback;
procedure RollbackRetaining;
property Active: Boolean read GetActive;
property TransactionIntf: IFDPhysTransaction read FTransactionIntf;
property DataSetCount: Integer read GetDataSetCount;
property DataSets[AIndex: Integer]: TFDDataSet read GetDataSets;
property Options: TFDTxOptions read FOptionsIntf write SetOptions;
property Connection: TFDCustomConnection read FConnection write SetConnection;
property BeforeStartTransaction: TNotifyEvent read FBeforeStartTransaction
write FBeforeStartTransaction;
property AfterStartTransaction: TNotifyEvent read FAfterStartTransaction
write FAfterStartTransaction;
property BeforeCommit: TNotifyEvent read FBeforeCommit write FBeforeCommit;
property AfterCommit: TNotifyEvent read FAfterCommit write FAfterCommit;
property BeforeRollback: TNotifyEvent read FBeforeRollback write FBeforeRollback;
property AfterRollback: TNotifyEvent read FAfterRollback write FAfterRollback;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDTransaction = class(TFDCustomTransaction)
published
property Options;
property Connection;
property BeforeStartTransaction;
property AfterStartTransaction;
property BeforeCommit;
property AfterCommit;
property BeforeRollback;
property AfterRollback;
end;
TFDCustomEventAlerter = class (TFDComponent, IFDPhysEventHandler)
private
FEventAlerterIntf: IFDPhysEventAlerter;
FConnection: TFDCustomConnection;
FNames: TStrings;
FOptionsIntf: TFDEventAlerterOptions;
FOnAlert: TFDEventAlerterEvent;
FOnTimeout: TNotifyEvent;
FStreamedActive: Boolean;
FSubscriptionName: String;
FChangeHandlers: TInterfaceList;
procedure CheckAutoRegister;
function GetActive: Boolean;
procedure SetConnection(const AValue: TFDCustomConnection);
procedure SetNames(const AValue: TStrings);
procedure SetOptions(const AValue: TFDEventAlerterOptions);
procedure DoConnectChanged(Sender: TObject; Connecting: Boolean);
procedure DoNamesChanged(ASender: TObject);
procedure SetActive(const AValue: Boolean);
procedure SetSubscriptionName(const AValue: String);
protected
// IFDPhysEventHandler
procedure HandleEvent(const AEventName: String; const AArgument: Variant);
procedure HandleTimeout(var AContinue: Boolean);
// other
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure Loaded; override;
/// <summary> Adds a change handler (eg, TFDAdaptedDataSet) to this event alerter.
/// AddChangeHandler is called automatically when TFDAdaptedDataSet.ChangeAlerter
/// is set to not nil value. </summary>
procedure AddChangeHandler(const AHandler: IFDPhysChangeHandler);
/// <summary> Removes a change handler (eg, TFDAdaptedDataSet) from this event alerter.
/// RemoveChangeHandler is called automatically when TFDAdaptedDataSet.ChangeAlerter
/// is set to nil. </summary>
procedure RemoveChangeHandler(const AHandler: IFDPhysChangeHandler);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Register;
procedure Unregister;
procedure Signal(const AEvent: String; const AArgument: Variant);
/// <summary> Refreshes the change handler (eg, TFDAdaptedDataSet) content.
/// When AForce=False, then refresh will be performed if alerter received
/// a change notification after last refreshing. When AForce=True, then
/// refresh will be performed unconditionally.
/// When AHandler=nil, then all registered change handlers will be refreshed.
/// Otherwise only specified change handler.
/// See also Options.AutoRefresh </summary>
procedure Refresh(const AHandler: IFDPhysChangeHandler; AForce: Boolean); overload;
property EventAlerterIntf: IFDPhysEventAlerter read FEventAlerterIntf;
property Active: Boolean read GetActive write SetActive default False;
property Connection: TFDCustomConnection read FConnection write SetConnection;
property Names: TStrings read FNames write SetNames;
/// <summary> Specifies a change notification subscription name.
/// The value depends on a database:
/// * InterBase - XE7 Change View subscription name
/// * SQL Server - <service>;<queue> </summary>
property SubscriptionName: String read FSubscriptionName write SetSubscriptionName;
property Options: TFDEventAlerterOptions read FOptionsIntf write SetOptions;
property OnAlert: TFDEventAlerterEvent read FOnAlert write FOnAlert;
property OnTimeout: TNotifyEvent read FOnTimeout write FOnTimeout;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDEventAlerter = class(TFDCustomEventAlerter)
published
property Active;
property Connection;
property Names;
property SubscriptionName;
property Options;
property OnAlert;
property OnTimeout;
end;
TFDCustomCommand = class(TFDComponent, IFDStanOptions, IFDStanErrorHandler,
IFDStanObject, IFDStanAsyncHandler, IFDPhysCommandStateHandler)
private
FCommandIntf: IFDPhysCommand;
FCommandText: TStrings;
FConnectionName: String;
FConnection: TFDCustomConnection;
FOptionsIntf: IFDStanOptions;
FParams: TFDParams;
FMacros: TFDMacros;
FStreamedActive, FStreamedPrepared: Boolean;
FFlags: TFDCommandFlags;
[Weak] FOwner: TFDDataSet;
FRowsAffected: TFDCounter;
FOverload: Word;
FBeforePrepare, FAfterPrepare,
FBeforeUnprepare, FAfterUnprepare,
FBeforeOpen, FAfterOpen,
FBeforeClose, FAfterClose,
FBeforeExecute, FAfterExecute,
FBeforeFetch, FAfterFetch: TNotifyEvent;
FFixedCommandKind: Boolean;
FCommandKind: TFDPhysCommandKind;
FBaseObjectName: String;
FSchemaName: String;
FCatalogName: String;
FBindedBy: TFDBindedBy;
FOnError: TFDErrorEvent;
FOnCommandChanged: TNotifyEvent;
FOperationFinished: TFDOperationFinishedEvent;
FThreadID: TThreadID;
[Weak] FTableAdapter: TFDCustomTableAdapter;
FTransaction: TFDCustomTransaction;
FActiveStoredUsage: TFDStoredActivationUsage;
function GetCommandKind: TFDPhysCommandKind;
function GetState: TFDPhysCommandState;
procedure SetConnection(const AValue: TFDCustomConnection);
procedure SetConnectionName(const AValue: String);
function GetActive: Boolean;
procedure SetActiveBase(const AValue, ABlocked: Boolean);
procedure SetActive(const AValue: Boolean);
function IsPS: Boolean;
function GetPrepared: Boolean;
procedure SetPrepared(const AValue: Boolean);
procedure CheckInactive;
procedure CheckActive;
procedure GetParentOptions(var AOpts: IFDStanOptions);
procedure SetOptionsIntf(const AValue: IFDStanOptions);
function GetFetchOptions: TFDFetchOptions;
function GetFormatOptions: TFDFormatOptions;
function GetResourceOptions: TFDBottomResourceOptions;
function GetUpdateOptions: TFDBottomUpdateOptions;
procedure SetFetchOptions(const AValue: TFDFetchOptions);
procedure SetFormatOptions(const AValue: TFDFormatOptions);
procedure SetUpdateOptions(const AValue: TFDBottomUpdateOptions);
procedure SetResourceOptions(const AValue: TFDBottomResourceOptions);
procedure DoSQLChanging(ASender: TObject);
procedure DoSQLChange(ASender: TObject);
procedure PreprocessSQL(const ASQL: String; AParams: TFDParams;
AMacrosUpd, AMacrosRead: TFDMacros; ACreateParams, ACreateMacros,
AExpandMacros, AExpandEscape, AParseSQL: Boolean;
var ACommandKind: TFDPhysCommandKind; var AFrom: String);
procedure SetCommandTextStrs(const AValue: TStrings); overload;
procedure SetCommandText(const ASQL: String; AResetParams: Boolean); overload;
procedure SetMacros(const AValue: TFDMacros);
procedure SetParams(const AValue: TFDParams);
function IsCNNS: Boolean;
function IsCNS: Boolean;
procedure SetOverload(const AValue: Word);
procedure CheckUnprepared;
procedure CheckAsyncProgress;
procedure CheckPrepared;
procedure SetCommandKind(const AValue: TFDPhysCommandKind);
procedure SetBaseObjectName(const AValue: String);
procedure SetSchemaName(const AValue: String);
function CheckComponentState(AState: TComponentState): Boolean;
procedure SetCatalogName(const AValue: String);
procedure MacrosChanged(ASender: TObject);
procedure PropertyChange;
procedure SetParamBindMode(const AValue: TFDParamBindMode);
procedure InternalCloseConnection;
function GetConnectionMetadata: IFDPhysConnectionMetadata;
procedure FetchFinished(ASender: TObject; AState: TFDStanAsyncState;
AException: Exception);
procedure WriteCollection(AWriter: TWriter; ACollection: TCollection);
procedure ReadCollection(AReader: TReader; ACollection: TCollection);
procedure ReadMacros(Reader: TReader);
procedure ReadParams(Reader: TReader);
procedure WriteMacros(Writer: TWriter);
procedure WriteParams(Writer: TWriter);
function GetParamBindMode: TFDParamBindMode;
function IsCKS: Boolean;
function GetParamsOwner: TPersistent;
function GetDisplayName: String;
function GetSQLText: String;
function GetValues(const AParamNames: String): Variant;
procedure SetValues(const AParamNames: String; const AValue: Variant);
procedure ReadPrepared(Reader: TReader);
function DoStoredActivation: Boolean;
protected
FEnableParamsStorage: Boolean;
{ IFDStanObject }
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
{ IFDStanErrorHandler }
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception); virtual;
{ IFDPhysCommandStateHandler }
procedure HandleFinished(const AInitiator: IFDStanObject;
AState: TFDStanAsyncState; AException: Exception); virtual;
procedure HandleUnprepare;
// other
procedure Loaded; override;
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure DefineProperties(AFiler: TFiler); override;
// own
procedure InternalCreateCommandIntf; virtual;
procedure InternalPrepare; virtual;
procedure InternalUnprepare; virtual;
procedure InternalOpen(ABlocked: Boolean); virtual;
procedure InternalOpenFinished(ASender: TObject; AState: TFDStanAsyncState;
AException: Exception); virtual;
procedure InternalClose(AAll: Boolean); virtual;
procedure InternalExecute(ATimes: Integer; AOffset: Integer; ABlocked: Boolean); virtual;
procedure InternalExecuteFinished(ASender: TObject; AState: TFDStanAsyncState;
AException: Exception); virtual;
procedure DoBeforePrepare; virtual;
procedure DoBeforeUnprepare; virtual;
procedure DoAfterPrepare; virtual;
procedure DoAfterUnprepare; virtual;
procedure DoBeforeOpen; virtual;
procedure DoBeforeClose; virtual;
procedure DoAfterOpen; virtual;
procedure DoAfterClose; virtual;
procedure DoAfterExecute; virtual;
procedure DoBeforeExecute; virtual;
procedure DoAfterFetch; virtual;
procedure DoBeforeFetch; virtual;
procedure SetTransaction(const AValue: TFDCustomTransaction); virtual;
// IFDStanOptions
property OptionsIntfImpl: IFDStanOptions read FOptionsIntf implements IFDStanOptions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetConnection(ACheck: Boolean): TFDCustomConnection;
function AcquireConnection: TFDCustomConnection;
procedure ReleaseConnection(var AConnection: TFDCustomConnection);
procedure FillParams(AParams: TFDParams; const ASQL: String = '');
function FindParam(const AValue: string): TFDParam;
function ParamByName(const AValue: string): TFDParam;
function FindMacro(const AValue: string): TFDMacro;
function MacroByName(const AValue: string): TFDMacro;
{$IFDEF FireDAC_MONITOR_Comp}
procedure Trace(AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
{$ENDIF}
procedure AbortJob(AWait: Boolean = False);
procedure Disconnect(AAbortJob: Boolean = False);
procedure Prepare(const ACommandText: String = '');
procedure Unprepare;
procedure Open(ABlocked: Boolean = False);
function OpenOrExecute(ABlocked: Boolean = False): Boolean;
procedure Close;
procedure CloseAll;
procedure CloseStreams;
procedure NextRecordSet;
procedure Execute(ATimes: Integer = 0; AOffset: Integer = 0; ABlocked: Boolean = False); overload;
function Execute(const ASQL: String): LongInt; overload;
function Execute(const ASQL: String; const AParams: array of Variant): LongInt; overload;
function Execute(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt; overload;
function Define(ASchema: TFDDatSManager; ATable: TFDDatSTable = nil;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset): TFDDatSTable; overload;
function Define(ATable: TFDDatSTable = nil;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode = mmReset): TFDDatSTable; overload;
procedure Fetch(ATable: TFDDatSTable; AAll: Boolean = True; ABlocked: Boolean = False); overload;
property BindedBy: TFDBindedBy read FBindedBy;
property CommandIntf: IFDPhysCommand read FCommandIntf;
property RowsAffected: TFDCounter read FRowsAffected;
property State: TFDPhysCommandState read GetState;
property SQLText: String read GetSQLText;
property DataSet: TFDDataSet read FOwner;
property OptionsIntf: IFDStanOptions read FOptionsIntf write SetOptionsIntf;
property FormatOptions: TFDFormatOptions read GetFormatOptions write SetFormatOptions;
property FetchOptions: TFDFetchOptions read GetFetchOptions write SetFetchOptions;
property ResourceOptions: TFDBottomResourceOptions read GetResourceOptions write SetResourceOptions;
property UpdateOptions: TFDBottomUpdateOptions read GetUpdateOptions write SetUpdateOptions;
property Connection: TFDCustomConnection read FConnection write SetConnection stored IsCNS;
property ConnectionName: String read FConnectionName write SetConnectionName stored IsCNNS;
property Transaction: TFDCustomTransaction read FTransaction write SetTransaction;
property CatalogName: String read FCatalogName write SetCatalogName;
property SchemaName: String read FSchemaName write SetSchemaName;
property BaseObjectName: String read FBaseObjectName write SetBaseObjectName;
property Overload: Word read FOverload write SetOverload default 0;
property Macros: TFDMacros read FMacros write SetMacros stored False;
property Params: TFDParams read FParams write SetParams stored False;
property ParamBindMode: TFDParamBindMode read GetParamBindMode
write SetParamBindMode default pbByName;
property FixedCommandKind: Boolean read FFixedCommandKind write FFixedCommandKind;
property CommandKind: TFDPhysCommandKind read GetCommandKind write SetCommandKind
stored IsCKS default skUnknown;
property CommandText: TStrings read FCommandText write SetCommandTextStrs;
property Values[const AParamNames: String]: Variant read GetValues write SetValues; default;
property Prepared: Boolean read GetPrepared write SetPrepared stored IsPS default False;
property Active: Boolean read GetActive write SetActive default False;
property ActiveStoredUsage: TFDStoredActivationUsage read FActiveStoredUsage
write FActiveStoredUsage default [auDesignTime, auRunTime];
property BeforePrepare: TNotifyEvent read FBeforePrepare write FBeforePrepare;
property AfterPrepare: TNotifyEvent read FAfterPrepare write FAfterPrepare;
property AfterUnprepare: TNotifyEvent read FAfterUnprepare write FAfterUnprepare;
property BeforeUnprepare: TNotifyEvent read FBeforeUnprepare write FBeforeUnprepare;
property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute;
property AfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute;
property BeforeClose: TNotifyEvent read FBeforeClose write FBeforeClose;
property AfterClose: TNotifyEvent read FAfterClose write FAfterClose;
property BeforeOpen: TNotifyEvent read FBeforeOpen write FBeforeOpen;
property AfterOpen: TNotifyEvent read FAfterOpen write FAfterOpen;
property BeforeFetch: TNotifyEvent read FBeforeFetch write FBeforeFetch;
property AfterFetch: TNotifyEvent read FAfterFetch write FAfterFetch;
property OnError: TFDErrorEvent read FOnError write FOnError;
property OnCommandChanged: TNotifyEvent read FOnCommandChanged write FOnCommandChanged;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDCommand = class(TFDCustomCommand)
published
property ConnectionName;
property Connection;
property Transaction;
property CatalogName;
property SchemaName;
property BaseObjectName;
property Overload;
property Params;
property Macros;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property CommandKind;
property CommandText;
property ActiveStoredUsage;
property Active;
property BeforeClose;
property BeforeOpen;
property AfterClose;
property AfterOpen;
property BeforeUnprepare;
property BeforePrepare;
property AfterUnprepare;
property AfterPrepare;
property BeforeExecute;
property AfterExecute;
property OnError;
property OnCommandChanged;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDMetaInfoCommand = class(TFDCustomCommand)
private
FWildcard: String;
FMetaInfoKind: TFDPhysMetaInfoKind;
FTableKinds: TFDPhysTableKinds;
FObjectScopes: TFDPhysObjectScopes;
procedure SetMetaInfoKind(const AValue: TFDPhysMetaInfoKind);
procedure SetTableKinds(const AValue: TFDPhysTableKinds);
procedure SetWildcard(const AValue: String);
function GetObjectName: String;
procedure SetObjectName(const AValue: String);
procedure SetObjectScopes(const AValue: TFDPhysObjectScopes);
protected
procedure InternalCreateCommandIntf; override;
procedure InternalPrepare; override;
procedure DoAfterClose; override;
public
constructor Create(AOwner: TComponent); override;
published
property Active;
property ConnectionName;
property Connection;
property FormatOptions;
property Overload;
property ObjectName: String read GetObjectName write SetObjectName;
property MetaInfoKind: TFDPhysMetaInfoKind read FMetaInfoKind
write SetMetaInfoKind default mkTables;
property TableKinds: TFDPhysTableKinds read FTableKinds
write SetTableKinds default [tkSynonym, tkTable, tkView];
property Wildcard: String read FWildcard write SetWildcard;
property ObjectScopes: TFDPhysObjectScopes read FObjectScopes
write SetObjectScopes default [osMy];
property CatalogName;
property SchemaName;
property BaseObjectName;
property BeforeClose;
property BeforeOpen;
property AfterClose;
property AfterOpen;
property OnError;
property OnCommandChanged;
end;
TFDCustomTableAdapter = class(TFDComponent, IFDStanErrorHandler,
IFDDAptUpdateHandler)
private
FTableAdapterIntf: IFDDAptTableAdapter;
FTableAdapterOwned: Boolean;
FSelectCommand: TFDCustomCommand;
FInsertCommand: TFDCustomCommand;
FUpdateCommand: TFDCustomCommand;
FDeleteCommand: TFDCustomCommand;
FLockCommand: TFDCustomCommand;
FUnLockCommand: TFDCustomCommand;
FFetchRowCommand: TFDCustomCommand;
FOnError: TFDErrorEvent;
FOnReconcileRow: TFDReconcileRowEvent;
FOnUpdateRow: TFDUpdateRowEvent;
FSchemaAdapter: TFDCustomSchemaAdapter;
[Weak] FAdaptedDataSet: TFDAdaptedDataSet;
FUpdateTransaction: TFDCustomTransaction;
procedure SetUpdateTransaction(const AValue: TFDCustomTransaction);
procedure SetDeleteCommand(const AValue: TFDCustomCommand);
procedure SetFetchRowCommand(const AValue: TFDCustomCommand);
procedure SetInsertCommand(const AValue: TFDCustomCommand);
procedure SetLockCommand(const AValue: TFDCustomCommand);
procedure SetSelectCommand(const AValue: TFDCustomCommand);
procedure SetUnLockCommand(const AValue: TFDCustomCommand);
procedure SetUpdateCommand(const AValue: TFDCustomCommand);
procedure InternalUpdateTransaction;
function InternalUpdateAdapterCmd(ACmd: TFDActionRequest): Boolean;
procedure UpdateAdapterCmd(ACmd: TFDActionRequest);
procedure UpdateAdapterCmds(const ACmds: array of TFDActionRequest);
procedure SetAdapterCmd(const ACmd: IFDPhysCommand;
ACmdKind: TFDActionRequest);
procedure SetCommand(var AVar: TFDCustomCommand;
const AValue: TFDCustomCommand; ACmdKind: TFDActionRequest);
function GetDatSTable: TFDDatSTable; inline;
function GetDatSTableName: String; inline;
function GetMetaInfoMergeMode: TFDPhysMetaInfoMergeMode; inline;
function GetSourceRecordSetID: Integer; inline;
function GetSourceRecordSetName: String; inline;
function GetUpdateTableName: String; inline;
procedure SetDatSTable(const AValue: TFDDatSTable); inline;
procedure SetDatSTableName(const AValue: String); inline;
procedure SetMetaInfoMergeMode(const AValue: TFDPhysMetaInfoMergeMode); inline;
procedure SetSourceRecordSetID(const AValue: Integer);
procedure SetSourceRecordSetName(const AValue: String);
procedure SetUpdateTableName(const AValue: String); inline;
function GetColumnMappings: TFDDAptColumnMappings; inline;
procedure SetSchemaAdapter(const AValue: TFDCustomSchemaAdapter);
function IsSRSNS: Boolean;
function GetCommand(ACmdKind: TFDActionRequest): TFDCustomCommand;
procedure SetTableAdapterIntf(const AAdapter: IFDDAptTableAdapter;
AOwned: Boolean);
procedure SetColumnMappings(const AValue: TFDDAptColumnMappings);
function IsDTNS: Boolean;
function IsUTNS: Boolean;
function IsCMS: Boolean;
function GetDatSManager: TFDDatSManager; inline;
procedure SetDatSManager(AValue: TFDDatSManager);
function GetSender: TObject;
function GetActualTransaction: TFDCustomTransaction;
function GetActualUpdateTransaction: TFDCustomTransaction;
protected
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception); virtual;
// IFDDAptUpdateHandler
procedure ReconcileRow(ARow: TFDDatSRow; var AAction: TFDDAptReconcileAction); virtual;
procedure UpdateRow(ARow: TFDDatSRow; ARequest: TFDUpdateRequest;
AUpdRowOptions: TFDUpdateRowOptions; var AAction: TFDErrorAction); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Define: TFDDatSTable;
procedure Fetch(AAll: Boolean = False); overload;
function ApplyUpdates(AMaxErrors: Integer = -1): Integer; overload;
function Reconcile: Boolean;
procedure Reset;
procedure Fetch(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AColumn: Integer; ARowOptions: TFDPhysFillRowOptions); overload;
procedure Update(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []; AForceRequest: TFDActionRequest = arFromRow); overload;
procedure Lock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []);
procedure UnLock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []);
property SchemaAdapter: TFDCustomSchemaAdapter read FSchemaAdapter
write SetSchemaAdapter;
property DataSet: TFDAdaptedDataSet read FAdaptedDataSet;
property SourceRecordSetName: String read GetSourceRecordSetName
write SetSourceRecordSetName stored IsSRSNS;
property SourceRecordSetID: Integer read GetSourceRecordSetID
write SetSourceRecordSetID default -1;
property UpdateTableName: String read GetUpdateTableName write SetUpdateTableName
stored IsUTNS;
property DatSTableName: String read GetDatSTableName write SetDatSTableName
stored IsDTNS;
property DatSTable: TFDDatSTable read GetDatSTable write SetDatSTable;
property MetaInfoMergeMode: TFDPhysMetaInfoMergeMode read GetMetaInfoMergeMode
write SetMetaInfoMergeMode default mmReset;
property DatSManager: TFDDatSManager read GetDatSManager write SetDatSManager;
property TableAdapterIntf: IFDDAptTableAdapter read FTableAdapterIntf;
property ColumnMappings: TFDDAptColumnMappings read GetColumnMappings
write SetColumnMappings stored IsCMS;
property UpdateTransaction: TFDCustomTransaction read FUpdateTransaction
write SetUpdateTransaction;
property SelectCommand: TFDCustomCommand read FSelectCommand
write SetSelectCommand;
property InsertCommand: TFDCustomCommand read FInsertCommand
write SetInsertCommand;
property UpdateCommand: TFDCustomCommand read FUpdateCommand
write SetUpdateCommand;
property DeleteCommand: TFDCustomCommand read FDeleteCommand
write SetDeleteCommand;
property LockCommand: TFDCustomCommand read FLockCommand
write SetLockCommand;
property UnLockCommand: TFDCustomCommand read FUnLockCommand
write SetUnLockCommand;
property FetchRowCommand: TFDCustomCommand read FFetchRowCommand
write SetFetchRowCommand;
property OnError: TFDErrorEvent read FOnError write FOnError;
property OnReconcileRow: TFDReconcileRowEvent read FOnReconcileRow
write FOnReconcileRow;
property OnUpdateRow: TFDUpdateRowEvent read FOnUpdateRow
write FOnUpdateRow;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDTableAdapter = class(TFDCustomTableAdapter)
published
property SchemaAdapter;
property SourceRecordSetName;
property SourceRecordSetID;
property UpdateTableName;
property DatSTableName;
property MetaInfoMergeMode;
property UpdateTransaction;
property SelectCommand;
property InsertCommand;
property UpdateCommand;
property DeleteCommand;
property LockCommand;
property UnLockCommand;
property FetchRowCommand;
property ColumnMappings;
property OnError;
property OnReconcileRow;
property OnUpdateRow;
end;
TFDCustomSchemaAdapter = class(TFDComponent, IUnknown,
IFDStanErrorHandler, IFDDAptUpdateHandler)
private
FTableAdapters: TFDObjList;
FDAptSchemaAdapter: IFDDAptSchemaAdapter;
FEncoder: TFDEncoder;
FBeforeApplyUpdate: TNotifyEvent;
FAfterApplyUpdate: TNotifyEvent;
FOnError: TFDErrorEvent;
FOnReconcileRow: TFDReconcileRowEvent;
FOnUpdateRow: TFDUpdateRowEvent;
function GetTableAdaptersIntf: IFDDAptTableAdapters; inline;
function GetDatSManager: TFDDatSManager; inline;
procedure SetDatSManager(const AValue: TFDDatSManager); inline;
function GetCount: Integer; inline;
function GetTableAdapters(AIndex: Integer): TFDCustomTableAdapter; inline;
function GetDataSets(AIndex: Integer): TFDAdaptedDataSet; inline;
function GetResourceOptions: TFDBottomResourceOptions;
procedure SetResourceOptions(const AValue: TFDBottomResourceOptions);
function GetUpdateOptions: TFDUpdateOptions;
procedure SetUpdateOptions(const AValue: TFDUpdateOptions);
procedure SaveToStorage(const AFileName: String; AStream: TStream;
AFormat: TFDStorageFormat);
procedure LoadFromStorage(const AFileName: String; AStream: TStream;
AFormat: TFDStorageFormat);
procedure StartWait;
procedure StopWait;
function GetChangeCount: Integer;
function GetSavePoint: Int64;
function GetUpdatesPending: Boolean;
procedure SetSavePoint(const AValue: Int64);
procedure CheckDataSets(ACancel: Boolean);
procedure ResyncDataSets;
procedure SetActive(AValue: Boolean);
protected
procedure DoAfterApplyUpdate(AErrors: Integer); virtual;
procedure DoBeforeApplyUpdate; virtual;
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception); virtual;
// IFDDAptUpdateHandler
procedure ReconcileRow(ARow: TFDDatSRow; var AAction: TFDDAptReconcileAction); virtual;
procedure UpdateRow(ARow: TFDDatSRow; ARequest: TFDUpdateRequest;
AUpdRowOptions: TFDUpdateRowOptions; var AAction: TFDErrorAction); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary> Open method opens all datasets associated with this schema adapter. </summary>
procedure Open;
/// <summary> Close method closes all datasets associated with this schema adapter. </summary>
procedure Close;
function ApplyUpdates(AMaxErrors: Integer = -1): Integer;
function Reconcile: Boolean;
/// <summary> CommitUpdates method marks all records in this schema adapter changes log
/// as unmodified and removes them from the changes log. </summary>
procedure CommitUpdates;
/// <summary> CancelUpdates method cancels changes for all records in this schema adapter
/// changes log and removes them from the changes log. </summary>
procedure CancelUpdates;
/// <summary> UndoLastChange method cancels last record change in this schema adapter
/// changes log and removes the record from the changes log. </summary>
function UndoLastChange: Boolean;
procedure LoadFromStream(AStream: TStream; AFormat: TFDStorageFormat = sfAuto);
procedure LoadFromFile(const AFileName: String = ''; AFormat: TFDStorageFormat = sfAuto);
procedure SaveToStream(AStream: TStream; AFormat: TFDStorageFormat = sfAuto);
procedure SaveToFile(const AFileName: String = ''; AFormat: TFDStorageFormat = sfAuto);
property DatSManager: TFDDatSManager read GetDatSManager write SetDatSManager;
property TableAdaptersIntf: IFDDAptTableAdapters read GetTableAdaptersIntf;
property TableAdapters[AIndex: Integer]: TFDCustomTableAdapter read GetTableAdapters; default;
property DataSets[AIndex: Integer]: TFDAdaptedDataSet read GetDataSets;
property Count: Integer read GetCount;
property ResourceOptions: TFDBottomResourceOptions read GetResourceOptions write SetResourceOptions;
/// <summary> UpdateOptions property returns reference to update options,
/// will be used at applying updates. </summary>
property UpdateOptions: TFDUpdateOptions read GetUpdateOptions write SetUpdateOptions;
/// <summary> SavePoint property returns current position in the changes log. When assigned,
/// then changes log will return to the state, when the value was obtained. </summary>
property SavePoint: Int64 read GetSavePoint write SetSavePoint;
/// <summary> UpdatesPending property returns True when changes log has changed rows. </summary>
property UpdatesPending: Boolean read GetUpdatesPending;
/// <summary> ChangeCount property returns the number of changes in the changes log. </summary>
property ChangeCount: Integer read GetChangeCount;
property BeforeApplyUpdate: TNotifyEvent read FBeforeApplyUpdate write FBeforeApplyUpdate;
property AfterApplyUpdate: TNotifyEvent read FAfterApplyUpdate write FAfterApplyUpdate;
property OnError: TFDErrorEvent read FOnError write FOnError;
property OnReconcileRow: TFDReconcileRowEvent read FOnReconcileRow write FOnReconcileRow;
property OnUpdateRow: TFDUpdateRowEvent read FOnUpdateRow write FOnUpdateRow;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDSchemaAdapter = class(TFDCustomSchemaAdapter)
published
property ResourceOptions;
property UpdateOptions;
property BeforeApplyUpdate;
property AfterApplyUpdate;
property OnError;
property OnReconcileRow;
property OnUpdateRow;
end;
TFDCustomUpdateObject = class(TFDComponent)
private
[Weak] FDataSet: TFDAdaptedDataSet;
procedure SetDataSet(const AValue: TFDAdaptedDataSet);
protected
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure AttachToAdapter; virtual; abstract;
procedure DetachFromAdapter; virtual; abstract;
public
procedure Apply(ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions); virtual; abstract;
property DataSet: TFDAdaptedDataSet read FDataSet write SetDataSet;
end;
TFDLocalSQLDataSet = class (TCollectionItem)
private
FDataSet: TDataSet;
FSchemaName: String;
FName: String;
FAdapter: IFDPhysLocalSQLAdapter;
FTemporary: Boolean;
FOwned: Boolean;
procedure SetSchemaName(const AValue: String);
procedure SetName(const AValue: String);
procedure SetDataSet(const AValue: TDataSet);
procedure Changing;
procedure Changed;
procedure UpdateAdapter;
function GetActualName: String;
function GetIsValid: Boolean;
procedure Vacate;
function GetActualSchemaName: String;
function GetFullName: String;
protected
function GetDisplayName: String; override;
public
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
property ActualSchemaName: String read GetActualSchemaName;
property ActualName: String read GetActualName;
property FullName: String read GetFullName;
property IsValid: Boolean read GetIsValid;
property Adapter: IFDPhysLocalSQLAdapter read FAdapter;
published
property DataSet: TDataSet read FDataSet write SetDataSet;
property SchemaName: String read FSchemaName write SetSchemaNAme;
property Name: String read FName write SetName;
property Temporary: Boolean read FTemporary write FTemporary default False;
property Owned: Boolean read FOwned write FOwned default False;
end;
TFDLocalSQLDataSets = class (TCollection)
private
[Weak] FOwner: TFDCustomLocalSQL;
function GetItems(AIndex: Integer): TFDLocalSQLDataSet;
procedure SetItems(AIndex: Integer; const AValue: TFDLocalSQLDataSet);
procedure CheckUnique(AItem: TFDLocalSQLDataSet);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TFDCustomLocalSQL);
function Add: TFDLocalSQLDataSet; overload;
function Add(ADataSet: TDataSet; const ASchemaName: String = '';
const AName: String = ''): TFDLocalSQLDataSet; overload;
procedure Remove(ADataSet: TDataSet);
procedure Vacate;
function FindDataSet(const ASchemaName, AName: String): TFDLocalSQLDataSet;
property Items[AIndex: Integer]: TFDLocalSQLDataSet read GetItems write SetItems; default;
end;
TFDCustomLocalSQL = class(TFDComponent, IFDPhysSQLHandler)
private
FSchemaName: String;
FActive: Boolean;
FStreamedActive: Boolean;
FActivated: Boolean;
FConnection: TFDCustomConnection;
FDataSets: TFDLocalSQLDataSets;
FOnGetDataSet: TFDGetDatasetEvent;
FOnOpenDataSet: TFDOpenDatasetEvent;
FOnCloseDataSet: TFDOpenDatasetEvent;
FOnReleaseDataSet: TFDGetDatasetEvent;
procedure SetSchemaName(const AValue: String);
procedure SetConnection(const AValue: TFDCustomConnection);
procedure DoConnectChanged(Sender: TObject; Connecting: Boolean);
procedure CheckDataSetAdded(const AItem: TFDLocalSQLDataSet);
procedure CheckDataSetRemoving(const AItem: TFDLocalSQLDataSet);
procedure SetActive(const AValue: Boolean);
procedure SetDataSets(const AValue: TFDLocalSQLDataSets);
procedure ReadDataSets(Reader: TReader);
procedure WriteDataSets(Writer: TWriter);
procedure ReleaseDataSet(AItem: TFDLocalSQLDataSet);
function MatchSchema(var ASchemaName: String): Boolean;
protected
// IFDPhysSQLHandler
function FindAdapter(const ASchemaName, AName: String): IFDPhysLocalSQLAdapter;
function GetDataSet(const ASchemaName, AName: String): Boolean;
procedure OpenDataSet(const ASchemaName, AName: String; ADataSet: TObject);
procedure CloseDataSet(const ASchemaName, AName: String; ADataSet: TObject);
// internal overridable
procedure InternalAttachToSQL; virtual; abstract;
procedure InternalDetachFromSQL; virtual; abstract;
procedure InternalDataSetAdded(ADataSet: TFDLocalSQLDataSet); virtual; abstract;
procedure InternalDataSetRemoving(ADataSet: TFDLocalSQLDataSet); virtual; abstract;
// user overridable
procedure DoGetDataSet(const ASchemaName, AName: String;
var ADataSet: TDataSet; var AOwned: Boolean); virtual;
procedure DoReleaseDataSet(const ASchemaName, AName: String;
var ADataSet: TDataSet; var AOwned: Boolean); virtual;
procedure DoOpenDataSet(const ASchemaName, AName: String;
const ADataSet: TDataSet); virtual;
procedure DoCloseDataSet(const ASchemaName, AName: String;
const ADataSet: TDataSet); virtual;
// other
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure DefineProperties(AFiler: TFiler); override;
procedure Loaded; override;
function GetActualActive: Boolean;
procedure CheckActivate;
procedure CheckDeactivate;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function FindDataSet(const ASchemaName, AName: String): TFDLocalSQLDataSet;
procedure RefreshDataSet(const ASchemaName, AName: String);
property SchemaName: String read FSchemaName write SetSchemaName;
property DataSets: TFDLocalSQLDataSets read FDataSets write SetDataSets stored False;
property Connection: TFDCustomConnection read FConnection write SetConnection;
property Active: Boolean read FActive write SetActive default False;
property OnGetDataSet: TFDGetDatasetEvent read FOnGetDataSet write FOnGetDataSet;
property OnReleaseDataSet: TFDGetDatasetEvent read FOnReleaseDataSet write FOnReleaseDataSet;
property OnOpenDataSet: TFDOpenDatasetEvent read FOnOpenDataSet write FOnOpenDataSet;
property OnCloseDataSet: TFDOpenDatasetEvent read FOnCloseDataSet write FOnCloseDataSet;
end;
TFDAdaptedDataSet = class(TFDDataSet, IFDPhysChangeHandler)
private
FAdapter: TFDCustomTableAdapter;
FDatSManager: TFDDatSManager;
FUpdateObject: TFDCustomUpdateObject;
FServerEditRow: TFDDatSRow;
FServerEditRequest: TFDActionRequest;
FOnExecuteError: TFDExecuteErrorEvent;
FOnError: TFDErrorEvent;
FUnpreparing: Boolean;
FForcePropertyChange: Boolean;
FLocalSQL: TFDCustomLocalSQL;
FChangeAlerter: TFDCustomEventAlerter;
FChangeAlertName: String;
FContentModified: Boolean;
FTxSupported: Integer;
procedure SetUpdateObject(const AValue: TFDCustomUpdateObject);
procedure InternalServerEdit(AServerEditRequest: TFDUpdateRequest);
function GetConnection(ACheck: Boolean): TFDCustomConnection;
function GetPointedConnection: TFDCustomConnection;
procedure InternalUpdateErrorHandler(ASender: TObject;
const AInitiator: IFDStanObject; var AException: Exception);
procedure InternalReconcileErrorHandler(ASender: TObject; ARow: TFDDatSRow;
var AAction: TFDDAptReconcileAction);
function GetCommand: TFDCustomCommand;
procedure InternalUpdateRecordHandler(ASender: TObject;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest;
AOptions: TFDUpdateRowOptions; var AAction: TFDErrorAction);
procedure SetDatSManager(AManager: TFDDatSManager);
procedure SetLocalSQL(const AValue: TFDCustomLocalSQL);
procedure SetChangeAlerter(const AValue: TFDCustomEventAlerter);
function InternalPSExecuteStatement(const ASQL: string; AParams: TParams;
AMode: Integer; var AResultSet: TFDQuery): Integer;
procedure SetChangeAlertName(const AValue: String);
protected
FVclParams: TParams;
procedure SetAdapter(AAdapter: TFDCustomTableAdapter);
// TComponent
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
// TDataSet
procedure InternalClose; override;
// TFDDataSet
procedure CheckOnline(APrepare: Boolean = True); override;
procedure ReleaseBase(AOffline: Boolean); override;
procedure DoDefineDatSManager; override;
procedure DoOpenSource(ABlocked, AInfoQuery, AStructQuery: Boolean); override;
function DoIsSourceOpen: Boolean; override;
function DoIsSourceAsync: Boolean; override;
function DoIsSourceOnline: Boolean; override;
procedure DoPrepareSource; override;
procedure DoUnprepareSource; override;
function DoApplyUpdates(ATable: TFDDatSTable; AMaxErrors: Integer): Integer; override;
function DoFetch(ATable: TFDDatSTable; AAll: Boolean;
ADirection: TFDFetchDirection = fdDown): Integer; overload; override;
function DoFetch(ARow: TFDDatSRow; AColumn: Integer;
ARowOptions: TFDPhysFillRowOptions): Boolean; overload; override;
procedure DoMasterClearDetails(AAll: Boolean); override;
procedure DoMasterDefined; override;
procedure DoMasterParamSetValues(AMasterFieldList: TFDFieldList); override;
function DoMasterParamDependent(AMasterFieldList: TFDFieldList): Boolean; override;
procedure DoCloseSource; override;
procedure DoResetDatSManager; override;
procedure DoResetAtLoading; override;
function DoGetDatSManager: TFDDatSManager; override;
function DoGetTableName: String; override;
procedure DoProcessUpdateRequest(ARequest: TFDUpdateRequest;
AOptions: TFDUpdateRowOptions); override;
procedure DoExecuteSource(ATimes, AOffset: Integer); override;
procedure DoCloneCursor(AReset, AKeepSettings: Boolean); override;
function GetParams: TFDParams; override;
function DoStoredActivation: Boolean; override;
property UpdateObject: TFDCustomUpdateObject read FUpdateObject
write SetUpdateObject;
// IFDStanOptions
function GetOptionsIntf: IFDStanOptions; override;
procedure SetOptionsIntf(const AValue: IFDStanOptions); override;
// IFDPhysLocalSQLAdapter
function GetConn: NativeUInt; override;
function GetFeatures: TFDPhysLocalSQLAdapterFeatures; override;
// IProviderSupport
{$WARN SYMBOL_DEPRECATED OFF}
function PSInTransaction: Boolean; override;
procedure PSStartTransaction; override;
procedure PSEndTransaction(Commit: Boolean); override;
function PSIsSQLBased: Boolean; override;
function PSIsSQLSupported: Boolean; override;
function PSGetQuoteChar: string; override;
function PSGetParams: TParams; override;
procedure PSSetParams(AParams: TParams); override;
function PSGetCommandText: string; override;
function PSGetCommandType: TPSCommandType; override;
procedure PSSetCommandText(const CommandText: string); override;
function PSExecuteStatement(const ASQL: string; AParams: TParams;
AResultSet: Pointer): Integer; overload; {$IFNDEF NEXTGEN} override; {$ENDIF}
function PSExecuteStatement(const ASQL: string; AParams: TParams;
var AResultSet: TDataSet): Integer; overload; override;
function PSExecuteStatement(const ASQL: string;
AParams: TParams): Integer; overload; override;
procedure PSGetAttributes(AList: TPacketAttributeList); override;
{$WARN SYMBOL_DEPRECATED ON}
// IFDPhysChangeHandler
function GetTrackCommand: IFDPhysCommand;
function GetTrackEventName: String;
function GetMergeTable: TFDDatSTable;
function GetMergeManager: TFDDatSManager;
function GetContentModified: Boolean;
procedure SetContentModified(AValue: Boolean);
procedure RefreshContent;
procedure ResyncContent;
// IDataSetCommandSupport
function GetCommandStates(const ACommand: String): TDataSetCommandStates; override;
procedure ExecuteCommand(const ACommand: String; const AArgs: array of const); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AttachTable(ATable: TFDDatSTable; AView: TFDDatSView); override;
procedure NextRecordSet;
procedure GetResults;
procedure CloseStreams;
procedure AbortJob(AWait: Boolean = False);
procedure Disconnect(AAbortJob: Boolean = False); override;
procedure ServerAppend;
procedure ServerEdit;
procedure ServerDelete;
procedure ServerPerform;
procedure ServerCancel;
procedure ServerDeleteAll(ANoUndo: Boolean = False); virtual;
procedure ServerSetKey;
function ServerGotoKey: Boolean;
property Adapter: TFDCustomTableAdapter read FAdapter;
property DatSManager write SetDatSManager;
property Command: TFDCustomCommand read GetCommand;
property PointedConnection: TFDCustomConnection read GetPointedConnection;
property ServerEditRequest: TFDActionRequest read FServerEditRequest;
property LocalSQL: TFDCustomLocalSQL read FLocalSQL write SetLocalSQL;
/// <summary> Associates dataset (change handler) with specified change alerter.
/// The dataset will be refreshed automatically on receiving change notification
/// by specified change alerter. A change notification name must match to
/// ChangeAlertName value. </summary>
property ChangeAlerter: TFDCustomEventAlerter read FChangeAlerter write SetChangeAlerter;
/// <summary> Specifies optional change notification name. By default it is
/// equal to a SQL query base table name. </summary>
property ChangeAlertName: String read FChangeAlertName write SetChangeAlertName;
property OnExecuteError: TFDExecuteErrorEvent read FOnExecuteError
write FOnExecuteError;
property OnError: TFDErrorEvent read FOnError write FOnError;
{ TFDDataSet }
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
end;
TFDCustomMemTable = class(TFDAdaptedDataSet)
private
FOptionsIntf: IFDStanOptions;
procedure ReadAutoCommitUpdates(AReader: TReader);
function GetDisableStringTrim: Boolean;
function GetFetchOnDemand: Boolean;
function GetIsClone: Boolean;
function GetLogChanges: Boolean;
function GetProviderEOF: Boolean;
function GetReadOnly: Boolean;
function GetStatusFilter: TFDUpdateRecordTypes;
function GetXMLData: string;
procedure SetDisableStringTrim(const AValue: Boolean);
procedure SetFetchOnDemand(const AValue: Boolean);
procedure SetLogChanges(const AValue: Boolean);
procedure SetProviderEOF(const AValue: Boolean);
procedure SetReadOnly(const AValue: Boolean);
procedure SetStatusFilter(const AValue: TFDUpdateRecordTypes);
procedure SetXMLData(const AValue: string);
function GetCommandText: String;
procedure SetCommandText(const AValue: String);
function GetFileName: string;
function GetPacketRecords: Integer;
procedure SetFileName(const AValue: string);
procedure SetPacketRecords(const AValue: Integer);
function GetOptionalParamTab: TFDDatSTable;
protected
FStoreDefs: Boolean;
procedure DefineProperties(AFiler: TFiler); override;
// TFDDataSet
procedure DefChanged(ASender: TObject); override;
function GetExists: Boolean; override;
function SaveToDFM(const AAncestor: TFDDataSet): Boolean; override;
property StoreDefs: Boolean read FStoreDefs write FStoreDefs default False;
// IFDStanOptions
function GetOptionsIntf: IFDStanOptions; override;
procedure GetParentOptions(var AOpts: IFDStanOptions);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Adapter write SetAdapter;
// TClientDataSet compatibility
procedure AppendData(const AData: IFDDataSetReference; AHitEOF: Boolean = True);
function ConstraintsDisabled: Boolean; inline;
procedure MergeChangeLog; inline;
function GetOptionalParam(const AParamName: string): Variant;
procedure SetOptionalParam(const AParamName: string; const AValue: Variant;
AIncludeInDelta: Boolean = False); virtual;
// Using Get/Set here prevents from Code Completion bug, when it does not
// check parent class for a field existence and adds the field to this class.
property IsClone: Boolean read GetIsClone;
property CommandText: String read GetCommandText write SetCommandText;
property DisableStringTrim: Boolean read GetDisableStringTrim write SetDisableStringTrim;
property FetchOnDemand: Boolean read GetFetchOnDemand write SetFetchOnDemand;
property FileName: string read GetFileName write SetFileName;
property LogChanges: Boolean read GetLogChanges write SetLogChanges;
property PacketRecords: Integer read GetPacketRecords write SetPacketRecords;
property ProviderEOF: Boolean read GetProviderEOF write SetProviderEOF;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property StatusFilter: TFDUpdateRecordTypes read GetStatusFilter write SetStatusFilter;
property XMLData: string read GetXMLData write SetXMLData;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDMemTable = class(TFDCustomMemTable)
published
property ActiveStoredUsage;
{ TDataSet }
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
property FieldOptions;
property Filtered;
property FilterOptions;
property Filter;
property OnFilterRecord;
property ObjectView default True;
property Constraints;
property DataSetField;
property FieldDefs stored FStoreDefs;
{ TFDDataSet }
property CachedUpdates;
property FilterChanges;
property IndexDefs stored FStoreDefs;
property Indexes;
property IndexesActive;
property IndexName;
property IndexFieldNames;
property Aggregates;
property AggregatesActive;
property ConstraintsEnabled;
property MasterSource;
property MasterFields;
property DetailFields;
property OnUpdateRecord;
property OnUpdateError;
property OnReconcileError;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property AfterGetRecord;
property BeforeRowRequest;
property AfterRowRequest;
property BeforeExecute;
property AfterExecute;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
{ TFDAdaptedDataSet }
property LocalSQL;
property ChangeAlerter;
property ChangeAlertName;
{ TFDCustomMemTable }
property Adapter;
property StoreDefs;
end;
TFDRdbmsDataSet = class(TFDAdaptedDataSet)
private
FStreamedPrepared: Boolean;
function GetConnection: TFDCustomConnection;
function GetConnectionName: String;
procedure SetConnection(const AValue: TFDCustomConnection);
procedure SetConnectionName(const AValue: String);
function GetPrepared: Boolean;
procedure SetPrepared(const AValue: Boolean);
function IsCNNS: Boolean;
function IsCNS: Boolean;
function GetOnError: TFDErrorEvent;
procedure SetOnError(const AValue: TFDErrorEvent);
function GetParamBindMode: TFDParamBindMode;
procedure SetParamBindMode(const AValue: TFDParamBindMode);
function GetOnCommandChanged: TNotifyEvent;
procedure SetOnCommandChanged(const AValue: TNotifyEvent);
function GetMacrosCount: Integer;
function GetMacros: TFDMacros;
procedure SetMacros(const AValue: TFDMacros);
function IsPS: Boolean;
function GetRowsAffected: TFDCounter;
function GetTransaction: TFDCustomTransaction;
function GetUpdateTransaction: TFDCustomTransaction;
function GetSchemaAdapter: TFDCustomSchemaAdapter;
procedure SetSchemaAdapter(const AValue: TFDCustomSchemaAdapter);
protected
procedure Loaded; override;
procedure DefineProperties(AFiler: TFiler); override;
// TDataSet
procedure InternalClose; override;
procedure OpenCursor(InfoQuery: Boolean); override;
procedure CheckCachedUpdatesMode; override;
procedure ReleaseBase(AOffline: Boolean); override;
procedure DoAfterOpenOrExecute; override;
// IProviderSupport
{$WARN SYMBOL_DEPRECATED OFF}
function PSGetCommandType: TPSCommandType; override;
{$WARN SYMBOL_DEPRECATED ON}
// introduced
function InternalCreateAdapter: TFDCustomTableAdapter; virtual;
procedure SetTransaction(const AValue: TFDCustomTransaction); virtual;
procedure SetUpdateTransaction(const AValue: TFDCustomTransaction); virtual;
// props
property ParamBindMode: TFDParamBindMode read GetParamBindMode write SetParamBindMode default pbByName;
property Macros: TFDMacros read GetMacros write SetMacros stored False;
property MacroCount: Integer read GetMacrosCount;
property RowsAffected: TFDCounter read GetRowsAffected;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Disconnect(AAbortJob: Boolean = False); override;
procedure Prepare;
procedure Unprepare;
procedure Open(const ASQL: String); overload;
procedure Open(const ASQL: String; const AParams: array of Variant); overload;
procedure Open(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType); overload;
function MacroByName(const AValue: string): TFDMacro;
function FindMacro(const AValue: string): TFDMacro;
property ConnectionName: String read GetConnectionName write SetConnectionName stored IsCNNS;
property Connection: TFDCustomConnection read GetConnection write SetConnection stored IsCNS;
property Prepared: Boolean read GetPrepared write SetPrepared stored IsPS default False;
property Transaction: TFDCustomTransaction read GetTransaction write SetTransaction;
property UpdateTransaction: TFDCustomTransaction read GetUpdateTransaction write SetUpdateTransaction;
property SchemaAdapter: TFDCustomSchemaAdapter read GetSchemaAdapter write SetSchemaAdapter;
property OnError: TFDErrorEvent read GetOnError write SetOnError;
property OnCommandChanged: TNotifyEvent read GetOnCommandChanged write SetOnCommandChanged;
{ TFDDataSet }
property Params;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDUpdateSQL = class(TFDCustomUpdateObject)
private
FCommands: array [0 .. 5] of TFDCustomCommand;
FConnectionName: String;
FConnection: TFDCustomConnection;
function GetSQL(const AIndex: Integer): TStrings;
procedure SetSQL(const AIndex: Integer; const AValue: TStrings);
function GetCommand(ARequest: TFDUpdateRequest): TFDCustomCommand;
function GetURSQL(ARequest: TFDUpdateRequest): TStrings;
procedure SetURSQL(ARequest: TFDUpdateRequest; const Value: TStrings);
procedure SetConnection(const Value: TFDCustomConnection);
procedure SetConnectionName(const Value: String);
procedure UpdateAdapter;
protected
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure AttachToAdapter; override;
procedure DetachFromAdapter; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Apply(ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions); override;
property Commands[ARequest: TFDUpdateRequest]: TFDCustomCommand read GetCommand;
property SQL[ARequest: TFDUpdateRequest]: TStrings read GetURSQL write SetURSQL;
published
property Connection: TFDCustomConnection read FConnection write SetConnection;
property ConnectionName: String read FConnectionName write SetConnectionName;
property InsertSQL: TStrings index 0 read GetSQL write SetSQL;
property ModifySQL: TStrings index 1 read GetSQL write SetSQL;
property DeleteSQL: TStrings index 2 read GetSQL write SetSQL;
property LockSQL: TStrings index 3 read GetSQL write SetSQL;
property UnlockSQL: TStrings index 4 read GetSQL write SetSQL;
property FetchRowSQL: TStrings index 5 read GetSQL write SetSQL;
end;
TFDCustomQuery = class(TFDRdbmsDataSet)
private
procedure SetSQL(const AValue: TStrings);
function GetSQL: TStrings;
function GetText: String;
function GetDS: TDataSource;
procedure SetDS(const AValue: TDataSource);
procedure ReadDataSource(AReader: TReader);
procedure ReadCommandText(AReader: TReader);
protected
procedure UpdateRecordCount; override;
procedure DefineProperties(AFiler: TFiler); override;
public
constructor Create(AOwner: TComponent); override;
procedure ExecSQL; overload;
function ExecSQL(AExecDirect: Boolean): LongInt; overload;
function ExecSQL(const ASQL: String): LongInt; overload;
function ExecSQL(const ASQL: String; const AParams: array of Variant): LongInt; overload;
function ExecSQL(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt; overload;
property SQL: TStrings read GetSQL write SetSQL;
property Text: String read GetText;
property ParamCount;
property DataSource: TDataSource read GetDS write SetDS;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDQuery = class(TFDCustomQuery)
public
property RowsAffected;
property MacroCount;
published
property ActiveStoredUsage;
{ TDataSet }
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
property FieldOptions;
property Filtered;
property FilterOptions;
property Filter;
property OnFilterRecord;
property ObjectView default True;
property Constraints;
{ TFDDataSet }
property CachedUpdates;
property FilterChanges;
property Indexes;
property IndexesActive;
property IndexName;
property IndexFieldNames;
property Aggregates;
property AggregatesActive;
property ConstraintsEnabled;
property MasterSource;
property MasterFields;
property DetailFields;
property OnUpdateRecord;
property OnUpdateError;
property OnReconcileError;
property BeforeExecute;
property AfterExecute;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property AfterGetRecord;
property BeforeRowRequest;
property AfterRowRequest;
property OnMasterSetValues;
{ TFDAdaptedDataSet }
property LocalSQL;
property ChangeAlerter;
property ChangeAlertName;
{ TFDRdbmsDataSet }
property ConnectionName;
property Connection;
property Transaction;
property UpdateTransaction;
property SchemaAdapter;
property Params;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property UpdateObject;
property OnError;
property OnExecuteError;
property OnCommandChanged;
{ TFDCustomQuery }
property SQL;
property Macros;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDTable = class(TFDCustomQuery)
private
FWindowSize: Integer;
FServerCursor: Boolean;
FTableName: String;
FExclusive: Boolean;
FCatalogName: String;
FSchemaName: String;
FTableParams: TFDPhysTableParams;
FWindowOperation: Boolean;
FPrimaryKeyFields: String;
FResetIndexFieldNames: Boolean;
FIndexFieldChanged: Boolean;
procedure MoveData(ATableSrc, ATableDst: TFDDatSTable);
procedure TableChanged;
procedure SetTableName(const AValue: String);
procedure SetCatalogName(const AValue: String);
procedure SetSchemaName(const AValue: String);
function GetColSize(ACol: TFDDatSColumn): LongWord;
function GetBookmarkColSize(ACol: TFDDatSColumn): LongWord;
function Bookmark2Fields(const ABookmark: Pointer; var ADataPtr: Pointer): String;
function Bookmark2Key(const ABookmark: Pointer; APKOnly: Boolean = False): Variant;
function InternalBookmarkValid(ABookmark: Pointer): Boolean;
procedure ParseIndexFields(out AOrderFields, ADescFields, ANoCaseFields, AExpression: String);
function GetActualIndexFields: String;
function AllIndexFieldNull(const ARowIndex: Integer = 0): Boolean;
procedure ClearTableButCurrent;
procedure UpdateLocalIndexName;
procedure SetupTable;
function GetWindowedRows: TFDDatSRowListBase;
protected
FAdjustIndexes: Boolean;
// TFDDataSet
function InternalCreateAdapter: TFDCustomTableAdapter; override;
procedure DoCachedUpdatesChanged; override;
function DoIsSourceOpen: Boolean; override;
procedure OpenCursor(AInfoQuery: Boolean); override;
procedure ReleaseBase(AOffline: Boolean); override;
function CalcBookmarkSize: LongWord; override;
procedure GetBookmarkData(Buffer: TRecBuf; Data: TBookmark); override;
procedure InternalGotoBookmark(ABookmark: Pointer); overload; {$IFNDEF NEXTGEN} override; {$ENDIF}
procedure InternalGotoBookmark(Bookmark: TBookmark); overload; override;
function DoAdjustSortFields(const AFields, AExpression: String; var AIndexOptions: TFDSortOptions): String; override;
procedure DoSortOrderChanging; override;
procedure DoSortOrderChanged; override;
procedure UpdateIndexDefs; override;
procedure DoFilteringUpdated(AResync: Boolean); override;
function DoPurge(AView: TFDDatSView; ADirection: TFDFetchDirection = fdDown): Integer; override;
function DoFetch(ATable: TFDDatSTable; AAll: Boolean; ADirection: TFDFetchDirection = fdDown): Integer; override;
procedure InternalFirst; override;
procedure InternalLast; override;
function InternalDefaultKeyFieldCount(ABuffer: PFDKeyBuffer; ADefault: Integer): Integer; override;
function InternalGotoKey(ANearest: Boolean): Boolean; override;
function GetCanRefresh: Boolean; override;
procedure InternalRefresh; override;
procedure InternalDelete; override;
procedure SetFieldData(AField: TField; ABuffer: TValueBuffer); override;
procedure InternalAddRecord(Buffer: TRecBuf;
Append: Boolean); override;
procedure InternalPost; override;
procedure InternalCancel; override;
procedure InternalResetRange; override;
function GetRecNo: Integer; override;
procedure InternalSetRecNo(AValue: Integer); override;
procedure SetRecNo(AValue: Integer); override;
function GetRecordCount: Integer; override;
procedure DoMasterDefined; override;
procedure DoMasterReset; override;
procedure MasterChanged(Sender: TObject); override;
procedure CheckMasterRange; override;
function GetExists: Boolean; override;
procedure SaveToStorage(const AFileName: String; AStream: TStream;
AFormat: TFDStorageFormat); override;
// TFDTable
function UpdateCursorKind: Boolean;
function GetCustomWhere: String; virtual;
procedure FetchWindow(out AFetched: Integer; APrepOnly: Boolean = False;
AForceClear: Boolean = False; ATable: TFDDatsTable = nil);
function InternalSearch(ATable: TFDDatSTable; const AKeyFields: String; const AKeyValues: Variant;
const AExpression: String = ''; const AResultFields: String = '';
AOptions: TFDDataSetLocateOptions = []): Boolean;
function InternalLocateEx(const AKeyFields: String; const AKeyValues: Variant;
const AExpression: String = ''; AOptions: TFDDataSetLocateOptions = [];
ApRecordIndex: PInteger = nil): Boolean;
function InternalLookupEx(const AKeyFields: String; const AKeyValues: Variant;
const AExpression: String; const AResultFields: String; AOptions: TFDDataSetLocateOptions = [];
ApRecordIndex: PInteger = nil): Variant;
// IProviderSupport
function PSGetTableName: string; override;
function PSGetCommandText: string; override;
function PSGetCommandType: TPSCommandType; override;
procedure PSSetCommandText(const ACommandText: string); override;
public
constructor Create(AOwner: TComponent); override;
function IsSequenced: Boolean; override;
procedure Open(const ATableName: String); overload;
procedure Disconnect(AAbortJob: Boolean = False); override;
function BookmarkValid(ABookmark: TBookmark): Boolean; override;
function CompareBookmarks(Bookmark1: TBookmark; Bookmark2: TBookmark): Integer; override;
function GenerateSQL: String;
procedure RefireSQL;
function LookupEx(const AExpression: String; const AResultFields: String;
AOptions: TFDDataSetLocateOptions = []; ApRecordIndex: PInteger = nil): Variant; override;
function LookupEx(const AKeyFields: String; const AKeyValues: Variant;
const AResultFields: String; AOptions: TFDDataSetLocateOptions = [];
ApRecordIndex: PInteger = nil): Variant; override;
function LocateEx(const AExpression: String; AOptions: TFDDataSetLocateOptions = [];
ApRecordIndex: PInteger = nil): Boolean; override;
function LocateEx(const AKeyFields: String; const AKeyValues: Variant;
AOptions: TFDDataSetLocateOptions = []; ApRecordIndex: PInteger = nil): Boolean; override;
procedure RefreshMetadata;
procedure CreateTable(ARecreate: Boolean = True;
AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]);
procedure CreateDataSet; override;
property ActualIndexFieldNames: String read GetActualIndexFields;
published
property ActiveStoredUsage;
{ TDataSet }
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
property FieldOptions;
property Filtered;
property FilterOptions;
property Filter;
property OnFilterRecord;
property ObjectView default True;
property Constraints;
{ TFDDataSet }
property CachedUpdates;
property FilterChanges;
property IndexName;
property IndexFieldNames;
property Aggregates;
property AggregatesActive;
property ConstraintsEnabled;
property MasterSource;
property MasterFields;
property DetailFields;
property OnUpdateRecord;
property OnUpdateError;
property OnReconcileError;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property AfterGetRecord;
property BeforeRowRequest;
property AfterRowRequest;
{ TFDAdaptedDataSet }
property LocalSQL;
property ChangeAlerter;
property ChangeAlertName;
{ TFDRdbmsDataSet }
property ConnectionName;
property Connection;
property Transaction;
property UpdateTransaction;
property SchemaAdapter;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property UpdateObject;
property OnError;
property OnExecuteError;
property OnCommandChanged;
{ TFDTable }
property Exclusive: Boolean read FExclusive write FExclusive default False;
property CatalogName: String read FCatalogName write SetCatalogName;
property SchemaName: String read FSchemaName write SetSchemaName;
property TableName: String read FTableName write SetTableName;
end;
TFDCustomStoredProc = class(TFDRdbmsDataSet)
private
procedure SetOverload(const AValue: Word);
procedure SetProcName(const AValue: string);
function GetOverload: Word;
function GetProcName: string;
function GetPackageName: String;
function GetSchemaName: String;
procedure SetPackageName(const AValue: String);
procedure SetSchemaName(const AValue: String);
procedure ProcNameChanged;
function GetCatalogName: String;
procedure SetCatalogName(const AValue: String);
procedure ExecProcBase(const AProcName: String; AFunction: Boolean;
const AParams: array of Variant; const ATypes: array of TFieldType);
function GetFuncResult: Variant;
protected
function InternalCreateAdapter: TFDCustomTableAdapter; override;
public
function DescriptionsAvailable: Boolean;
procedure ExecProc; overload;
function ExecProc(const AProcName: String): LongInt; overload;
function ExecProc(const AProcName: String; const AParams: array of Variant): LongInt; overload;
function ExecProc(const AProcName: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt; overload;
function ExecFunc: Variant; overload;
function ExecFunc(const AProcName: String): Variant; overload;
function ExecFunc(const AProcName: String; const AParams: array of Variant): Variant; overload;
function ExecFunc(const AProcName: String; const AParams: array of Variant;
const ATypes: array of TFieldType): Variant; overload;
property CatalogName: String read GetCatalogName write SetCatalogName;
property SchemaName: String read GetSchemaName write SetSchemaName;
property PackageName: String read GetPackageName write SetPackageName;
property StoredProcName: string read GetProcName write SetProcName;
property Overload: Word read GetOverload write SetOverload default 0;
property ParamCount;
property RowsAffected;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDStoredProc = class(TFDCustomStoredProc)
published
property ActiveStoredUsage;
{ TDataSet }
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
property FieldOptions;
property Filtered;
property FilterOptions;
property Filter;
property OnFilterRecord;
property ObjectView default True;
property Constraints;
{ TFDDataSet }
property CachedUpdates;
property FilterChanges;
property Indexes;
property IndexesActive;
property IndexName;
property IndexFieldNames;
property Aggregates;
property AggregatesActive;
property ConstraintsEnabled;
property MasterSource;
property MasterFields;
property DetailFields;
property OnUpdateRecord;
property OnUpdateError;
property OnReconcileError;
property BeforeExecute;
property AfterExecute;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property AfterGetRecord;
property BeforeRowRequest;
property AfterRowRequest;
{ TFDAdaptedDataSet }
property LocalSQL;
property ChangeAlerter;
property ChangeAlertName;
{ TFDRdbmsDataSet }
property ConnectionName;
property Connection;
property Transaction;
property UpdateTransaction;
property SchemaAdapter;
property Params;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property UpdateOptions;
property UpdateObject;
property OnError;
property OnExecuteError;
property OnCommandChanged;
property ParamBindMode;
{ TFDCustomStoredProc }
property CatalogName;
property SchemaName;
property PackageName;
property StoredProcName;
property Overload;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDMetaInfoQuery = class(TFDRdbmsDataSet)
private
function GetMetaInfoKind: TFDPhysMetaInfoKind;
function GetObjectName: String;
function GetTableKinds: TFDPhysTableKinds;
function GetWildcard: String;
procedure SetMetaInfoKind(const AValue: TFDPhysMetaInfoKind);
procedure SetObjectName(const AValue: String);
procedure SetTableKinds(const AValue: TFDPhysTableKinds);
procedure SetWildcard(const AValue: String);
function GetOverload: Word;
procedure SetOverload(const AValue: Word);
procedure SetObjectScopes(const AValue: TFDPhysObjectScopes);
function GetObjectScopes: TFDPhysObjectScopes;
function GetBaseObjectName: String;
function GetSchemaName: String;
procedure SetBaseObjectName(const AValue: String);
procedure SetSchemaName(const AValue: String);
function GetCatalogName: String;
procedure SetCatalogName(const AValue: String);
protected
function InternalCreateAdapter: TFDCustomTableAdapter; override;
published
property ActiveStoredUsage;
{ TDataSet }
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property FieldOptions;
property Filtered;
property FilterOptions;
property Filter;
property OnFilterRecord;
{ TFDDataSet }
property Indexes;
property IndexesActive;
property IndexName;
property IndexFieldNames;
property Aggregates;
property AggregatesActive;
property BeforeGetRecords;
property AfterGetRecords;
property AfterGetRecord;
property BeforeRowRequest;
property AfterRowRequest;
{ TFDAdaptedDataSet }
property LocalSQL;
{ TFDRdbmsDataSet }
property ConnectionName;
property Connection;
property Transaction;
property UpdateTransaction;
property SchemaAdapter;
property FetchOptions;
property FormatOptions;
property ResourceOptions;
property OnError;
property OnCommandChanged;
{ Introduced }
property MetaInfoKind: TFDPhysMetaInfoKind read GetMetaInfoKind
write SetMetaInfoKind default mkTables;
property TableKinds: TFDPhysTableKinds read GetTableKinds
write SetTableKinds default [tkSynonym, tkTable, tkView];
property Wildcard: String read GetWildcard write SetWildcard;
property ObjectScopes: TFDPhysObjectScopes read GetObjectScopes
write SetObjectScopes default [osMy];
property CatalogName: String read GetCatalogName write SetCatalogName;
property SchemaName: String read GetSchemaName write SetSchemaName;
property BaseObjectName: String read GetBaseObjectName write SetBaseObjectName;
property Overload: Word read GetOverload write SetOverload default 0;
property ObjectName: String read GetObjectName write SetObjectName;
end;
function FDManager: TFDCustomManager; inline;
procedure FDSetManagerClass(AClass: TFDCustomManagerClass);
procedure FDSetConnectionClass(AClass: TFDCustomConnectionClass);
function FDFindDefaultConnection(AComp: TComponent): TFDCustomConnection;
function FDIsDesigning(AComp: TComponent): Boolean;
{-------------------------------------------------------------------------------}
implementation
uses
System.Variants, Data.FmtBcd, Data.SqlTimSt, System.Types, System.TypInfo,
FireDAC.Stan.Consts, FireDAC.Stan.SQLTimeInt, FireDAC.Stan.Expr,
FireDAC.Stan.Factory, FireDAC.Stan.ResStrs,
FireDAC.Phys.SQLPreprocessor;
{$HINTS OFF}
type
__TReader = class(TReader)
end;
__TWriter = class(TFiler)
private
FRootAncestor: TComponent;
FPropPath: string;
end;
{$HINTS ON}
{-------------------------------------------------------------------------------}
function FDManager: TFDCustomManager;
begin
Result := TFDCustomManager.GetSingleton;
end;
{-------------------------------------------------------------------------------}
procedure FDSetManagerClass(AClass: TFDCustomManagerClass);
begin
TFDCustomManager.FSingletonClass := AClass;
end;
{-------------------------------------------------------------------------------}
procedure FDSetConnectionClass(AClass: TFDCustomConnectionClass);
begin
TFDCustomManager.FConnectionClass := AClass;
end;
{-------------------------------------------------------------------------------}
function FDFindDefaultConnection(AComp: TComponent): TFDCustomConnection;
var
oRoot: TComponent;
i: Integer;
begin
Result := nil;
oRoot := AComp;
while (oRoot.Owner <> nil) and (Result = nil) do begin
oRoot := oRoot.Owner;
for i := 0 to oRoot.ComponentCount - 1 do
if oRoot.Components[i] is TFDCustomConnection then begin
Result := TFDCustomConnection(oRoot.Components[i]);
Break;
end;
end;
end;
{-------------------------------------------------------------------------------}
function FDIsDesigning(AComp: TComponent): Boolean;
begin
Result :=
([csDesigning, csLoading] * AComp.ComponentState = [csDesigning]) and
((AComp.Owner = nil) or
([csDesigning, csLoading] * AComp.Owner.ComponentState = [csDesigning]));
end;
{-------------------------------------------------------------------------------}
{ TFDCustomManager }
{-------------------------------------------------------------------------------}
class constructor TFDCustomManager.Create;
begin
FSingletonLock := TCriticalSection.Create;
FSingletonClass := TFDManager;
FSingleton := nil;
FSingletonOptsIntf := nil;
FConnectionClass := TFDConnection;
end;
{-------------------------------------------------------------------------------}
class destructor TFDCustomManager.Destroy;
begin
if (FSingleton <> nil) and FSingleton.FAutoCreated then begin
FDFree(FSingleton);
FSingleton := nil;
end;
FDFreeAndNil(FSingletonLock);
end;
{-------------------------------------------------------------------------------}
class function TFDCustomManager.GetSingleton: TFDCustomManager;
begin
if (FSingleton = nil) and (FSingletonLock <> nil) then begin
FSingletonLock.Enter;
try
if FSingleton = nil then begin
FSingleton := FSingletonClass.Create(nil);
FSingleton.FAutoCreated := True;
end;
finally
FSingletonLock.Leave;
end;
end;
Result := FSingleton;
end;
{-------------------------------------------------------------------------------}
class function TFDCustomManager.GetSingletonOptsIntf: IFDStanOptions;
begin
if FSingletonOptsIntf = nil then
FDManager();
Result := FSingletonOptsIntf;
end;
{-------------------------------------------------------------------------------}
constructor TFDCustomManager.Create(AOwner: TComponent);
var
oPrevMgr: TFDCustomManager;
i: Integer;
begin
if (FSingleton <> nil) and not FSingleton.FAutoCreated and
((AOwner = nil) or not (csDesigning in AOwner.ComponentState)) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntSessMBSingle, []);
FLock := TMultiReadExclusiveWriteSynchronizer.Create;
FLock.BeginWrite;
try
inherited Create(AOwner);
SetOptionsIntf(nil);
FConnections := TFDObjList.Create;
FActiveStoredUsage := [auDesignTime, auRunTime];
if (FSingleton = nil) or FSingleton.FAutoCreated then begin
oPrevMgr := FSingleton;
FSingleton := Self;
QueryInterface(IFDStanOptions, FSingletonOptsIntf);
if oPrevMgr <> nil then begin
FConnections.Clear;
for i := 0 to oPrevMgr.FConnections.Count - 1 do
FConnections.Add(oPrevMgr.FConnections[i]);
oPrevMgr.FConnections.Clear;
FDFree(oPrevMgr);
end;
end;
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomManager.Destroy;
begin
if FLock <> nil then
FLock.BeginWrite;
Destroying;
if FSingleton = Self then begin
Close;
FSingletonOptsIntf := nil;
FSingleton := nil;
end;
inherited Destroy;
FDFreeAndNil(FConnections);
if FOptionsIntf <> nil then begin
FOptionsIntf.ObjectDestroyed(Self);
FOptionsIntf := nil;
end;
FDFreeAndNil(FLock);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.Loaded;
begin
inherited Loaded;
try
if FStreamedActive and FDCheckStoredUsage(ComponentState, ActiveStoredUsage) then
SetActive(True);
except
if csDesigning in ComponentState then
FDHandleException
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.CheckInactive;
begin
if Active then
if (csDesigning in ComponentState) or ResourceOptions.AutoConnect then
Close
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntSessMBInactive, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.CheckActive;
begin
if not Active then
if ResourceOptions.AutoConnect then
Open
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntSessMBActive, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetSilentMode: Boolean;
begin
Result := FFDGUIxSilentMode;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetSilentMode(const AValue: Boolean);
begin
FFDGUIxSilentMode := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetWaitCursor: TFDGUIxScreenCursor;
var
oWait: IFDGUIxWaitCursor;
begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
Result := oWait.WaitCursor;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetWaitCursor(const AValue: TFDGUIxScreenCursor);
var
oWait: IFDGUIxWaitCursor;
begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.WaitCursor := AValue;
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDCustomManager.GetName: TComponentName;
begin
if Name = '' then
Result := '$' + IntToHex(Integer(Self), 8)
else
Result := Name;
Result := Result + ': ' + ClassName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetParent: IFDStanObject;
begin
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDStanOptions
procedure TFDCustomManager.SetOptionsIntf(const AValue: IFDStanOptions);
begin
if (FOptionsIntf <> AValue) or (FOptionsIntf = nil) and (AValue = nil) then begin
FOptionsIntf := AValue;
if FOptionsIntf = nil then begin
FOptionsIntf := TFDOptionsContainer.Create(Self, TFDFetchOptions,
TFDUpdateOptions, TFDTopResourceOptions, nil);
FOptionsIntf.FormatOptions.OwnMapRules := True;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetFetchOptions: TFDFetchOptions;
begin
Result := FOptionsIntf.FetchOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetFetchOptions(const AValue: TFDFetchOptions);
begin
FOptionsIntf.FetchOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetFormatOptions: TFDFormatOptions;
begin
Result := FOptionsIntf.FormatOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetFormatOptions(const AValue: TFDFormatOptions);
begin
FOptionsIntf.FormatOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetUpdateOptions: TFDUpdateOptions;
begin
Result := FOptionsIntf.UpdateOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetUpdateOptions(const AValue: TFDUpdateOptions);
begin
FOptionsIntf.UpdateOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetResourceOptions: TFDTopResourceOptions;
begin
Result := TFDTopResourceOptions(FOptionsIntf.ResourceOptions);
ASSERT((Result <> nil) and (Result is TFDTopResourceOptions));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetResourceOptions(const AValue: TFDTopResourceOptions);
begin
FOptionsIntf.ResourceOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
// Phys Manager control
function TFDCustomManager.GetActive: Boolean;
var
oMgr: IFDPhysManager;
begin
FDCreateInterface(IFDPhysManager, oMgr, False);
Result := (oMgr <> nil) and (oMgr.State = dmsActive);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetState: TFDPhysManagerState;
var
oMgr: IFDPhysManager;
begin
FDCreateInterface(IFDPhysManager, oMgr, False);
if oMgr <> nil then
Result := oMgr.State
else
Result := dmsInactive;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetActive(const AValue: Boolean);
var
i, iAct: Integer;
oConn: TFDCustomConnection;
begin
if csReading in ComponentState then
FStreamedActive := AValue
else begin
iAct := 0;
if Active <> AValue then
if AValue then
DoBeforeStartup
else
DoBeforeShutdown;
FLock.BeginRead;
try
if Active <> AValue then
if AValue then begin
FLock.BeginWrite;
try
// check that IFDPhysManager implementation is linked
FDPhysManager();
finally
FLock.EndWrite;
end;
iAct := 1;
end
else begin
FLock.BeginWrite;
try
for i := FConnections.Count - 1 downto 0 do begin
oConn := TFDCustomConnection(FConnections[i]);
if oConn.Temporary then
FDFree(oConn)
else begin
oConn.Close;
oConn.ResultConnectionDef.ParentDefinition := nil;
end;
end;
finally
FLock.EndWrite;
end;
iAct := -1;
end;
finally
FLock.EndRead;
end;
if iAct = 1 then begin
InternalOpen;
DoAfterStartup;
end
else if iAct = -1 then begin
InternalClose;
DoAfterShutdown;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.InternalOpen;
begin
FDPhysManager.Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DoBeforeStartup;
begin
if Assigned(FBeforeStartup) then
FBeforeStartup(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DoAfterStartup;
begin
if Assigned(FAfterStartup) then
FAfterStartup(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.Open;
begin
Active := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.InternalClose;
begin
FDPhysManager.Close(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DoBeforeShutdown;
begin
if Assigned(FBeforeShutdown) then
FBeforeShutdown(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DoAfterShutdown;
begin
if Assigned(FAfterShutdown) then
FAfterShutdown(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.Close;
begin
Active := False;
end;
{-------------------------------------------------------------------------------}
// Connection management
procedure TFDCustomManager.AddConnection(AConn: TFDCustomConnection);
begin
FLock.BeginWrite;
try
if FConnections.IndexOf(AConn) = -1 then begin
FConnections.Add(AConn);
FreeNotification(AConn);
end;
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.RemoveConnection(AConn: TFDCustomConnection);
begin
FLock.BeginWrite;
try
if FCachedConnection = AConn then
FCachedConnection := nil;
RemoveFreeNotification(AConn);
FConnections.Remove(AConn);
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetConnectionCount: Integer;
begin
FLock.BeginRead;
try;
Result := FConnections.Count;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetConnection(AIndex: Integer): TFDCustomConnection;
begin
FLock.BeginRead;
try;
Result := TFDCustomConnection(FConnections[AIndex]);
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.InternalAcquireConnection(AConnection: TFDCustomConnection;
const AConnectionName, AObjName: String): TFDCustomConnection;
begin
if (AConnection = nil) and (AConnectionName = '') then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbNotDefined, [AObjName]);
FLock.BeginWrite;
try
if AConnection <> nil then
Result := AConnection
else begin
Result := FindConnection(AConnectionName);
if Result = nil then
Result := InternalAcquireTemporaryConnection(AConnectionName);
end;
if Result.FRefCount >= 0 then
Inc(Result.FRefCount);
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.InternalAcquireTemporaryConnection(
const AConnectionName: string): TFDCustomConnection;
begin
Result := FConnectionClass.Create(Self);
try
Result.ConnectionName := AConnectionName;
Result.Temporary := True;
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.AcquireConnection(const AConnectionName: string;
const AObjName: String): TFDCustomConnection;
begin
Result := InternalAcquireConnection(nil, AConnectionName, AObjName);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.AcquireConnection(AConnection: TFDCustomConnection;
const AObjName: String): TFDCustomConnection;
begin
Result := InternalAcquireConnection(AConnection, '', AObjName);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.InternalReleaseConnection(var AConnection: TFDCustomConnection);
begin
FLock.BeginWrite;
try
AConnection.FLastUsed := Now();
if AConnection.FRefCount > 0 then
Dec(AConnection.FRefCount);
if (AConnection.FRefCount = 0) and not AConnection.ResourceOptions.KeepConnection then
if not AConnection.Temporary then
AConnection.Close
else if not (csDestroying in AConnection.ComponentState) then begin
FDFree(AConnection);
AConnection := nil;
end;
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.ReleaseConnection(var AConnection: TFDCustomConnection);
begin
if AConnection = nil then
Exit;
InternalReleaseConnection(AConnection);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DropConnections;
var
i: Integer;
oConn: TFDCustomConnection;
begin
FLock.BeginWrite;
try
for i := FConnections.Count - 1 downto 0 do begin
oConn := TFDCustomConnection(FConnections[i]);
if oConn.RefCount = 0 then
if oConn.Temporary then
FDFree(oConn)
else
oConn.Connected := False;
end;
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.FindConnection(const AConnectionName: string): TFDCustomConnection;
begin
if AConnectionName = '' then begin
Result := nil;
Exit;
end;
FLock.BeginRead;
try
if (FCachedConnection <> nil) and
({$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(FCachedConnection.ConnectionName, AConnectionName) = 0) then
Result := FCachedConnection
else begin
Result := InternalFindConnection(AConnectionName);
if Result <> nil then
FCachedConnection := Result;
end;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.InternalFindConnection(const AConnectionName: string): TFDCustomConnection;
var
i: Integer;
oConn: TFDCustomConnection;
begin
Result := nil;
for i := 0 to FConnections.Count - 1 do begin
oConn := TFDCustomConnection(FConnections[i]);
if {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(oConn.ConnectionName, AConnectionName) = 0 then begin
Result := oConn;
Break;
end;
end;
end;
{-------------------------------------------------------------------------------}
// Get XXX names
procedure TFDCustomManager.GetConnectionNames(AList: TStrings);
begin
GetConnectionNames(AList, '');
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetConnectionNames(AList: TStrings; ADriverName: string);
var
i: Integer;
oNames: TFDStringList;
oConn: TFDCustomConnection;
begin
Active := True;
oNames := TFDStringList.Create(dupIgnore, True, False);
FLock.BeginRead;
try
oNames.BeginUpdate;
for i := 0 to ConnectionDefs.Count - 1 do
if (ConnectionDefs[i].Name <> '') and ((ADriverName = '') or (CompareText(ADriverName, ConnectionDefs[i].Params.DriverID) = 0)) then
oNames.Add(ConnectionDefs[i].Name);
for i := 0 to FConnections.Count - 1 do begin
oConn := TFDCustomConnection(FConnections[I]);
if (oConn.ConnectionName <> '') and ((ADriverName = '') or (CompareText(ADriverName, oConn.DriverName) = 0)) then
oNames.Add(oConn.ConnectionName);
end;
AList.SetStrings(oNames);
finally
FLock.EndRead;
FDFree(oNames);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetConnectionDefNames(AList: TStrings);
var
i: Integer;
oNames: TFDStringList;
begin
Active := True;
oNames := TFDStringList.Create(dupIgnore, True, False);
FLock.BeginRead;
try
oNames.BeginUpdate;
for i := 0 to ConnectionDefs.Count - 1 do
if ConnectionDefs[i].Name <> '' then
oNames.Add(ConnectionDefs[i].Name);
AList.SetStrings(oNames);
finally
FLock.EndRead;
FDFree(oNames);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetDriverNames(AList: TStrings;
AValidate: Boolean = False; ABaseOnly: Boolean = False);
var
oNames: TFDStringList;
i: Integer;
oManMeta: IFDPhysManagerMetadata;
oDrv: IFDPhysDriver;
begin
Open;
oNames := TFDStringList.Create(dupIgnore, True, False);
try
oNames.BeginUpdate;
FDPhysManager.CreateMetadata(oManMeta);
for i := 0 to oManMeta.DriverCount - 1 do
if not ABaseOnly or (CompareText(oManMeta.DriverID[i], oManMeta.BaseDriverID[i]) = 0) then
try
if AValidate then
FDPhysManager.CreateDriver(oManMeta.DriverID[i], oDrv);
oNames.Add(oManMeta.DriverID[i]);
except
// silent
end;
AList.SetStrings(oNames);
finally
FDFree(oNames);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetCatalogNames(const AConnectionName,
APattern: string; AList: TStrings);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetCatalogNames(APattern, AList);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetSchemaNames(const AConnectionName, ACatalogName,
APattern: string; AList: TStrings);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetSchemaNames(ACatalogName, APattern, AList);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetTableNames(const AConnectionName, ACatalogName,
ASchemaName, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AFullName: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetTableNames(ACatalogName, ASchemaName, APattern, AList, AScopes,
[tkSynonym, tkTable, tkView], AFullName);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetFieldNames(const AConnectionName, ACatalogName,
ASchemaName, ATableName, APattern: string; AList: TStrings);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetFieldNames(ACatalogName, ASchemaName, ATableName, APattern, AList);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetKeyFieldNames(const AConnectionName, ACatalogName,
ASchemaName, ATableName, APattern: string; AList: TStrings);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetKeyFieldNames(ACatalogName, ASchemaName, ATableName, APattern, AList);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetIndexNames(const AConnectionName, ACatalogName,
ASchemaName, ATableName, APattern: string; AList: TStrings);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetIndexNames(ACatalogName, ASchemaName, ATableName, APattern, AList);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetPackageNames(const AConnectionName, ACatalogName,
ASchemaName, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AFullName: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetPackageNames(ACatalogName, ASchemaName, APattern, AList, AScopes,
AFullName);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetStoredProcNames(const AConnectionName, ACatalogName,
ASchemaName, APackage, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AFullName: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetStoredProcNames(ACatalogName, ASchemaName, APackage, APattern,
AList, AScopes, AFullName);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetGeneratorNames(const AConnectionName, ACatalogName,
ASchemaName, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AFullName: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := AcquireConnection(AConnectionName, Name);
try
oConn.GetGeneratorNames(ACatalogName, ASchemaName, APattern, AList, AScopes,
AFullName);
finally
ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
// Connection definitions
function TFDCustomManager.GetConnectionDefs: IFDStanConnectionDefs;
begin
Result := FDPhysManager.ConnectionDefs;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetConnectionDefFileName: String;
begin
Result := ConnectionDefs.Storage.FileName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetConnectionDefFileName(const AValue: String);
begin
ConnectionDefs.Storage.FileName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetActualConnectionDefFileName: String;
begin
Result := ConnectionDefs.Storage.ActualFileName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetAfterLoadConnectionDefFile: TNotifyEvent;
begin
Result := ConnectionDefs.AfterLoad;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetAfterLoadConnectionDefFile(const AValue: TNotifyEvent);
begin
ConnectionDefs.AfterLoad := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetBeforeLoadConnectionDefFile: TNotifyEvent;
begin
Result := ConnectionDefs.BeforeLoad;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetBeforeLoadConnectionDefFile(const AValue: TNotifyEvent);
begin
ConnectionDefs.BeforeLoad := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetConnectionDefAutoLoad: Boolean;
begin
Result := ConnectionDefs.AutoLoad;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetConnectionDefAutoLoad(const AValue: Boolean);
begin
ConnectionDefs.AutoLoad := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetConnectionDefsLoaded: Boolean;
begin
Result := ConnectionDefs.Loaded;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.IsConnectionDef(const AName: String): Boolean;
begin
Result := (AName <> '') and (ConnectionDefs.FindConnectionDef(AName) <> nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.AddConnectionDef(const AName, ADriver: string;
AList: TStrings = nil; APersistent: Boolean = False);
var
oDef: IFDStanConnectionDef;
begin
oDef := ConnectionDefs.AddConnectionDef;
try
oDef.Params.BeginUpdate;
try
if AList <> nil then
oDef.Params.SetStrings(AList);
if AName <> '' then
oDef.Name := AName;
if ADriver <> '' then
oDef.Params.DriverID := ADriver;
finally
oDef.Params.EndUpdate;
end;
if APersistent then
oDef.MarkPersistent;
except
oDef.Delete;
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.DeleteConnectionDef(const AName: string);
begin
ConnectionDefs.ConnectionDefByName(AName).Delete;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.ModifyConnectionDef(const AName: string; AList: TStrings);
var
i: Integer;
sName, sValue: String;
oDef: IFDStanConnectionDef;
begin
oDef := ConnectionDefs.ConnectionDefByName(AName);
oDef.Params.BeginUpdate;
try
for i := 0 to AList.Count - 1 do begin
sName := AList.KeyNames[i];
sValue := AList.ValueFromIndex[i];
oDef.AsString[sName] := sValue;
end;
finally
oDef.Params.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.RenameConnectionDef(const AOldName, ANewName: string);
begin
ConnectionDefs.ConnectionDefByName(AOldName).Name := ANewName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.GetConnectionDefParams(const AName: string; AList: TStrings);
begin
AList.SetStrings(ConnectionDefs.ConnectionDefByName(AName).Params);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.CloseConnectionDef(const AName: string);
var
oDef: IFDStanConnectionDef;
i: Integer;
begin
oDef := ConnectionDefs.FindConnectionDef(AName);
if oDef = nil then
Exit;
FLock.BeginWrite;
try
for i := ConnectionCount - 1 downto 0 do
if (CompareText(Connections[i].ConnectionDefName, AName) = 0) and
not Connections[i].Offlined then
Connections[i].Close;
FDPhysManager.CloseConnectionDef(oDef);
finally
FLock.EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SaveConnectionDefFile;
begin
ConnectionDefs.Save;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.LoadConnectionDefFile;
begin
ConnectionDefs.Load;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.RefreshMetadataCache;
begin
if Active then
FDPhysManager.RefreshMetadataCache;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.RefreshConnectionDefFile;
begin
if ConnectionDefs.Loaded then
ConnectionDefs.Refresh;
end;
{-------------------------------------------------------------------------------}
// Driver configurations
function TFDCustomManager.GetDriverDefs: IFDStanDefinitions;
begin
Result := FDPhysManager.DriverDefs;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetDriverDefAutoLoad: Boolean;
begin
Result := FDPhysManager.DriverDefs.AutoLoad;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetDriverDefAutoLoad(const AValue: Boolean);
begin
FDPhysManager.DriverDefs.AutoLoad := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetDriverDefFileName: String;
begin
Result := FDPhysManager.DriverDefs.Storage.FileName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomManager.SetDriverDefFileName(const AValue: String);
begin
FDPhysManager.DriverDefs.Storage.FileName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetActualDriverDefFileName: String;
begin
Result := FDPhysManager.DriverDefs.Storage.ActualFileName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetBaseDriverID(const ADriverID: String): String;
var
oManMeta: IFDPhysManagerMetadata;
begin
FDPhysManager.CreateMetadata(oManMeta);
Result := oManMeta.GetBaseDriverID(ADriverID);
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetBaseDriverDesc(const ADriverID: String): String;
var
oManMeta: IFDPhysManagerMetadata;
oDrvMeta: IFDPhysDriverMetadata;
begin
FDPhysManager.CreateMetadata(oManMeta);
oManMeta.CreateDriverMetadata(ADriverID, oDrvMeta);
Result := oDrvMeta.BaseDriverDesc;
end;
{-------------------------------------------------------------------------------}
function TFDCustomManager.GetRDBMSKind(const ADriverID: String): TFDRDBMSKind;
var
oManMeta: IFDPhysManagerMetadata;
begin
FDPhysManager.CreateMetadata(oManMeta);
Result := oManMeta.GetRDBMSKind(ADriverID);
end;
{-------------------------------------------------------------------------------}
{ TFDCustomConnection }
{-------------------------------------------------------------------------------}
constructor TFDCustomConnection.Create(AOwner: TComponent);
var
oOpts: IFDStanOptions;
begin
inherited Create(AOwner);
SetOptionsIntf(nil);
FDCreateInterface(IFDStanConnectionDef, FParams);
FParams.OnChanging := ParamsChanging;
FTxOptions := TFDTxOptions.Create;
FCommands := TFDObjList.Create;
LoginPrompt := True;
oOpts := Self as IFDStanOptions;
FOptionsIntf := oOpts;
FLastUsed := Now;
FConnectedStoredUsage := [auDesignTime, auRunTime];
FDeferredUnregs := TFDObjList.Create;
FDManager.AddConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomConnection.Destroy;
begin
Destroying;
Close;
if TFDCustomManager.FSingleton <> nil then
FDManager.RemoveConnection(Self);
inherited Destroy;
SetLoginDialog(nil);
FParams := nil;
if FOptionsIntf <> nil then begin
FOptionsIntf.ObjectDestroyed(Self);
FOptionsIntf := nil;
end;
FDFreeAndNil(FCommands);
FDFreeAndNil(FTxOptions);
FDFreeAndNil(FDeferredUnregs);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Loaded;
begin
StreamedConnected := StreamedConnected and
FDCheckStoredUsage(ComponentState, FDManager.ActiveStoredUsage * ConnectedStoredUsage);
inherited Loaded;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
if AOperation = opRemove then
if FLoginDialog = AComponent then
SetLoginDialog(nil)
else if Transaction = AComponent then
Transaction := nil
else if UpdateTransaction = AComponent then
UpdateTransaction := nil;
inherited Notification(AComponent, AOperation);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Assign(Source: TPersistent);
var
oSrc: TFDCustomConnection;
begin
if Source is TFDCustomConnection then begin
oSrc := Source as TFDCustomConnection;
Connected := False;
Params := oSrc.Params;
FetchOptions := oSrc.FetchOptions;
FormatOptions := oSrc.FormatOptions;
ResourceOptions := oSrc.ResourceOptions;
UpdateOptions := oSrc.UpdateOptions;
TxOptions := oSrc.TxOptions;
SharedCliHandle := oSrc.SharedCliHandle;
Temporary := oSrc.Temporary;
ConnectedStoredUsage := oSrc.ConnectedStoredUsage;
Offlined := oSrc.Offlined;
LoginPrompt := oSrc.LoginPrompt;
LoginDialog := oSrc.LoginDialog;
AfterConnect := oSrc.AfterConnect;
BeforeConnect := oSrc.BeforeConnect;
AfterDisconnect := oSrc.AfterDisconnect;
BeforeDisconnect := oSrc.BeforeDisconnect;
OnLogin := oSrc.OnLogin;
OnError := oSrc.OnError;
OnLost := oSrc.OnLost;
OnRestored := oSrc.OnRestored;
OnRecover := oSrc.OnRecover;
BeforeStartTransaction := oSrc.BeforeStartTransaction;
AfterStartTransaction := oSrc.AfterStartTransaction;
BeforeCommit := oSrc.BeforeCommit;
AfterCommit := oSrc.AfterCommit;
BeforeRollback := oSrc.BeforeRollback;
AfterRollback := oSrc.AfterRollback;
end
else
inherited Assign(Source);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.CloneConnection: TFDCustomConnection;
begin
Result := TFDCustomConnectionClass(ClassType).Create(nil);
Result.Assign(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.CheckActive;
begin
CheckOnline;
if not Connected then
if Temporary or ResourceOptions.AutoConnect then
Open
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbMBActive, [GetName]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.CheckInactive;
begin
if Connected then
if (csDesigning in ComponentState) or Temporary or ResourceOptions.AutoConnect then
Close
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbMBInactive, [GetName]);
end;
{-------------------------------------------------------------------------------}
// IFDStanOptions
procedure TFDCustomConnection.GetParentOptions(var AOpts: IFDStanOptions);
begin
AOpts := TFDCustomManager.GetSingletonOptsIntf;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetOptionsIntf(const AValue: IFDStanOptions);
begin
if (FOptionsIntf <> AValue) or (FOptionsIntf = nil) and (AValue = nil) then begin
FOptionsIntf := AValue;
if FOptionsIntf = nil then
FOptionsIntf := TFDOptionsContainer.Create(Self, TFDFetchOptions,
TFDUpdateOptions, TFDTopResourceOptions, GetParentOptions);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetFetchOptions: TFDFetchOptions;
begin
Result := FOptionsIntf.FetchOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetFetchOptions(const AValue: TFDFetchOptions);
begin
FOptionsIntf.FetchOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetFormatOptions: TFDFormatOptions;
begin
Result := FOptionsIntf.FormatOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetFormatOptions(const AValue: TFDFormatOptions);
begin
FOptionsIntf.FormatOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetUpdateOptions: TFDUpdateOptions;
begin
Result := FOptionsIntf.UpdateOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetUpdateOptions(const AValue: TFDUpdateOptions);
begin
FOptionsIntf.UpdateOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetResourceOptions: TFDTopResourceOptions;
begin
Result := TFDTopResourceOptions(FOptionsIntf.ResourceOptions);
ASSERT((Result <> nil) and (Result is TFDTopResourceOptions));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetResourceOptions(const AValue: TFDTopResourceOptions);
begin
FOptionsIntf.ResourceOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
// Other
procedure TFDCustomConnection.SetTxOptions(const AValue: TFDTxOptions);
begin
FTxOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
begin
if Assigned(FOnError) then
if AInitiator = nil then
FOnError(Self, Self, AException)
else
FOnError(Self, AInitiator as TObject, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoRecover(const AInitiator: IFDStanObject;
AException: Exception; var AAction: TFDPhysConnectionRecoverAction);
begin
if Assigned(FOnRecover) then
FOnRecover(Self, AInitiator as TObject, AException, AAction);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleConnectionRecover(const AInitiator: IFDStanObject;
AException: Exception; var AAction: TFDPhysConnectionRecoverAction);
begin
if csReading in ComponentState then
AAction := faFail
else if AInitiator = nil then
DoRecover(Self as IFDStanObject, AException, AAction)
else
DoRecover(AInitiator, AException, AAction);
FTmpConnectionIntf := FConnectionIntf;
case AAction of
faCloseAbort:
Connected := False;
faOfflineAbort:
Offlined := True;
faFail:
Connected := False;
faDefault:
if not GetResourceOptions.AutoReconnect then begin
DoLost;
Connected := False;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoLost;
begin
if Assigned(FOnLost) then
FOnLost(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleConnectionLost;
begin
if Connected and not Offlined then
Connected := False;
ReleaseConnectionIntf(FTmpConnectionIntf);
DoLost;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoRestored;
begin
if Assigned(FOnRestored) then
FOnRestored(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleConnectionRestored;
begin
if FTmpConnectionIntf = FConnectionIntf then
FTmpConnectionIntf := nil
else
ReleaseConnectionIntf(FTmpConnectionIntf);
DoRestored;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetSQLBased: Boolean;
begin
Result := not (RDBMSKind in [TFDRDBMSKinds.Unknown, TFDRDBMSKinds.DataSnap]);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetRDBMSKind: TFDRDBMSKind;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
if ConnectionIntf <> nil then begin
ConnectionIntf.CreateMetadata(oConnMeta);
Result := oConnMeta.Kind;
end
else
Result := FDManager.GetRDBMSKind(ActualDriverID);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetParams: TFDConnectionDefParams;
var
sDef: String;
oParDef: IFDStanDefinition;
begin
sDef := FParams.Params.Values[S_FD_DefinitionParam_Common_ConnectionDef];
if sDef = '' then
sDef := ConnectionName;
oParDef := FParams.ParentDefinition;
if (sDef <> '') xor (oParDef <> nil) or
(sDef <> '') and (CompareText(oParDef.Name, sDef) <> 0) then
PrepareConnectionDef(False);
Result := FParams.Params;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.ParamsChanging(ASender: TObject);
begin
CheckInactive;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetParams(const AValue: TFDConnectionDefParams);
begin
FParams.Params.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetConnectionDefName: string;
begin
Result := FParams.Params.ConnectionDef;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetConnectionDefName(const AValue: string);
begin
if FParams.Params.Values[S_FD_DefinitionParam_Common_ConnectionDef] <> AValue then begin
FParams.ParentDefinition := nil;
FParams.Params.DriverID := '';
FParams.Params.ConnectionDef := AValue;
PrepareConnectionDef(False);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetDriverName: string;
begin
Result := FParams.Params.DriverID;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetDriverName(const AValue: string);
begin
if FParams.Params.Values[S_FD_ConnParam_Common_DriverID] <> AValue then begin
FParams.ParentDefinition := nil;
FParams.Params.ConnectionDef := '';
FParams.Params.DriverID := AValue;
PrepareConnectionDef(False);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetActualDriverID: String;
var
oDef: IFDStanConnectionDef;
begin
Result := DriverName;
if Result = '' then begin
FDManager.CheckActive;
if ConnectionDefName <> '' then
oDef := FDManager.ConnectionDefs.FindConnectionDef(ConnectionDefName)
else if ConnectionName <> '' then
oDef := FDManager.ConnectionDefs.FindConnectionDef(ConnectionName)
else
oDef := nil;
if oDef <> nil then
Result := oDef.Params.DriverID;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoValidateName(const AName: string);
var
oConn: TFDCustomConnection;
begin
if AName <> '' then begin
oConn := FDManager.FindConnection(AName);
if (oConn <> nil) and (oConn <> Self) then begin
if not oConn.Temporary or (oConn.FRefCount <> 0) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbDupName, [AName]);
FDFree(oConn);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetConnectionName(const AValue: String);
begin
if csReading in ComponentState then
FConnectionName := AValue
else if FConnectionName <> AValue then begin
CheckInactive;
DoValidateName(AValue);
FConnectionName := AValue;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetLoginDialog(const AValue: TFDGUIxLoginDialog);
begin
if FLoginDialog <> nil then begin
FLoginDialog.RemoveFreeNotification(Self);
FLoginDialog.ConnectionDef := nil;
end;
FLoginDialog := AValue;
if FLoginDialog <> nil then begin
FLoginDialog.FreeNotification(Self);
FLoginDialog.ConnectionDef := ResultConnectionDef;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoInternalLogin;
begin
ConnectionIntf.LoginPrompt := False;
ConnectionIntf.Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoLogin(const AConnectionDef: IFDStanConnectionDef);
procedure ErrorLoginAborted;
var
s: String;
begin
s := ConnectionName;
if s = '' then
s := ConnectionDefName;
if s = '' then
s := ResultConnectionDef.Name;
if s = '' then
s := S_FD_Unnamed;
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbLoginAborted, [s]);
end;
var
oDlg: IFDGUIxLoginDialog;
begin
if Assigned(FOnLogin) then
FOnLogin(Self, AConnectionDef.Params)
else begin
if (Assigned(FLoginDialog) and not Assigned(FLoginDialog.LoginDialog)) or
not Assigned(FLoginDialog) then begin
FDCreateInterface(IFDGUIxLoginDialog, oDlg, False);
if oDlg = nil then begin
DoInternalLogin;
Exit;
end;
oDlg.ConnectionDef := ResultConnectionDef;
end
else
oDlg := FLoginDialog as IFDGUIxLoginDialog;
try
if not oDlg.Execute(DoInternalLogin) then
ErrorLoginAborted;
finally
if not Assigned(FLoginDialog) then
oDlg.ConnectionDef := nil;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.PrepareConnectionDef(ACheckDef: Boolean);
begin
if (ConnectionDefName <> '') or (ConnectionName <> '') then
FDManager.CheckActive;
FParams.ParentDefinition := nil;
if ConnectionDefName <> '' then
if ACheckDef then
FParams.ParentDefinition := FDManager.ConnectionDefs.ConnectionDefByName(ConnectionDefName)
else
FParams.ParentDefinition := FDManager.ConnectionDefs.FindConnectionDef(ConnectionDefName)
else if ConnectionName <> '' then
FParams.ParentDefinition := FDManager.ConnectionDefs.FindConnectionDef(ConnectionName);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.CheckConnectionDef;
begin
PrepareConnectionDef(True);
try
if FParams.Params.Pooled and
not ((FParams.Params.Count = 0) or
(FParams.Params.Count = 1) and
(FParams.Params.Names[0] = S_FD_DefinitionParam_Common_ConnectionDef)) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbCantConnPooled, [GetName]);
if FParams.Params.DriverID = '' then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_AccSrvNotDefined, []);
except
FParams.ParentDefinition := nil;
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetConnectionMetadata(AOpen: Boolean): IFDPhysConnectionMetadata;
begin
if AOpen then
CheckActive;
if ConnectionIntf <> nil then
ConnectionIntf.CreateMetadata(Result)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetConnectionMetadataIntf: IFDPhysConnectionMetadata;
begin
Result := GetConnectionMetadata(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.AcquireDefaultTransaction(const AConnIntf: IFDPhysConnection);
var
oTX: IFDPhysTransaction;
begin
if AConnIntf.Transaction = nil then begin
AConnIntf.CreateTransaction(oTX);
AConnIntf.Transaction := oTX;
end;
AConnIntf.Transaction.AddStateHandler(Self as IFDPhysTransactionStateHandler);
AConnIntf.Transaction.Options := FTxOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.AcquireConnectionIntf(out AConnIntf: IFDPhysConnection);
var
oObjIntf: IFDStanObject;
begin
FDManager.CheckActive;
CheckConnectionDef;
if FParams.Params.Pooled then
FDPhysManager.CreateConnection(
FParams.ParentDefinition as IFDStanConnectionDef, AConnIntf)
else begin
FDPhysManager.CreateConnection(FParams, AConnIntf);
if FSharedCliHandle <> nil then
AConnIntf.SharedCliHandle := FSharedCliHandle;
end;
if Supports(AConnIntf, IFDStanObject, oObjIntf) then begin
oObjIntf.SetOwner(Self, '');
oObjIntf := nil;
end;
AConnIntf.ErrorHandler := Self as IFDStanErrorHandler;
AConnIntf.RecoveryHandler := Self as IFDPhysConnectionRecoveryHandler;
AConnIntf.Options := Self as IFDStanOptions;
FParams.ReadOptions(FormatOptions, UpdateOptions, FetchOptions, ResourceOptions);
AcquireDefaultTransaction(AConnIntf);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.ReleaseDefaultTransaction(const AConnIntf: IFDPhysConnection);
begin
if AConnIntf.Transaction <> nil then begin
AConnIntf.Transaction.Options := nil;
AConnIntf.Transaction.RemoveStateHandler(Self as IFDPhysTransactionStateHandler);
AConnIntf.Transaction := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.ReleaseConnectionIntf(var AConnIntf: IFDPhysConnection);
procedure DoCleanup;
begin
AConnIntf.ErrorHandler := nil;
AConnIntf.RecoveryHandler := nil;
ReleaseDefaultTransaction(AConnIntf);
AConnIntf := nil;
end;
begin
if AConnIntf <> nil then
DoCleanup;
if AConnIntf = FConnectionIntf then
FParams.ParentDefinition := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetConnected: Boolean;
begin
Result := (ConnectionIntf <> nil) and
(ConnectionIntf.State in [csRecovering, csConnected]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.UnRegisterClient(AClient: TObject);
begin
if FDisconnecting then
FDeferredUnregs.Add(AClient)
else
inherited UnRegisterClient(AClient);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetConnected(AValue: Boolean);
var
i: Integer;
begin
try
try
FDisconnecting := not AValue;
inherited SetConnected(AValue);
finally
FDisconnecting := False;
if FDeferredUnregs <> nil then
for i := 0 to FDeferredUnregs.Count - 1 do
UnRegisterClient(TObject(FDeferredUnregs[i]));
end;
finally
if FDeferredUnregs <> nil then
FDeferredUnregs.Clear;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoConnect;
var
lErasePassword: Boolean;
lFailed: Boolean;
begin
if not Connected then
try
inherited DoConnect;
lErasePassword := False;
lFailed := False;
try
try
AcquireConnectionIntf(FConnectionIntf);
lErasePassword := not FParams.HasValue(S_FD_ConnParam_Common_Password) and
not ResourceOptions.AutoReconnect and not FParams.Params.Pooled;
if LoginPrompt and not FParams.Params.Pooled and (Assigned(FOnLogin) or not FDGUIxSilent()) and
(FSharedCliHandle = nil) then
DoLogin(FParams);
if ConnectionIntf.State = csDisconnected then
DoInternalLogin;
FOfflined := False;
except
lFailed := True;
raise;
end;
finally
FParams.OnChanging := nil;
if lErasePassword then
FParams.Params.Password := ''
else if (FParams.Params.NewPassword <> '') and not lFailed then
FParams.Params.Password := FParams.Params.NewPassword;
FParams.Params.NewPassword := '';
FParams.OnChanging := ParamsChanging;
end;
except
ReleaseConnectionIntf(FConnectionIntf);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DoDisconnect;
begin
if not Connected then
Exit;
if FExecSQLCommand <> nil then begin
FExecSQLCommand.ErrorHandler := nil;
FExecSQLCommand := nil;
end;
FDFreeAndNil(FExecSQLTab);
if ConnectionIntf <> nil then begin
try
FRefCount := -1;
if FOfflined then
ReleaseClients(rmOffline)
else
ReleaseClients(rmDisconnect);
if not FParams.Params.Pooled then
ConnectionIntf.Close;
finally
FRefCount := 0;
end;
end;
if FTmpConnectionIntf = FConnectionIntf then
FConnectionIntf := nil
else
ReleaseConnectionIntf(FConnectionIntf);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetConnectionString: String;
var
sName: String;
sStr: String;
begin
sName := ConnectionDefName;
sStr := Trim(ResultConnectionDef.BuildString());
if (sName <> '') and
(CompareText(sStr, S_FD_DefinitionParam_Common_ConnectionDef + '=' + sName) = 0) then
Result := sName
else
Result := sStr;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetConnectionString(const AConnectionString: String);
begin
Connected := False;
ResultConnectionDef.Clear;
if Pos('=', AConnectionString) <> 0 then
ResultConnectionDef.ParseString(AConnectionString)
else
ConnectionDefName := AConnectionString;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetUserNamePassword(const AUserName: String;
const APassword: String);
begin
Connected := False;
if AUserName <> '' then
Params.UserName := AUserName;
if APassword <> '' then
Params.Password := APassword;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Open(const AConnectionString: String);
begin
if ConnectionString <> AConnectionString then
SetConnectionString(AConnectionString);
Connected := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Open(const AConnectionString: String;
const AUserName: String; const APassword: String);
begin
SetConnectionString(AConnectionString);
SetUserNamePassword(AUserName, APassword);
Connected := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Open(const AUserName: String; const APassword: String);
begin
SetUserNamePassword(AUserName, APassword);
Connected := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetOfflined(AValue: Boolean);
begin
if Offlined <> AValue then begin
FOfflined := AValue;
Connected := not AValue;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Offline;
begin
Offlined := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Online;
begin
Offlined := False;
Connected := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.CheckOnline;
begin
if Offlined then
if Temporary or ResourceOptions.AutoConnect then
Online
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbMBOnline, [GetName]);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.Ping: Boolean;
begin
if ConnectionIntf <> nil then
Result := ConnectionIntf.Ping
else
try
Connected := True;
Result := True;
except
Result := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.AbortJob(AWait: Boolean = False);
var
i: Integer;
begin
i := DataSetCount - 1;
while i >= 0 do begin
if (i < DataSetCount) and (DataSets[i] is TFDAdaptedDataSet) then
try
TFDAdaptedDataSet(DataSets[i]).AbortJob(AWait);
except
// silent
end;
Dec(i);
end;
i := CommandCount - 1;
while i >= 0 do begin
if i < CommandCount then
try
Commands[i].AbortJob(AWait);
except
// silent
end;
Dec(i);
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR_Comp}
procedure TFDCustomConnection.Trace(AStep: TFDMoniEventStep; ASender: TObject;
const AMsg: String; const AArgs: array of const);
begin
if (ConnectionIntf <> nil) and ConnectionIntf.Tracing then
ConnectionIntf.Monitor.Notify(ekComponent, AStep, ASender, AMsg, AArgs);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetInfoReport(AList: TStrings;
AItems: TFDInfoReportItems = [riConnDef .. riKeepConnected]): TFDInfoReportStatus;
var
oWait: IFDGUIxWaitCursor;
oMAIntf: IFDMoniAdapter;
i: Integer;
sSessionMsg, sClientMsg, sMsg, sName, sVal: String;
oDef: IFDStanDefinition;
oConnIntf: IFDPhysConnection;
lHasInfo, lDisconnect: Boolean;
oMessages: TStrings;
procedure Header(const ACaption: String);
begin
AList.Add('================================');
AList.Add(ACaption);
AList.Add('================================');
lHasInfo := False;
end;
procedure CheckNA;
begin
if not lHasInfo then
AList.Add(S_FD_ClntNotAccessible);
end;
procedure PutItems(AKind: TFDMoniAdapterItemKind);
var
i: Integer;
sName: String;
vValue: Variant;
eKind: TFDMoniAdapterItemKind;
begin
if oMAIntf <> nil then
for i := 0 to oMAIntf.ItemCount - 1 do begin
oMAIntf.GetItem(i, sName, vValue, eKind);
if eKind = AKind then begin
AList.Add(sName + ' = ' + VarToStr(vValue));
lHasInfo := True;
end;
end;
end;
begin
Result := [];
oWait := nil;
sSessionMsg := '';
sClientMsg := '';
sMsg := '';
lDisconnect := False;
AList.BeginUpdate;
if not ResourceOptions.ActualSilentMode then begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
end;
try
AList.Clear;
if (riTryConnect in AItems) and not Connected then
try
Connected := True;
lDisconnect := not (riKeepConnected in AItems);
except
on E: Exception do
sSessionMsg := E.Message;
end;
try
if ConnectionIntf = nil then
AcquireConnectionIntf(oConnIntf)
else
oConnIntf := ConnectionIntf;
if (oConnIntf <> nil) and (oConnIntf.Driver.State = drsRegistered) then
oConnIntf.Driver.Load;
except
on E: Exception do
sClientMsg := E.Message;
end;
if (oConnIntf = nil) or (oConnIntf.Driver.State = drsRegistered) then
Include(Result, rsClientError)
else if (oConnIntf.State <> csConnected) and (riTryConnect in AItems) then
Include(Result, rsSessionError);
try
if riConnDef in AItems then begin
Header(S_FD_ClntConnDefParams);
oDef := ResultConnectionDef;
while oDef <> nil do begin
for i := 0 to oDef.Params.Count - 1 do begin
sName := oDef.Params.KeyNames[i];
sVal := oDef.Params.ValueFromIndex[i];
if Pos(UpperCase(S_FD_ConnParam_Common_Password), UpperCase(sName)) <> 0 then
sVal := '*****';
AList.Add(sName + '=' + sVal);
lHasInfo := True;
end;
oDef := oDef.ParentDefinition;
end;
CheckNA;
end;
oMAIntf := oConnIntf as IFDMoniAdapter;
if riFireDAC in AItems then begin
Header(C_FD_Product + ' info');
PutItems(ikFireDACInfo);
CheckNA;
end;
if riClient in AItems then begin
Header(S_FD_ClntClientInfo);
if (riClientLog in AItems) and
(oConnIntf <> nil) and (oConnIntf.Driver.Messages <> nil) then begin
lHasInfo := True;
for i := 0 to oConnIntf.Driver.Messages.Count - 1 do begin
sMsg := oConnIntf.Driver.Messages[i];
if (Pos(S_FD_Warning, sMsg) > 0) or (Pos(S_FD_Error, sMsg) > 0) then
Include(Result, rsClientWarning);
AList.Add(sMsg);
end;
end;
if sClientMsg <> '' then begin
AList.Add(S_FD_ClntFailedToLoad);
if Pos(sClientMsg, sMsg) = 0 then begin
AList.Add(sClientMsg);
lHasInfo := True;
end;
end
else
PutItems(ikClientInfo);
CheckNA;
end;
if riSession in AItems then begin
Header(S_FD_ClntSessionInfo);
if (sSessionMsg <> '') and (not (riClient in AItems) or (sClientMsg <> sSessionMsg)) then begin
AList.Add(S_FD_ClntFailedToConnect);
AList.Add(sSessionMsg);
lHasInfo := True;
end
else if (oConnIntf = nil) or (oConnIntf.State <> csConnected) then begin
AList.Add(S_FD_ClntNotConnected);
lHasInfo := True;
end
else begin
if riSessionHints in AItems then begin
oMessages := TFDStringList.Create;
try
oConnIntf.AnalyzeSession(oMessages);
if oMessages.Count > 0 then begin
lHasInfo := True;
AList.Add(S_FD_ClntCheckingSession);
for i := 0 to oMessages.Count - 1 do begin
sMsg := oMessages[i];
if (Pos(S_FD_Warning, sMsg) > 0) or (Pos(S_FD_Error, sMsg) > 0) then
Include(Result, rsSessionWarning);
AList.Add(' ' + sMsg);
end;
end;
finally
FDFree(oMessages);
end;
end;
PutItems(ikSessionInfo);
end;
CheckNA;
end;
finally
if ConnectionIntf = nil then
ReleaseConnectionIntf(oConnIntf);
end;
finally
if lDisconnect then
Connected := False;
if oWait <> nil then
oWait.StopWait;
AList.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetInTransaction: Boolean;
begin
if Connected then
Result := ConnectionIntf.Transaction.Active
else
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.StartTransaction;
begin
CheckActive;
ConnectionIntf.Transaction.StartTransaction;
if (FUpdateTransaction <> nil) and
(ConnectionIntf.Transaction <> FUpdateTransaction.TransactionIntf) then
FUpdateTransaction.StartTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Commit;
begin
CheckActive;
ConnectionIntf.Transaction.Commit;
if (FUpdateTransaction <> nil) and
(ConnectionIntf.Transaction <> FUpdateTransaction.TransactionIntf) then
FUpdateTransaction.Commit;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.CommitRetaining;
begin
CheckActive;
ConnectionIntf.Transaction.CommitRetaining;
if (FUpdateTransaction <> nil) and
(ConnectionIntf.Transaction <> FUpdateTransaction.TransactionIntf) then
FUpdateTransaction.CommitRetaining;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.Rollback;
begin
CheckActive;
ConnectionIntf.Transaction.Rollback;
if (FUpdateTransaction <> nil) and
(ConnectionIntf.Transaction <> FUpdateTransaction.TransactionIntf) then
FUpdateTransaction.Rollback;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.RollbackRetaining;
begin
CheckActive;
ConnectionIntf.Transaction.RollbackRetaining;
if (FUpdateTransaction <> nil) and
(ConnectionIntf.Transaction <> FUpdateTransaction.TransactionIntf) then
FUpdateTransaction.RollbackRetaining;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleDisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
var
i: Integer;
oDS: TFDRdbmsDataSet;
begin
for i := DataSetCount - 1 downto 0 do
if DataSets[i] is TFDRdbmsDataSet then begin
oDS := TFDRdbmsDataSet(DataSets[i]);
if (oDS.Transaction = nil) and oDS.Prepared and
(not Assigned(AFilter) or AFilter(oDS.Command.CommandIntf.CliObj)) then
case AMode of
dmOffline: oDS.Offline;
dmRelease: oDS.Release;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.HandleTxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
begin
case AOperation of
tsActive:
if ABefore then begin
if Assigned(BeforeStartTransaction) then
BeforeStartTransaction(Self);
end
else begin
if Assigned(AfterStartTransaction) then
AfterStartTransaction(Self);
end;
tsCommiting:
if ABefore then begin
if Assigned(BeforeCommit) then
BeforeCommit(Self);
end
else begin
if Assigned(AfterCommit) then
AfterCommit(Self);
end;
tsRollingback:
if ABefore then begin
if Assigned(BeforeRollback) then
BeforeRollback(Self);
end
else begin
if Assigned(AfterRollback) then
AfterRollback(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.ReleaseClients(AMode: TFDReleaseClientMode = rmDisconnect);
var
n, i: Integer;
oDS: TFDAdaptedDataSet;
begin
for i := DataSetCount - 1 downto 0 do
case AMode of
rmFetchAll:
begin
oDS := TFDAdaptedDataSet(DataSets[i]);
if oDS.Active and not oDS.SourceEOF and oDS.DoIsSourceOpen then
if not oDS.FClientCursor then
oDS.Release
else if oDS.FetchOptions.Unidirectional then
oDS.Close
else
oDS.FetchAll;
end;
rmClose:
DataSets[i].Close;
rmOffline:
DataSets[i].Offline;
rmDisconnect:
begin
n := DataSetCount;
DataSets[i].Disconnect(True);
if n = DataSetCount then
DetachClient(DataSets[i]);
end;
end;
for i := CommandCount - 1 downto 0 do begin
case AMode of
rmFetchAll,
rmClose:
Commands[i].Close;
rmOffline,
rmDisconnect:
begin
n := CommandCount;
Commands[i].Disconnect(True);
if n = CommandCount then
DetachClient(Commands[i]);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetADDataSet(AIndex: Integer): TFDDataSet;
begin
Result := inherited DataSets[AIndex] as TFDDataSet;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCommandCount: Integer;
begin
Result := FCommands.Count;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCommands(AIndex: Integer): TFDCustomCommand;
begin
Result := TFDCustomCommand(FCommands[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.AttachClient(AClient: TObject);
begin
RegisterClient(AClient);
if AClient is TFDCustomCommand then
FCommands.Add(AClient);
if FRefCount = 0 then
Open
else if FRefCount > 0 then
Inc(FRefCount);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DetachClient(AClient: TObject);
begin
UnRegisterClient(AClient);
if AClient is TFDCustomCommand then
FCommands.Remove(AClient);
if FRefCount = 1 then begin
if not ResourceOptions.KeepConnection then
Close;
end
else if FRefCount > 0 then
Dec(FRefCount);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetFieldNames(const ACatalogName, ASchemaName,
ATableName, APattern: String; AList: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetTableFields(ACatalogName, ASchemaName, ATableName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeObjectName('*', '*', '*',
CnvMetaValue(oView.Rows[i].GetData('COLUMN_NAME'))));
finally
AList.EndUpdate;
FDClearMetaView(oView, FetchOptions);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetKeyFieldNames(const ACatalogName,
ASchemaName, ATableName, APattern: string; AList: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetTablePrimaryKeyFields(ACatalogName, ASchemaName, ATableName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeObjectName('*', '*', '*',
CnvMetaValue(oView.Rows[i].GetData('COLUMN_NAME'))));
finally
AList.EndUpdate;
FDClearMetaView(oView, FetchOptions);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetIndexNames(const ACatalogName, ASchemaName,
ATableName, APattern: string; AList: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetTableIndexes(ACatalogName, ASchemaName, ATableName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeObjectName('*', '*', '*',
CnvMetaValue(oView.Rows[i].GetData('INDEX_NAME'))));
finally
AList.EndUpdate;
FDClearMetaView(oView, FetchOptions);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.EncodeObjectName(const ACatalogName, ASchemaName,
ABaseObjectName, AObjectName: String): String;
var
oConMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
begin
CheckActive;
rName.FCatalog := CnvMetaValue(ACatalogName);
rName.FSchema := CnvMetaValue(ASchemaName);
rName.FBaseObject := CnvMetaValue(ABaseObjectName);
rName.FObject := CnvMetaValue(AObjectName);
ConnectionIntf.CreateMetadata(oConMeta);
Result := oConMeta.EncodeObjName(rName, nil, [eoBeautify]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.DecodeObjectName(const AFullName: String;
var ACatalogName, ASchemaName, ABaseObjectName, AObjectName: String);
var
oConMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
begin
CheckActive;
ConnectionIntf.CreateMetadata(oConMeta);
oConMeta.DecodeObjName(AFullName, rName, nil, [doUnquote, doNormalize]);
ACatalogName := rName.FCatalog;
ASchemaName := rName.FSchema;
ABaseObjectName := rName.FBaseObject;
AObjectName := rName.FObject;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.CnvMetaValue(const AStr: Variant; const ADefault: String = ''): String;
begin
Result := VarToStrDef(AStr, '');
if (CompareText(Result, '<NULL>') = 0) or
(ADefault <> '') and (CompareText(Result, ADefault) = 0) then
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetCatalogNames(const APattern: string;
AList: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetCatalogs(APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(CnvMetaValue(oView.Rows[i].GetData('CATALOG_NAME'), ''));
finally
AList.EndUpdate;
FDFree(oView.Table);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetSchemaNames(const ACatalogName,
APattern: string; AList: TStrings);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetSchemas(ACatalogName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(CnvMetaValue(oView.Rows[i].GetData('SCHEMA_NAME'), ''));
finally
AList.EndUpdate;
FDFree(oView.Table);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.EncodeListName(const ACatalogName, ASchemaName: String;
const ABaseField, AObjField: String; ARow: TFDDatSRow; AList: TStrings;
AFullName: Boolean): String;
var
sBase, sObj, sName: String;
begin
Result := '';
sBase := '';
sObj := '';
sName := '';
if ABaseField <> '' then begin
sBase := CnvMetaValue(ARow.GetData(ABaseField));
sName := sBase;
end;
if AObjField <> '' then begin
sObj := CnvMetaValue(ARow.GetData(AObjField));
sName := sObj;
end;
if not AFullName then begin
Result := EncodeObjectName('', '', '', sName);
if AList.IndexOf(Result) >= 0 then
Result := '';
end;
if Result = '' then
Result := EncodeObjectName(
CnvMetaValue(ARow.GetData('CATALOG_NAME'), ACatalogName),
CnvMetaValue(ARow.GetData('SCHEMA_NAME'), ASchemaName),
sBase, sObj);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetTableNames(const ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AKinds: TFDPhysTableKinds; AFullName: Boolean);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetTables(AScopes, AKinds, ACatalogName, ASchemaName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeListName(ACatalogName, ASchemaName, '', 'TABLE_NAME',
oView.Rows[i], AList, AFullName));
finally
AList.EndUpdate;
FDFree(oView.Table);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetPackageNames(const ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes; AFullName: Boolean);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetPackages(AScopes, ACatalogName, ASchemaName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeListName(ACatalogName, ASchemaName, 'PACKAGE_NAME', '',
oView.Rows[i], AList, AFullName));
finally
AList.EndUpdate;
FDFree(oView.Table);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetStoredProcNames(const ACatalogName, ASchemaName,
APackage, APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes;
AFullName: Boolean);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
s: String;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
if APackage = '' then
oView := oConnMeta.GetProcs(AScopes, ACatalogName, ASchemaName, APattern)
else
oView := oConnMeta.GetPackageProcs(ACatalogName, ASchemaName, APackage, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do begin
if APackage <> '' then
s := CnvMetaValue(oView.Rows[i].GetData('PROC_NAME'))
else
s := EncodeListName(ACatalogName, ASchemaName, '', 'PROC_NAME',
oView.Rows[i], AList, AFullName);
AList.Add(s);
end;
finally
AList.EndUpdate;
if APackage = '' then
FDFree(oView.Table)
else
FDClearMetaView(oView, FetchOptions);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.GetGeneratorNames(const ACatalogName, ASchemaName,
APattern: string; AList: TStrings; AScopes: TFDPhysObjectScopes; AFullName: Boolean);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
i: Integer;
oConn: TFDCustomConnection;
begin
oConn := FDManager.AcquireConnection(Self, Name);
try
oConnMeta := GetConnectionMetadata(True);
oView := oConnMeta.GetGenerators(AScopes, ACatalogName, ASchemaName, APattern);
AList.BeginUpdate;
try
AList.Clear;
for i := 0 to oView.Rows.Count - 1 do
AList.Add(EncodeListName(ACatalogName, ASchemaName, '', 'GENERATOR_NAME',
oView.Rows[i], AList, AFullName));
finally
AList.EndUpdate;
FDFree(oView.Table);
end;
finally
FDManager.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.RefreshMetadataCache(const AObjName: String = '');
var
oConnMeta: IFDPhysConnectionMetadata;
begin
if Connected then begin
oConnMeta := GetConnectionMetadata(False);
oConnMeta.RefreshMetadataCache(AObjName);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.ApplyUpdates(const ADataSets: array of TFDDataSet);
var
i: Integer;
oDS: TFDDataSet;
oConn: TFDCustomConnection;
begin
StartTransaction;
try
for i := Low(ADataSets) to High(ADataSets) do begin
oDS := ADataSets[i];
if oDS is TFDAdaptedDataSet then begin
oConn := TFDAdaptedDataSet(oDS).GetConnection(False);
if (oConn <> nil) and (oConn <> Self) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntConnNotMatch, []);
end;
oDS.ApplyUpdates;
end;
Commit;
except
Rollback;
raise;
end;
for i := Low(ADataSets) to High(ADataSets) do
ADataSets[i].CommitUpdates;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetName: TComponentName;
begin
if Name = '' then
Result := '$' + IntToHex(Integer(Self), 8)
else
Result := Name;
Result := Result + ': ' + ClassName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetParent: IFDStanObject;
begin
Result := FDManager as IFDStanObject;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetLastAutoGenValue(const AName: String): Variant;
begin
CheckActive;
Result := ConnectionIntf.GetLastAutoGenValue(AName);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetMessages: EFDDBEngineException;
begin
if ConnectionIntf <> nil then
Result := ConnectionIntf.Messages
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCurrentCatalog: String;
begin
if ConnectionIntf <> nil then
Result := ConnectionIntf.CurrentCatalog
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCurrentSchema: String;
begin
if ConnectionIntf <> nil then
Result := ConnectionIntf.CurrentSchema
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetState: TFDPhysConnectionState;
begin
if ConnectionIntf <> nil then
Result := ConnectionIntf.State
else
Result := csDisconnected;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.BaseCreateSQL: IFDPhysCommand;
var
oFtch: TFDFetchOptions;
oRes: TFDResourceOptions;
begin
CheckActive;
if FExecSQLCommand = nil then begin
FConnectionIntf.CreateCommand(Result);
oFtch := Result.Options.FetchOptions;
oFtch.RowsetSize := 1;
oFtch.Items := oFtch.Items - [fiMeta];
oFtch.AutoClose := True;
oFtch.AutoFetchAll := afAll;
oFtch.RecordCountMode := cmVisible;
oFtch.Mode := fmOnDemand;
oRes := Result.Options.ResourceOptions;
if oRes.CmdExecMode = amAsync then
oRes.CmdExecMode := amBlocking;
oRes.DirectExecute := True;
oRes.ParamCreate := True;
oRes.ParamExpand := True;
oRes.Persistent := False;
Result.ErrorHandler := Self as IFDStanErrorHandler;
if FExecSQLCommand = nil then
FExecSQLCommand := Result;
end
else
Result := FExecSQLCommand;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.BasePrepareSQL(const ACommand: IFDPhysCommand; const ASQL: String;
const AParams: array of Variant; const ATypes: array of TFieldType; ABindMode: TFDParamBindMode): Boolean;
var
i: Integer;
begin
Result := (ACommand.CommandText <> ASQL) and (ASQL <> '') or
(ACommand.Params.BindMode <> ABindMode);
if Result then begin
ACommand.Disconnect;
ACommand.Params.Clear;
ACommand.CommandText := '';
ACommand.Params.BindMode := ABindMode;
ACommand.CommandKind := skUnknown;
ACommand.CommandText := ASQL;
end;
if High(AParams) >= Low(AParams) then begin
for i := Low(ATypes) to High(ATypes) do
if ATypes[i] <> ftUnknown then
ACommand.Params[i].DataType := ATypes[i];
for i := Low(AParams) to High(AParams) do
ACommand.Params[i].Value := AParams[i];
if ACommand.State = csInactive then begin
Result := True;
ACommand.Prepare();
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt;
var
oCmd: IFDPhysCommand;
begin
oCmd := BaseCreateSQL;
try
BasePrepareSQL(oCmd, ASQL, AParams, ATypes, pbByName);
oCmd.Execute();
Result := oCmd.RowsAffected;
finally
oCmd.AbortJob(True);
oCmd.CloseAll;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; AIgnoreObjNotExists: Boolean = False): LongInt;
begin
try
Result := ExecSQL(ASQL, [], []);
except
on E: EFDDBEngineException do
if not AIgnoreObjNotExists or (E.Kind <> ekObjNotExists) then
raise
else
Result := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; const AParams: array of Variant): LongInt;
begin
Result := ExecSQL(ASQL, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; AParams: TFDParams): LongInt;
var
oCmd: IFDPhysCommand;
begin
oCmd := BaseCreateSQL;
try
BasePrepareSQL(oCmd, ASQL, [], [], pbByNumber);
AParams.BindMode := pbByNumber;
oCmd.Params := AParams;
oCmd.Execute();
Result := oCmd.RowsAffected;
finally
oCmd.AbortJob(True);
oCmd.CloseAll;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; AParams: TFDParams;
var AResultSet: TDataSet): LongInt;
var
oQry: TFDQuery;
begin
oQry := TFDQuery.Create(nil);
try
oQry.Connection := Self;
oQry.SQL.Text := ASQL;
if AParams <> nil then begin
AParams.BindMode := pbByNumber;
oQry.Params := AParams;
end;
oQry.Open;
Result := oQry.RecordCount;
finally
AResultSet := oQry;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQL(const ASQL: String; var AResultSet: TDataSet): LongInt;
begin
Result := ExecSQL(ASQL, nil, AResultSet);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQLScalar(const ASQL: String;
const AParams: array of Variant; const ATypes: array of TFieldType): Variant;
var
oCmd: IFDPhysCommand;
begin
oCmd := BaseCreateSQL;
try
if BasePrepareSQL(oCmd, ASQL, AParams, ATypes, pbByName) or (FExecSQLTab = nil) then begin
FDFreeAndNil(FExecSQLTab);
FExecSQLTab := oCmd.Define;
end;
oCmd.Open;
oCmd.Fetch(FExecSQLTab);
if (FExecSQLTab.Rows.Count > 0) and (FExecSQLTab.Columns.Count > 0) then
Result := FExecSQLTab.Rows[0].GetData(0)
else
Result := Unassigned;
finally
if FExecSQLTab <> nil then
FExecSQLTab.Clear;
oCmd.AbortJob(True);
oCmd.CloseAll;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQLScalar(const ASQL: String): Variant;
begin
Result := ExecSQLScalar(ASQL, [], []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.ExecSQLScalar(const ASQL: String;
const AParams: array of Variant): Variant;
begin
Result := ExecSQLScalar(ASQL, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCliObj: Pointer;
begin
CheckActive;
Result := ConnectionIntf.CliObj;
end;
{-------------------------------------------------------------------------------}
function TFDCustomConnection.GetCliHandle: Pointer;
begin
CheckActive;
Result := ConnectionIntf.CliHandle;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetSharedCliHandle(const AValue: Pointer);
begin
if SharedCliHandle <> AValue then begin
CheckInactive;
FSharedCliHandle := AValue;
DriverName := FDPhysManager.DriverIDFromSharedCliHandle(AValue);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetTransaction(const AValue: TFDCustomTransaction);
begin
if FTransaction <> AValue then begin
FTransaction := AValue;
if FTransaction <> nil then begin
FTransaction.FreeNotification(Self);
FTransaction.Connection := Self;
if ConnectionIntf <> nil then
ConnectionIntf.Transaction := FTransaction.TransactionIntf;
end
else begin
if ConnectionIntf <> nil then begin
ConnectionIntf.Transaction := nil;
AcquireDefaultTransaction(ConnectionIntf);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomConnection.SetUpdateTransaction(const AValue: TFDCustomTransaction);
begin
if FUpdateTransaction <> AValue then begin
FUpdateTransaction := AValue;
if FUpdateTransaction <> nil then begin
FUpdateTransaction.FreeNotification(Self);
FUpdateTransaction.Connection := Self;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomTransaction }
{-------------------------------------------------------------------------------}
constructor TFDCustomTransaction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOptionsIntf := TFDTxOptions.Create;
FDataSets := TFDObjList.Create;
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomTransaction.Destroy;
begin
Destroying;
Connection := nil;
inherited Destroy;
FDFreeAndNil(FOptionsIntf);
FDFreeAndNil(FDataSets);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if AComponent = Connection then
Connection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.SetConnection(const AValue: TFDCustomConnection);
begin
if FConnection <> AValue then begin
if FConnection <> nil then begin
InternalDeleteTxIntf;
FConnection.UnRegisterClient(Self);
end;
FConnection := AValue;
if FConnection <> nil then begin
FConnection.RegisterClient(Self, DoConnectChanged);
FConnection.FreeNotification(Self);
if FConnection.Connected then
InternalCreateTxIntf;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.DoConnectChanged(Sender: TObject; Connecting: Boolean);
begin
if Connecting then
InternalCreateTxIntf
else
InternalDeleteTxIntf;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.SetOptions(const AValue: TFDTxOptions);
begin
FOptionsIntf.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTransaction.GetActive: Boolean;
begin
Result := (FTransactionIntf <> nil) and FTransactionIntf.Active;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTransaction.GetDataSetCount: Integer;
begin
Result := FDataSets.Count;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTransaction.GetDataSets(AIndex: Integer): TFDDataSet;
begin
Result := TFDDataSet(FDataSets[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.InternalCreateTxIntf;
begin
if FTransactionIntf = nil then begin
Connection.ConnectionIntf.CreateTransaction(FTransactionIntf);
FTransactionIntf.Options.Assign(FOptionsIntf);
FTransactionIntf.AddStateHandler(Self);
FDFree(FOptionsIntf);
FOptionsIntf := FTransactionIntf.Options;
if Connection.Transaction = Self then
Connection.ConnectionIntf.Transaction := FTransactionIntf;
FSerialID := 0;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.InternalDeleteTxIntf;
var
i: Integer;
begin
HandleDisconnectCommands(nil, dmRelease);
if FTransactionIntf <> nil then begin
if (FTransactionIntf.State = tsActive) and (FSerialID = FTransactionIntf.SerialID) then
if FNestingLevel = FTransactionIntf.NestingLevel then
FTransactionIntf.Disconnect
else begin
for i := FNestingLevel downto 1 do
if Active then
case Options.DisconnectAction of
xdCommit: Commit;
xdRollback: Rollback;
end;
end;
if (Connection <> nil) and (Connection.ConnectionIntf <> nil) and
(Connection.ConnectionIntf.Transaction = FTransactionIntf) and
Connection.ConnectionMetaDataIntf.TxMultiple then begin
Connection.ConnectionIntf.Transaction := nil;
Connection.AcquireDefaultTransaction(Connection.ConnectionIntf);
end;
FOptionsIntf := TFDTxOptions.Create;
FOptionsIntf.Assign(FTransactionIntf.Options);
FTransactionIntf.RemoveStateHandler(Self);
FTransactionIntf := nil;
FSerialID := 0;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.StartTransaction;
begin
if FNestingLevel = 0 then
FDManager.AcquireConnection(FConnection, Name);
try
FConnection.CheckActive;
ASSERT(FTransactionIntf <> nil);
FTransactionIntf.StartTransaction;
except
if FNestingLevel = 0 then
FDManager.ReleaseConnection(FConnection);
raise;
end;
Inc(FNestingLevel);
FSerialID := FTransactionIntf.SerialID;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.CheckConnected;
begin
if Connection = nil then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbNotDefined, [Name]);
if not FConnection.Connected then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDbMBActive, [Name]);
ASSERT(FTransactionIntf <> nil);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTransaction.CheckActive: Boolean;
begin
CheckConnected;
if not FTransactionIntf.Active then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntTxMBActive, [Name]);
Result := FSerialID = FTransactionIntf.SerialID;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.CheckReleased(ARetaining, AMyTrans: Boolean);
begin
// if retaining, then just sync local field to Phys Layer value
if ARetaining then
FNestingLevel := FTransactionIntf.NestingLevel
// if finishing, then if Phys Layer TX finished or Comp Layer is finishing,
// then release connection objects
else if (FTransactionIntf = nil) or (FTransactionIntf.NestingLevel = 0) or
(FNestingLevel = 1) then begin
FDManager.ReleaseConnection(FConnection);
FNestingLevel := 0;
end
// sync local field to Phys Layer value
else if FNestingLevel > 0 then begin
FNestingLevel := FTransactionIntf.NestingLevel;
if FNestingLevel > 0 then
Dec(FNestingLevel);
end;
if AMyTrans then
FSerialID := FTransactionIntf.SerialID
else
FSerialID := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.Commit;
var
lMyTrans: Boolean;
begin
lMyTrans := CheckActive;
try
FTransactionIntf.Commit;
finally
CheckReleased(False, lMyTrans);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.CommitRetaining;
var
lMyTrans: Boolean;
begin
lMyTrans := CheckActive;
try
FTransactionIntf.CommitRetaining;
finally
CheckReleased(True, lMyTrans);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.Rollback;
var
lMyTrans: Boolean;
begin
lMyTrans := CheckActive;
try
FTransactionIntf.Rollback;
finally
CheckReleased(False, lMyTrans);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.RollbackRetaining;
var
lMyTrans: Boolean;
begin
lMyTrans := CheckActive;
try
FTransactionIntf.RollbackRetaining;
finally
CheckReleased(True, lMyTrans);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.HandleDisconnectCommands(AFilter: TFDPhysDisconnectFilter;
AMode: TFDPhysDisconnectMode);
var
i: Integer;
oDS: TFDRdbmsDataSet;
begin
for i := DataSetCount - 1 downto 0 do
if (i < DataSetCount) and (DataSets[i] is TFDRdbmsDataSet) then begin
oDS := TFDRdbmsDataSet(DataSets[i]);
if (oDS.Command.CommandIntf <> nil) and
(not Assigned(AFilter) or AFilter(oDS.Command.CommandIntf.CliObj)) then
case AMode of
dmOffline: oDS.Offline;
dmRelease: oDS.Release;
end
else
if (AMode = dmRelease) and
not ((TransactionIntf <> nil) and
(TransactionIntf.State in [tsStarting, tsCommiting, tsRollingback])) then
oDS.Cancel;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTransaction.HandleTxOperation(AOperation: TFDPhysTransactionState;
ABefore: Boolean);
begin
case AOperation of
tsActive:
if ABefore then begin
if Assigned(BeforeStartTransaction) then
BeforeStartTransaction(Self);
end
else begin
if Assigned(AfterStartTransaction) then
AfterStartTransaction(Self);
end;
tsCommiting:
if ABefore then begin
if Assigned(BeforeCommit) then
BeforeCommit(Self);
end
else begin
if Assigned(AfterCommit) then
AfterCommit(Self);
end;
tsRollingback:
if ABefore then begin
if Assigned(BeforeRollback) then
BeforeRollback(Self);
end
else begin
if Assigned(AfterRollback) then
AfterRollback(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomEventAlerter }
{-------------------------------------------------------------------------------}
constructor TFDCustomEventAlerter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FNames := TFDStringList.Create;
TFDStringList(FNames).OnChange := DoNamesChanged;
FOptionsIntf := TFDEventAlerterOptions.Create;
FChangeHandlers := TInterfaceList.Create;
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomEventAlerter.Destroy;
begin
Destroying;
Connection := nil;
inherited Destroy;
FDFreeAndNil(FOptionsIntf);
FDFreeAndNil(FNames);
FDFreeAndNil(FChangeHandlers);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if AComponent = Connection then
Connection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Loaded;
begin
inherited Loaded;
try
if FStreamedActive then
SetActive(True);
except
if csDesigning in ComponentState then
FDHandleException
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.CheckAutoRegister;
begin
if not (csDestroying in ComponentState) and
Options.AutoRegister and (Names.Count > 0) and
(Connection <> nil) and Connection.Connected then
Register;
end;
{-------------------------------------------------------------------------------}
function TFDCustomEventAlerter.GetActive: Boolean;
begin
Result := (FEventAlerterIntf <> nil) and
(FEventAlerterIntf.State in [esRegistered, esFiring]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.SetActive(const AValue: Boolean);
begin
if csReading in ComponentState then
FStreamedActive := AValue
else if Active <> AValue then
if AValue then
Register
else
Unregister;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.SetConnection(const AValue: TFDCustomConnection);
begin
if FConnection <> AValue then begin
if FConnection <> nil then begin
Unregister;
FConnection.UnRegisterClient(Self);
end;
FConnection := AValue;
if FConnection <> nil then begin
FConnection.RegisterClient(Self, DoConnectChanged);
FConnection.FreeNotification(Self);
CheckAutoRegister;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.DoConnectChanged(Sender: TObject; Connecting: Boolean);
begin
if Connecting then
CheckAutoRegister
else
Unregister;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.DoNamesChanged(ASender: TObject);
begin
Unregister;
CheckAutoRegister;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.SetNames(const AValue: TStrings);
begin
FNames.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.SetSubscriptionName(const AValue: String);
begin
if FSubscriptionName <> AValue then begin
Unregister;
FSubscriptionName := AValue;
CheckAutoRegister;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.SetOptions(const AValue: TFDEventAlerterOptions);
begin
FOptionsIntf.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.HandleEvent(const AEventName: String;
const AArgument: Variant);
begin
if Assigned(FOnAlert) then
FOnAlert(Self, AEventName, AArgument);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.HandleTimeout(var AContinue: Boolean);
begin
if Assigned(FOnTimeout) then
FOnTimeout(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Register;
var
i: Integer;
begin
if Active then
Exit;
FDManager.AcquireConnection(FConnection, Name);
try
Connection.CheckActive;
Connection.ConnectionIntf.CreateEvent(Options.Kind, FEventAlerterIntf);
FEventAlerterIntf.SubscriptionName := FSubscriptionName;
FEventAlerterIntf.Options := FOptionsIntf;
FEventAlerterIntf.Names := FNames;
FEventAlerterIntf.Handler := Self as IFDPhysEventHandler;
for i := 0 to FChangeHandlers.Count - 1 do
FEventAlerterIntf.AddChangeHandler(FChangeHandlers[i] as IFDPhysChangeHandler);
FEventAlerterIntf.Register;
except
FDManager.ReleaseConnection(FConnection);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Unregister;
begin
if not Active then
Exit;
FEventAlerterIntf.Unregister;
FEventAlerterIntf.Options := nil;
FEventAlerterIntf.Handler := nil;
FEventAlerterIntf := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Signal(const AEvent: String;
const AArgument: Variant);
begin
Register;
FEventAlerterIntf.Signal(AEvent, AArgument);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.Refresh(const AHandler: IFDPhysChangeHandler; AForce: Boolean);
begin
Register;
FEventAlerterIntf.Refresh(AHandler, AForce);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.AddChangeHandler(const AHandler: IFDPhysChangeHandler);
begin
FChangeHandlers.Add(AHandler);
if Active then
FEventAlerterIntf.AddChangeHandler(AHandler);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomEventAlerter.RemoveChangeHandler(const AHandler: IFDPhysChangeHandler);
begin
FChangeHandlers.Remove(AHandler);
if Active then
FEventAlerterIntf.RemoveChangeHandler(AHandler);
end;
{-------------------------------------------------------------------------------}
{ TFDCustomCommand }
{-------------------------------------------------------------------------------}
constructor TFDCustomCommand.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnableParamsStorage := True;
SetOptionsIntf(nil);
FCommandText := TFDStringList.Create;
TFDStringList(FCommandText).TrailingLineBreak := False;
TFDStringList(FCommandText).OnChanging := DoSQLChanging;
TFDStringList(FCommandText).OnChange := DoSQLChange;
FMacros := TFDMacros.CreateRefCounted(GetParamsOwner);
FMacros.OnChanged := MacrosChanged;
FParams := TFDParams.CreateRefCounted(GetParamsOwner);
FRowsAffected := -1;
FActiveStoredUsage := [auDesignTime, auRunTime];
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomCommand.Destroy;
begin
Destroying;
Disconnect(True);
Transaction := nil;
inherited Destroy;
FParams.RemRef;
FParams := nil;
FMacros.RemRef;
FMacros := nil;
if FOptionsIntf <> nil then begin
FOptionsIntf.ObjectDestroyed(Self);
FOptionsIntf := nil;
end;
FDFreeAndNil(FCommandText);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetParamsOwner: TPersistent;
begin
if FOwner <> nil then
Result := FOwner
else
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetDisplayName: String;
begin
if FOwner <> nil then
Result := FOwner.Name
else
Result := GetName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.PropertyChange;
begin
if (FOwner <> nil) and (FOwner is TFDAdaptedDataSet) and
not (csDestroying in FOwner.ComponentState) then
TFDAdaptedDataSet(FOwner).DataEvent(dePropertyChange, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Loaded;
begin
inherited Loaded;
try
if DoStoredActivation then begin
if FStreamedPrepared then
SetPrepared(True);
if FStreamedActive then
SetActive(True);
end;
except
if csDesigning in ComponentState then
FDHandleException
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
if AOperation = opRemove then
if AComponent = FConnection then
SetConnection(nil)
else if AComponent = FTransaction then
SetTransaction(nil);
inherited Notification(AComponent, AOperation);
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR_Comp}
procedure TFDCustomCommand.Trace(AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
begin
if FConnection <> nil then
FConnection.Trace(AStep, Self, AMsg, AArgs);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDCustomCommand.CheckComponentState(AState: TComponentState): Boolean;
begin
Result := (AState * ComponentState <> []) or
(FOwner <> nil) and (AState * FOwner.ComponentState <> []);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CheckInactive;
begin
if Active then
if CheckComponentState([csDesigning]) then
CloseAll
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntAdaptMBInactive,
[GetDisplayName]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CheckActive;
begin
if not Active then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntAdaptMBActive,
[GetDisplayName]);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CheckUnprepared;
begin
CheckInactive;
Prepared := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CheckAsyncProgress;
begin
if CommandIntf <> nil then
CommandIntf.CheckAsyncProgress;
if (FOwner <> nil) and (FOwner.State = dsOpening) and
((FThreadID = 0) or (FThreadID <> TThread.CurrentThread.ThreadID)) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_AccAsyncOperInProgress, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CheckPrepared;
begin
CheckAsyncProgress;
Prepared := True;
end;
{-------------------------------------------------------------------------------}
// IFDStanOptions
procedure TFDCustomCommand.GetParentOptions(var AOpts: IFDStanOptions);
var
oConn: TFDCustomConnection;
begin
if FConnection <> nil then
AOpts := FConnection.OptionsIntf
else begin
oConn := GetConnection(False);
if oConn <> nil then
AOpts := oConn.OptionsIntf;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetOptionsIntf(const AValue: IFDStanOptions);
begin
if (FOptionsIntf <> AValue) or (FOptionsIntf = nil) and (AValue = nil) then begin
FOptionsIntf := AValue;
if FOptionsIntf = nil then
FOptionsIntf := TFDOptionsContainer.Create(Self, TFDFetchOptions,
TFDBottomUpdateOptions, TFDBottomResourceOptions, GetParentOptions);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetFetchOptions: TFDFetchOptions;
begin
Result := FOptionsIntf.FetchOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetFetchOptions(const AValue: TFDFetchOptions);
begin
FOptionsIntf.FetchOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetFormatOptions: TFDFormatOptions;
begin
Result := FOptionsIntf.FormatOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetFormatOptions(const AValue: TFDFormatOptions);
begin
FOptionsIntf.FormatOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetUpdateOptions: TFDBottomUpdateOptions;
begin
Result := TFDBottomUpdateOptions(FOptionsIntf.UpdateOptions);
ASSERT((Result <> nil) and (Result is TFDBottomUpdateOptions));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetUpdateOptions(const AValue: TFDBottomUpdateOptions);
begin
FOptionsIntf.UpdateOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetResourceOptions: TFDBottomResourceOptions;
begin
Result := TFDBottomResourceOptions(FOptionsIntf.ResourceOptions);
ASSERT((Result <> nil) and (Result is TFDBottomResourceOptions));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetResourceOptions(const AValue: TFDBottomResourceOptions);
begin
FOptionsIntf.ResourceOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
// Other
function TFDCustomCommand.GetConnection(ACheck: Boolean): TFDCustomConnection;
begin
if FConnection <> nil then
Result := FConnection
else begin
Result := FDManager.FindConnection(ConnectionName);
if (Result = nil) and ACheck then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDBNotFound,
[ConnectionName, GetDisplayName]);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetConnection(const AValue: TFDCustomConnection);
begin
if FConnection <> AValue then begin
CheckUnprepared;
FConnection := AValue;
if FConnection <> nil then begin
FConnection.FreeNotification(Self);
FConnectionName := FConnection.ConnectionName;
FBindedBy := bbObject;
end
else begin
FConnectionName := '';
FBindedBy := bbNone;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetConnectionName(const AValue: String);
begin
if FConnectionName <> AValue then begin
CheckUnprepared;
FConnectionName := AValue;
FConnection := nil;
FBindedBy := bbName;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.IsCNNS: Boolean;
begin
Result := (FBindedBy = bbName);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.IsCNS: Boolean;
begin
Result := (FBindedBy = bbObject);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetTransaction(const AValue: TFDCustomTransaction);
begin
if FTransaction <> AValue then begin
CheckUnprepared;
if FTransaction <> nil then
if FOwner <> nil then
FTransaction.FDataSets.Remove(FOwner);
FTransaction := AValue;
if FTransaction <> nil then begin
FTransaction.FreeNotification(Self);
if FOwner <> nil then
FTransaction.FDataSets.Add(FOwner);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.AcquireConnection: TFDCustomConnection;
begin
if FBindedBy = bbObject then
Result := FDManager.AcquireConnection(FConnection, GetDisplayName)
else
Result := FDManager.AcquireConnection(ConnectionName, GetDisplayName);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.ReleaseConnection(var AConnection: TFDCustomConnection);
begin
FDManager.ReleaseConnection(AConnection);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalCreateCommandIntf;
begin
FConnection.ConnectionIntf.CreateCommand(FCommandIntf);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.HandleFinished(const AInitiator: IFDStanObject;
AState: TFDStanAsyncState; AException: Exception);
var
oFinished: TFDOperationFinishedEvent;
begin
if Assigned(FOperationFinished) then begin
oFinished := FOperationFinished;
FOperationFinished := nil;
FThreadID := TThread.CurrentThread.ThreadID;
try
oFinished(Self, AState, AException);
finally
FThreadID := 0;
// an interface releasing is deferred in the TFDCustomCommand.SetPrepared
// until an operation finish handler will fire
if (FCommandIntf <> nil) and (FCommandIntf.State = csInactive) then begin
FCommandIntf := nil;
InternalCloseConnection;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.HandleUnprepare;
begin
if ckPrepare in FFlags then
Exit;
if (CommandIntf <> nil) and (FRowsAffected = 0) and (CommandIntf.RowsAffected > 0) then
FRowsAffected := CommandIntf.RowsAffected;
Unprepare;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforePrepare;
begin
if Assigned(FBeforePrepare) then
FBeforePrepare(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterPrepare;
begin
if Assigned(FAfterPrepare) then
FAfterPrepare(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforeUnprepare;
begin
if Assigned(FBeforeUnprepare) then
FBeforeUnprepare(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterUnprepare;
begin
if Assigned(FAfterUnprepare) then
FAfterUnprepare(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalPrepare;
begin
if Transaction <> nil then begin
Transaction.CheckConnected;
CommandIntf.Transaction := Transaction.TransactionIntf;
end;
CommandIntf.StateHandler := Self as IFDPhysCommandStateHandler;
CommandIntf.ErrorHandler := Self as IFDStanErrorHandler;
CommandIntf.Options := Self as IFDStanOptions;
if FFixedCommandKind then
CommandIntf.CommandKind := FCommandKind;
CommandIntf.CatalogName := FCatalogName;
CommandIntf.SchemaName := FSchemaName;
CommandIntf.BaseObjectName := FBaseObjectName;
CommandIntf.Overload := FOverload;
CommandIntf.Macros := FMacros;
if (FCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) and
(fiMeta in CommandIntf.Options.FetchOptions.Items) and not (ckCreateIntfDontPrepare in FFlags) then begin
CommandIntf.Params.BindMode := FParams.BindMode;
CommandIntf.Prepare(FCommandText.Text);
if CommandIntf.Params <> FParams then begin
CommandIntf.Params.AssignValues(FParams);
FParams.Assign(CommandIntf.Params);
CommandIntf.Params := FParams;
end;
end
else begin
CommandIntf.Params := FParams;
if not (ckCreateIntfDontPrepare in FFlags) then
CommandIntf.Prepare(FCommandText.Text, False)
else
CommandIntf.CommandText := FCommandText.Text;
end;
FRowsAffected := -1;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalUnprepare;
begin
if CommandIntf.State = csOpen then
CommandIntf.CloseAll;
if CommandIntf.State = csPrepared then
CommandIntf.Unprepare;
// Do not clear StateHandler, while we are inside of operation
if not Assigned(FOperationFinished) then
CommandIntf.StateHandler := nil;
CommandIntf.ErrorHandler := nil;
// Do not clear Options, it is refcounted now
// CommandIntf.Options := nil;
CommandIntf.Params := nil;
CommandIntf.Macros := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalCloseConnection;
var
oConn: TFDCustomConnection;
begin
oConn := FConnection;
if FBindedBy <> bbObject then
FConnection := nil;
ReleaseConnection(oConn);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetPrepared: Boolean;
begin
Result := (CommandIntf <> nil) and (CommandIntf.State <> csInactive);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.DoStoredActivation: Boolean;
var
eUsage: TFDStoredActivationUsage;
begin
eUsage := FDManager.ActiveStoredUsage;
if GetConnection(False) <> nil then
eUsage := eUsage * GetConnection(False).ConnectedStoredUsage;
Result := FDCheckStoredUsage(ComponentState, eUsage * ActiveStoredUsage);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetPrepared(const AValue: Boolean);
var
lFull: Boolean;
oObjIntf: IFDStanObject;
{$IFDEF FireDAC_MONITOR_Comp}
oConn: TFDCustomConnection;
{$ENDIF}
begin
if csReading in ComponentState then
FStreamedPrepared := AValue
else if not (ckPrepare in FFlags) and ((Prepared <> AValue) or
not AValue and (CommandIntf <> nil) and (CommandIntf.Connection.State <> csRecovering)) then begin
Include(FFlags, ckPrepare);
try
if AValue then begin
DoBeforePrepare;
lFull := (CommandIntf = nil) or (FConnection = nil);
if lFull then
FConnection := AcquireConnection;
{$IFDEF FireDAC_MONITOR_Comp}
Trace(esStart, 'TFDCustomCommand.Prepare', ['Command', CommandText.Text]);
try
try
{$ENDIF}
try
FConnection.CheckActive;
if lFull then
InternalCreateCommandIntf;
try
if Supports(CommandIntf, IFDStanObject, oObjIntf) then begin
if FOwner <> nil then
oObjIntf.SetOwner(FOwner, '')
else
oObjIntf.SetOwner(Self, '');
oObjIntf := nil;
end;
InternalPrepare;
except
InternalUnprepare;
FCommandIntf := nil;
raise;
end;
except
InternalCloseConnection;
raise;
end;
if lFull then
FConnection.AttachClient(Self);
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
Trace(esProgress, 'TFDCustomCommand.Prepare - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
Trace(esEnd, 'TFDCustomCommand.Prepare', ['Command', CommandText.Text]);
end;
{$ENDIF}
DoAfterPrepare;
end
else begin
CheckAsyncProgress;
DoBeforeUnprepare;
{$IFDEF FireDAC_MONITOR_Comp}
oConn := FConnection;
Trace(esStart, 'TFDCustomCommand.Unprepare', ['Command', CommandText.Text]);
try
try
{$ENDIF}
if FConnection <> nil then
FConnection.DetachClient(Self);
try
if FOwner <> nil then
FOwner.Offline;
InternalUnprepare;
finally
// defer interface releasing to the operation finish handler
if not Assigned(FOperationFinished) then begin
FCommandIntf := nil;
InternalCloseConnection;
end;
if (FTableAdapter <> nil) and (FTableAdapter.SelectCommand = Self) then
FTableAdapter.Reset;
end;
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
if oConn <> nil then
oConn.Trace(esProgress, Self, 'TFDCustomCommand.Unprepare - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
if oConn <> nil then
oConn.Trace(esEnd, Self, 'TFDCustomCommand.Unprepare',
['Command', CommandText.Text]);
end;
{$ENDIF}
DoAfterUnprepare;
end;
PropertyChange;
finally
Exclude(FFlags, ckPrepare);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.IsPS: Boolean;
begin
Result := Prepared and not Active;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Prepare(const ACommandText: String = '');
begin
if ACommandText <> '' then
SetCommandText(ACommandText, False);
Prepared := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Unprepare;
begin
Prepared := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforeOpen;
begin
if Assigned(FBeforeOpen) then
FBeforeOpen(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterOpen;
begin
if Assigned(FAfterOpen) then
FAfterOpen(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforeClose;
begin
if Assigned(FBeforeClose) then
FBeforeClose(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterClose;
begin
if Assigned(FAfterClose) then
FAfterClose(self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalClose(AAll: Boolean);
begin
if not Active then
Exit;
{$IFDEF FireDAC_MONITOR_Comp}
Trace(esStart, 'TFDCustomCommand.InternalClose',
['Command', CommandText.Text, 'AAll', AAll]);
try
try
{$ENDIF}
if AAll then
CommandIntf.CloseAll
else
CommandIntf.Close;
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
Trace(esProgress, 'TFDCustomCommand.InternalClose - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
Trace(esEnd, 'TFDCustomCommand.InternalClose',
['Command', CommandText.Text, 'AAll', AAll]);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalOpenFinished(ASender: TObject;
AState: TFDStanAsyncState; AException: Exception);
begin
{$IFDEF FireDAC_MONITOR_Comp}
if AException <> nil then
Trace(esProgress, 'TFDCustomCommand.InternalOpenFinished - Exception',
['Class', AException.ClassName, 'Msg', AException.Message]);
Trace(esProgress, 'TFDCustomCommand.InternalOpenFinished',
['Command', CommandText.Text, 'AState', Integer(AState)]);
{$ENDIF}
if AState = asFinished then begin
DoAfterOpen;
if FOwner <> nil then
TFDAdaptedDataSet(FOwner).CheckAsyncOpenComplete;
end
else if AState in [asFailed, asAborted, asExpired] then begin
if FOwner <> nil then
TFDAdaptedDataSet(FOwner).CheckAsyncOpenFailed;
end;
end;
procedure TFDCustomCommand.InternalOpen(ABlocked: Boolean);
begin
if Active then
Exit;
{$IFDEF FireDAC_MONITOR_Comp}
Trace(esStart, 'TFDCustomCommand.InternalOpen',
['Command', CommandText.Text, 'ABlocked', ABlocked]);
try
try
{$ENDIF}
FOperationFinished := InternalOpenFinished;
CommandIntf.Open(ABlocked);
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
Trace(esProgress, 'TFDCustomCommand.InternalOpen - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
Trace(esEnd, 'TFDCustomCommand.InternalOpen',
['Command', CommandText.Text, 'ABlocked', ABlocked]);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetActive: Boolean;
begin
Result := Prepared and (CommandIntf.State = csOpen);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetActiveBase(const AValue, ABlocked: Boolean);
begin
if csReading in ComponentState then
FStreamedActive := AValue
else if Active <> AValue then
if AValue then begin
CheckPrepared;
DoBeforeOpen;
InternalOpen(ABlocked);
end
else begin
CheckAsyncProgress;
DoBeforeClose;
InternalClose(False);
DoAfterClose;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetActive(const AValue: Boolean);
begin
SetActiveBase(AValue, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Open(ABlocked: Boolean = False);
begin
SetActiveBase(True, ABlocked);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.OpenOrExecute(ABlocked: Boolean = False): Boolean;
begin
try
Open(ABlocked);
except
on E: EFDException do
if E.FDCode <> er_FD_AccCmdMHRowSet then
raise;
end;
Result := Active;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Close;
begin
Active := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CloseAll;
begin
if Active then begin
CheckAsyncProgress;
DoBeforeClose;
InternalClose(True);
DoAfterClose;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.AbortJob(AWait: Boolean = False);
begin
if GetState in [csExecuting, csFetching] then
CommandIntf.AbortJob(AWait);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Disconnect(AAbortJob: Boolean = False);
begin
if AAbortJob then
AbortJob(True);
Active := False;
Prepared := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforeExecute;
begin
if Assigned(FBeforeExecute) then
FBeforeExecute(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterExecute;
begin
if Assigned(FAfterExecute) then
FAfterExecute(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.InternalExecuteFinished(ASender: TObject;
AState: TFDStanAsyncState; AException: Exception);
begin
if CommandIntf <> nil then
FRowsAffected := CommandIntf.RowsAffected;
{$IFDEF FireDAC_MONITOR_Comp}
if AException <> nil then
Trace(esProgress, 'TFDCustomCommand.InternalExecuteFinished - Exception',
['Class', AException.ClassName, 'Msg', AException.Message]);
Trace(esProgress, 'TFDCustomCommand.InternalExecuteFinished',
['Command', CommandText.Text, 'AState', Integer(AState),
'FRowsAffected', FRowsAffected]);
{$ENDIF}
if CommandKind in [skCreate, skAlter, skDrop,
skStartTransaction, skCommit, skRollback,
skSet, skSetSchema] then
Unprepare;
if AState = asFinished then begin
DoAfterExecute;
if FOwner <> nil then
TFDAdaptedDataSet(FOwner).CheckAsyncExecFinished;
end;
end;
procedure TFDCustomCommand.InternalExecute(ATimes: Integer; AOffset: Integer;
ABlocked: Boolean);
begin
{$IFDEF FireDAC_MONITOR_Comp}
Trace(esStart, 'TFDCustomCommand.InternalExecute',
['Command', CommandText.Text, 'ATimes', ATimes, 'AOffset', AOffset,
'ABlocked', ABlocked]);
try
try
{$ENDIF}
FRowsAffected := -1;
FOperationFinished := InternalExecuteFinished;
CommandIntf.Execute(ATimes, AOffset, ABlocked);
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
Trace(esProgress, 'TFDCustomCommand.InternalExecute - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
Trace(esEnd, 'TFDCustomCommand.InternalExecute',
['Command', CommandText.Text, 'ATimes', ATimes, 'AOffset', AOffset,
'ABlocked', ABlocked]);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.Execute(ATimes: Integer = 0; AOffset: Integer = 0;
ABlocked: Boolean = False);
begin
CheckPrepared;
DoBeforeExecute;
InternalExecute(ATimes, AOffset, ABlocked);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.Execute(const ASQL: String;
const AParams: array of Variant; const ATypes: array of TFieldType): LongInt;
var
i: Integer;
begin
Close;
if ASQL <> '' then
SetCommandText(ASQL, ResourceOptions.ParamCreate);
if Params.BindMode = pbByNumber then
for i := 0 to Params.Count - 1 do
Params[i].Position := i + 1;
for i := Low(ATypes) to High(ATypes) do
if ATypes[i] <> ftUnknown then
Params[i].DataType := ATypes[i];
for i := Low(AParams) to High(AParams) do
Params[i].Value := AParams[i];
Prepare;
Execute(1, 0);
Result := RowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.Execute(const ASQL: String): LongInt;
begin
Result := Execute(ASQL, [], []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.Execute(const ASQL: String;
const AParams: array of Variant): LongInt;
begin
Result := Execute(ASQL, AParams, []);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.NextRecordSet;
begin
CheckPrepared;
CommandIntf.NextRecordSet := True;
try
Close;
PropertyChange;
Open;
finally
CommandIntf.NextRecordSet := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.CloseStreams;
begin
if CommandIntf <> nil then
CommandIntf.CloseStreams;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetCommandKind: TFDPhysCommandKind;
begin
if (CommandIntf <> nil) and not FFixedCommandKind then
Result := CommandIntf.CommandKind
else
Result := FCommandKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetCommandKind(const AValue: TFDPhysCommandKind);
begin
if FCommandKind <> AValue then begin
CheckUnprepared;
FCommandKind := AValue;
FFixedCommandKind := (AValue <> skUnknown);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.IsCKS: Boolean;
begin
Result := FFixedCommandKind and (CommandKind <> skUnknown);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetState: TFDPhysCommandState;
begin
if CommandIntf <> nil then
Result := CommandIntf.State
else
Result := csInactive;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetSQLText: String;
begin
if CommandIntf <> nil then
Result := CommandIntf.SQLText
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetOverload(const AValue: Word);
begin
if FOverload <> AValue then begin
CheckUnprepared;
FOverload := AValue;
if not CheckComponentState([csReading]) then
FParams.Clear;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetBaseObjectName(const AValue: String);
begin
if FBaseObjectName <> AValue then begin
CheckUnprepared;
FBaseObjectName := AValue;
if not CheckComponentState([csReading]) then
FParams.Clear;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetSchemaName(const AValue: String);
begin
if FSchemaName <> AValue then begin
CheckUnprepared;
FSchemaName := AValue;
if not CheckComponentState([csReading]) then
FParams.Clear;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetCatalogName(const AValue: String);
begin
if FCatalogName <> AValue then begin
CheckUnprepared;
FCatalogName := AValue;
if not CheckComponentState([csReading]) then
FParams.Clear;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetParamBindMode(const AValue: TFDParamBindMode);
begin
if FParams.BindMode <> AValue then begin
CheckUnprepared;
FParams.BindMode := AValue;
if not CheckComponentState([csReading]) then
FParams.Clear;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetParamBindMode: TFDParamBindMode;
begin
Result := FParams.BindMode;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.Define(ATable: TFDDatSTable;
AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
begin
CheckPrepared;
Result := CommandIntf.Define(ATable, AMetaInfoMergeMode);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.Define(ASchema: TFDDatSManager;
ATable: TFDDatSTable; AMetaInfoMergeMode: TFDPhysMetaInfoMergeMode): TFDDatSTable;
begin
CheckPrepared;
if CommandKind = skStoredProc then begin
FCommandKind := skStoredProcWithCrs;
CommandIntf.CommandKind := skStoredProcWithCrs;
end;
Result := CommandIntf.Define(ASchema, ATable, AMetaInfoMergeMode);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoBeforeFetch;
begin
if Assigned(FBeforeFetch) then
FBeforeFetch(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoAfterFetch;
begin
if Assigned(FAfterFetch) then
FAfterFetch(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.FetchFinished(ASender: TObject;
AState: TFDStanAsyncState; AException: Exception);
begin
if CommandIntf <> nil then
FRowsAffected := CommandIntf.RowsAffected;
{$IFDEF FireDAC_MONITOR_Comp}
if AException <> nil then
Trace(esProgress, 'TFDCustomCommand.FetchFinished - Exception',
['Class', AException.ClassName, 'Msg', AException.Message]);
Trace(esProgress, 'TFDCustomCommand.FetchFinished',
['Command', CommandText.Text, 'AState', Integer(AState),
'FRowsAffected', FRowsAffected]);
{$ENDIF}
if AState = asFinished then
DoAfterFetch;
end;
procedure TFDCustomCommand.Fetch(ATable: TFDDatSTable; AAll: Boolean = True;
ABlocked: Boolean = False);
begin
CheckActive;
DoBeforeFetch;
{$IFDEF FireDAC_MONITOR_Comp}
Trace(esStart, 'TFDCustomCommand.Fetch',
['Command', CommandText.Text, 'AAll', AAll, 'ABlocked', ABlocked]);
try
try
{$ENDIF}
FRowsAffected := 0;
FOperationFinished := FetchFinished;
CommandIntf.Fetch(ATable, AAll, ABlocked);
{$IFDEF FireDAC_MONITOR_Comp}
except
on E: Exception do begin
Trace(esProgress, 'TFDCustomCommand.Fetch - Exception',
['Class', E.ClassName, 'Msg', E.Message]);
raise;
end;
end;
finally
Trace(esEnd, 'TFDCustomCommand.Fetch',
['Command', CommandText.Text, 'AAll', AAll, 'ABlocked', ABlocked]);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetCommandTextStrs(const AValue: TStrings);
begin
if FCommandText <> AValue then
FCommandText.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetCommandText(const ASQL: String; AResetParams: Boolean);
begin
if (CommandText.Count = 1) and (CommandText[0] = ASQL) then
Exit;
CommandText.BeginUpdate;
try
if AResetParams then
Params.Clear;
CommandText.Clear;
CommandText.Add(ASQL);
finally
CommandText.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetMacros(const AValue: TFDMacros);
begin
if AValue <> FMacros then
FMacros.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetParams(const AValue: TFDParams);
begin
if AValue <> FParams then
FParams.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.PreprocessSQL(const ASQL: String; AParams: TFDParams;
AMacrosUpd, AMacrosRead: TFDMacros; ACreateParams, ACreateMacros, AExpandMacros,
AExpandEscape, AParseSQL: Boolean; var ACommandKind: TFDPhysCommandKind;
var AFrom: String);
var
oConMeta: IFDPhysConnectionMetadata;
oPrep: TFDPhysPreprocessor;
begin
if not ACreateParams and not ACreateMacros and not AParseSQL then
Exit;
oPrep := TFDPhysPreprocessor.Create;
try
oPrep.Params := AParams;
oPrep.MacrosUpd := AMacrosUpd;
oPrep.MacrosRead := AMacrosRead;
oPrep.Source := ASQL;
oPrep.DesignMode := CheckComponentState([csDesigning]);
oPrep.Instrs := [];
oPrep.ConnMetadata := GetConnectionMetadata;
if oPrep.ConnMetadata = nil then begin
FDPhysManager.CreateDefaultConnectionMetadata(oConMeta);
oPrep.ConnMetadata := oConMeta;
end;
if ACreateParams then
oPrep.Instrs := oPrep.Instrs + [piCreateParams];
if ACreateMacros then
oPrep.Instrs := oPrep.Instrs + [piCreateMacros];
if AExpandMacros then
oPrep.Instrs := oPrep.Instrs + [piExpandMacros];
if AExpandEscape then
oPrep.Instrs := oPrep.Instrs + [piExpandEscapes];
if AParseSQL then
oPrep.Instrs := oPrep.Instrs + [piParseSQL];
oPrep.Execute;
ACommandKind := oPrep.SQLCommandKind;
AFrom := oPrep.SQLFromValue;
finally
FDFree(oPrep);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.FillParams(AParams: TFDParams; const ASQL: String = '');
var
oConn: TFDCustomConnection;
oGen: IFDPhysCommandGenerator;
eCmdKind: TFDPhysCommandKind;
s: String;
oRes: TFDResourceOptions;
begin
if ASQL = '' then
s := Trim(CommandText.Text)
else
s := ASQL;
if CommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
oConn := AcquireConnection;
try
oConn.CheckActive;
oConn.ConnectionIntf.CreateCommandGenerator(oGen, nil);
oGen.Params := AParams;
oGen.Options := Self as IFDStanOptions;
oGen.GenerateStoredProcParams(CatalogName, SchemaName, BaseObjectName, s, Overload);
finally
ReleaseConnection(oConn);
end;
end
else begin
eCmdKind := skUnknown;
oRes := ResourceOptions;
PreprocessSQL(s, AParams, nil, nil, True, False, oRes.MacroExpand,
oRes.EscapeExpand, False, eCmdKind, s);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoSQLChanging(ASender: TObject);
begin
CheckAsyncProgress;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DoSQLChange(ASender: TObject);
var
oPList: TFDParams;
oMList: TFDMacros;
eCmdKind: TFDPhysCommandKind;
lPCreate, lMCreate, lMExpand, lEExpand: Boolean;
sFrom: String;
oRes: TFDResourceOptions;
begin
if CheckComponentState([csReading]) or TFDStringList(CommandText).Updating or
(ckLockParse in FFlags) then
Exit;
if FOwner <> nil then
FOwner.Disconnect
else
Disconnect;
oRes := GetResourceOptions;
lPCreate := oRes.ParamCreate;
lMCreate := oRes.MacroCreate and not (ckMacros in FFlags);
lMExpand := oRes.MacroExpand;
lEExpand := oRes.EscapeExpand;
if lPCreate or lMCreate or CheckComponentState([csDesigning]) then begin
oPList := nil;
if lPCreate then begin
oPList := TFDParams.CreateRefCounted(GetParamsOwner);
oPList.BindMode := FParams.BindMode;
end;
oMList := nil;
if lMCreate then
oMList := TFDMacros.CreateRefCounted(GetParamsOwner);
Include(FFlags, ckLockParse);
try
try
eCmdKind := skUnknown;
PreprocessSQL(FCommandText.Text, oPList, oMList, FMacros, lPCreate,
lMCreate, lMExpand, lEExpand, False, eCmdKind, sFrom);
if not FFixedCommandKind then
FCommandKind := eCmdKind;
if lPCreate then begin
oPList.AssignValues(FParams);
FParams.Assign(oPList);
end;
if lMCreate then begin
oMList.AssignValues(FMacros);
FMacros.Assign(oMList);
end;
finally
if lPCreate then
oPList.RemRef;
if lMCreate then
oMList.RemRef;
end;
finally
Exclude(FFlags, ckLockParse);
end;
end;
Include(FFlags, ckLockParse);
try
if Assigned(FOnCommandChanged) then
FOnCommandChanged(Self);
finally
Exclude(FFlags, ckLockParse);
end;
PropertyChange;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.MacrosChanged(ASender: TObject);
begin
if FCommandText.Count > 0 then
try
Include(FFlags, ckMacros);
DoSQLChange(nil);
finally
Exclude(FFlags, ckMacros);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.FindParam(const AValue: string): TFDParam;
begin
Result := FParams.FindParam(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.ParamByName(const AValue: string): TFDParam;
begin
Result := FParams.ParamByName(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.FindMacro(const AValue: string): TFDMacro;
begin
Result := FMacros.FindMacro(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.MacroByName(const AValue: string): TFDMacro;
begin
Result := FMacros.MacroByName(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
var
oInit: IFDStanObject;
begin
if AInitiator = nil then begin
if (FOwner = nil) or not Supports(TObject(FOwner), IFDStanObject, oInit) then
oInit := Self as IFDStanObject;
end
else
oInit := AInitiator;
if Assigned(FOnError) then
FOnError(Self, oInit as TObject, AException);
if (Connection <> nil) and (AException <> nil) then
Connection.HandleException(oInit, AException);
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetConnectionMetadata: IFDPhysConnectionMetadata;
var
oConn: TFDCustomConnection;
begin
oConn := GetConnection(False);
if oConn <> nil then
Result := oConn.GetConnectionMetadata
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetName: TComponentName;
begin
if Name = '' then
Result := '$' + IntToHex(Integer(Self), 8)
else
Result := Name;
Result := Result + ': ' + ClassName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetParent: IFDStanObject;
begin
Result := GetConnection(False) as IFDStanObject;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.DefineProperties(AFiler: TFiler);
function AreParamsStorable(AFiler: TFiler): Boolean;
begin
if not FEnableParamsStorage then
Result := False
else begin
Result := Params.Count > 0;
if AFiler.Ancestor <> nil then
if AFiler.Ancestor is TFDCustomCommand then
Result := not Params.IsEqual(TFDCustomCommand(AFiler.Ancestor).Params)
else if AFiler.Ancestor is TFDRdbmsDataSet then
Result := not Params.IsEqual(TFDRdbmsDataSet(AFiler.Ancestor).Params);
end;
end;
function AreMacrosStorable(AFiler: TFiler): Boolean;
begin
if not FEnableParamsStorage then
Result := False
else begin
Result := Macros.Count > 0;
if AFiler.Ancestor <> nil then
if AFiler.Ancestor is TFDCustomCommand then
Result := not Macros.IsEqual(TFDCustomCommand(AFiler.Ancestor).Macros)
else if AFiler.Ancestor is TFDRdbmsDataSet then
Result := not Macros.IsEqual(TFDRdbmsDataSet(AFiler.Ancestor).Macros);
end;
end;
begin
AFiler.DefineProperty('ParamData', ReadParams, WriteParams, AreParamsStorable(AFiler));
AFiler.DefineProperty('MacroData', ReadMacros, WriteMacros, AreMacrosStorable(AFiler));
AFiler.DefineProperty('Prepared', ReadPrepared, nil, False);
if FOwner = nil then
inherited DefineProperties(AFiler);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.WriteCollection(AWriter: TWriter; ACollection: TCollection);
var
sPropPath: String;
begin
sPropPath := __TWriter(AWriter).FPropPath;
try
if (FOwner <> nil) and (csSubComponent in FOwner.ComponentStyle) or
(FOwner = nil) and (csSubComponent in ComponentStyle) then
__TWriter(AWriter).FPropPath := '';
AWriter.WriteCollection(ACollection);
finally
__TWriter(AWriter).FPropPath := sPropPath;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.ReadCollection(AReader: TReader; ACollection: TCollection);
begin
AReader.ReadValue;
AReader.ReadCollection(ACollection);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.ReadParams(Reader: TReader);
begin
ReadCollection(Reader, Params);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.WriteParams(Writer: TWriter);
begin
WriteCollection(Writer, Params);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.ReadMacros(Reader: TReader);
begin
ReadCollection(Reader, Macros);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.WriteMacros(Writer: TWriter);
begin
WriteCollection(Writer, Macros);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.ReadPrepared(Reader: TReader);
begin
Reader.ReadBoolean;
end;
{-------------------------------------------------------------------------------}
function TFDCustomCommand.GetValues(const AParamNames: String): Variant;
begin
Result := Params.ParamValues[AParamNames];
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomCommand.SetValues(const AParamNames: String; const AValue: Variant);
begin
Params.ParamValues[AParamNames] := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDMetaInfoCommand }
{-------------------------------------------------------------------------------}
constructor TFDMetaInfoCommand.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMetaInfoKind := mkTables;
FTableKinds := [tkSynonym, tkTable, tkView];
FObjectScopes := [osMy];
UpdateOptions.ReadOnly := True;
FEnableParamsStorage := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.InternalCreateCommandIntf;
var
oMetaInfoCmd: IFDPhysMetaInfoCommand;
begin
FConnection.ConnectionIntf.CreateMetaInfoCommand(oMetaInfoCmd);
FCommandIntf := oMetaInfoCmd as IFDPhysCommand;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.InternalPrepare;
var
oCmd: IFDPhysMetaInfoCommand;
begin
oCmd := CommandIntf as IFDPhysMetaInfoCommand;
oCmd.MetaInfoKind := FMetaInfoKind;
oCmd.TableKinds := FTableKinds;
oCmd.Wildcard := FWildcard;
oCmd.ObjectScopes := FObjectScopes;
inherited InternalPrepare;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.DoAfterClose;
begin
try
inherited DoAfterClose;
finally
Prepared := False;
end;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoCommand.GetObjectName: String;
begin
Result := Trim(CommandText.Text);
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.SetObjectName(const AValue: String);
begin
SetCommandText(AValue, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.SetMetaInfoKind(const AValue: TFDPhysMetaInfoKind);
begin
CheckUnprepared;
FMetaInfoKind := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.SetTableKinds(const AValue: TFDPhysTableKinds);
begin
CheckUnprepared;
FTableKinds := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.SetWildcard(const AValue: String);
begin
CheckUnprepared;
FWildcard := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoCommand.SetObjectScopes(const AValue: TFDPhysObjectScopes);
begin
CheckUnprepared;
FObjectScopes := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomTableAdapter }
{-------------------------------------------------------------------------------}
constructor TFDCustomTableAdapter.Create(AOwner: TComponent);
var
oAdapt: IFDDAptTableAdapter;
begin
inherited Create(AOwner);
FDCreateInterface(IFDDAptTableAdapter, oAdapt);
SetTableAdapterIntf(oAdapt, True);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomTableAdapter.Destroy;
begin
Destroying;
SelectCommand := nil;
InsertCommand := nil;
UpdateCommand := nil;
DeleteCommand := nil;
LockCommand := nil;
UnLockCommand := nil;
FetchRowCommand := nil;
SchemaAdapter := nil;
inherited Destroy;
if FTableAdapterIntf <> nil then begin
FTableAdapterIntf.DatSTable := nil;
SetTableAdapterIntf(nil, True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetTableAdapterIntf(const AAdapter: IFDDAptTableAdapter;
AOwned: Boolean);
begin
if FTableAdapterIntf <> nil then begin
FTableAdapterIntf.ErrorHandler := nil;
FTableAdapterIntf.UpdateHandler := nil;
FTableAdapterIntf.ColumnMappings.SetOwner(nil);
end;
FTableAdapterIntf := AAdapter;
FTableAdapterOwned := AOwned;
if FTableAdapterIntf <> nil then begin
FTableAdapterIntf.ErrorHandler := Self as IFDStanErrorHandler;
FTableAdapterIntf.UpdateHandler := Self as IFDDAptUpdateHandler;
FTableAdapterIntf.ColumnMappings.SetOwner(Self);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if UpdateTransaction = AComponent then
UpdateTransaction := nil
else if SelectCommand = AComponent then
SelectCommand := nil
else if InsertCommand = AComponent then
InsertCommand := nil
else if UpdateCommand = AComponent then
UpdateCommand := nil
else if DeleteCommand = AComponent then
DeleteCommand := nil
else if LockCommand = AComponent then
LockCommand := nil
else if UnLockCommand = AComponent then
UnLockCommand := nil
else if FetchRowCommand = AComponent then
FetchRowCommand := nil
else if SchemaAdapter = AComponent then
SchemaAdapter := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetSender: TObject;
begin
if Assigned(DataSet) then
Result := DataSet
else
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.HandleException(
const AInitiator: IFDStanObject; var AException: Exception);
begin
if Assigned(DataSet) then
DataSet.InternalUpdateErrorHandler(GetSender, AInitiator, AException);
if (AException <> nil) and Assigned(FOnError) then
FOnError(GetSender, AInitiator as TObject, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.ReconcileRow(ARow: TFDDatSRow;
var AAction: TFDDAptReconcileAction);
begin
if Assigned(DataSet) then
DataSet.InternalReconcileErrorHandler(GetSender, ARow, AAction);
if Assigned(FOnReconcileRow) then
FOnReconcileRow(GetSender, ARow, AAction);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.UpdateRow(ARow: TFDDatSRow;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
var AAction: TFDErrorAction);
begin
if Assigned(DataSet) then
DataSet.InternalUpdateRecordHandler(GetSender, ARow, ARequest,
AUpdRowOptions, AAction);
if Assigned(FOnUpdateRow) then
FOnUpdateRow(GetSender, ARow, ARequest, AUpdRowOptions, AAction);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetActualTransaction: TFDCustomTransaction;
var
oConn: TFDCustomConnection;
begin
if SelectCommand = nil then
Result := nil
else if SelectCommand.Transaction <> nil then
Result := SelectCommand.Transaction
else begin
oConn := SelectCommand.GetConnection(False);
Result := oConn.Transaction;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetActualUpdateTransaction: TFDCustomTransaction;
var
oConn: TFDCustomConnection;
begin
if UpdateTransaction <> nil then
Result := UpdateTransaction
else if SelectCommand = nil then
Result := nil
else begin
oConn := SelectCommand.GetConnection(False);
if oConn.UpdateTransaction <> nil then
Result := oConn.UpdateTransaction
else
Result := GetActualTransaction;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.InternalUpdateTransaction;
var
oUpdTX: TFDCustomTransaction;
begin
oUpdTX := GetActualUpdateTransaction;
if oUpdTX <> nil then begin
oUpdTX.CheckConnected;
FTableAdapterIntf.UpdateTransaction := oUpdTX.TransactionIntf;
end
else
FTableAdapterIntf.UpdateTransaction := nil;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.InternalUpdateAdapterCmd(ACmd: TFDActionRequest): Boolean;
var
oCmd: TFDCustomCommand;
begin
Result := True;
oCmd := GetCommand(ACmd);
if oCmd <> nil then begin
if oCmd.CommandIntf = nil then begin
if ACmd = arSelect then
oCmd.Transaction := GetActualTransaction
else
oCmd.Transaction := GetActualUpdateTransaction;
if oCmd.CommandText.Count > 0 then begin
Include(oCmd.FFlags, ckCreateIntfDontPrepare);
try
oCmd.Prepare;
finally
Exclude(oCmd.FFlags, ckCreateIntfDontPrepare);
end;
end;
end;
if oCmd.CommandIntf <> nil then begin
SetAdapterCmd(oCmd.CommandIntf, ACmd);
Result := False;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.UpdateAdapterCmd(ACmd: TFDActionRequest);
begin
if InternalUpdateAdapterCmd(ACmd) then
InternalUpdateTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.UpdateAdapterCmds(const ACmds: array of TFDActionRequest);
var
i: Integer;
lUpdated, lUpdateTX: Boolean;
begin
lUpdateTX := False;
for i := Low(ACmds) to High(ACmds) do begin
lUpdated := InternalUpdateAdapterCmd(ACmds[i]);
lUpdateTX := lUpdateTX or lUpdated;
end;
if lUpdateTX then
InternalUpdateTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetAdapterCmd(const ACmd: IFDPhysCommand;
ACmdKind: TFDActionRequest);
begin
case ACmdKind of
arSelect: FTableAdapterIntf.SelectCommand := ACmd;
arInsert: FTableAdapterIntf.InsertCommand := ACmd;
arUpdate: FTableAdapterIntf.UpdateCommand := ACmd;
arDelete: FTableAdapterIntf.DeleteCommand := ACmd;
arLock: FTableAdapterIntf.LockCommand := ACmd;
arUnlock: FTableAdapterIntf.UnLockCommand := ACmd;
arFetchRow: FTableAdapterIntf.FetchRowCommand := ACmd;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetCommand(ACmdKind: TFDActionRequest): TFDCustomCommand;
begin
case ACmdKind of
arSelect: Result := SelectCommand;
arInsert: Result := InsertCommand;
arUpdate: Result := UpdateCommand;
arDelete: Result := DeleteCommand;
arLock: Result := LockCommand;
arUnlock: Result := UnLockCommand;
arFetchRow: Result := FetchRowCommand;
else Result := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetCommand(var AVar: TFDCustomCommand;
const AValue: TFDCustomCommand; ACmdKind: TFDActionRequest);
begin
if AVar <> nil then begin
AVar.FTableAdapter := nil;
AVar.RemoveFreeNotification(Self);
SetAdapterCmd(nil, ACmdKind);
end;
AVar := AValue;
if AVar <> nil then begin
AVar.FTableAdapter := Self;
AVar.FreeNotification(Self);
if AVar.CommandIntf <> nil then
SetAdapterCmd(AVar.CommandIntf, ACmdKind);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.Define: TFDDatSTable;
begin
UpdateAdapterCmd(arSelect);
Result := FTableAdapterIntf.Define;
if (Result <> nil) and (FAdaptedDataSet <> nil) and (FAdaptedDataSet.Name <> '') and
(DatSTableName = SourceRecordSetName) and (Result.Name <> FAdaptedDataSet.Name) then
Result.Name := Result.TableList.BuildUniqueName(FAdaptedDataSet.Name);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Fetch(AAll: Boolean);
begin
UpdateAdapterCmd(arSelect);
// Call TFDCustomCommand.Fetch here to properly handle async commands
FSelectCommand.Fetch(FTableAdapterIntf.DatSTable, AAll, True);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.ApplyUpdates(AMaxErrors: Integer): Integer;
begin
UpdateAdapterCmds([arInsert, arUpdate, arDelete, arLock, arUnlock, arFetchRow]);
Result := FTableAdapterIntf.Update(AMaxErrors);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.Reconcile: Boolean;
begin
Result := FTableAdapterIntf.Reconcile;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Fetch(ARow: TFDDatSRow;
var AAction: TFDErrorAction; AColumn: Integer;
ARowOptions: TFDPhysFillRowOptions);
begin
UpdateAdapterCmd(arFetchRow);
FTableAdapterIntf.Fetch(ARow, AAction, AColumn, ARowOptions);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Update(ARow: TFDDatSRow;
var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions;
AForceRequest: TFDActionRequest);
begin
if AForceRequest = arFromRow then
UpdateAdapterCmds([arInsert, arUpdate, arDelete, arLock, arUnlock, arFetchRow])
else if AForceRequest in [arInsert, arUpdate] then
UpdateAdapterCmds([AForceRequest, arFetchRow])
else
UpdateAdapterCmd(AForceRequest);
FTableAdapterIntf.Update(ARow, AAction, AUpdRowOptions, AForceRequest);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Lock(ARow: TFDDatSRow;
var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions);
begin
UpdateAdapterCmd(arLock);
FTableAdapterIntf.Update(ARow, AAction, AUpdRowOptions, arLock);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.UnLock(ARow: TFDDatSRow;
var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions);
begin
UpdateAdapterCmd(arUnLock);
FTableAdapterIntf.Update(ARow, AAction, AUpdRowOptions, arUnlock);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetUpdateTransaction(const AValue: TFDCustomTransaction);
begin
if FUpdateTransaction <> AValue then begin
FUpdateTransaction := AValue;
if FUpdateTransaction <> nil then
FUpdateTransaction.FreeNotification(Self);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetDeleteCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FDeleteCommand, AValue, arDelete);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetFetchRowCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FFetchRowCommand, AValue, arFetchRow);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetInsertCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FInsertCommand, AValue, arInsert);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetLockCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FLockCommand, AValue, arLock);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetSelectCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FSelectCommand, AValue, arSelect);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetUnLockCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FUnLockCommand, AValue, arUnLock);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetUpdateCommand(const AValue: TFDCustomCommand);
begin
SetCommand(FUpdateCommand, AValue, arUpdate);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetColumnMappings: TFDDAptColumnMappings;
begin
Result := FTableAdapterIntf.ColumnMappings;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetColumnMappings(const AValue: TFDDAptColumnMappings);
begin
FTableAdapterIntf.ColumnMappings.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.IsCMS: Boolean;
begin
Result := ColumnMappings.Count > 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetSchemaAdapter(const AValue: TFDCustomSchemaAdapter);
var
oAdapt: IFDDAptTableAdapter;
begin
if FSchemaAdapter <> AValue then begin
if FSchemaAdapter <> nil then begin
FSchemaAdapter.FTableAdapters.Remove(Self);
FSchemaAdapter.RemoveFreeNotification(Self);
if DataSet <> nil then
DataSet.DatSManager := nil;
if FTableAdapterOwned then
FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Remove(FTableAdapterIntf)
else begin
FDCreateInterface(IFDDAptTableAdapter, oAdapt);
SetTableAdapterIntf(oAdapt, True);
end;
end;
FSchemaAdapter := AValue;
if FSchemaAdapter <> nil then begin
FSchemaAdapter.FTableAdapters.Add(Self);
FSchemaAdapter.FreeNotification(Self);
if FTableAdapterOwned then
FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Add(FTableAdapterIntf);
if DataSet <> nil then
DataSet.DatSManager := FSchemaAdapter.DatSManager;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetDatSTable: TFDDatSTable;
begin
Result := FTableAdapterIntf.DatSTable;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetDatSTable(const AValue: TFDDatSTable);
begin
FTableAdapterIntf.DatSTable := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetDatSTableName: String;
begin
Result := FTableAdapterIntf.DatSTableName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetDatSTableName(const AValue: String);
begin
FTableAdapterIntf.DatSTableName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.IsDTNS: Boolean;
begin
Result := DatSTableName <> SourceRecordSetName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetMetaInfoMergeMode: TFDPhysMetaInfoMergeMode;
begin
Result := FTableAdapterIntf.MetaInfoMergeMode;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetMetaInfoMergeMode(const AValue: TFDPhysMetaInfoMergeMode);
begin
FTableAdapterIntf.MetaInfoMergeMode := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetSourceRecordSetID: Integer;
begin
Result := FTableAdapterIntf.SourceRecordSetID;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetSourceRecordSetID(const AValue: Integer);
begin
if FSchemaAdapter <> nil then begin
if FTableAdapterOwned then
FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Remove(FTableAdapterIntf);
SetTableAdapterIntf(FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Lookup(
TFDPhysMappingName.Create(AValue, nkID)), False);
if FTableAdapterIntf = nil then begin
SetTableAdapterIntf(FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Add('', '', ''), True);
FTableAdapterIntf.SourceRecordSetID := AValue;
end;
end
else
FTableAdapterIntf.SourceRecordSetID := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetSourceRecordSetName: String;
begin
Result := FTableAdapterIntf.SourceRecordSetName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetSourceRecordSetName(const AValue: String);
begin
if FSchemaAdapter <> nil then begin
if FTableAdapterOwned then
FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Remove(FTableAdapterIntf);
SetTableAdapterIntf(FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Lookup(
TFDPhysMappingName.Create(AValue, nkSource)), False);
if FTableAdapterIntf = nil then begin
SetTableAdapterIntf(FSchemaAdapter.FDAptSchemaAdapter.TableAdapters.Add(AValue, '', ''), True);
FTableAdapterIntf.SourceRecordSetName := AValue;
end;
end
else
FTableAdapterIntf.SourceRecordSetName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.IsSRSNS: Boolean;
begin
if (SelectCommand <> nil) and (SelectCommand.CommandIntf <> nil) then
Result := SourceRecordSetName <> SelectCommand.CommandIntf.SourceObjectName
else
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetUpdateTableName: String;
begin
Result := FTableAdapterIntf.UpdateTableName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetUpdateTableName(const AValue: String);
begin
FTableAdapterIntf.UpdateTableName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.IsUTNS: Boolean;
begin
Result := UpdateTableName <> SourceRecordSetName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomTableAdapter.GetDatSManager: TFDDatSManager;
begin
Result := FTableAdapterIntf.DatSManager;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.SetDatSManager(AValue: TFDDatSManager);
begin
ASSERT((csDestroying in ComponentState) or (FTableAdapterIntf <> nil));
if FTableAdapterIntf <> nil then
FTableAdapterIntf.DatSManager := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomTableAdapter.Reset;
var
i: TFDActionRequest;
oCmd: TFDCustomCommand;
begin
for i := Low(TFDActionRequest) to High(TFDActionRequest) do begin
oCmd := GetCommand(i);
if oCmd <> nil then begin
SetAdapterCmd(nil, i);
oCmd.Prepared := False;
end;
end;
FTableAdapterIntf.Reset;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomSchemaAdapter }
{-------------------------------------------------------------------------------}
constructor TFDCustomSchemaAdapter.Create(AOwner: TComponent);
var
oMgr: TFDDatSManager;
begin
inherited Create(AOwner);
FTableAdapters := TFDObjList.Create;
FDCreateInterface(IFDDAptSchemaAdapter, FDAptSchemaAdapter);
oMgr := TFDDatSManager.Create;
oMgr.UpdatesRegistry := True;
oMgr.CountRef(0);
FDAptSchemaAdapter.DatSManager := oMgr;
FDAptSchemaAdapter.ErrorHandler := Self as IFDStanErrorHandler;
FDAptSchemaAdapter.UpdateHandler := Self as IFDDAptUpdateHandler;
FDAptSchemaAdapter.Options.ParentOptions := TFDCustomManager.GetSingletonOptsIntf;
FEncoder := TFDEncoder.Create(nil);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomSchemaAdapter.Destroy;
begin
inherited Destroy;
FDAptSchemaAdapter.Options.ParentOptions := nil;
FDAptSchemaAdapter.DatSManager := nil;
FDAptSchemaAdapter.ErrorHandler := nil;
FDAptSchemaAdapter.UpdateHandler := nil;
FDAptSchemaAdapter := nil;
FDFreeAndNil(FTableAdapters);
FDFreeAndNil(FEncoder);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.StartWait;
var
oWait: IFDGUIxWaitCursor;
begin
if not ResourceOptions.ActualSilentMode then begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.StopWait;
var
oWait: IFDGUIxWaitCursor;
begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StopWait;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetCount: Integer;
begin
Result := FTableAdapters.Count;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetTableAdapters(AIndex: Integer): TFDCustomTableAdapter;
begin
Result := TFDCustomTableAdapter(FTableAdapters[AIndex]);
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetDataSets(AIndex: Integer): TFDAdaptedDataSet;
begin
Result := TableAdapters[AIndex].DataSet;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetTableAdaptersIntf: IFDDAptTableAdapters;
begin
Result := FDAptSchemaAdapter.TableAdapters;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetDatSManager: TFDDatSManager;
begin
Result := FDAptSchemaAdapter.DatSManager;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SetDatSManager(const AValue: TFDDatSManager);
begin
FDAptSchemaAdapter.DatSManager := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetResourceOptions: TFDBottomResourceOptions;
begin
Result := FDAptSchemaAdapter.Options.ResourceOptions as TFDBottomResourceOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SetResourceOptions(const AValue: TFDBottomResourceOptions);
begin
FDAptSchemaAdapter.Options.ResourceOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetUpdateOptions: TFDUpdateOptions;
begin
Result := FDAptSchemaAdapter.Options.UpdateOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SetUpdateOptions(const AValue: TFDUpdateOptions);
begin
FDAptSchemaAdapter.Options.UpdateOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.HandleException(
const AInitiator: IFDStanObject; var AException: Exception);
begin
if Assigned(FOnError) then
FOnError(Self, AInitiator as TObject, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SetActive(AValue: Boolean);
var
i: Integer;
oDS: TFDAdaptedDataSet;
begin
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if oDS <> nil then
oDS.Active := AValue;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.Open;
begin
SetActive(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.Close;
begin
SetActive(False);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.ReconcileRow(ARow: TFDDatSRow;
var AAction: TFDDAptReconcileAction);
begin
if Assigned(FOnReconcileRow) then
FOnReconcileRow(Self, ARow, AAction);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.UpdateRow(ARow: TFDDatSRow;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
var AAction: TFDErrorAction);
begin
if Assigned(FOnUpdateRow) then
FOnUpdateRow(Self, ARow, ARequest, AUpdRowOptions, AAction);
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.Reconcile: Boolean;
begin
Result := FDAptSchemaAdapter.Reconcile;
ResyncDataSets;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.DoBeforeApplyUpdate;
begin
if Assigned(FBeforeApplyUpdate) then
FBeforeApplyUpdate(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.DoAfterApplyUpdate(AErrors: Integer);
begin
if Assigned(FAfterApplyUpdate) then
FAfterApplyUpdate(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.CheckDataSets(ACancel: Boolean);
var
i: Integer;
oDS: TFDAdaptedDataSet;
begin
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if (oDS <> nil) and oDS.Active then begin
if ACancel then
oDS.Cancel;
oDS.CheckBrowseMode;
oDS.CheckCachedUpdatesMode;
oDS.UpdateCursorPos;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.ResyncDataSets;
var
i: Integer;
oDS: TFDAdaptedDataSet;
begin
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if (oDS <> nil) and oDS.Active then
oDS.ResyncViews;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.ApplyUpdates(AMaxErrors: Integer): Integer;
var
i: Integer;
begin
StartWait;
try
DoBeforeApplyUpdate;
CheckDataSets(False);
for i := 0 to Count - 1 do
TableAdapters[i].UpdateAdapterCmds([arSelect, arInsert, arUpdate, arDelete,
arLock, arUnlock, arFetchRow]);
Result := FDAptSchemaAdapter.Update(AMaxErrors);
DoAfterApplyUpdate(Result);
if DatSManager.HasErrors then
Reconcile
else if UpdateOptions.AutoCommitUpdates then
CommitUpdates
else
ResyncDataSets;
finally
StopWait;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.CommitUpdates;
begin
CheckDataSets(False);
DatSManager.Updates.AcceptChanges(nil);
ResyncDataSets;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.UndoLastChange: Boolean;
var
oRow: TFDDatSRow;
begin
CheckDataSets(True);
Result := UpdatesPending;
if Result then begin
oRow := DatSManager.Updates.LastChange(nil);
oRow.RejectChanges;
ResyncDataSets;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.CancelUpdates;
begin
SetSavePoint(0);
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetSavePoint: Int64;
begin
CheckDataSets(False);
Result := DatSManager.Updates.SavePoint;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SetSavePoint(const AValue: Int64);
begin
CheckDataSets(True);
DatSManager.Updates.SavePoint := AValue;
ResyncDataSets;
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetUpdatesPending: Boolean;
begin
Result := DatSManager.Updates.HasChanges(nil);
end;
{-------------------------------------------------------------------------------}
function TFDCustomSchemaAdapter.GetChangeCount: Integer;
begin
Result := DatSManager.Updates.GetCount(nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SaveToStorage(const AFileName: String;
AStream: TStream; AFormat: TFDStorageFormat);
var
oStrg: IFDStanStorage;
i: Integer;
oDS: TFDAdaptedDataSet;
begin
StartWait;
try
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if (oDS <> nil) and oDS.Active then begin
oDS.CheckBrowseMode;
oDS.CheckFetchedAll;
end;
end;
oStrg := ResourceOptions.GetStorage(AFileName, AFormat);
if oStrg.IsStored(siVisible) then
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if (oDS <> nil) and (oDS.Table <> nil) and (oDS.SourceView <> nil) then
oStrg.AddFilterObj(oDS.Table, oDS.SourceView);
end;
oStrg.Open(ResourceOptions, FEncoder, AFileName, AStream, smWrite);
DatSManager.SaveToStorage(oStrg);
finally
StopWait;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.LoadFromStorage(const AFileName: String;
AStream: TStream; AFormat: TFDStorageFormat);
var
oStrg: IFDStanStorage;
i: Integer;
oDS: TFDAdaptedDataSet;
oAdapt: TFDCustomTableAdapter;
begin
StartWait;
try
oStrg := ResourceOptions.GetStorage(AFileName, AFormat);
oStrg.Open(ResourceOptions, FEncoder, AFileName, AStream, smRead);
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if oDS <> nil then
oDS.DisableControls;
end;
try
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if oDS <> nil then
if not ResourceOptions.StoreMerge then
oDS.Disconnect
else
oDS.Open;
end;
DatSManager.LoadFromStorage(oStrg, ResourceOptions.StoreMergeData,
ResourceOptions.StoreMergeMeta, [moPreserveState]);
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if oDS <> nil then
if not ResourceOptions.StoreMerge then begin
Include(oDS.FFlags, dfOfflining);
try
oAdapt := oDS.Adapter;
oDS.SetAdapter(nil);
oDS.SetAdapter(oAdapt);
oDS.Open;
finally
Exclude(oDS.FFlags, dfOfflining);
end;
end
else
oDS.Resync([]);
end;
finally
for i := 0 to Count - 1 do begin
oDS := DataSets[i];
if oDS <> nil then
oDS.EnableControls;
end;
end;
finally
StopWait;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SaveToStream(AStream: TStream;
AFormat: TFDStorageFormat);
begin
SaveToStorage('', AStream, AFormat);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.SaveToFile(const AFileName: String;
AFormat: TFDStorageFormat);
begin
SaveToStorage(AFileName, nil, AFormat);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.LoadFromStream(AStream: TStream;
AFormat: TFDStorageFormat);
begin
LoadFromStorage('', AStream, AFormat);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomSchemaAdapter.LoadFromFile(const AFileName: String;
AFormat: TFDStorageFormat);
begin
LoadFromStorage(AFileName, nil, AFormat);
end;
{-------------------------------------------------------------------------------}
{ TFDCustomUpdateObject }
{-------------------------------------------------------------------------------}
procedure TFDCustomUpdateObject.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
if (AOperation = opRemove) and (AComponent = FDataSet) then
DataSet := nil;
inherited Notification(AComponent, AOperation);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomUpdateObject.SetDataSet(const AValue: TFDAdaptedDataSet);
begin
if FDataSet <> AValue then begin
if FDataSet <> nil then
FDataSet.UpdateObject := nil;
FDataSet := AValue;
if FDataSet <> nil then
FDataSet.UpdateObject := Self;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDDefaultLocalSQLAdapter }
{-------------------------------------------------------------------------------}
type
TFDDefaultLocalSQLAdapter = class (TFDObject, IFDPhysLocalSQLAdapter)
private
FDataSet: TDataSet;
protected
// IFDPhysLocalSQLAdapter
function GetFeatures: TFDPhysLocalSQLAdapterFeatures;
function GetCachedUpdates: Boolean;
procedure SetCachedUpdates(const AValue: Boolean);
function GetSavePoint: Int64;
procedure SetSavePoint(const AValue: Int64);
function GetIndexFieldNames: String;
procedure SetIndexFieldNames(const AValue: String);
function GetDataSet: TObject;
procedure SetDataSet(ADataSet: TObject);
function GetConn: NativeUInt;
function ApplyUpdates(AMaxErrors: Integer = -1): Integer;
procedure CommitUpdates;
procedure CancelUpdates;
procedure SetRange(const AStartValues, AEndValues: array of const;
AStartExclusive: Boolean = False; AEndExclusive: Boolean = False);
procedure CancelRange;
function IsPKViolation(AExc: Exception): Boolean;
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetDataSet: TObject;
begin
Result := FDataSet;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.SetDataSet(ADataSet: TObject);
begin
FDataSet := ADataSet as TDataSet;
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetConn: NativeUInt;
begin
// nothing
Result := 0;
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetFeatures: TFDPhysLocalSQLAdapterFeatures;
begin
// nothing
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetCachedUpdates: Boolean;
begin
// nothing
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.SetCachedUpdates(const AValue: Boolean);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetSavePoint: Int64;
begin
// nothing
Result := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.SetSavePoint(const AValue: Int64);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.GetIndexFieldNames: String;
begin
// nothing
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.SetIndexFieldNames(const AValue: String);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.SetRange(const AStartValues,
AEndValues: array of const; AStartExclusive: Boolean = False;
AEndExclusive: Boolean = False);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.CancelRange;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.ApplyUpdates(AMaxErrors: Integer): Integer;
begin
// nothing
Result := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.CommitUpdates;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDefaultLocalSQLAdapter.CancelUpdates;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDDefaultLocalSQLAdapter.IsPKViolation(AExc: Exception): Boolean;
begin
// nothing
Result := False;
end;
{-------------------------------------------------------------------------------}
{ TFDLocalSQLDataSet }
{-------------------------------------------------------------------------------}
destructor TFDLocalSQLDataSet.Destroy;
begin
Vacate;
DataSet := nil;
Changing;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.Vacate;
begin
if DataSet <> nil then begin
if (Collection <> nil) and (TFDLocalSQLDataSets(Collection).FOwner <> nil) then
TFDLocalSQLDataSets(Collection).FOwner.ReleaseDataSet(Self);
if Owned and (DataSet <> nil) then begin
FDFreeAndNil(FDataSet);
FAdapter := nil;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.Assign(ASource: TPersistent);
begin
if ASource is TFDLocalSQLDataSet then begin
Changing;
FDataSet := TFDLocalSQLDataSet(ASource).FDataSet;
FSchemaName := TFDLocalSQLDataSet(ASource).FSchemaName;
FName := TFDLocalSQLDataSet(ASource).FName;
FTemporary := TFDLocalSQLDataSet(ASource).FTemporary;
FOwned := TFDLocalSQLDataSet(ASource).FOwned;
UpdateAdapter;
Changed;
end
else
inherited Assign(ASource);
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSet.GetDisplayName: String;
begin
Result := FullName;
if Result = '' then
Result := inherited GetDisplayName;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSet.GetActualSchemaName: String;
begin
if SchemaName <> '' then
Result := SchemaName
else if (Collection <> nil) and (TFDLocalSQLDataSets(Collection).FOwner <> nil) and
(TFDLocalSQLDataSets(Collection).FOwner.SchemaName <> '') then
Result := TFDLocalSQLDataSets(Collection).FOwner.SchemaName
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSet.GetActualName: String;
begin
if Name <> '' then
Result := Name
else if DataSet <> nil then
Result := DataSet.Name
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSet.GetFullName: String;
var
sSchema: String;
begin
Result := ActualName;
sSchema := ActualSchemaName;
if (sSchema <> '') and (Result <> '') then
Result := sSchema + '.' + Result;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSet.GetIsValid: Boolean;
begin
Result := (FullName <> '') and (FAdapter <> nil) and
(FDataSet <> nil) and (Collection <> nil) and
(TFDLocalSQLDataSets(Collection).FOwner <> nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.Changing;
begin
if IsValid then
TFDLocalSQLDataSets(Collection).FOwner.CheckDataSetRemoving(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.Changed;
begin
if IsValid and not (csDestroying in FDataSet.ComponentState) then
TFDLocalSQLDataSets(Collection).FOwner.CheckDataSetAdded(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.UpdateAdapter;
var
oClass: TClass;
begin
if (FAdapter = nil) and (FDataSet <> nil) then
if not Supports(FDataSet, IFDPhysLocalSQLAdapter, FAdapter) then begin
oClass := FDataSet.ClassType;
repeat
FDCreateInterface(IFDPhysLocalSQLAdapter, FAdapter, False, oClass.ClassName);
oClass := oClass.ClassParent;
until (FAdapter <> nil) or (oClass = nil) or (oClass = TDataSet);
if FAdapter = nil then
FAdapter := IFDPhysLocalSQLAdapter(TFDDefaultLocalSQLAdapter.Create);
FAdapter.DataSet := FDataSet;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.SetSchemaName(const AValue: String);
begin
if FName <> AValue then begin
Changing;
FSchemaName := AValue;
Changed;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.SetName(const AValue: String);
begin
if FName <> AValue then begin
Changing;
FName := AValue;
Changed;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSet.SetDataSet(const AValue: TDataSet);
begin
if FDataSet <> AValue then begin
Changing;
if (FDataSet <> nil) and (TFDLocalSQLDataSets(Collection).FOwner <> nil) then
FDataSet.RemoveFreeNotification(TFDLocalSQLDataSets(Collection).FOwner);
FDataSet := AValue;
FAdapter := nil;
if (FDataSet <> nil) and (TFDLocalSQLDataSets(Collection).FOwner <> nil) then
FDataSet.FreeNotification(TFDLocalSQLDataSets(Collection).FOwner);
UpdateAdapter;
Changed;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDLocalSQLDataSets }
{-------------------------------------------------------------------------------}
constructor TFDLocalSQLDataSets.Create(AOwner: TFDCustomLocalSQL);
begin
inherited Create(TFDLocalSQLDataSet);
FOwner := AOwner;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSets.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSets.GetItems(AIndex: Integer): TFDLocalSQLDataSet;
begin
Result := TFDLocalSQLDataSet(inherited Items[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSets.SetItems(AIndex: Integer; const AValue: TFDLocalSQLDataSet);
begin
inherited Items[AIndex] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSets.Add: TFDLocalSQLDataSet;
begin
Result := TFDLocalSQLDataSet(inherited Add);
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSets.Add(ADataSet: TDataSet; const ASchemaName: String = '';
const AName: String = ''): TFDLocalSQLDataSet;
begin
Result := Add;
Result.FDataSet := ADataSet;
Result.FSchemaName := ASchemaName;
Result.FName := AName;
if ADataSet <> nil then
ADataSet.FreeNotification(FOwner);
Result.UpdateAdapter;
Result.Changed;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSets.Remove(ADataSet: TDataSet);
var
i: Integer;
oItem: TFDLocalSQLDataSet;
begin
for i := Count - 1 downto 0 do begin
oItem := Items[i];
if oItem.DataSet = ADataSet then
if oItem.Temporary then
FDFree(oItem)
else begin
oItem.Vacate;
oItem.DataSet := nil;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSets.Vacate;
var
i: Integer;
oItem: TFDLocalSQLDataSet;
begin
for i := Count - 1 downto 0 do begin
oItem := Items[i];
if oItem.Owned then
if oItem.Temporary then
FDFree(oItem)
else
oItem.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDLocalSQLDataSets.CheckUnique(AItem: TFDLocalSQLDataSet);
var
i: Integer;
sFull, sName: String;
begin
sFull := AItem.FullName;
if sFull = '' then
Exit;
for i := 0 to Count - 1 do
if (Items[i] <> AItem) and (CompareText(Items[i].FullName, sFull) = 0) then begin
if FOwner <> nil then
sName := FOwner.Name
else
sName := '';
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDSNameNotUnique,
[sFull, sName]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDLocalSQLDataSets.FindDataSet(const ASchemaName, AName: String): TFDLocalSQLDataSet;
var
i: Integer;
oItem: TFDLocalSQLDataSet;
sName: String;
begin
Result := nil;
sName := AName;
if ASchemaName <> '' then
sName := ASchemaName + '.' + sName;
for i := 0 to Count - 1 do begin
oItem := Items[i];
if CompareText(oItem.FullName, sName) = 0 then begin
Result := oItem;
Exit;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomLocalSQL }
{-------------------------------------------------------------------------------}
constructor TFDCustomLocalSQL.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataSets := TFDLocalSQLDataSets.Create(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomLocalSQL.Destroy;
begin
Destroying;
Connection := nil;
inherited Destroy;
FDFreeAndNil(FDataSets);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if AComponent = Connection then
Connection := nil
else if AComponent is TDataSet then
DataSets.Remove(TDataSet(AComponent));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.ReadDataSets(Reader: TReader);
begin
Reader.ReadCollection(DataSets);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.WriteDataSets(Writer: TWriter);
var
oCol: TFDLocalSQLDataSets;
i: Integer;
begin
oCol := TFDLocalSQLDataSets.Create(nil);
try
for i := 0 to DataSets.Count - 1 do
if not DataSets[i].Temporary then
oCol.Add.Assign(DataSets[i]);
Writer.WriteCollection(oCol);
finally
FDFree(oCol);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DefineProperties(AFiler: TFiler);
function AreDataSetsStorable(AFiler: TFiler): Boolean;
begin
Result := DataSets.Count > 0;
if AFiler.Ancestor <> nil then
if AFiler.Ancestor is TFDCustomLocalSQL then
Result := not CollectionsEqual(DataSets, TFDCustomLocalSQL(AFiler.Ancestor).DataSets,
Self, TFDCustomLocalSQL(AFiler.Ancestor));
end;
begin
AFiler.DefineProperty('DataSets', ReadDataSets, WriteDataSets, AreDataSetsStorable(AFiler));
inherited DefineProperties(AFiler);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.Loaded;
begin
inherited Loaded;
try
if FStreamedActive then
SetActive(True);
except
if csDesigning in ComponentState then
FDHandleException
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.SetDataSets(const AValue: TFDLocalSQLDataSets);
begin
FDataSets.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.SetActive(const AValue: Boolean);
begin
if csReading in ComponentState then
FStreamedActive := AValue
else if FActive <> AValue then begin
FActive := AValue;
if Active then
CheckActivate
else
CheckDeactivate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomLocalSQL.GetActualActive: Boolean;
begin
Result := Active and (Connection <> nil) and Connection.Connected;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.CheckActivate;
var
i: Integer;
begin
if GetActualActive and not FActivated then begin
for i := 0 to DataSets.Count - 1 do
DataSets.CheckUnique(DataSets[i]);
FActivated := True;
InternalAttachToSQL;
for i := 0 to DataSets.Count - 1 do
if DataSets[i].IsValid then
InternalDataSetAdded(DataSets[i]);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.CheckDeactivate;
var
i: Integer;
begin
if GetActualActive and FActivated then begin
FActivated := False;
for i := 0 to DataSets.Count - 1 do
if DataSets[i].IsValid then
InternalDataSetRemoving(DataSets[i]);
InternalDetachFromSQL;
DataSets.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.CheckDataSetAdded(const AItem: TFDLocalSQLDataSet);
begin
if GetActualActive then begin
DataSets.CheckUnique(AItem);
InternalDataSetAdded(AItem);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.CheckDataSetRemoving(const AItem: TFDLocalSQLDataSet);
begin
if GetActualActive then
InternalDataSetRemoving(AItem);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DoConnectChanged(Sender: TObject; Connecting: Boolean);
begin
if Connecting then
CheckActivate
else
CheckDeactivate;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.SetConnection(const AValue: TFDCustomConnection);
begin
if FConnection <> AValue then begin
if FConnection <> nil then begin
CheckDeactivate;
FConnection.UnRegisterClient(Self);
end;
FConnection := AValue;
if FConnection <> nil then begin
FConnection.RegisterClient(Self, DoConnectChanged);
FConnection.FreeNotification(Self);
CheckActivate;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.SetSchemaName(const AValue: String);
begin
if FSchemaName <> AValue then begin
CheckDeactivate;
FSchemaName := AValue;
CheckActivate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomLocalSQL.MatchSchema(var ASchemaName: String): Boolean;
begin
if CompareText(ASchemaName, 'main') = 0 then
ASchemaName := '';
Result := not (csDestroying in ComponentState) and
((SchemaName = '') or (CompareText(SchemaName, ASchemaName) = 0));
end;
{-------------------------------------------------------------------------------}
function TFDCustomLocalSQL.FindDataSet(const ASchemaName, AName: String): TFDLocalSQLDataSet;
var
sSchema: String;
begin
sSchema := ASchemaName;
if MatchSchema(sSchema) then
Result := DataSets.FindDataSet(sSchema, AName)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.RefreshDataSet(const ASchemaName, AName: String);
var
oDS: TFDLocalSQLDataSet;
begin
oDS := FindDataSet(ASchemaName, AName);
if (oDS <> nil) and oDS.IsValid then begin
InternalDataSetRemoving(oDS);
InternalDataSetAdded(oDS);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomLocalSQL.FindAdapter(const ASchemaName, AName: String): IFDPhysLocalSQLAdapter;
var
oDS: TFDLocalSQLDataSet;
begin
oDS := FindDataSet(ASchemaName, AName);
if (oDS <> nil) and oDS.IsValid then
Result := oDS.Adapter
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DoGetDataSet(const ASchemaName, AName: String;
var ADataSet: TDataSet; var AOwned: Boolean);
begin
if Assigned(OnGetDataSet) then
OnGetDataSet(Self, ASchemaName, AName, ADataSet, AOwned);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DoReleaseDataSet(const ASchemaName, AName: String;
var ADataSet: TDataSet; var AOwned: Boolean);
begin
if Assigned(OnReleaseDataSet) then
OnReleaseDataSet(Self, ASchemaName, AName, ADataSet, AOwned);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DoOpenDataSet(const ASchemaName, AName: String;
const ADataSet: TDataSet);
begin
if Assigned(OnOpenDataSet) then
OnOpenDataSet(Self, ASchemaName, AName, ADataSet);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.DoCloseDataSet(const ASchemaName, AName: String;
const ADataSet: TDataSet);
begin
if Assigned(OnCloseDataSet) then
OnCloseDataSet(Self, ASchemaName, AName, ADataSet);
end;
{-------------------------------------------------------------------------------}
function TFDCustomLocalSQL.GetDataSet(const ASchemaName, AName: String): Boolean;
var
oDS: TDataSet;
oItem: TFDLocalSQLDataSet;
lOwned: Boolean;
sSchema: String;
begin
Result := False;
sSchema := ASchemaName;
if MatchSchema(sSchema) then begin
oItem := DataSets.FindDataSet(ASchemaName, AName);
if (oItem = nil) or (oItem.DataSet = nil) then begin
oDS := nil;
lOwned := (oItem = nil) or oItem.Owned;
DoGetDataSet(ASchemaName, AName, oDS, lOwned);
if oDS <> nil then begin
if oItem = nil then begin
oItem := DataSets.Add(oDS, ASchemaName, AName);
oItem.Temporary := True;
end
else
oItem.DataSet := oDS;
oItem.Owned := lOwned;
Result := True;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.ReleaseDataSet(AItem: TFDLocalSQLDataSet);
begin
if AItem.DataSet <> nil then
try
DoReleaseDataSet(AItem.ActualSchemaName, AItem.ActualName,
AItem.FDataSet, AItem.FOwned);
finally
if AItem.FDataSet = nil then
AItem.FAdapter := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.OpenDataSet(const ASchemaName, AName: String;
ADataSet: TObject);
begin
if not (csDestroying in ComponentState) then
DoOpenDataSet(ASchemaName, AName, TDataSet(ADataSet));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomLocalSQL.CloseDataSet(const ASchemaName, AName: String;
ADataSet: TObject);
begin
if not (csDestroying in ComponentState) then
DoCloseDataSet(ASchemaName, AName, TDataSet(ADataSet));
end;
{-------------------------------------------------------------------------------}
{ TFDAdaptedDataSet }
{-------------------------------------------------------------------------------}
constructor TFDAdaptedDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
NestedDataSetClass := TFDCustomMemTable;
FDatSManager := TFDDatSManager.Create;
FDatSManager.UpdatesRegistry := True;
FDatSManager.CountRef;
FTxSupported := -1;
end;
{-------------------------------------------------------------------------------}
destructor TFDAdaptedDataSet.Destroy;
begin
LocalSQL := nil;
ChangeAlerter := nil;
FDFreeAndNil(FVclParams);
SetDatSManager(nil);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if AComponent = UpdateObject then
UpdateObject := nil
else if AComponent = Adapter then begin
Disconnect(True);
SetAdapter(nil);
end
else if AComponent = Command then
Disconnect(True)
else if AComponent = LocalSQL then
LocalSQL := nil
else if AComponent = ChangeAlerter then
ChangeAlerter := nil;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetCommand: TFDCustomCommand;
begin
if Adapter <> nil then
Result := Adapter.SelectCommand
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetParams: TFDParams;
begin
if Command <> nil then
Result := Command.Params
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetLocalSQL(const AValue: TFDCustomLocalSQL);
begin
if FLocalSQL <> AValue then begin
if FLocalSQL <> nil then
FLocalSQL.DataSets.Remove(Self);
FLocalSQL := AValue;
if FLocalSQL <> nil then begin
FLocalSQL.DataSets.Add(Self).Temporary := True;
FLocalSQL.FreeNotification(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetChangeAlerter(const AValue: TFDCustomEventAlerter);
begin
if FChangeAlerter <> AValue then begin
if FChangeAlerter <> nil then
FChangeAlerter.RemoveChangeHandler(Self);
FChangeAlerter := AValue;
if FChangeAlerter <> nil then begin
FChangeAlerter.AddChangeHandler(Self);
FChangeAlerter.FreeNotification(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetChangeAlertName(const AValue: String);
var
oAlerter: TFDCustomEventAlerter;
begin
if FChangeAlertName <> AValue then begin
oAlerter := ChangeAlerter;
ChangeAlerter := nil;
FChangeAlertName := AValue;
ChangeAlerter := oAlerter;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.CheckOnline(APrepare: Boolean = True);
var
oConn: TFDCustomConnection;
begin
if Command <> nil then begin
oConn := Command.GetConnection(False);
if oConn <> nil then
oConn.CheckOnline;
if not Command.Prepared and APrepare then
DoPrepareSource;
if (Command.CommandIntf = nil) or
(Command.CommandIntf <> FAdapter.TableAdapterIntf.SelectCommand) then
FAdapter.UpdateAdapterCmd(arSelect);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ReleaseBase(AOffline: Boolean);
var
oConn: TFDCustomConnection;
begin
if Command <> nil then begin
oConn := PointedConnection;
if Active and (oConn <> nil) and
((oConn.ConnectionIntf = nil) or (oConn.ConnectionIntf.State = csRecovering)) then
FSourceEOF := True;
end;
inherited ReleaseBase(AOffline);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.InternalUpdateErrorHandler(ASender: TObject;
const AInitiator: IFDStanObject; var AException: Exception);
var
eAction: TFDErrorAction;
oConn: TFDCustomConnection;
oUpdExc: EFDDAptRowUpdateException;
oArrErr: EFDDBArrayExecuteError;
begin
if AException is EFDDAptRowUpdateException then begin
oUpdExc := EFDDAptRowUpdateException(AException);
eAction := oUpdExc.Action;
DoUpdateErrorHandler(oUpdExc.Row, oUpdExc.Exception, oUpdExc.Request, eAction);
oUpdExc.Action := eAction;
end
else if AException is EFDDBArrayExecuteError then begin
if Assigned(FOnExecuteError) then begin
oArrErr := EFDDBArrayExecuteError(AException);
eAction := oArrErr.Action;
FOnExecuteError(Self, oArrErr.Times, oArrErr.Offset, oArrErr.Exception, eAction);
oArrErr.Action := eAction;
end;
end
else begin
if Assigned(FOnError) then
FOnError(Self, AInitiator as TObject, AException);
if (Command <> nil) and (AException <> nil) then begin
oConn := Command.GetConnection(False);
if oConn <> nil then
oConn.HandleException(AInitiator, AException);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.InternalUpdateRecordHandler(ASender: TObject;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest; AOptions: TFDUpdateRowOptions;
var AAction: TFDErrorAction);
begin
DoUpdateRecordHandler(ARow, ARequest, AOptions, AAction);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.InternalReconcileErrorHandler(ASender: TObject;
ARow: TFDDatSRow; var AAction: TFDDAptReconcileAction);
begin
DoReconcileErrorHandler(ARow, ARow.RowError, ARow.RowState, AAction);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetAdapter(AAdapter: TFDCustomTableAdapter);
begin
if FAdapter <> AAdapter then begin
if (AAdapter <> nil) and (AAdapter.DataSet <> nil) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntCantShareAdapt,
[AAdapter.Name, GetDisplayName, AAdapter.DataSet.GetDisplayName]);
if FAdapter <> nil then begin
FAdapter.RemoveFreeNotification(Self);
if (FAdapter.DatSTable <> nil) and
(FAdapter.DatSTable = Table) then
AttachTable(nil, nil)
else
FAdapter.DatSTable := nil;
if (FAdapter.SchemaAdapter <> nil) and
(FAdapter.SchemaAdapter.DatSManager = DatSManager) then
DatSManager := nil
else
FAdapter.DatSManager := nil;
if FAdapter.SelectCommand <> nil then
FAdapter.SelectCommand.RemoveFreeNotification(Self);
FAdapter.FAdaptedDataSet := nil;
if FUpdateObject <> nil then
FUpdateObject.DetachFromAdapter;
end;
FAdapter := AAdapter;
if FAdapter <> nil then begin
FAdapter.FreeNotification(Self);
if FAdapter.SchemaAdapter <> nil then
DatSManager := FAdapter.SchemaAdapter.DatSManager
else
FAdapter.DatSManager := DatSManager;
if FAdapter.DatSTable <> nil then
AttachTable(FAdapter.DatSTable, nil)
else
FAdapter.DatSTable := Table;
if FAdapter.SelectCommand <> nil then
FAdapter.SelectCommand.FreeNotification(Self);
FAdapter.FAdaptedDataSet := Self;
if FUpdateObject <> nil then
FUpdateObject.AttachToAdapter;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetDatSManager(AManager: TFDDatSManager);
begin
if FDatSManager <> AManager then begin
if (AManager = nil) or
(Table <> nil) and (AManager.Tables.IndexOf(Table) = -1) or
(BaseView <> nil) and (AManager.Tables.IndexOf(BaseView.Table) = -1) then
AttachTable(nil, nil);
if Adapter <> nil then
Adapter.DatSManager := nil;
if FDatSManager <> nil then begin
FDatSManager.RemRef;
FDatSManager := nil;
end;
FDatSManager := AManager;
if FDatSManager <> nil then
FDatSManager.AddRef;
if Adapter <> nil then
Adapter.DatSManager := AManager;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.AttachTable(ATable: TFDDatSTable; AView: TFDDatSView);
begin
inherited AttachTable(ATable, AView);
if (Table <> nil) and (DatSManager <> nil) and
(Adapter <> nil) and (Adapter.DatSManager = DatSManager) and
(Adapter.DatSTable <> Table) then
Adapter.DatSTable := Table;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoCloneCursor(AReset, AKeepSettings: Boolean);
begin
DatSManager := CloneSource.DatSManager;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetUpdateObject(const AValue: TFDCustomUpdateObject);
begin
if FUpdateObject <> AValue then begin
if (AValue <> nil) and (AValue.DataSet <> nil) then
AValue.DataSet.UpdateObject := nil;
if (FUpdateObject <> nil) and (FUpdateObject.DataSet = Self) then begin
FUpdateObject.RemoveFreeNotification(Self);
if Adapter <> nil then
FUpdateObject.DetachFromAdapter;
FUpdateObject.FDataSet := nil;
end;
FUpdateObject := AValue;
if FUpdateObject <> nil then begin
FUpdateObject.FDataSet := Self;
if Adapter <> nil then
FUpdateObject.AttachToAdapter;
FUpdateObject.FreeNotification(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.NextRecordSet;
begin
if Command <> nil then begin
CheckOnline;
DisableControls;
Command.CommandIntf.NextRecordSet := True;
try
Close;
Command.PropertyChange;
DoOpenSource(True, False, False);
if Command.Active then begin
Open;
FForcePropertyChange := True;
end
else
FForcePropertyChange := False;
finally
if Command.CommandIntf <> nil then
Command.CommandIntf.NextRecordSet := False;
EnableControls;
end;
end
else
Close;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.GetResults;
begin
DisableControls;
StartWait;
try
repeat
NextRecordSet;
until not Active;
finally
StopWait;
EnableControls;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.CloseStreams;
begin
if Command <> nil then
Command.CloseStreams;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.AbortJob(AWait: Boolean = False);
begin
if Command <> nil then
Command.AbortJob(AWait);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.InternalClose;
begin
ServerCancel;
inherited InternalClose;
if FForcePropertyChange then begin
FForcePropertyChange := False;
if Command <> nil then
Command.PropertyChange;
end;
FTxSupported := -1;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.Disconnect(AAbortJob: Boolean = False);
begin
if AAbortJob then
AbortJob(True);
inherited Disconnect(AAbortJob);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.InternalServerEdit(AServerEditRequest: TFDUpdateRequest);
begin
if (Adapter = nil) or (FServerEditRequest <> arNone) then
Exit;
CheckOnline;
CheckBrowseMode;
FServerEditRow := Table.NewRow(False);
FServerEditRequest := AServerEditRequest;
BeginForceRow(FServerEditRow, True, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerAppend;
begin
if Adapter = nil then
Append
else
InternalServerEdit(arInsert);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerDelete;
begin
InternalServerEdit(arDelete);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerEdit;
begin
InternalServerEdit(arUpdate);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerPerform;
var
eAction: TFDErrorAction;
begin
if (Adapter = nil) and (State = dsInsert) then
Post
else begin
CheckOnline;
CheckBrowseMode;
if FServerEditRequest <> arNone then begin
StartWait;
try
if Adapter <> nil then begin
eAction := eaApplied;
Adapter.Update(FServerEditRow, eAction, [], FServerEditRequest);
end;
finally
StopWait;
ServerCancel;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerCancel;
begin
if (Adapter = nil) and (State = dsInsert) then
Cancel
else if FServerEditRequest <> arNone then begin
EndForceRow;
FDFreeAndNil(FServerEditRow);
FServerEditRequest := arNone;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerDeleteAll(ANoUndo: Boolean);
var
oGen: IFDPhysCommandGenerator;
oCmd: IFDPhysCommand;
oConn: TFDCustomConnection;
oConnMeta: IFDPhysConnectionMetadata;
begin
CheckOnline;
if Adapter <> nil then begin
StartWait;
try
oConn := PointedConnection;
oConn.ConnectionIntf.CreateMetadata(oConnMeta);
if ANoUndo and oConnMeta.TruncateSupported then
while oConn.InTransaction do
oConn.Commit;
oConn.ConnectionIntf.CreateCommandGenerator(oGen, nil);
oGen.MappingHandler := Adapter.TableAdapterIntf as IFDPhysMappingHandler;
oConn.ConnectionIntf.CreateCommand(oCmd);
oCmd.CommandText := oGen.GenerateDeleteAll(ANoUndo);
oCmd.CommandKind := oGen.CommandKind;
oCmd.Prepare;
oCmd.Execute;
finally
StopWait;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ServerSetKey;
begin
raise Exception.Create('Not implemented');
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.ServerGotoKey: Boolean;
begin
raise Exception.Create('Not implemented');
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoMasterDefined;
begin
if Command <> nil then
inherited DoMasterDefined;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoMasterParamSetValues(AMasterFieldList: TFDFieldList);
begin
if Command <> nil then
inherited DoMasterParamSetValues(AMasterFieldList);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoMasterParamDependent(AMasterFieldList: TFDFieldList): Boolean;
begin
if Command <> nil then
Result := inherited DoMasterParamDependent(AMasterFieldList)
else
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoPrepareSource;
var
oConn: TFDCustomConnection;
begin
if (Command <> nil) and (Command.State = csInactive) then begin
oConn := PointedConnection;
if (LocalSQL <> nil) and (LocalSQL.Connection = oConn) and
not oConn.Connected and oConn.ResourceOptions.AutoConnect then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntLocalSQLMisuse,
[GetDisplayName]);
FieldDefs.Updated := False;
IndexDefs.Updated := False;
DoMasterDefined;
Command.Prepare;
FAdapter.UpdateAdapterCmd(arSelect);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoUnprepareSource;
begin
if FUnpreparing then
Exit;
FUnpreparing := True;
try
if Command <> nil then begin
if Command.State <> csInactive then begin
if not (dfOfflining in FFlags) then begin
FieldDefs.Updated := False;
IndexDefs.Updated := False;
end
else
Command.AbortJob(False);
end;
if Command.CommandIntf <> nil then
Command.Unprepare;
end;
if Adapter <> nil then
Adapter.Reset;
finally
FUnpreparing := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoDefineDatSManager;
var
oTab: TFDDatSTable;
begin
if (Command <> nil) and not (dfOfflining in FFlags) then begin
CheckOnline;
oTab := Adapter.Define;
AttachTable(oTab, nil);
// if to call TFDAdaptedDataSet.Open for command returning resultset without columns,
// then it will be executed twice:
// - here at Adapter.Define call -> state remains csPrepared, so second time ...
// - at TFDDataSet.InternalOpen.DoOpenSource
if Command.State = csPrepared then
FSourceEOF := True;
end
else begin
inherited DoDefineDatSManager;
FSourceEOF := dfOfflining in FFlags;
if (Adapter <> nil) and (Table <> nil) and
(Adapter.DatSTableName = Adapter.SourceRecordSetName) and (Table.Name <> '') then
Adapter.DatSTableName := Table.Name;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoOpenSource(ABlocked, AInfoQuery, AStructQuery: Boolean);
begin
if Command <> nil then begin
CheckOnline;
if Command.State = csPrepared then
Command.Open(ABlocked);
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoIsSourceOpen: Boolean;
begin
Result := (Command <> nil) and (Command.State = csOpen);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoIsSourceAsync: Boolean;
begin
Result := inherited DoIsSourceAsync and
not ((Command <> nil) and (Command.CommandIntf <> nil) and
Command.CommandIntf.NextRecordSet);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoIsSourceOnline: Boolean;
var
oConn: TFDCustomConnection;
begin
Result := inherited DoIsSourceOnline;
if Result and (Command <> nil) then begin
oConn := Command.GetConnection(False);
if oConn <> nil then
Result := not oConn.Offlined and oConn.Connected;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoCloseSource;
begin
if Command <> nil then begin
if Command.State = csOpen then
Command.Close;
end
else
inherited DoCloseSource;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoResetDatSManager;
begin
inherited DoResetDatSManager;
AttachTable(nil, nil);
if DatSManager <> nil then begin
if (Adapter <> nil) and (Adapter.DatSTable <> nil) and
(Adapter.DatSTable.Manager = DatSManager) then
Adapter.DatSTable := nil;
if not ((Adapter <> nil) and (Adapter.DatSManager = DatSManager) and (DatSManager.Refs > 2) or
(Adapter = nil) and (DatSManager.Refs > 1)) then
DatSManager.Reset;
end;
ASSERT(Table = nil); // else we need Table.Reset;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoResetAtLoading;
begin
inherited DoResetAtLoading;
if Adapter = nil then begin
SetDatSManager(nil);
FDatSManager := TFDDatSManager.Create;
FDatSManager.UpdatesRegistry := True;
FDatSManager.CountRef;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoGetDatSManager: TFDDatSManager;
begin
Result := FDatSManager;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoGetTableName: String;
var
eCmdKind: TFDPhysCommandKind;
oCmd: TFDCustomCommand;
oRes: TFDResourceOptions;
oConn: TFDCustomConnection;
rName: TFDPhysParsedName;
begin
Result := '';
oCmd := Command;
if oCmd <> nil then begin
if oCmd.CommandIntf <> nil then
Result := oCmd.CommandIntf.SourceObjectName;
if Result = '' then begin
eCmdKind := skUnknown;
oRes := ResourceOptions;
oCmd.PreprocessSQL(oCmd.CommandText.Text, oCmd.Params, nil, oCmd.Macros,
False, False, oRes.MacroExpand, oRes.EscapeExpand, True, eCmdKind, Result);
oConn := PointedConnection;
if oConn <> nil then begin
rName.FObject := Result;
Result := PointedConnection.ConnectionMetaDataIntf.EncodeObjName(
rName, nil, [eoNormalize]);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoFetch(ATable: TFDDatSTable; AAll: Boolean;
ADirection: TFDFetchDirection = fdDown): Integer;
begin
if (ADirection = fdDown) and (Command <> nil) and (Command.State = csOpen) then begin
ASSERT(Adapter.DatSTable = ATable);
Adapter.Fetch(AAll);
Result := Command.RowsAffected;
end
else
Result := 0;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoFetch(ARow: TFDDatSRow; AColumn: Integer;
ARowOptions: TFDPhysFillRowOptions): Boolean;
var
eAction: TFDErrorAction;
begin
eAction := eaDefault;
if Adapter <> nil then
Adapter.Fetch(ARow, eAction, AColumn, ARowOptions);
Result := eAction in [eaApplied, eaExitSuccess];
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoMasterClearDetails(AAll: Boolean);
var
oFtch: TFDFetchOptions;
begin
if Command <> nil then
inherited DoMasterClearDetails(AAll)
else begin
oFtch := FetchOptions;
if not (fiDetails in oFtch.Cache) then
oFtch.Cache := oFtch.Cache + [fiDetails];
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoExecuteSource(ATimes, AOffset: Integer);
begin
if Command <> nil then begin
CheckOnline;
Command.Execute(ATimes, AOffset);
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoApplyUpdates(ATable: TFDDatSTable; AMaxErrors: Integer): Integer;
begin
if Adapter <> nil then begin
CheckOnline(False);
ASSERT(Adapter.DatSTable = ATable);
Result := Adapter.ApplyUpdates(AMaxErrors);
end
else
Result := inherited DoApplyUpdates(ATable, AMaxErrors);
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.DoProcessUpdateRequest(ARequest: TFDUpdateRequest;
AOptions: TFDUpdateRowOptions);
var
oConn: TFDCustomConnection;
oRow: TFDDatSRow;
eAction: TFDErrorAction;
begin
if ParentDataSet <> nil then
TFDAdaptedDataSet(ParentDataSet).DoProcessUpdateRequest(ARequest, AOptions)
else if UpdateOptions.CheckRequest(ARequest, AOptions, CachedUpdates) then begin
oConn := PointedConnection;
oRow := GetRow(TRecBuf(ActiveBuffer));
eAction := eaApplied;
if not (csDestroying in ComponentState) and (Adapter <> nil) and
((oConn = nil) or (oConn.ConnectionIntf = nil) or
(oConn.ConnectionIntf.State <> csRecovering)) then begin
CheckOnline(False);
case ARequest of
arLock: Adapter.Lock(oRow, eAction, AOptions);
arUnLock: Adapter.UnLock(oRow, eAction, AOptions);
arFetchGenerators,
arInsert,
arUpdate,
arDelete: Adapter.Update(oRow, eAction, AOptions, ARequest);
end;
end
else
inherited DoProcessUpdateRequest(ARequest, AOptions);
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetOptionsIntf: IFDStanOptions;
begin
Result := Command.OptionsIntf;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetOptionsIntf(const AValue: IFDStanOptions);
begin
Command.OptionsIntf := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetConnection(ACheck: Boolean): TFDCustomConnection;
begin
if Command <> nil then
Result := Command.GetConnection(ACheck)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetPointedConnection: TFDCustomConnection;
begin
Result := GetConnection(False);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.DoStoredActivation: Boolean;
var
eUsage: TFDStoredActivationUsage;
begin
eUsage := FDManager.ActiveStoredUsage;
if PointedConnection <> nil then
eUsage := eUsage * PointedConnection.ConnectedStoredUsage;
Result := FDCheckStoredUsage(ComponentState, eUsage * ActiveStoredUsage);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetConn: NativeUInt;
begin
Result := NativeUInt(PointedConnection);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetFeatures: TFDPhysLocalSQLAdapterFeatures;
procedure UpdateTxSup;
begin
if (PointedConnection <> nil) and PointedConnection.Connected and
PointedConnection.ConnectionMetaDataIntf.TxSupported then
FTxSupported := 1
else
FTxSupported := 0;
end;
begin
Result := inherited GetFeatures;
if FTxSupported = -1 then
UpdateTxSup;
if FTxSupported <> 0 then
Include(Result, afTransactions);
end;
{-------------------------------------------------------------------------------}
{ IProviderSupport }
function TFDAdaptedDataSet.PSInTransaction: Boolean;
var
oConn: TFDCustomConnection;
begin
oConn := GetConnection(False);
Result := (oConn <> nil) and oConn.InTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.PSStartTransaction;
var
oConn: TFDCustomConnection;
begin
oConn := GetConnection(False);
if oConn <> nil then begin
oConn.CheckOnline;
if oConn.ConnectionMetaDataIntf.TxSupported then
oConn.StartTransaction;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.PSEndTransaction(Commit: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := GetConnection(False);
if oConn <> nil then begin
oConn.CheckOnline;
if oConn.ConnectionMetaDataIntf.TxSupported then
if Commit then
oConn.Commit
else
oConn.Rollback;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSIsSQLBased: Boolean;
var
oConn: TFDCustomConnection;
begin
oConn := GetConnection(False);
Result := (oConn <> nil) and oConn.IsSQLBased;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSIsSQLSupported: Boolean;
begin
Result := PSIsSQLBased;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSGetQuoteChar: string;
var
oConn: TFDCustomConnection;
oConnMeta: IFDPhysConnectionMetadata;
eQuote: TFDPhysNameQuoteLevel;
begin
Result := '"';
oConn := GetConnection(False);
if oConn <> nil then begin
oConn.CheckOnline;
oConnMeta := oConn.GetConnectionMetadata;
if oConnMeta <> nil then
for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do
// TSQLResolver supports only single quote char for both start and end
if not FDInSet(oConnMeta.NameQuoteChar[eQuote, nsLeft], [#0, ' ']) and
(oConnMeta.NameQuoteChar[eQuote, nsLeft] = oConnMeta.NameQuoteChar[eQuote, nsRight]) then begin
Result := oConnMeta.NameQuoteChar[eQuote, nsLeft];
Break;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSGetParams: TParams;
begin
if Command <> nil then begin
if FVclParams = nil then
FVclParams := TParams.Create;
FVclParams.Assign(Params);
Result := FVclParams;
end
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.PSSetParams(AParams: TParams);
begin
if Command <> nil then begin
if AParams.Count <> 0 then
Params.Assign(AParams);
Close;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSGetCommandText: string;
begin
if Command <> nil then
Result := Command.CommandText.Text
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSGetCommandType: TPSCommandType;
begin
Result := ctUnknown;
if Command <> nil then
case Command.CommandKind of
skSelect,
skSelectForLock,
skSelectForUnLock: Result := ctSelect;
skDelete: Result := ctDelete;
skInsert,
skMerge: Result := ctInsert;
skUpdate: Result := ctUpdate;
skCreate,
skAlter,
skDrop: Result := ctDDL;
skStoredProc,
skStoredProcWithCrs,
skStoredProcNoCrs: Result := ctStoredProc;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.PSSetCommandText(const CommandText: string);
begin
if Command <> nil then
Command.SetCommandText(CommandText, False);
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.InternalPSExecuteStatement(const ASQL: string;
AParams: TParams; AMode: Integer; var AResultSet: TFDQuery): Integer;
begin
Result := 0;
CheckOnline(False);
AResultSet := TFDQuery.Create(nil);
try
AResultSet.OptionsIntf.ParentOptions := OptionsIntf;
AResultSet.FormatOptions.DataSnapCompatibility := True;
AResultSet.ResourceOptions.ParamCreate := False;
AResultSet.ResourceOptions.MacroCreate := False;
AResultSet.ResourceOptions.MacroExpand := False;
AResultSet.Connection := GetConnection(True);
if Command <> nil then
AResultSet.Transaction := Command.Transaction;
AResultSet.Command.SetCommandText(ASQL, False);
AResultSet.Params.Assign(AParams);
case AMode of
0:
begin
AResultSet.ExecSQL;
Result := AResultSet.RowsAffected;
end;
1:
begin
AResultSet.Open;
Result := AResultSet.RecordCount;
end;
2:
if AResultSet.OpenOrExecute then
Result := AResultSet.RecordCount
else
Result := AResultSet.RowsAffected;
end;
except
FDFreeAndNil(AResultSet);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSExecuteStatement(const ASQL: string;
AParams: TParams; AResultSet: Pointer): Integer;
var
oQry: TFDQuery;
begin
oQry := nil;
try
Result := InternalPSExecuteStatement(ASQL, AParams, Integer(Assigned(AResultSet)), oQry);
finally
if Assigned(AResultSet) then
TFDQuery(AResultSet^) := oQry
else
FDFree(oQry);
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSExecuteStatement(const ASQL: string;
AParams: TParams; var AResultSet: TDataSet): Integer;
var
oQry: TFDQuery;
begin
oQry := nil;
try
Result := InternalPSExecuteStatement(ASQL, AParams, 2, oQry);
finally
AResultSet := oQry;
end;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.PSExecuteStatement(const ASQL: string;
AParams: TParams): Integer;
var
oQry: TFDQuery;
begin
oQry := nil;
try
Result := InternalPSExecuteStatement(ASQL, AParams, 0, oQry);
finally
FDFree(oQry);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.PSGetAttributes(AList: TPacketAttributeList);
begin
inherited PSGetAttributes(AList);
end;
{-------------------------------------------------------------------------------}
{ IFDPhysChangeHandler }
function TFDAdaptedDataSet.GetTrackCommand: IFDPhysCommand;
begin
if Command <> nil then begin
if not (csDestroying in ComponentState) then
CheckOnline(False);
Result := Command.CommandIntf;
end
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetTrackEventName: String;
begin
if ChangeAlertName <> '' then
Result := ChangeAlertName
else
Result := PSGetTableName;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetMergeTable: TFDDatSTable;
begin
Result := Table;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetMergeManager: TFDDatSManager;
begin
Result := DatSManager;
end;
{-------------------------------------------------------------------------------}
function TFDAdaptedDataSet.GetContentModified: Boolean;
begin
Result := FContentModified;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.SetContentModified(AValue: Boolean);
begin
FContentModified := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.RefreshContent;
begin
FContentModified := False;
if UpdatesPending then
CancelUpdates;
Refresh;
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ResyncContent;
begin
FContentModified := False;
ResyncViews;
end;
{-------------------------------------------------------------------------------}
{ IDataSetCommandSupport }
function TFDAdaptedDataSet.GetCommandStates(const ACommand: String): TDataSetCommandStates;
begin
if (Adapter = nil) or (Adapter.SchemaAdapter = nil) then
Result := inherited GetCommandStates(ACommand)
else if SameText(ACommand, sApplyUpdatesDataSetCommand) or
SameText(ACommand, sCancelUpdatesDataSetCommand) then begin
Result := [dcSupported];
if Adapter.SchemaAdapter.UpdatesPending then
Include(Result, dcEnabled);
end
else
Result := [];
end;
{-------------------------------------------------------------------------------}
procedure TFDAdaptedDataSet.ExecuteCommand(const ACommand: String;
const AArgs: array of const);
var
iMaxErrors: Integer;
begin
if (Adapter = nil) or (Adapter.SchemaAdapter = nil) then
inherited ExecuteCommand(ACommand, AArgs)
else if SameText(ACommand, sApplyUpdatesDataSetCommand) then begin
if Length(AArgs) = 1 then
iMaxErrors := AArgs[0].VInteger
else
iMaxErrors := -1;
Adapter.SchemaAdapter.ApplyUpdates(iMaxErrors);
end
else if SameText(ACommand, sCancelUpdatesDataSetCommand) then
Adapter.SchemaAdapter.CancelUpdates;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomMemTable }
{-------------------------------------------------------------------------------}
constructor TFDCustomMemTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FetchOptions.Mode := fmAll;
ResourceOptions.SilentMode := True;
UpdateOptions.CheckRequired := False;
UpdateOptions.AutoCommitUpdates := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDCustomMemTable.Destroy;
begin
Close;
Destroying;
inherited Destroy;
Adapter := nil;
if FOptionsIntf <> nil then begin
FOptionsIntf.ObjectDestroyed(Self);
FOptionsIntf := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.DefineProperties(AFiler: TFiler);
begin
inherited DefineProperties(AFiler);
AFiler.DefineProperty('AutoCommitUpdates', ReadAutoCommitUpdates, nil, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.ReadAutoCommitUpdates(AReader: TReader);
var
lAutoCommit: Boolean;
begin
lAutoCommit := AReader.ReadBoolean;
if UpdateOptions.AutoCommitUpdates <> lAutoCommit then
UpdateOptions.AutoCommitUpdates := lAutoCommit;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetOptionsIntf: IFDStanOptions;
begin
if Command = nil then begin
if FOptionsIntf = nil then
FOptionsIntf := TFDOptionsContainer.Create(Self, TFDFetchOptions,
TFDBottomUpdateOptions, TFDBottomResourceOptions, GetParentOptions);
Result := FOptionsIntf;
end
else begin
if FOptionsIntf <> nil then begin
// Override the command options by the FDMemTable options
Command.FetchOptions := FOptionsIntf.FetchOptions;
Command.FormatOptions := FOptionsIntf.FormatOptions;
Command.UpdateOptions := FOptionsIntf.UpdateOptions as TFDBottomUpdateOptions;
Command.ResourceOptions := FOptionsIntf.ResourceOptions as TFDBottomResourceOptions;
// And switch to the command options usage
FOptionsIntf := nil;
end;
Result := inherited GetOptionsIntf;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.GetParentOptions(var AOpts: IFDStanOptions);
begin
if Command <> nil then
Command.GetParentOptions(AOpts)
else
AOpts := TFDCustomManager.GetSingletonOptsIntf;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.DefChanged(ASender: TObject);
begin
FStoreDefs := True;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.SaveToDFM(const AAncestor: TFDDataSet): Boolean;
begin
Result := (DataSetField = nil) and (ParentDataSet = nil) and (DatSManager <> nil) and
Active and (FStorage = nil) and ResourceOptions.Persistent and (ResourceOptions.PersistentFileName = '');
if Result and (AAncestor <> nil) then
Result := not TFDCustomMemTable(AAncestor).SaveToDFM(nil) or
not Table.IsEqualTo(TFDCustomMemTable(AAncestor).Table) or
not Table.Rows.IsEqualTo(TFDCustomMemTable(AAncestor).Table.Rows);
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetCommandText: String;
begin
if Command <> nil then
Result := Command.CommandText.Text
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetDisableStringTrim: Boolean;
begin
Result := not FormatOptions.StrsTrim;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetFetchOnDemand: Boolean;
begin
Result := FetchOptions.Mode = fmOnDemand;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetIsClone: Boolean;
var
oBaseDS: TFDDataSet;
begin
oBaseDS := Self;
while Assigned(oBaseDS.DataSetField) do
oBaseDS := oBaseDS.DataSetField.DataSet as TFDDataSet;
Result := Assigned(oBaseDS.CloneSource);
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetLogChanges: Boolean;
begin
Result := CachedUpdates;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetProviderEOF: Boolean;
begin
Result := SourceEOF;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetReadOnly: Boolean;
begin
Result := UpdateOptions.ReadOnly;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetStatusFilter: TFDUpdateRecordTypes;
begin
Result := FilterChanges;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetXMLData: string;
var
oStr: TStringStream;
begin
oStr := TStringStream.Create('', TEncoding.UTF8);
try
SaveToStream(oStr, sfXML);
Result := oStr.DataString;
finally
FDFree(oStr);
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetPacketRecords: Integer;
begin
Result := FetchOptions.RowsetSize;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetFileName: string;
begin
Result := ResourceOptions.PersistentFileName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetCommandText(const AValue: String);
begin
if Command <> nil then
Command.CommandText.Text := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetDisableStringTrim(const AValue: Boolean);
begin
FormatOptions.StrsTrim := not AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetFetchOnDemand(const AValue: Boolean);
begin
if AValue then
FetchOptions.Mode := fmOnDemand
else
FetchOptions.Mode := fmManual;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetLogChanges(const AValue: Boolean);
begin
CachedUpdates := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetProviderEOF(const AValue: Boolean);
begin
FSourceEOF := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetReadOnly(const AValue: Boolean);
begin
UpdateOptions.ReadOnly := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetStatusFilter(const AValue: TFDUpdateRecordTypes);
begin
FilterChanges := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetXMLData(const AValue: string);
var
oStr: TStringStream;
begin
oStr := TStringStream.Create(AValue, TEncoding.UTF8);
try
LoadFromStream(oStr, sfXML);
finally
FDFree(oStr);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetFileName(const AValue: string);
begin
ResourceOptions.PersistentFileName := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetPacketRecords(const AValue: Integer);
begin
FetchOptions.RowsetSize := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.AppendData(const AData: IFDDataSetReference; AHitEOF: Boolean = True);
begin
if Active then begin
if (AData <> nil) and (AData.DataView <> nil) then begin
Table.Import(AData.DataView);
Resync([]);
end;
end
else
Data := AData;
if AHitEOF then
FSourceEOF := True;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.ConstraintsDisabled: Boolean;
begin
Result := not ConstraintsEnabled;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.MergeChangeLog;
begin
CommitUpdates;
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetOptionalParamTab: TFDDatSTable;
var
i: Integer;
sTabName: String;
begin
sTabName := C_FD_SysNamePrefix + 'OPTIONAL_PARAMS';
i := DatSManager.Tables.IndexOfName(sTabName);
if i >= 0 then
Result := DatSManager.Tables[i]
else
Result := DatSManager.Tables.Add(sTabName);
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetOptionalParam(const AParamName: string): Variant;
var
oTab: TFDDatSTable;
iCol: Integer;
begin
oTab := GetOptionalParamTab;
iCol := oTab.Columns.IndexOfName(AParamName);
if (iCol = -1) or (oTab.Rows.Count <> 1) then
Result := Unassigned
else
Result := oTab.Rows[0].GetData(iCol);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomMemTable.SetOptionalParam(const AParamName: string;
const AValue: Variant; AIncludeInDelta: Boolean);
function GetValueType: TFDDataType;
var
tp: Word;
begin
tp := VarType(AValue);
case tp of
varShortInt:
Result := dtSByte;
varByte:
Result := dtByte;
varSmallint:
Result := dtInt16;
varWord:
Result := dtUInt16;
varLongWord:
Result := dtUInt32;
varInteger:
Result := dtInt32;
varCurrency:
Result := dtCurrency;
varSingle:
Result := dtSingle;
varDouble:
Result := dtDouble;
varDate:
Result := dtDateTime;
varBoolean:
Result := dtBoolean;
varUString,
varString,
varOleStr:
Result := dtWideMemo;
varUInt64:
Result := dtUInt64;
varInt64:
Result := dtInt64;
varArray or varByte:
Result := dtBlob;
else
if tp = VarFMTBcd then
Result := dtFmtBCD
else if tp = VarSQLTimeStamp then
Result := dtDateTimeStamp
else if tp = FDVarSQLTimeInterval then
Result := dtTimeIntervalFull
else
Result := dtBlob;
end;
end;
var
oTab, oTab2: TFDDatSTable;
iCol: Integer;
oRow: TFDDatSRow;
begin
oTab := GetOptionalParamTab;
iCol := oTab.Columns.IndexOfName(AParamName);
if (oTab.Rows.Count > 0) and (iCol = -1) then begin
oTab2 := TFDDatSTable.Create;
oTab2.Columns.Assign(oTab.Columns);
iCol := oTab2.Columns.Add(AParamName, GetValueType).Index;
oTab2.ImportRow(oTab.Rows[0]);
FDFree(oTab);
oTab2.Name := C_FD_SysNamePrefix + 'OPTIONAL_PARAMS';
DatSManager.Tables.Add(oTab2);
oTab := oTab2;
end
else if (oTab.Rows.Count = 0) and (iCol = -1) then begin
iCol := oTab.Columns.Add(AParamName, GetValueType).Index;
oTab.Rows.Add([]);
end;
oRow := oTab.Rows[0];
oRow.BeginEdit;
oRow.SetData(iCol, AValue);
oRow.EndEdit(True);
end;
{-------------------------------------------------------------------------------}
function TFDCustomMemTable.GetExists: Boolean;
begin
Result := Active;
end;
{-------------------------------------------------------------------------------}
{ TFDRdbmsDataSet }
{-------------------------------------------------------------------------------}
constructor TFDRdbmsDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetAdapter(InternalCreateAdapter);
Command.FOwner := Self;
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDRdbmsDataSet.Destroy;
begin
Destroying;
ChangeAlerter := nil;
Disconnect(True);
Connection := nil;
ConnectionName := '';
Transaction := nil;
inherited Destroy;
if Command <> nil then
Command.FOwner := nil;
FDFreeAndNil(FAdapter);
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Loaded;
begin
inherited Loaded;
try
if FStreamedPrepared and DoStoredActivation then
SetPrepared(True);
except
if csDesigning in ComponentState then
InternalHandleException
else
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.DefineProperties(AFiler: TFiler);
begin
inherited DefineProperties(AFiler);
Command.DefineProperties(AFiler);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.InternalCreateAdapter: TFDCustomTableAdapter;
begin
Result := TFDTableAdapter.Create(nil);
Result.SelectCommand := TFDCommand.Create(Result);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetConnection: TFDCustomConnection;
begin
if Command = nil then
Result := nil
else
Result := Command.Connection;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetConnection(const AValue: TFDCustomConnection);
begin
if Connection <> AValue then begin
Disconnect(True);
Command.Connection := AValue;
end;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetConnectionName: String;
begin
if Command = nil then
Result := ''
else
Result := Command.ConnectionName;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetConnectionName(const AValue: String);
begin
if ConnectionName <> AValue then
Command.ConnectionName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.IsCNNS: Boolean;
begin
Result := not IsCNS;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.IsCNS: Boolean;
begin
Result := (Connection <> nil) and
(Connection.Name <> '') and (Connection.Owner <> nil) and
(Connection.ConnectionName = ConnectionName);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetTransaction: TFDCustomTransaction;
begin
if Command = nil then
Result := nil
else
Result := Command.Transaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetTransaction(const AValue: TFDCustomTransaction);
begin
if Transaction <> AValue then
Command.Transaction := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetUpdateTransaction: TFDCustomTransaction;
begin
Result := Adapter.UpdateTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetUpdateTransaction(const AValue: TFDCustomTransaction);
begin
Adapter.UpdateTransaction := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetSchemaAdapter: TFDCustomSchemaAdapter;
begin
Result := Adapter.SchemaAdapter;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetSchemaAdapter(const AValue: TFDCustomSchemaAdapter);
begin
CheckInactive;
Adapter.SchemaAdapter := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetPrepared: Boolean;
begin
Result := Command.Prepared;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetPrepared(const AValue: Boolean);
begin
if csReading in ComponentState then
FStreamedPrepared := AValue
else if (Command <> nil) and
// The second OR part protects against the case, when the command interface was
// created with ckCreateIntfDontPrepare in FFlags. Without it an app may run
// into "FDPhysManager timeout". See FD-0250 for details.
((Command.Prepared <> AValue) or not AValue and (Command.CommandIntf <> nil)) then begin
if AValue then
DoPrepareSource
else
DoUnprepareSource;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.ReleaseBase(AOffline: Boolean);
var
oAdapt: IFDDAptTableAdapter;
begin
inherited ReleaseBase(AOffline);
if Adapter <> nil then begin
oAdapt := Adapter.TableAdapterIntf;
if oAdapt <> nil then begin
oAdapt.Transaction := nil;
oAdapt.UpdateTransaction := nil;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.IsPS: Boolean;
begin
Result := Prepared and not Active;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.CheckCachedUpdatesMode;
begin
if not CachedUpdates then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntNotCachedUpdates,
[GetDisplayName]);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.FindMacro(const AValue: string): TFDMacro;
begin
Result := Command.Macros.FindMacro(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.MacroByName(const AValue: string): TFDMacro;
begin
Result := Command.Macros.MacroByName(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetMacrosCount: Integer;
begin
Result := Command.Macros.Count;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetMacros: TFDMacros;
begin
Result := Command.Macros;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetMacros(const AValue: TFDMacros);
begin
Command.Macros := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.OpenCursor(InfoQuery: Boolean);
var
oConn: TFDCustomConnection;
begin
oConn := Command.AcquireConnection;
try
oConn.AttachClient(Self);
try
inherited OpenCursor(InfoQuery);
except
on E: Exception do begin
oConn.DetachClient(Self);
raise;
end;
end;
finally
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.DoAfterOpenOrExecute;
begin
Command.InternalExecuteFinished(Command, asFinished, nil);
if not DoIsSourceAsync then
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.InternalClose;
var
oConn: TFDCustomConnection;
begin
oConn := Command.GetConnection(False);
try
inherited InternalClose;
finally
if oConn <> nil then
oConn.DetachClient(Self);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Disconnect(AAbortJob: Boolean = False);
begin
inherited Disconnect(AAbortJob);
Prepared := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Prepare;
begin
Prepared := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Unprepare;
begin
Prepared := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Open(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType);
var
i: Integer;
begin
Close;
if ASQL <> '' then
Command.SetCommandText(ASQL,
not (Command.CommandKind in [skStoredProc, skStoredProcNoCrs, skStoredProcWithCrs]) and
ResourceOptions.ParamCreate);
if Command.CommandKind in [skStoredProc, skStoredProcNoCrs, skStoredProcWithCrs] then
Prepare;
if Params.BindMode = pbByNumber then
for i := 0 to Params.Count - 1 do
Params[i].Position := i + 1;
for i := Low(ATypes) to High(ATypes) do
if ATypes[i] <> ftUnknown then
Params[i].DataType := ATypes[i];
for i := Low(AParams) to High(AParams) do
Params[i].Value := AParams[i];
if not (Command.CommandKind in [skStoredProc, skStoredProcNoCrs, skStoredProcWithCrs]) then
Prepare;
Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Open(const ASQL: String);
begin
Open(ASQL, [], []);
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.Open(const ASQL: String; const AParams: array of Variant);
begin
Open(ASQL, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetOnError: TFDErrorEvent;
begin
Result := FAdapter.OnError;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetOnError(const AValue: TFDErrorEvent);
begin
FAdapter.OnError := AValue;
Command.OnError := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetOnCommandChanged: TNotifyEvent;
begin
Result := Command.OnCommandChanged;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetOnCommandChanged(const AValue: TNotifyEvent);
begin
Command.OnCommandChanged := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetParamBindMode: TFDParamBindMode;
begin
Result := Command.ParamBindMode;
end;
{-------------------------------------------------------------------------------}
procedure TFDRdbmsDataSet.SetParamBindMode(const AValue: TFDParamBindMode);
begin
Command.ParamBindMode := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.GetRowsAffected: TFDCounter;
begin
Result := Command.RowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDRdbmsDataSet.PSGetCommandType: TPSCommandType;
begin
if Command.CommandText.Count > 0 then
Prepared := True;
Result := inherited PSGetCommandType;
end;
{-------------------------------------------------------------------------------}
{ TFDUpdateSQL }
{-------------------------------------------------------------------------------}
constructor TFDUpdateSQL.Create(AOwner: TComponent);
var
i: Integer;
begin
inherited Create(AOwner);
for i := 0 to 5 do
FCommands[i] := TFDCustomCommand.Create(nil);
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDUpdateSQL.Destroy;
var
i: Integer;
begin
for i := 0 to 5 do
if FCommands[i] <> nil then
FDFreeAndNil(FCommands[i]);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.Notification(AComponent: TComponent; AOperation: TOperation);
begin
if (AOperation = opRemove) and (AComponent = Connection) then
Connection := nil;
inherited Notification(AComponent, AOperation);
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.AttachToAdapter;
var
oAdapt: TFDCustomTableAdapter;
begin
oAdapt := FDataSet.Adapter;
oAdapt.InsertCommand := GetCommand(arInsert);
oAdapt.UpdateCommand := GetCommand(arUpdate);
oAdapt.DeleteCommand := GetCommand(arDelete);
oAdapt.LockCommand := GetCommand(arLock);
oAdapt.UnLockCommand := GetCommand(arUnlock);
oAdapt.FetchRowCommand := GetCommand(arFetchRow);
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.DetachFromAdapter;
var
i: Integer;
oAdapt: TFDCustomTableAdapter;
begin
for i := 0 to 5 do
if FCommands[i] <> nil then
FCommands[i].OptionsIntf.ParentOptions := nil;
oAdapt := FDataSet.Adapter;
oAdapt.InsertCommand := nil;
oAdapt.UpdateCommand := nil;
oAdapt.DeleteCommand := nil;
oAdapt.LockCommand := nil;
oAdapt.UnLockCommand := nil;
oAdapt.FetchRowCommand := nil;
end;
{-------------------------------------------------------------------------------}
function TFDUpdateSQL.GetCommand(ARequest: TFDUpdateRequest): TFDCustomCommand;
var
sConnName: String;
oConn: TFDCustomConnection;
onErr: TFDErrorEvent;
oFtch: TFDFetchOptions;
oRes: TFDResourceOptions;
begin
Result := FCommands[Integer(ARequest) - Integer(Low(TFDUpdateRequest))];
sConnName := ConnectionName;
oConn := Connection;
onErr := nil;
if DataSet is TFDRdbmsDataSet then begin
if (sConnName = '') and (oConn = nil) then begin
oConn := TFDRdbmsDataSet(DataSet).Connection;
sConnName := TFDRdbmsDataSet(DataSet).ConnectionName;
end;
onErr := TFDRdbmsDataSet(DataSet).OnError;
end;
if (Result.ConnectionName <> sConnName) or (Result.Connection <> oConn) or
not Result.Prepared then begin
Result.Disconnect;
Result.ConnectionName := sConnName;
Result.Connection := oConn;
if DataSet <> nil then
Result.OptionsIntf.ParentOptions := DataSet.OptionsIntf
else
Result.OptionsIntf.ParentOptions := nil;
oFtch := Result.FetchOptions;
oFtch.Mode := fmExactRecsMax;
oFtch.RecsMax := 1;
oFtch.Items := oFtch.Items - [fiMeta];
oFtch.Cache := [];
oFtch.AutoClose := True;
oFtch.AutoFetchAll := afAll;
oRes := Result.ResourceOptions;
if oRes.CmdExecMode = amAsync then
oRes.CmdExecMode := amBlocking;
oRes.Persistent := False;
Result.OnError := onErr;
end;
end;
{-------------------------------------------------------------------------------}
function TFDUpdateSQL.GetSQL(const AIndex: Integer): TStrings;
begin
Result := FCommands[AIndex].CommandText;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.SetSQL(const AIndex: Integer; const AValue: TStrings);
begin
FCommands[AIndex].CommandText := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDUpdateSQL.GetURSQL(ARequest: TFDUpdateRequest): TStrings;
begin
Result := FCommands[Integer(ARequest) - Integer(Low(TFDUpdateRequest))].CommandText;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.SetURSQL(ARequest: TFDUpdateRequest;
const Value: TStrings);
begin
FCommands[Integer(ARequest) - Integer(Low(TFDUpdateRequest))].CommandText := Value;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.UpdateAdapter;
begin
if (FDataSet <> nil) and (FDataSet.Adapter <> nil) then begin
DetachFromAdapter;
AttachToAdapter;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.SetConnection(const Value: TFDCustomConnection);
begin
if FConnection <> Value then begin
FConnection := Value;
if FConnection <> nil then
FConnection.FreeNotification(Self);
UpdateAdapter;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.SetConnectionName(const Value: String);
begin
if FConnectionName <> Value then begin
FConnectionName := Value;
UpdateAdapter;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDUpdateSQL.Apply(ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
var
oCmd: TFDCustomCommand;
begin
oCmd := Commands[ARequest];
if (oCmd.CommandText.Count > 0) and (DataSet <> nil) and (DataSet.Adapter <> nil) then begin
DataSet.Adapter.Update(DataSet.GetRow(), AAction, AOptions, ARequest);
if oCmd.CommandIntf <> nil then
oCmd.FRowsAffected := oCmd.CommandIntf.RowsAffected;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomQuery }
{-------------------------------------------------------------------------------}
constructor TFDCustomQuery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// FetchOptions.Items := FetchOptions.Items - [fiMeta];
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.DefineProperties(AFiler: TFiler);
begin
inherited DefineProperties(AFiler);
AFiler.DefineProperty('DataSource', ReadDataSource, nil, False);
AFiler.DefineProperty('CommandText', ReadCommandText, nil, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.ReadDataSource(AReader: TReader);
begin
__TReader(AReader).ReadPropValue(Self, GetPropInfo(ClassInfo, 'MasterSource'));
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.ReadCommandText(AReader: TReader);
begin
Command.CommandText.Text := AReader.ReadString;
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.GetSQL: TStrings;
begin
Result := Command.CommandText;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.SetSQL(const AValue: TStrings);
begin
Command.CommandText := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.GetText: String;
begin
Result := Command.SQLText;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.ExecSQL;
begin
Execute;
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.ExecSQL(AExecDirect: Boolean): LongInt;
begin
ResourceOptions.CmdExecMode := amBlocking;
ResourceOptions.DirectExecute := AExecDirect;
try
Execute;
finally
if AExecDirect then
Disconnect();
end;
Result := RowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.ExecSQL(const ASQL: String; const AParams: array of Variant;
const ATypes: array of TFieldType): LongInt;
var
i: Integer;
begin
Close;
if ASQL <> '' then
Command.SetCommandText(ASQL, ResourceOptions.ParamCreate);
if Params.BindMode = pbByNumber then
for i := 0 to Params.Count - 1 do
Params[i].Position := i + 1;
for i := Low(ATypes) to High(ATypes) do
if ATypes[i] <> ftUnknown then
Params[i].DataType := ATypes[i];
for i := Low(AParams) to High(AParams) do
Params[i].Value := AParams[i];
Prepare;
Execute;
Result := RowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.ExecSQL(const ASQL: String): LongInt;
begin
Result := ExecSQL(ASQL, [], []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.ExecSQL(const ASQL: String;
const AParams: array of Variant): LongInt;
begin
Result := ExecSQL(ASQL, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomQuery.GetDS: TDataSource;
begin
Result := MasterSource;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.SetDS(const AValue: TDataSource);
begin
MasterSource := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomQuery.UpdateRecordCount;
var
oQuery: TFDQuery;
oGen: IFDPhysCommandGenerator;
oFtch: TFDFetchOptions;
oRes: TFDResourceOptions;
begin
FRecordCount := 0;
Prepared := True;
oQuery := TFDQuery.Create(nil);
try
oQuery.ConnectionName := ConnectionName;
oQuery.Connection := Connection;
oQuery.Transaction := Transaction;
oFtch := oQuery.FetchOptions;
oFtch.RecsMax := 1;
oFtch.Items := [];
oFtch.AutoClose := True;
oFtch.AutoFetchAll := afAll;
oFtch.RecordCountMode := cmVisible;
oFtch.Mode := fmExactRecsMax;
oRes := oQuery.ResourceOptions;
if oRes.CmdExecMode = amAsync then
oRes.CmdExecMode := amBlocking;
oRes.DirectExecute := True;
oRes.PreprocessCmdText := False;
oRes.Persistent := False;
PointedConnection.ConnectionIntf.CreateCommandGenerator(oGen, Command.CommandIntf);
oQuery.SQL.Text := oGen.GenerateCountSelect();
oQuery.Params.Assign(Params);
oQuery.Open;
FRecordCount := oQuery.Fields[0].AsInteger;
// If RecsMax >= 0, then TFDPhysCommand.GenerateLimitSelect always
// asks for RecsMax + 1 records.
oFtch := FetchOptions;
if (oFtch.Mode = fmExactRecsMax) and (oFtch.RecsMax >= 0) and (FRecordCount > 0) then
Dec(FRecordCount);
finally
FDFree(oQuery);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDTable }
{-------------------------------------------------------------------------------}
constructor TFDTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClientCursor := False;
FWindowSize := 2;
UpdateOptions.RequestLive := True;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalCreateAdapter: TFDCustomTableAdapter;
begin
Result := inherited InternalCreateAdapter;
Result.SelectCommand.FEnableParamsStorage := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.MoveData(ATableSrc, ATableDst: TFDDatSTable);
var
rState: TFDDatSLoadState;
begin
ATableDst.BeginLoadData(rState, lmHavyLoading);
try
ATableDst.Import(ATableSrc);
finally
ATableDst.EndLoadData(rState);
end;
end;
{-------------------------------------------------------------------------------}
{ Get / set props }
function TFDTable.GetCustomWhere: String;
begin
// nothing
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.TableChanged;
begin
Unprepare;
FPrimaryKeyFields := '';
if FResetIndexFieldNames then begin
IndexFieldNames := '';
FResetIndexFieldNames := False;
end;
SQL.Clear;
Indexes.Clear;
IndexDefs.Clear;
IndexDefs.Updated := False;
FieldDefs.Updated := False;
DataEvent(dePropertyChange, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetTableName(const AValue: String);
begin
CheckInactive;
if FTableName <> AValue then begin
FTableName := AValue;
UpdateOptions.UpdateTableName := AValue;
TableChanged;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetSchemaName(const AValue: String);
begin
CheckInactive;
if FSchemaName <> AValue then begin
FSchemaName := AValue;
TableChanged;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetCatalogName(const AValue: String);
begin
CheckInactive;
if FCatalogName <> AValue then begin
FCatalogName := AValue;
TableChanged;
end;
end;
{-------------------------------------------------------------------------------}
{ Open / close }
function TFDTable.UpdateCursorKind: Boolean;
var
lPrevCursor: Boolean;
begin
lPrevCursor := FClientCursor;
// Setup cursor kind
if CachedUpdates or FetchOptions.Unidirectional or Filtered and Assigned(OnFilterRecord) or
(FStorage <> nil) then
FClientCursor := True
else
case FetchOptions.CursorKind of
ckAutomatic:
FClientCursor := FPrimaryKeyFields = '';
ckDefault,
ckStatic,
ckForwardOnly:
FClientCursor := True;
ckDynamic:
FClientCursor := False;
end;
// The table must have a primary key !
// Without it the live data window will not work properly.
if Active and not FClientCursor and (FPrimaryKeyFields = '') then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntPKNotFound,
[GetDisplayName]);
Result := (lPrevCursor <> FClientCursor) and Active;
// After changing the cursor kind the bookmark size may be changed
if Result then begin
BookmarkSize := CalcBookmarkSize;
Adapter.DatSTable := Table;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.IsSequenced: Boolean;
begin
Result := FClientCursor or FetchOptions.LiveWindowParanoic;
end;
{-------------------------------------------------------------------------------}
function TFDTable.DoIsSourceOpen: Boolean;
begin
if FClientCursor then
Result := inherited DoIsSourceOpen
else
Result := Active;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetupTable;
var
oView, oView2: TFDDatSView;
oConnMeta: IFDPhysConnectionMetadata;
oConn: TFDCustomConnection;
iVal, i: Integer;
begin
if TableName = '' then
FDException(Self, [S_FD_LComp, S_FD_LComp_PDS], er_FD_AccCommandMBFilled, [GetDisplayName]);
oConn := Command.AcquireConnection;
try
oConnMeta := oConn.GetConnectionMetadataIntf;
FServerCursor := oConnMeta.ServerCursorSupported;
// Get unique identifying fields
if FPrimaryKeyFields = '' then
FPrimaryKeyFields := PSGetKeyFields;
if (FPrimaryKeyFields = '') and (fiMeta in FetchOptions.Items) then begin
oView := oConnMeta.GetTablePrimaryKeyFields(CatalogName, SchemaName, TableName, '');
try
FPrimaryKeyFields := oView.Rows.GetValuesList('COLUMN_NAME', ';', '');
finally
FDClearMetaView(oView, FetchOptions);
end;
if FPrimaryKeyFields = '' then begin
oView := oConnMeta.GetTableIndexes(CatalogName, SchemaName, TableName, '');
try
for i := 0 to oView.Rows.Count - 1 do begin
iVal := oView.Rows[i].GetData('INDEX_TYPE');
if TFDPhysIndexKind(iVal) = ikUnique then begin
oView2 := oConnMeta.GetTableIndexFields(CatalogName, SchemaName,
TableName, oView.Rows[i].GetData('INDEX_NAME'), '');
try
FPrimaryKeyFields := oView2.Rows.GetValuesList('COLUMN_NAME', ';', '');
finally
FDFree(oView2);
end;
Break;
end;
end;
finally
FDClearMetaView(oView, FetchOptions);
end;
end;
end;
// Setup cursor kind
UpdateCursorKind();
// Save null location for window generation
FTableParams.FNullLocation := oConnMeta.NullLocations;
finally
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.OpenCursor(AInfoQuery: Boolean);
var
iFetched: Integer;
eOptions: TFDSortOptions;
begin
SetupTable;
UpdateIndexDefs;
eOptions := [];
FResetIndexFieldNames := (IndexFieldNames = '') and (IndexName = '');
if FResetIndexFieldNames then
IndexFieldNames := DoAdjustSortFields('', '', eOptions);
FTableParams.FTableCommand := tcBof;
FTableParams.FLastTableCommand := tcUnknown;
FetchWindow(iFetched, True);
inherited OpenCursor(AInfoQuery);
if not FClientCursor and (FRecordIndex > -1) then
FRecordIndex := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.Open(const ATableName: String);
begin
Close;
if ATableName <> '' then
TableName := ATableName;
Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.ReleaseBase(AOffline: Boolean);
begin
inherited ReleaseBase(AOffline);
if FClientCursor then
Exit;
FSourceEOF := False;
FTableParams.FLastTableCommand := tcUnknown;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.Disconnect(AAbortJob: Boolean);
begin
if not FWindowOperation or FClientCursor then
inherited Disconnect(AAbortJob);
Prepared := False;
end;
{-------------------------------------------------------------------------------}
{ Bookmarks }
type
TLen = Cardinal;
PLen = ^TLen;
{-------------------------------------------------------------------------------}
function TFDTable.GetColSize(ACol: TFDDatSColumn): LongWord;
begin
if caBlobData in ACol.Attributes then
Result := FormatOptions.InlineDataSize
else if ACol.DataType in C_FD_StrTypes then
Result := ACol.StorageSize - SizeOf(Word)
else
Result := ACol.StorageSize;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetBookmarkColSize(ACol: TFDDatSColumn): LongWord;
begin
Result := SizeOf(TLen) + FDAlign(GetColSize(ACol));
end;
{-------------------------------------------------------------------------------}
function TFDTable.CalcBookmarkSize: LongWord;
var
i: Integer;
sIndexFields: String;
oCol: TFDDatSColumn;
begin
Result := inherited CalcBookmarkSize;
if FClientCursor then
Exit;
i := 1;
sIndexFields := ActualIndexFieldNames;
while i <= Length(sIndexFields) do begin
oCol := Table.Columns.ColumnByName(FDExtractFieldName(sIndexFields, i));
Inc(Result, GetBookmarkColSize(oCol));
end;
Result := LongWord(SizeOf(TLen) + // Str length
FDAlign(Length(sIndexFields) * SizeOf(Char))) + // str
Result; // data buffer
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.GetBookmarkData(Buffer: TRecBuf; Data: TBookmark);
var
i, iIndFldLen: Integer;
oCol: TFDDatSColumn;
iBuffLen,
iDataLen: LongWord;
pBuff,
pData: Pointer;
sIndexFields: String;
begin
inherited GetBookmarkData(Buffer, Data);
if FClientCursor then
Exit;
sIndexFields := ActualIndexFieldNames;
iIndFldLen := Length(sIndexFields) * SizeOf(Char);
// length of index fields
pBuff := PByte(Data) + SizeOf(TFDBookmarkData);
PLen(pBuff)^ := iIndFldLen;
// index fields
pBuff := PByte(pBuff) + SizeOf(TLen);
Move(sIndexFields[1], pBuff^, iIndFldLen);
pBuff := PByte(pBuff) + FDAlign(iIndFldLen);
// fields data
i := 1;
while i <= Length(sIndexFields) do begin
oCol := PFDBookmarkData(Data)^.FRow.Table.Columns.ColumnByName(
FDExtractFieldName(sIndexFields, i));
iDataLen := GetColSize(oCol);
iBuffLen := FDAlign(iDataLen);
pData := PByte(pBuff) + SizeOf(TLen);
if PFDBookmarkData(Data)^.FRow.GetData(oCol.Index, rvDefault, pData,
iDataLen, iDataLen, True) then
PLen(pBuff)^ := iDataLen
else
PLen(pBuff)^ := TLen(-1);
pBuff := PByte(pBuff) + SizeOf(TLen) + iBuffLen;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.Bookmark2Fields(const ABookmark: Pointer; var ADataPtr: Pointer): String;
var
iDataLen: Integer;
pBuff: Pointer;
begin
Result := '';
if ABookmark <> nil then begin
pBuff := PByte(ABookmark) + SizeOf(TFDBookmarkData);
iDataLen := PLen(pBuff)^;
pBuff := PByte(pBuff) + SizeOf(TLen);
SetString(Result, PChar(pBuff), iDataLen div SizeOf(Char));
ADataPtr := PByte(pBuff) + FDAlign(iDataLen);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.Bookmark2Key(const ABookmark: Pointer; APKOnly: Boolean = False): Variant;
var
oRow: TFDDatSRow;
oCol: TFDDatSColumn;
i: Integer;
iBuffLen,
iDataLen: LongWord;
pBuff: Pointer;
sIndexFields: String;
begin
oRow := Table.NewRow(False);
try
sIndexFields := Bookmark2Fields(ABookmark, pBuff);
i := 1;
while i <= Length(sIndexFields) do begin
oCol := oRow.Table.Columns.ColumnByName(FDExtractFieldName(sIndexFields, i));
iBuffLen := GetBookmarkColSize(oCol);
iDataLen := PLen(pBuff)^;
if iDataLen = TLen(-1) then
oRow.SetData(oCol.Index, nil, 0)
else
oRow.SetData(oCol.Index, PByte(pBuff) + SizeOf(TLen), iDataLen);
pBuff := PByte(pBuff) + iBuffLen;
end;
if APKOnly then
Result := oRow.GetValues(FPrimaryKeyFields)
else
Result := oRow.GetValues(sIndexFields);
finally
FDFree(oRow);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalBookmarkValid(ABookmark: Pointer): Boolean;
var
i: Integer;
sBookmarFields: String;
sField: String;
pBuff: Pointer;
begin
sBookmarFields := ';' + UpperCase(Bookmark2Fields(ABookmark, pBuff)) + ';';
Result := True;
i := 1;
while i <= Length(FPrimaryKeyFields) do begin
sField := ';' + UpperCase(FDExtractFieldName(FPrimaryKeyFields, i)) + ';';
if Pos(sField, sBookmarFields) = 0 then begin
Result := False;
Break;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.BookmarkValid(ABookmark: TBookmark): Boolean;
begin
if FClientCursor then begin
Result := inherited BookmarkValid(ABookmark);
Exit;
end;
Result := (ABookmark <> nil) and InternalBookmarkValid(ABookmark);
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalGotoBookmark(ABookmark: Pointer);
procedure ErrorNoBmk;
var
pBuff: Pointer;
begin
FDException(Self, [S_FD_LComp, S_FD_LComp_PDS], er_FD_DSIncompatBmkFields,
[Bookmark2Fields(ABookmark, pBuff), GetDisplayName, FPrimaryKeyFields]);
end;
var
vLocValue: Variant;
oTable: TFDDatSTable;
begin
if FClientCursor then begin
inherited InternalGotoBookmark(ABookmark);
Exit;
end;
if not InternalBookmarkValid(ABookmark) then
ErrorNoBmk;
oTable := nil;
try
vLocValue := Bookmark2Key(ABookmark, True);
if not inherited LocateRecord(FPrimaryKeyFields, vLocValue, [lxoCheckOnly], FRecordIndex) then begin
oTable := TFDDatSTable.Create;
if InternalSearch(oTable, FPrimaryKeyFields, vLocValue) then begin
Table.Clear;
MoveData(oTable, Table);
FRecordIndex := 0;
end;
end;
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalGotoBookmark(Bookmark: TBookmark);
begin
InternalGotoBookmark(Pointer(Bookmark));
end;
{-------------------------------------------------------------------------------}
function TFDTable.CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer;
procedure ErrorNoBmk(const AFields1, AFields2: String);
begin
FDException(Self, [S_FD_LComp, S_FD_LComp_PDS], er_FD_DSIncompatBmkFields,
[AFields1, GetDisplayName, AFields2]);
end;
var
vValues1: Variant;
vValues2: Variant;
sFields1: String;
sFields2: String;
lPKOnly1: Boolean;
lPKOnly2: Boolean;
sIndexFields: String;
lNullFirst: Boolean;
sDescFields: String;
sNoCaseFields: String;
sTmp: String;
sField: String;
i: Integer;
iVarIndex: Integer;
pBuff: Pointer;
function CompareVar(const AValue1, AValue2: Variant; const AField: String): Integer;
var
lDesc: Boolean;
lNoCase: Boolean;
eCmpResult: TVariantRelationship;
begin
ASSERT(not VarIsArray(AValue1) and not VarIsArray(AValue2));
Result := 0;
if FDSameVariants(AValue1, AValue2) or
VarIsNull(AValue1) and VarIsNull(AValue2) then
// nothing to do
else if VarIsNull(AValue1) and not VarIsNull(AValue2) then
if lNullFirst then
Result := -1
else
Result := 1
else if not VarIsNull(AValue1) and VarIsNull(AValue2) then
if lNullFirst then
Result := 1
else
Result := -1
else begin
lDesc := Pos(UpperCase(sDescFields), AField) > 0;
lNoCase := Pos(UpperCase(sNoCaseFields), AField) > 0;
// DescFields handling
if lDesc and not lNoCase then begin
eCmpResult := VarCompareValue(AValue1, AValue2);
// invert result comparsion.
if eCmpResult = vrLessThan then
Result := 1
else if eCmpResult = vrGreaterThan then
Result := -1
else
// never happen unless varEmpty
ASSERT(False);
end
// nocase field handling
else if not lDesc and lNoCase then
Result := CompareText(VarToStr(vValues1), VarToStr(vValues2))
else if lDesc and lNoCase then begin
Result := CompareText(VarToStr(vValues1), VarToStr(vValues2));
// invert result
Result := -Result;
end
// not lDesc and not lNoCase
else begin
eCmpResult := VarCompareValue(AValue1, AValue2);
if eCmpResult = vrLessThan then
Result := -1
else if eCmpResult = vrGreaterThan then
Result := 1
else
// never happens unless varEmpty
ASSERT(False);
end;
end;
end;
begin
if FClientCursor then begin
Result := inherited CompareBookmarks(Bookmark1, Bookmark2);
Exit;
end;
lNullFirst := FTableParams.FNullLocation = [nlAscFirst, nlDescLast];
if (Bookmark1 = nil) or (Bookmark2 = nil) then begin
if (Bookmark1 <> nil) and (Bookmark2 = nil) then
if lNullFirst then
Result := 1
else
Result := -1
else if (Bookmark1 = nil) and (Bookmark2 <> nil) then
if lNullFirst then
Result := -1
else
Result := 1
else
Result := 0;
Exit;
end;
sIndexFields := ActualIndexFieldNames;
ParseIndexFields(sTmp, sDescFields, sNoCaseFields, sTmp);
sFields1 := Bookmark2Fields(Bookmark1, pBuff);
sFields2 := Bookmark2Fields(Bookmark2, pBuff);
lPKOnly1 := (sFields1 <> sIndexFields);
lPKOnly2 := (sFields2 <> sIndexFields);
if lPKOnly1 and (FPrimaryKeyFields = '') then
ErrorNoBmk(sFields1, sIndexFields);
try
vValues1 := Bookmark2Key(Bookmark1, lPKOnly1 or lPKOnly2);
except
ErrorNoBmk(sFields1, sIndexFields);
end;
if lPKOnly2 and (FPrimaryKeyFields = '') then
ErrorNoBmk(sFields2, sIndexFields);
try
vValues2 := Bookmark2Key(Bookmark2, lPKOnly1 or lPKOnly2);
except
ErrorNoBmk(sFields2, sIndexFields);
end;
if lPKOnly1 or lPKOnly2 then
sIndexFields := FPrimaryKeyFields;
if not VarIsArray(vValues1) then
// for one field in bookmark
Result := CompareVar(vValues1, vValues2, sIndexFields)
else begin
// compare values in index order
i := 1;
iVarIndex := 0;
Result := 0;
while i <= Length(sIndexFields) do begin
sField := FDExtractFieldName(sIndexFields, i);
Result := CompareVar(vValues1[iVarIndex], vValues2[iVarIndex], sField);
if Result <> 0 then
Break;
Inc(iVarIndex);
end;
end;
end;
{-------------------------------------------------------------------------------}
{ Indexes / Filters }
procedure TFDTable.ParseIndexFields(out AOrderFields, ADescFields, ANoCaseFields,
AExpression: String);
var
oIndDef: TIndexDef;
begin
ADescFields := '';
ANoCaseFields := '';
AExpression := '';
// If IndexFieldNames is specified
if IndexFieldNames <> '' then
ParseIndexFieldNames(AOrderFields, ADescFields, ANoCaseFields)
// If IndexName is specified
else if IndexName <> '' then begin
IndexDefs.Update;
UpdateLocalIndexName;
oIndDef := IndexDefs.Find(LocalIndexName);
if (oIndDef = nil) or (oIndDef.Expression <> '') or (ixExpression in oIndDef.Options) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntWrongIndex,
[GetDisplayName, IndexName]);
AOrderFields := oIndDef.Fields;
ADescFields := oIndDef.DescFields;
ANocaseFields := oIndDef.CaseInsFields;
if ixCaseInsensitive in oIndDef.Options then
ANocaseFields := AOrderFields;
if ixDescending in oIndDef.Options then
ADescFields := AOrderFields;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetActualIndexFields: String;
var
sOrderFields, sDescFields, sNoCaseFields, sExpression: String;
begin
ParseIndexFields(sOrderFields, sDescFields, sNoCaseFields, sExpression);
Result := FDMergeFieldNames(sOrderFields, FPrimaryKeyFields);
end;
{-------------------------------------------------------------------------------}
function TFDTable.DoAdjustSortFields(const AFields, AExpression: String;
var AIndexOptions: TFDSortOptions): String;
var
oConnMeta: IFDPhysConnectionMetadata;
oConn: TFDCustomConnection;
eLoc: TFDPhysNullLocations;
begin
Result := AFields;
oConn := Command.AcquireConnection;
try
if AExpression = '' then begin
Result := FDMergeFieldNames(Result, FPrimaryKeyFields, True);
// Set Null location. Null location on server and client MUST BE THE SAME.
// Without that the data window WILL NOT WORK PROPERLY.
oConnMeta := oConn.GetConnectionMetadataIntf;
eLoc := oConnMeta.NullLocations;
if nlAscFirst in eLoc then
Include(AIndexOptions, soNullFirst)
else if nlAscLast in eLoc then
Exclude(AIndexOptions, soNullFirst);
if nlDescLast in eLoc then
Include(AIndexOptions, soDescNullLast)
else if nlDescFirst in eLoc then
Exclude(AIndexOptions, soDescNullLast);
end;
finally
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.UpdateLocalIndexName;
var
oConn: TFDCustomConnection;
sTmp, sIndex: String;
begin
if IndexName <> '' then begin
oConn := PointedConnection;
if (oConn <> nil) and oConn.Connected then begin
oConn.DecodeObjectName(IndexName, sTmp, sTmp, sTmp, sIndex);
FLocalIndexName := sIndex;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoSortOrderChanging;
begin
FTableParams.FLastTableCommand := tcUnknown;
UpdateLocalIndexName;
inherited DoSortOrderChanging;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoSortOrderChanged;
begin
if Active and not FClientCursor then begin
// After changing the sort order the bookmark size may be changed
BookmarkSize := CalcBookmarkSize;
// Remove references (FRow) to existing records for 2 reasons:
// 1) When BookmarkSize is changed, then "touching" to a buffer may lead to AV
// 2) When dataset will be refreshed later, then record references are invalid
ClearBuffers;
if not IsLinkedDetail and not FWindowOperation then
InternalRefresh;
end;
inherited DoSortOrderChanged;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoCachedUpdatesChanged;
begin
inherited DoCachedUpdatesChanged;
if UpdateCursorKind() then
RefireSQL;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoFilteringUpdated(AResync: Boolean);
var
oRow: TFDDatSRow;
vKeyValues: Variant;
begin
if UpdateCursorKind() then begin
inherited DoFilteringUpdated(False);
RefireSQL;
end
else if not FClientCursor and Active and not Assigned(OnFilterRecord) then begin
FTableParams.FLastTableCommand := tcUnknown;
inherited DoFilteringUpdated(False);
UpdateCursorPos;
oRow := GetRow();
if oRow <> nil then
vKeyValues := oRow.GetValues(FPrimaryKeyFields);
Table.Clear;
First;
if (oRow <> nil) and AResync then
inherited LocateEx(FPrimaryKeyFields, vKeyValues, []);
end
else
inherited DoFilteringUpdated(AResync);
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.UpdateIndexDefs;
var
i, j: Integer;
oConn: TFDCustomConnection;
oConnMeta: IFDPhysConnectionMetadata;
oVInds, oVIndFlds: TFDDatSView;
oInd: TFDIndex;
sName: String;
eOptions: TFDSortOptions;
oRow: TFDDatSRow;
sDesc: String;
function NormName(const AName: Variant; APart: TFDPhysNamePart): String;
begin
Result := oConn.CnvMetaValue(AName);
// PostgreSQL: when a DB was created with quoted mixed-case name and
// catalog name is not quoted here, then GetTableIndexFields will
// lower case it and no fields will be returned.
if (APart = npObject) or
(APart in (oConnMeta.NameQuotedSupportedParts - oConnMeta.NameParts)) then
Result := oConnMeta.QuoteObjName(Result, APart);
end;
begin
if (csDesigning in ComponentState) and (IndexDefs.Count > 0) then
Exit;
// Really IndexDefs can be updated only for closed dataset
if not IndexDefs.Updated then begin
if fiMeta in FetchOptions.Items then begin
oConn := Command.AcquireConnection;
try
oConnMeta := oConn.GetConnectionMetadata(True);
oVInds := oConnMeta.GetTableIndexes(CatalogName, SchemaName, TableName, '');
try
for i := 0 to oVInds.Rows.Count - 1 do begin
oRow := oVInds.Rows[i];
oVIndFlds := oConnMeta.GetTableIndexFields(
NormName(oRow.GetData('CATALOG_NAME'), npCatalog),
NormName(oRow.GetData('SCHEMA_NAME'), npSchema),
NormName(oRow.GetData('TABLE_NAME'), npObject),
NormName(oRow.GetData('INDEX_NAME'), npObject), '');
try
sName := oConn.CnvMetaValue(oRow.GetData('INDEX_NAME'));
oInd := Indexes.FindIndex(sName);
if oInd = nil then
oInd := Indexes.Add;
oInd.Name := sName;
oInd.Fields := oVIndFlds.Rows.GetValuesList('COLUMN_NAME', ';', '');
// Avoid expression-based indexes
for j := 1 to Length(oInd.Fields) do
if FDInSet(oInd.Fields[j], ['(', ')', '+', '-', '*', '/', '|']) then begin
oInd.Fields := '';
Break;
end;
oInd.Options := FormatOptions.SortOptions - [soUnique, soPrimary];
case TFDPhysIndexKind(oRow.GetData('INDEX_TYPE')) of
ikNonUnique: ;
ikUnique: oInd.Options := oInd.Options + [soUnique];
ikPrimaryKey: oInd.Options := oInd.Options + [soPrimary];
end;
sDesc := '';
for j := 0 to oVIndFlds.Rows.Count - 1 do
if oVIndFlds.Rows[j].GetData('SORT_ORDER') = 'D' then begin
if sDesc <> '' then
sDesc := sDesc + ';';
sDesc := sDesc + oVIndFlds.Rows[j].GetData('COLUMN_NAME');
end;
oInd.DescFields := sDesc;
if FAdjustIndexes then begin
eOptions := oInd.Options;
oInd.Fields := DoAdjustSortFields(oInd.Fields, '', eOptions);
oInd.Options := eOptions;
end;
oInd.Active := oInd.Fields <> '';
finally
FDClearMetaView(oVIndFlds, FetchOptions);
end;
end;
finally
FDClearMetaView(oVInds, FetchOptions);
end;
finally
Command.ReleaseConnection(oConn);
end;
end;
inherited UpdateIndexDefs;
end;
end;
{-------------------------------------------------------------------------------}
{ Data window SQL generation / fetching }
function TFDTable.GetWindowedRows: TFDDatSRowListBase;
begin
if SourceView.SortingMechanism <> nil then
Result := SourceView.SortingMechanism.SortedRows
else
Result := Table.Rows;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GenerateSQL: String;
var
sCat, sSch, sBObj, sObj, sOrdFields, sDescFields,
sNocaseFields, sExpression, sMastFields, sMastNullFields: String;
oConn: TFDCustomConnection;
oGen: IFDPhysCommandGenerator;
oRows: TFDDatSRowListBase;
i: Integer;
pKeyBuff: PFDKeyBuffer;
begin
ASSERT(not FClientCursor or (FTableParams.FTableCommand = tcBof));
oConn := Command.AcquireConnection;
try
Command.Unprepare;
oConn.CheckActive;
oConn.ConnectionIntf.CreateCommandGenerator(oGen, nil);
// Prepare table name
oConn.DecodeObjectName(TableName, sCat, sSch, sBObj, sObj);
if sCat = '' then
sCat := CatalogName;
if sSch = '' then
sSch := SchemaName;
if (sBObj <> '') and (sObj = '') then
sObj := sBObj;
FTableParams.FCatalog := sCat;
FTableParams.FSchema := sSch;
FTableParams.FTable := sObj;
FTableParams.FPrimaryKeyFields := '';
FTableParams.FRangeStartRow := nil;
FTableParams.FRangeStartFieldCount := -1;
FTableParams.FRangeStartExclusive := False;
FTableParams.FRangeEndRow := nil;
FTableParams.FRangeEndFieldCount := -1;
FTableParams.FRangeEndExclusive := False;
FTableParams.FLocateRow := nil;
FTableParams.FIndexFields := '';
FTableParams.FDescFields := '';
FTableParams.FNoCaseFields := '';
FTableParams.FIndexExpression := '';
FTableParams.FMasterFields := '';
FTableParams.FFilter := '';
FTableParams.FFiltered := False;
FTableParams.FFilterNoCase := False;
FTableParams.FFilterPartial := False;
FTableParams.FRanged := False;
FTableParams.FExclusive := False;
FTableParams.FReadOnly := UpdateOptions.ReadOnly;
FTableParams.FCustomWhere := '';
FTableParams.FKeyFieldCount := -1;
FTableParams.FRecordCount := -1;
if FClientCursor then begin
Result := oGen.GenerateSelectTable(FTableParams);
Exit;
end;
sOrdFields := '';
sDescFields := '';
sNocaseFields := '';
sExpression := '';
sMastFields := '';
sMastNullFields := '';
if (FTableParams.FTableCommand <> tcGetRowCount) or
(FetchOptions.RecordCountMode <> cmTotal) then begin
// Prepare indexed field lists
ParseIndexFields(sOrdFields, sDescFields, sNocaseFields, sExpression);
// When sOrdFields does not contain PK fields, then add them
FTableParams.FPrimaryKeyFields := FPrimaryKeyFields;
if IsLinkedDetail then begin
sMastFields := MasterFields;
if not FClientCursor then
for i := 0 to MasterLink.Fields.Count - 1 do
if MasterLink.Fields[i].IsNull then
sMastNullFields := sMastNullFields + ';' + MasterLink.Fields[i].FieldName;
end;
oGen.Params := Params;
oGen.Options := Command;
// Set range rows
if IsRanged then begin
pKeyBuff := GetKeyBuffer(kiRangeStart);
if Assigned(pKeyBuff) then begin
FTableParams.FRangeStartRow := GetKeyRow(pKeyBuff);
FTableParams.FRangeStartFieldCount := FRangeFromFieldCount;
FTableParams.FRangeStartExclusive := pKeyBuff^.FExclusive;
end;
pKeyBuff := GetKeyBuffer(kiRangeEnd);
if Assigned(pKeyBuff) then begin
FTableParams.FRangeEndRow := GetKeyRow(pKeyBuff);
FTableParams.FRangeEndFieldCount := FRangeToFieldCount;
FTableParams.FRangeEndExclusive := pKeyBuff^.FExclusive;
end;
end;
end;
// Set current and locate rows
case FTableParams.FTableCommand of
tcLocate:
begin
FTableParams.FLocateRow := GetLocateRow;
if (FRecordIndex = -1) or (FRecordIndex > SourceView.Rows.Count - 1) then
// no record
oGen.Row := nil
else
// set current record
oGen.Row := SourceView.Rows[FRecordIndex];
FTableParams.FRecordCount := 1;
end;
tcGetRecNo:
begin
if SourceView.Rows.Count > 0 then begin
if Bof or (FRecordIndex < 0) then
// special for bof
oGen.Row := SourceView.Rows[0]
else if Eof or (FRecordIndex > SourceView.Rows.Count - 1) then
// special for eof
oGen.Row := SourceView.Rows[SourceView.Rows.Count - 1]
else
// in other cases
oGen.Row := SourceView.Rows[FRecordIndex];
end
else
oGen.Row := nil;
FTableParams.FRecordCount := 1;
end;
tcFindKey,
tcFindNearest:
begin
pKeyBuff := GetKeyBuffer(kiLookup);
oGen.Row := GetKeyRow(pKeyBuff);
FTableParams.FRecordCount := 1;
if FKeyBuffer^.FFieldCount <= 0 then
FTableParams.FKeyFieldCount := InternalDefaultKeyFieldCount(pKeyBuff,
SortView.SortingMechanism.SortColumnList.Count)
else
FTableParams.FKeyFieldCount := pKeyBuff^.FFieldCount;
end;
tcPageDown:
begin
oRows := GetWindowedRows;
oGen.Row := oRows[oRows.Count - 1];
if FServerCursor and not (FetchOptions.LiveWindowFastFirst and not FClientCursor) then
FTableParams.FRecordCount := -1
else
FTableParams.FRecordCount := FWindowSize * FetchOptions.RowsetSize;
end;
tcPageUp:
begin
oRows := GetWindowedRows;
oGen.Row := oRows[0];
if FServerCursor and not (FetchOptions.LiveWindowFastFirst and not FClientCursor) then
FTableParams.FRecordCount := -1
else
FTableParams.FRecordCount := FWindowSize * FetchOptions.RowsetSize;
end;
tcBof,
tcEof:
if (FClientCursor or FServerCursor) and
not (FetchOptions.LiveWindowFastFirst and not FClientCursor) then
FTableParams.FRecordCount := -1
else
FTableParams.FRecordCount := FWindowSize * FetchOptions.RowsetSize;
tcSetRecNo:
FTableParams.FRecordCount := 1;
tcCurrentRecord:
begin
oGen.Row := SourceView.Rows[FRecordIndex];
FTableParams.FRecordCount := 1;
end;
end;
if sExpression = '' then begin
FTableParams.FIndexFields := sOrdFields;
FTableParams.FDescFields := sDescFields;
FTableParams.FNoCaseFields := sNocaseFields;
end
else
FTableParams.FIndexExpression := sExpression;
if (FTableParams.FTableCommand <> tcGetRowCount) or
(FetchOptions.RecordCountMode <> cmTotal) then begin
FTableParams.FMasterFields := sMastFields;
FTableParams.FMasterNullFields := sMastNullFields;
FTableParams.FFilter := Filter;
FTableParams.FFiltered := Filtered and not Assigned(OnFilterRecord);
FTableParams.FFilterNoCase := foCaseInsensitive in FilterOptions;
FTableParams.FFilterPartial := not (foNoPartialCompare in FilterOptions);
FTableParams.FRanged := IsRanged;
FTableParams.FExclusive := (FKeyBuffer <> nil) and FKeyBuffer^.FExclusive;
FTableParams.FCustomWhere := GetCustomWhere;
end;
Result := oGen.GenerateSelectTable(FTableParams);
finally
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.FetchWindow(out AFetched: Integer; APrepOnly: Boolean = False;
AForceClear: Boolean = False; ATable: TFDDatsTable = nil);
function IsPrefixed(const AName, APrefix: String; var AField: String): Boolean;
begin
Result := Pos(UpperCase(APrefix), UpperCase(AName)) = 1;
if Result then
AField := Copy(AName, Length(APrefix) + 1, Length(AName))
else
AField := '';
end;
var
i: Integer;
oParam: TFDParam;
sField: String;
oField: TField;
iNullCount: Integer;
lIndDefUpdated: Boolean;
lFldDefUpdated: Boolean;
oRows: TFDDatSRowListBase;
oFtch: TFDFetchOptions;
begin
ASSERT(not FClientCursor or (FTableParams.FTableCommand = tcBof));
ASSERT(not FWindowOperation);
FWindowOperation := True;
try
oFtch := FetchOptions;
AFetched := 0;
iNullCount := 0;
if ATable = nil then
ATable := Table;
lIndDefUpdated := IndexDefs.Updated;
lFldDefUpdated := FieldDefs.Updated;
try
// avoid repeatative, not needed window operations
if FServerCursor and (ATable = Table) and (Table <> nil) and (Table.Columns.Count > 0) and
not (oFtch.LiveWindowFastFirst and not FClientCursor) then
case FTableParams.FTableCommand of
tcBof:
if (FTableParams.FLastTableCommand = tcBof) and
not oFtch.LiveWindowParanoic then begin
AFetched := Table.Rows.Count;
Exit;
end;
tcPageUp:
if FTableParams.FLastTableCommand in [tcPageUp, tcEof] then begin
if Command.Active then begin
Command.Fetch(ATable, False, True);
AFetched := Command.RowsAffected;
end;
FTableParams.FLastTableCommand := FTableParams.FTableCommand;
Exit;
end;
tcPageDown:
if FTableParams.FLastTableCommand in [tcPageDown, tcBof] then begin
if Command.Active then begin
Command.Fetch(ATable, False, True);
AFetched := Command.RowsAffected;
end;
FTableParams.FLastTableCommand := FTableParams.FTableCommand;
Exit;
end;
tcEof:
if (FTableParams.FLastTableCommand = tcEof) and
not oFtch.LiveWindowParanoic then begin
AFetched := Table.Rows.Count;
Exit;
end;
end;
Command.CommandText.Clear;
finally
IndexDefs.Updated := lIndDefUpdated;
FieldDefs.Updated := lFldDefUpdated;
end;
Command.CommandText.Add(GenerateSQL);
// Set master params
DoMasterParamSetValues(MasterLink.Fields);
// Set other params
for i := 0 to Command.Params.Count - 1 do begin
oParam := Command.Params[i];
// check range params
if IsPrefixed(oParam.Name, C_FD_CmdGenRangeStart, sField) then
oParam.AssignFieldValue(FieldByName(sField),
GetKeyRow(GetKeyBuffer(kiRangeStart)).ValueS[sField])
else if IsPrefixed(oParam.Name, C_FD_CmdGenRangeFinish, sField) then
oParam.AssignFieldValue(FieldByName(sField),
GetKeyRow(GetKeyBuffer(kiRangeEnd)).ValueS[sField])
// check locate params
else if IsPrefixed(oParam.Name, C_FD_CmdGenLocate, sField) then begin
oParam.AssignFieldValue(FieldByName(sField), GetLocateRow.ValueS[sField]);
// make LIKE compatible String
if FTableParams.FLocatePartial and
(oParam.DataType in [ftString, ftWideString, ftFixedChar, ftFixedWideChar]) then begin
oParam.Size := oParam.Size + 1;
oParam.Value := VarToStr(oParam.Value) + '%';
end;
end
// all other params must have WINDOW_ prefix or does not have a prefix for master/detail
else begin
if not IsPrefixed(oParam.Name, C_FD_CmdGenWindow, sField) then
Continue;
oField := FieldByName(sField);
case FTableParams.FTableCommand of
tcBof,
tcEof,
tcFindKey,
tcFindNearest:
// use key buffer
oParam.AssignFieldValue(oField, GetKeyRow(GetKeyBuffer(kiLookup)).ValueS[sField]);
tcPageUp:
begin
// use first row
oRows := GetWindowedRows;
oParam.AssignFieldValue(oField, oRows[0].ValueS[sField]);
end;
tcPageDown:
begin
// use last row
oRows := GetWindowedRows;
oParam.AssignFieldValue(oField, oRows[oRows.Count - 1].ValueS[sField]);
end;
tcCurrentRecord,
tcGetRecNo,
tcLocate:
// for locate (lxoCurrentRecord)
if SourceView.Rows.Count > 0 then begin
if Bof or (FRecordIndex < 0) then
// use first row
oParam.AssignFieldValue(oField, SourceView.Rows[0].ValueS[sField])
else if Eof or (FRecordIndex > SourceView.Rows.Count - 1) then
// use last row
oParam.AssignFieldValue(oField, SourceView.Rows[SourceView.Rows.Count - 1].ValueS[sField])
else
// use current row
oParam.AssignFieldValue(oField, SourceView.Rows[FRecordIndex].ValueS[sField]);
end
else
oParam.Clear;
end;
end;
if oParam.IsNull then
Inc(iNullCount);
end;
// When all params are null's or just preparing a SQL - nothing to do
if not ((Command.Params.Count > 0) and (Command.Params.Count = iNullCount)) and
not APrepOnly then begin
lIndDefUpdated := IndexDefs.Updated;
lFldDefUpdated := FieldDefs.Updated;
try
// open and fetch data
DoPrepareSource;
DoOpenSource(True, False, False);
// When paging then append fetched record to the existing ones, otherwise - replace
if not (FTableParams.FTableCommand in [tcPageUp, tcPageDown]) or AForceClear then
ATable.Clear;
if ATable.Columns.Count = 0 then
Command.Define(ATable);
Command.Fetch(ATable, (oFtch.LiveWindowFastFirst and not FClientCursor) or
not FServerCursor or
not (FTableParams.FTableCommand in
[tcBof, tcEof, tcPageUp, tcPageDown]), True);
AFetched := Command.RowsAffected;
FAdapter.DatSTableName := ATable.Name;
FTableParams.FLastTableCommand := FTableParams.FTableCommand;
finally
IndexDefs.Updated := lIndDefUpdated;
FieldDefs.Updated := lFldDefUpdated;
end;
end;
finally
FWindowOperation := False;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.DoPurge(AView: TFDDatSView; ADirection: TFDFetchDirection): Integer;
var
rState: TFDDatSLoadState;
i: Integer;
ircWindowSize: Integer;
begin
Result := inherited DoPurge(AView, ADirection);
if FClientCursor then
Exit;
// Calc window size
ircWindowSize := FWindowSize * FetchOptions.RowsetSize;
// ATable must be greater than buffer count
Result := AView.Rows.Count - ircWindowSize - BufferCount;
if Result <= 0 then begin
Result := 0;
Exit;
end;
AView.Table.BeginLoadData(rState, lmDestroying);
try
case ADirection of
fdDown:
// remove top records
for i := 0 to Result - 1 do
AView.Table.Rows.Remove(AView.Rows[i]);
fdUp:
// remove bottom records
for i := AView.Rows.Count - 1 downto AView.Rows.Count - Result - 1 do
AView.Table.Rows.Remove(AView.Rows[i]);
end;
finally
AView.Table.EndLoadData(rState);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.DoFetch(ATable: TFDDatSTable; AAll: Boolean;
ADirection: TFDFetchDirection): Integer;
begin
if FClientCursor then begin
Result := inherited DoFetch(ATable, AAll, ADirection);
Exit;
end;
if AAll then
FDCapabilityNotSupported(Self, [S_FD_LComp, S_FD_LComp_PClnt]);
case ADirection of
fdUp:
begin
if GetWindowedRows.Count = 0 then
FTableParams.FTableCommand := tcEof
else
FTableParams.FTableCommand := tcPageUp;
FetchWindow(Result);
end;
fdDown:
begin
if GetWindowedRows.Count = 0 then
FTableParams.FTableCommand := tcBof
else
FTableParams.FTableCommand := tcPageDown;
FetchWindow(Result);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalSearch(ATable: TFDDatSTable; const AKeyFields: String;
const AKeyValues: Variant; const AExpression, AResultFields: String;
AOptions: TFDDataSetLocateOptions): Boolean;
var
iFetched: Integer;
begin
try
if AKeyFields <> '' then
InitLocateRow(AKeyFields, AKeyValues);
FTableParams.FTableCommand := tcLocate;
FTableParams.FSelectFields := AResultFields;
FTableParams.FLocateIgnoreCase := lxoCaseInsensitive in AOptions;
FTableParams.FLocatePartial := lxoPartialKey in AOptions;
FTableParams.FLocateBackward := lxoBackward in AOptions;
FTableParams.FLocateFromCurrent := lxoFromCurrent in AOptions;
if AExpression = '' then
FTableParams.FLocateFields := AKeyFields
else
FTableParams.FLocateExpression := AExpression;
FetchWindow(iFetched, False, False, ATable);
Result := iFetched > 0;
finally
FTableParams.FSelectFields := '';
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.RefireSQL;
begin
FTableParams.FLastTableCommand := tcUnknown;
if Active then begin
DisableControls;
try
Disconnect;
Open;
finally
EnableControls;
end;
end
else
SQL.Clear;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalFirst;
var
iFetched: Integer;
begin
if not FClientCursor then begin
FTableParams.FTableCommand := tcBof;
FSourceEOF := False;
FetchWindow(iFetched);
end;
inherited InternalFirst;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalLast;
var
iFetched: Integer;
begin
if not FClientCursor then begin
FTableParams.FTableCommand := tcEof;
FSourceEOF := False;
FetchWindow(iFetched);
end;
inherited InternalLast;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalDefaultKeyFieldCount(ABuffer: PFDKeyBuffer; ADefault: Integer): Integer;
begin
Result := ABuffer^.FAssignedFieldCount;
if Result <= 0 then
Result := ADefault;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalGotoKey(ANearest: Boolean): Boolean;
var
iFetched: Integer;
oTable: TFDDatSTable;
iPos: Integer;
oPrevScroll: TDataSetNotifyEvent;
begin
oPrevScroll := AfterScroll;
AfterScroll := nil;
try
Result := inherited InternalGotoKey(ANearest);
finally
AfterScroll := oPrevScroll;
end;
if FClientCursor or
Result and not FetchOptions.LiveWindowParanoic then begin
if Result or ANearest then
DoAfterScroll;
Exit;
end;
oPrevScroll := BeforeScroll;
BeforeScroll := nil;
try
BeginLocate([], nil);
finally
BeforeScroll := oPrevScroll;
end;
if ANearest then
FTableParams.FTableCommand := tcFindNearest
else
FTableParams.FTableCommand := tcFindKey;
oTable := TFDDatSTable.Create;
try
oTable.Assign(Table);
FetchWindow(iFetched, False, False, oTable);
Result := iFetched > 0;
if Result then begin
Table.Clear;
MoveData(oTable, Table);
FRecordIndex := 0;
end;
finally
FDFree(oTable);
end;
if not Result and ANearest then begin
InternalLast;
iPos := SourceView.Rows.Count - 1;
Result := True;
end
else
iPos := 0;
EndLocate(Result, iPos, [], nil);
end;
{-------------------------------------------------------------------------------}
function TFDTable.AllIndexFieldNull(const ARowIndex: Integer): Boolean;
var
i: Integer;
sField: String;
begin
Result := False;
if SourceView.Rows.Count = 0 then
Exit;
i := 1;
while i <= Length(FTableParams.FIndexFields) do begin
sField := FDExtractFieldName(FTableParams.FIndexFields, i);
if not VarIsNull(SourceView.Rows[ARowIndex].ValueS[sField]) then
Exit;
end;
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.ClearTableButCurrent;
var
i: Integer;
rState: TFDDatSLoadState;
oRow: TFDDatSRow;
begin
// all clear
if SourceView.Rows.Count <= 1 then
Exit;
Table.BeginLoadData(rState, lmDestroying);
try
oRow := SourceView.Rows[FRecordIndex];
for i := Table.Rows.Count - 1 downto 0 do
if Table.Rows[i] <> oRow then
Table.Rows.RemoveAt(i);
finally
Table.EndLoadData(rState);
ASSERT((Table.Rows.Count = 1) and (SourceView.Rows.Count <= 1));
end;
// set correct index
FRecordIndex := 0;
FTableParams.FLastTableCommand := tcUnknown;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetCanRefresh: Boolean;
begin
Result := not FetchOptions.Unidirectional and inherited GetCanRefresh;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalRefresh;
var
lHasRecs: Boolean;
iFetched: Integer;
iLastRecord: Integer;
oTable: TFDDatSTable;
begin
if FClientCursor then begin
inherited InternalRefresh;
Exit;
end;
CheckBrowseMode;
CheckBidirectional;
if UpdatesPending then
FDException(Self, [S_FD_LComp, S_FD_LComp_PDS], er_FD_DSRefreshError,
[GetDisplayName]);
// check no records or stand on a "all null's record"
lHasRecs := not (IsEmpty or AllIndexFieldNull) and
(FRecordIndex > -1) and (FRecordIndex <= SourceView.Rows.Count - 1);
iLastRecord := FRecordIndex;
// make temporary row
oTable := TFDDatSTable.Create;
try
oTable.Assign(Table);
FSourceEOF := False;
// when records exist, then try refetch current record
if lHasRecs then begin
ClearTableButCurrent;
lHasRecs := SourceView.Rows.Count > 0;
end;
if not lHasRecs then begin
// when no records, then just fetch bof
FTableParams.FTableCommand := tcBof;
FetchWindow(iFetched);
if iFetched > 0 then
FRecordIndex := 0
else
// set to Bof
FRecordIndex := -1;
end
else begin
oTable.Clear;
// backup current rows
MoveData(Table, oTable);
FTableParams.FTableCommand := tcCurrentRecord;
FetchWindow(iFetched);
if iFetched = 0 then begin
// check page down
// current record index
iLastRecord := -1;
Table.Clear;
// restore current rows
MoveData(oTable, Table);
FTableParams.FTableCommand := tcPageDown;
// force clear
FetchWindow(iFetched, False, True);
if iFetched = 0 then begin
// check page up
Table.Clear;
// restore current row
MoveData(oTable, Table);
FTableParams.FTableCommand := tcPageUp;
// force clear
FetchWindow(iFetched, False, True);
if iFetched = 0 then
// nothing found
FSourceEOF := True;
end;
end;
end;
// just stay on single row in buffer and let Resync refetch window
FRecordIndex := iLastRecord;
if FRecordIndex > SourceView.Rows.Count - 1 then
FRecordIndex := SourceView.Rows.Count - 1;
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalDelete;
var
iFetched: Integer;
begin
if not FClientCursor then begin
// If to delete single cached record, then Resync([]) will jump to the
// first record. Because DoFetch will perform tcBof.
if SourceView.Rows.Count = 1 then begin
FTableParams.FTableCommand := tcPageDown;
FetchWindow(iFetched);
end;
end;
inherited InternalDelete;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetFieldData(AField: TField; ABuffer: TValueBuffer);
begin
inherited SetFieldData(AField, ABuffer);
if (State in [dsEdit, dsInsert]) and GetIsIndexField(AField) then
FIndexFieldChanged := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalAddRecord(Buffer: TRecBuf; Append: Boolean);
begin
inherited InternalAddRecord(Buffer, Append);
if not FClientCursor and FIndexFieldChanged then
ClearTableButCurrent;
FIndexFieldChanged := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalPost;
begin
inherited InternalPost;
if not FClientCursor and FIndexFieldChanged then
if State = dsEdit then begin
ClearTableButCurrent;
if IsRanged or Filtered then
FTableParams.FLastTableCommand := tcUnknown;
end;
FIndexFieldChanged := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalCancel;
begin
inherited InternalCancel;
FIndexFieldChanged := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalResetRange;
var
iFetched: Integer;
begin
if FClientCursor then begin
inherited InternalResetRange;
Exit;
end;
if IsRanged then begin
FTableParams.FLastTableCommand := tcUnknown;
FTableParams.FTableCommand := tcBof;
FetchWindow(iFetched);
First;
end
else begin
FTableParams.FRanged := False;
FTableParams.FLastTableCommand := tcUnknown;
FSourceEOF := False;
Resync([]);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.InternalSetRecNo(AValue: Integer);
var
oTable: TFDDatSTable;
iFetched: Integer;
begin
if FClientCursor then begin
inherited InternalSetRecNo(AValue);
Exit;
end;
if AValue < 1 then
FRecordIndex := -1;
FTableParams.FTableCommand := tcSetRecNo;
FTableParams.FRecordNumber := AValue;
oTable := TFDDatSTable.Create;
try
oTable.Assign(Table);
FetchWindow(iFetched, False, False, oTable);
if iFetched > 0 then begin
Table.Clear;
MoveData(oTable, Table);
FRecordIndex := 0;
end;
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SetRecNo(AValue: Integer);
begin
if not FClientCursor then
Include(FFlags, dfNoRecNoCmp)
else
Exclude(FFlags, dfNoRecNoCmp);
inherited SetRecNo(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetRecNo: Integer;
var
oTable: TFDDatSTable;
iFetched: Integer;
begin
if FClientCursor then begin
Result := inherited GetRecNo;
Exit;
end;
Result := -1;
if not FetchOptions.LiveWindowParanoic or (State = dsInsert) or
(SourceView = nil) or (SourceView.Rows.Count = 0) then
Exit;
FTableParams.FTableCommand := tcGetRecNo;
oTable := TFDDatSTable.Create;
try
FetchWindow(iFetched, False, False, oTable);
ASSERT(oTable.Rows.Count > 0);
Result := oTable.Rows[0].ValueI[0];
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetRecordCount: Integer;
var
oTable: TFDDatSTable;
iFetched: Integer;
begin
if FClientCursor then begin
Result := inherited GetRecordCount;
Exit;
end;
Result := 0;
if (SourceView = nil) or (SourceView.Rows.Count = 0) then
Exit;
FTableParams.FTableCommand := tcGetRowCount;
FTableParams.FRecordCount := 0;
oTable := TFDDatSTable.Create;
try
FetchWindow(iFetched, False, False, oTable);
ASSERT(oTable.Rows.Count > 0);
Result := oTable.Rows[0].ValueI[0];
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalLookupEx(const AKeyFields: String; const AKeyValues: Variant;
const AExpression: String; const AResultFields: String;
AOptions: TFDDataSetLocateOptions = []; ApRecordIndex: PInteger = nil): Variant;
var
oTable: TFDDatSTable;
lResult: Boolean;
i, iData, iCols: Integer;
iPos: Integer;
begin
// for data window table record index has no sense
if ApRecordIndex <> nil then
ApRecordIndex^ := -1;
if AExpression = '' then
Result := inherited LookupEx(AKeyFields, AKeyValues, AResultFields, AOptions, @iPos)
else
Result := inherited LookupEx(AExpression, AResultFields, AOptions, @iPos);
if not VarIsNull(Result) and not FetchOptions.LiveWindowParanoic then
Exit;
Result := Null;
oTable := TFDDatSTable.Create;
try
lResult := InternalSearch(oTable, AKeyFields, AKeyValues, '', AResultFields, AOptions);
if lResult and (oTable.Rows.Count > 0) then begin
iCols := 0;
iData := -1;
for i := 0 to oTable.Columns.Count - 1 do
if not (caInternal in oTable.Columns[i].Attributes) then begin
iData := i;
Inc(iCols);
end;
if iCols = 1 then
Result := oTable.Rows[0].ValueI[iData]
else if iCols > 1 then begin
Result := VarArrayCreate([0, iCols - 1], varVariant);
iData := 0;
for i := 0 to oTable.Columns.Count - 1 do
if not (caInternal in oTable.Columns[i].Attributes) then begin
Result[iData] := oTable.Rows[0].ValueI[i];
Inc(iData);
end;
end;
end;
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.LookupEx(const AExpression, AResultFields: String;
AOptions: TFDDataSetLocateOptions; ApRecordIndex: PInteger): Variant;
begin
if FClientCursor then
Result := inherited LookupEx(AExpression, AResultFields, AOptions,
ApRecordIndex)
else
Result := InternalLookupEx('', Null, AExpression, AResultFields, AOptions,
ApRecordIndex);
end;
{-------------------------------------------------------------------------------}
function TFDTable.LookupEx(const AKeyFields: String; const AKeyValues: Variant;
const AResultFields: String; AOptions: TFDDataSetLocateOptions;
ApRecordIndex: PInteger): Variant;
begin
if FClientCursor then
Result := inherited LookupEx(AKeyFields, AKeyValues, AResultFields, AOptions,
ApRecordIndex)
else
Result := InternalLookupEx(AKeyFields, AKeyValues, '', AResultFields, AOptions,
ApRecordIndex);
end;
{-------------------------------------------------------------------------------}
function TFDTable.InternalLocateEx(const AKeyFields: String;
const AKeyValues: Variant; const AExpression: String;
AOptions: TFDDataSetLocateOptions; ApRecordIndex: PInteger): Boolean;
var
oTable: TFDDatSTable;
iPos: Integer;
begin
iPos := BeginLocate(AOptions, ApRecordIndex);
// for data window table record index has no sense
if ApRecordIndex <> nil then
ApRecordIndex^ := -1;
if AExpression = '' then
Result := inherited LocateRecord(AKeyFields, AKeyValues, AOptions, iPos)
else
Result := inherited LocateRecord(AExpression, AOptions, iPos);
if Result and not FetchOptions.LiveWindowParanoic and
((iPos > 0) or (iPos < SourceView.Rows.Count - 1)) then begin
// when matching record exists in window and it is not FIRST
// or LAST (for lxoBackward) matching record in index
EndLocate(True, iPos, AOptions, nil);
Exit;
end;
oTable := TFDDatSTable.Create;
try
// for columns and others
oTable.Assign(Table);
Result := InternalSearch(oTable, AKeyFields, AKeyValues, AExpression, '', AOptions);
if Result and not (lxoCheckOnly in AOptions) then begin
Table.Clear;
MoveData(oTable, Table);
EndLocate(True, 0, AOptions, nil);
end
else
EndLocate(False, -1, AOptions, nil);
finally
FDFree(oTable);
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.LocateEx(const AKeyFields: String; const AKeyValues: Variant;
AOptions: TFDDataSetLocateOptions; ApRecordIndex: PInteger): Boolean;
begin
if FClientCursor then
Result := inherited LocateEx(AKeyFields, AKeyValues, AOptions, ApRecordIndex)
else
Result := InternalLocateEx(AKeyFields, AKeyValues, '', AOptions, ApRecordIndex);
end;
{-------------------------------------------------------------------------------}
function TFDTable.LocateEx(const AExpression: String;
AOptions: TFDDataSetLocateOptions; ApRecordIndex: PInteger): Boolean;
begin
if FClientCursor then
Result := inherited LocateEx(AExpression, AOptions, ApRecordIndex)
else
Result := InternalLocateEx('', Null, AExpression, AOptions, ApRecordIndex);
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoMasterDefined;
var
sFields: String;
begin
sFields := MasterFields;
inherited DoMasterDefined;
if sFields <> MasterFields then
RefireSQL;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.DoMasterReset;
begin
if not FClientCursor then begin
FTableParams.FLastTableCommand := tcUnknown;
InternalRefresh;
Resync([]);
end;
inherited DoMasterReset;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.MasterChanged(Sender: TObject);
begin
if FClientCursor or
(IndexFieldNames <> '') or (IndexName <> '') then begin
FTableParams.FLastTableCommand := tcUnknown;
inherited MasterChanged(Sender);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.CheckMasterRange;
begin
if FClientCursor then begin
inherited CheckMasterRange;
Exit;
end;
if IsLinkedDetail and ((IndexFieldCount = 0) or MasterRangeChanged()) then
if Active then begin
FRecordIndex := -1;
Table.Clear;
First;
end;
end;
{-------------------------------------------------------------------------------}
function TFDTable.PSGetCommandText: String;
begin
Result := TableName;
end;
{-------------------------------------------------------------------------------}
function TFDTable.PSGetCommandType: TPSCommandType;
begin
Result := ctTable;
end;
{-------------------------------------------------------------------------------}
function TFDTable.PSGetTableName: String;
begin
Result := TableName;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.PSSetCommandText(const ACommandText: String);
begin
TableName := ACommandText;
end;
{-------------------------------------------------------------------------------}
function TFDTable.GetExists: Boolean;
var
oConn: TFDCustomConnection;
oList: TStrings;
begin
oConn := Command.AcquireConnection;
oList := TFDStringList.Create;
try
try
oConn.GetFieldNames(CatalogName, SchemaName, TableName, '', oList);
Result := (oList.Count > 0);
except
Result := False;
end;
finally
FDFree(oList);
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.RefreshMetadata;
var
oConn: TFDCustomConnection;
begin
if ((Connection = nil) and (ConnectionName = '')) or
(TableName = '') then
Exit;
oConn := Command.AcquireConnection;
try
if not oConn.Connected then
Exit;
oConn.RefreshMetadataCache(TableName);
IndexDefs.Updated := False;
IndexDefs.Update;
finally
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.CreateTable(ARecreate: Boolean = True;
AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]);
var
sCat, sSch, sBObj, sObj: String;
oConn: TFDCustomConnection;
oGen: IFDPhysCommandGenerator;
oSQLs: TStrings;
i: Integer;
lClearIndexes: Boolean;
begin
CheckInactive;
Include(FFlags, dfOfflining);
lClearIndexes := Indexes.Count = 0;
try
// Build Table from FieldDefs and IndexDefs
CheckTable;
OpenIndexes;
oConn := Command.AcquireConnection;
try
Command.Disconnect;
oConn.CheckActive;
oConn.ConnectionIntf.CreateCommandGenerator(oGen, nil);
oGen.Options := OptionsIntf;
oGen.Table := Table;
oGen.GenOptions := [goBeautify, goSkipUnsupTypes];
// Prepare table name
oConn.DecodeObjectName(TableName, sCat, sSch, sBObj, sObj);
if sCat = '' then
sCat := CatalogName;
if sSch = '' then
sSch := SchemaName;
if (sBObj <> '') and (sObj = '') then
sObj := sBObj;
Table.SourceName := oConn.EncodeObjectName(sCat, sSch, sBObj, sObj);
// Generate DROP TABLE SQL's and execute them
if ARecreate then begin
oSQLs := oGen.GenerateDropTable(AParts);
try
for i := 0 to oSQLs.Count - 1 do
try
Command.Execute(oSQLs[i]);
except
on E: EFDDBEngineException do
if E.Kind <> ekObjNotExists then
raise;
end;
finally
FDFree(oSQLs);
end;
end;
// Generate CREATE TABLE SQL's and execute them
oSQLs := oGen.GenerateCreateTable(AParts);
try
for i := 0 to oSQLs.Count - 1 do
Command.Execute(oSQLs[i]);
finally
FDFree(oSQLs);
end;
finally
Command.Disconnect;
Command.CommandText.Clear;
Command.ReleaseConnection(oConn);
end;
finally
if lClearIndexes then
Indexes.Clear;
Exclude(FFlags, dfOfflining);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.CreateDataSet;
begin
CreateTable(True, [tpTable .. tpIndexes]);
Active := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDTable.SaveToStorage(const AFileName: String; AStream: TStream;
AFormat: TFDStorageFormat);
var
lPrevCachedUpdates: Boolean;
begin
lPrevCachedUpdates := CachedUpdates;
if not lPrevCachedUpdates then
CachedUpdates := True;
try
inherited SaveToStorage(AFileName, AStream, AFormat);
finally
if not lPrevCachedUpdates then
CachedUpdates := False;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomStoredProc }
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.InternalCreateAdapter: TFDCustomTableAdapter;
begin
Result := inherited InternalCreateAdapter;
Result.SelectCommand.CommandKind := skStoredProc;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.DescriptionsAvailable: Boolean;
var
oConn: TFDCustomConnection;
oList: TStrings;
begin
oConn := Command.AcquireConnection;
oList := TFDStringList.Create;
try
try
oConn.GetStoredProcNames(CatalogName, SchemaName, PackageName, StoredProcName,
oList, [osMy, osOther]);
Result := (oList.Count > 0);
except
Result := False;
end;
finally
FDFree(oList);
Command.ReleaseConnection(oConn);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.ProcNameChanged;
begin
Command.CommandKind := skStoredProc;
if not (csReading in ComponentState) and (csDesigning in ComponentState) and
(StoredProcName <> '') then
Prepare;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.ExecProc;
begin
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.ExecProcBase(const AProcName: String;
AFunction: Boolean; const AParams: array of Variant;
const ATypes: array of TFieldType);
var
i, j, iOver, iErr: Integer;
s: String;
begin
Close;
if AProcName <> '' then begin
s := AProcName;
iOver := 0;
i := Pos(';', s);
if i <> 0 then begin
Val(Copy(s, i + 1, MAXINT), iOver, iErr);
if iErr = 0 then
s := Copy(s, 1, i - 1);
end;
Overload := iOver;
StoredProcName := s;
end;
if not (fiMeta in FetchOptions.Items) and (Params.Count = 0) then begin
Params.BindMode := pbByNumber;
if AFunction then
Params.Add.ParamType := ptResult;
for i := 0 to High(AParams) do
Params.Add;
end;
if Params.BindMode = pbByNumber then
for i := 0 to Params.Count - 1 do
Params[i].Position := i + 1;
for i := 0 to High(ATypes) do
if ATypes[i] <> ftUnknown then
Params[i].DataType := ATypes[i];
if fiMeta in FetchOptions.Items then
Prepare;
j := 0;
for i := 0 to High(AParams) do begin
if Params[j].ParamType = ptResult then
Inc(j);
Params[j].Value := AParams[i];
Inc(j);
end;
if not (fiMeta in FetchOptions.Items) then
Prepare;
Execute;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecProc(const AProcName: String;
const AParams: array of Variant; const ATypes: array of TFieldType): LongInt;
begin
ExecProcBase(AProcName, False, AParams, ATypes);
Result := RowsAffected;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecProc(const AProcName: String): LongInt;
begin
Result := ExecProc(AProcName, [], []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecProc(const AProcName: String;
const AParams: array of Variant): LongInt;
begin
Result := ExecProc(AProcName, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetFuncResult: Variant;
var
oPar: TFDParam;
begin
oPar := FindParam('@RETURN_VALUE');
if oPar <> nil then
Result := oPar.Value
else
Result := ParamByName('Result').Value;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecFunc: Variant;
begin
Execute;
Result := GetFuncResult;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecFunc(const AProcName: String;
const AParams: array of Variant; const ATypes: array of TFieldType): Variant;
begin
ExecProcBase(AProcName, True, AParams, ATypes);
Result := GetFuncResult;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecFunc(const AProcName: String): Variant;
begin
Result := ExecFunc(AProcName, [], []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.ExecFunc(const AProcName: String;
const AParams: array of Variant): Variant;
begin
Result := ExecFunc(AProcName, AParams, []);
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetOverload: Word;
begin
Result := Command.Overload;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.SetOverload(const AValue: Word);
begin
if Command.Overload <> AValue then begin
Command.Overload := AValue;
ProcNameChanged;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetProcName: string;
begin
Result := Trim(Command.CommandText.Text);
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.SetProcName(const AValue: string);
var
s: String;
begin
s := Trim(AValue);
if Trim(Command.CommandText.Text) <> s then begin
Command.SetCommandText(s, False);
ProcNameChanged;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetPackageName: String;
begin
Result := Command.BaseObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.SetPackageName(const AValue: String);
begin
if Command.BaseObjectName <> AValue then begin
Command.BaseObjectName := AValue;
ProcNameChanged;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetSchemaName: String;
begin
Result := Command.SchemaName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.SetSchemaName(const AValue: String);
begin
if Command.SchemaName <> AValue then begin
Command.SchemaName := AValue;
ProcNameChanged;
end;
end;
{-------------------------------------------------------------------------------}
function TFDCustomStoredProc.GetCatalogName: String;
begin
Result := Command.CatalogName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomStoredProc.SetCatalogName(const AValue: String);
begin
if Command.CatalogName <> AValue then begin
Command.CatalogName := AValue;
ProcNameChanged;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDMetaInfoQuery }
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.InternalCreateAdapter: TFDCustomTableAdapter;
begin
Result := TFDTableAdapter.Create(nil);
Result.SelectCommand := TFDMetaInfoCommand.Create(Result);
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetMetaInfoKind: TFDPhysMetaInfoKind;
begin
Result := TFDMetaInfoCommand(Command).MetaInfoKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetMetaInfoKind(
const AValue: TFDPhysMetaInfoKind);
begin
TFDMetaInfoCommand(Command).MetaInfoKind := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetObjectName: String;
begin
Result := TFDMetaInfoCommand(Command).ObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetObjectName(const AValue: String);
begin
TFDMetaInfoCommand(Command).ObjectName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetTableKinds: TFDPhysTableKinds;
begin
Result := TFDMetaInfoCommand(Command).TableKinds;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetTableKinds(const AValue: TFDPhysTableKinds);
begin
TFDMetaInfoCommand(Command).TableKinds := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetWildcard: String;
begin
Result := TFDMetaInfoCommand(Command).Wildcard;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetWildcard(const AValue: String);
begin
TFDMetaInfoCommand(Command).Wildcard := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetOverload: Word;
begin
Result := TFDMetaInfoCommand(Command).Overload;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetOverload(const AValue: Word);
begin
TFDMetaInfoCommand(Command).Overload := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetObjectScopes: TFDPhysObjectScopes;
begin
Result := TFDMetaInfoCommand(Command).ObjectScopes;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetObjectScopes(const AValue: TFDPhysObjectScopes);
begin
TFDMetaInfoCommand(Command).ObjectScopes := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetBaseObjectName: String;
begin
Result := TFDMetaInfoCommand(Command).BaseObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetBaseObjectName(const AValue: String);
begin
TFDMetaInfoCommand(Command).BaseObjectName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetSchemaName: String;
begin
Result := TFDMetaInfoCommand(Command).SchemaName;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetSchemaName(const AValue: String);
begin
TFDMetaInfoCommand(Command).SchemaName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDMetaInfoQuery.GetCatalogName: String;
begin
Result := TFDMetaInfoCommand(Command).CatalogName;
end;
{-------------------------------------------------------------------------------}
procedure TFDMetaInfoQuery.SetCatalogName(const AValue: String);
begin
TFDMetaInfoCommand(Command).CatalogName := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDDataSetParamObject }
{-------------------------------------------------------------------------------}
type
TFDDataSetParamObject = class(TParamObject, IFDPhysDataSetParamReader)
protected
// IFDPhysDataSetParamReader
function Reset: Boolean;
function Next: Boolean;
function GetData(const AColumn: Integer; var ABuff: Pointer;
ABuffLen: LongWord; var ADataLen: LongWord; AByVal: Boolean): Boolean;
public
constructor Create(AObject: TObject; ADataType: TFieldType; AInstanceOwner: Boolean); override;
end;
{-------------------------------------------------------------------------------}
constructor TFDDataSetParamObject.Create(AObject: TObject; ADataType: TFieldType;
AInstanceOwner: Boolean);
var
oDS: TFDDataSet;
begin
if not (((AObject is TFDDatSTable) or (AObject is TFDDataSet)) and (ADataType = ftDataSet)) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PClnt], er_FD_ClntDataSetParamIncompat, []);
if AObject is TFDDatSTable then begin
oDS := TFDMemTable.Create(nil);
TFDDatSTable(AObject).CountRef(0);
oDS.AttachTable(TFDDatSTable(AObject), nil);
end
else
oDS := TFDDataSet(AObject);
oDS.Active := True;
inherited Create(oDS, ADataType, AInstanceOwner);
end;
{-------------------------------------------------------------------------------}
function TFDDataSetParamObject.Reset: Boolean;
var
oDS: TFDDataSet;
begin
oDS := GetInstance(False) as TFDDataSet;
if oDS = nil then
Result := False
else begin
if not oDS.OptionsIntf.FetchOptions.Unidirectional then
oDS.First;
Result := oDS.Active and not oDS.Eof;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDataSetParamObject.Next: Boolean;
var
oDS: TFDDataSet;
begin
oDS := GetInstance(False) as TFDDataSet;
if oDS = nil then
Result := False
else begin
oDS.Next;
Result := oDS.Active and not oDS.Eof;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDataSetParamObject.GetData(const AColumn: Integer;
var ABuff: Pointer; ABuffLen: LongWord; var ADataLen: LongWord; AByVal: Boolean): Boolean;
var
oDS: TFDDataSet;
begin
oDS := GetInstance(False) as TFDDataSet;
Result := oDS.GetRow().GetData(AColumn, rvDefault, ABuff, ABuffLen, ADataLen, AByVal);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterParamObjectClass(ftDataSet, TFDDataSetParamObject);
FDRegisterParamObjectClass(ftStream, TParamStreamObject);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLHeightTileFileHDS<p>
HeightDataSource for the HTF (HeightTileFile) format.<p>
<b>History : </b><font size=-1><ul>
<li>10/03/09 - DanB - Bug fix for invisible terrain, now changes
heightdata.DataState to hdsPreparing in StartPreparingData
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>15/02/07 - LIN -Added OpenHTF function, for direct access to the HeightTileFile object.
<li>25/01/07 - LIN -Added Width and Height properties to GLHeightTileFieHDS
<li>19/01/07 - LIN -Bug fix/workaround: Added 'Inverted' property to GLHeightTileFieHDS
Set Inverted to false, if you DONT want your rendered
terrain to be a mirror image of your height data.
(Defaults to true, so it doesnt affect existing apps);
<li>29/01/03 - EG - Creation
</ul></font>
}
unit GLHeightTileFileHDS;
interface
{$I GLScene.inc}
uses
Classes, SysUtils,
//GLS
GLHeightData, GLHeightTileFile;
type
// TGLHeightTileFileHDS
//
{: An Height Data Source for the HTF format.<p> }
TGLHeightTileFileHDS = class (THeightDataSource)
private
{ Private Declarations }
FInfiniteWrap : Boolean;
FInverted : Boolean;
FHTFFileName : String;
FHTF : THeightTileFile;
FMinElevation : Integer;
protected
{ Protected Declarations }
procedure SetHTFFileName(const val : String);
procedure SetInfiniteWrap(val : Boolean);
procedure SetInverted(val : Boolean);
procedure SetMinElevation(val : Integer);
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure StartPreparingData(HeightData : THeightData); override;
function Width :integer; override;
function Height:integer; override;
function OpenHTF:THeightTileFile; //gives you direct access to the HTF object
published
{ Published Declarations }
{: FileName of the HTF file.<p>
Note that it is accessed via the services of GLApplicationFileIO,
so this may not necessarily be a regular file on a disk... }
property HTFFileName : String read FHTFFileName write SetHTFFileName;
{: If true the height field is wrapped indefinetely. }
property InfiniteWrap : Boolean read FInfiniteWrap write SetInfiniteWrap default True;
{: If true the height data is inverted.(Top to bottom) }
property Inverted : Boolean read FInverted write SetInverted default True;
{: Minimum elevation of the tiles that are considered to exist.<p>
This property can typically be used to hide underwater tiles. }
property MinElevation : Integer read FMinElevation write SetMinElevation default -32768;
property MaxPoolSize;
property DefaultHeight;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLHeightTileFileHDS ------------------
// ------------------
// Create
//
constructor TGLHeightTileFileHDS.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInfiniteWrap:=True;
FInverted:=True;
FMinElevation:=-32768;
end;
// Destroy
//
destructor TGLHeightTileFileHDS.Destroy;
begin
FHTF.Free;
inherited Destroy;
end;
// SetHTFFileName
//
procedure TGLHeightTileFileHDS.SetHTFFileName(const val : String);
begin
if FHTFFileName<>val then begin
MarkDirty;
FreeAndNil(FHTF);
FHTFFileName:=val;
end;
end;
// SetInfiniteWrap
//
procedure TGLHeightTileFileHDS.SetInfiniteWrap(val : Boolean);
begin
if FInfiniteWrap=val then exit;
FInfiniteWrap:=val;
MarkDirty;
end;
// SetInverted
//
procedure TGLHeightTileFileHDS.SetInverted(val : Boolean);
begin
if FInverted=Val then exit;
FInverted:=val;
MarkDirty;
end;
// SetMinElevation
//
procedure TGLHeightTileFileHDS.SetMinElevation(val : Integer);
begin
if FMinElevation<>val then begin
FMinElevation:=val;
MarkDirty;
end;
end;
// OpenHTF
// Tries to open the assigned HeightTileFile.
//
function TGLHeightTileFileHDS.OpenHTF:THeightTileFile;
begin
if not Assigned(FHTF) then begin
if FHTFFileName='' then FHTF:=nil
else FHTF:=THeightTileFile.Create(FHTFFileName);
end;
result:=FHTF;
end;
// StartPreparingData
//
procedure TGLHeightTileFileHDS.StartPreparingData(HeightData : THeightData);
var
oldType : THeightDataType;
htfTile : PHeightTile;
htfTileInfo : PHeightTileInfo;
x, y : Integer;
YPos:integer;
inY,outY:integer;
PLineIn, PLineOut : ^PSmallIntArray;
LineDataSize:integer;
begin
// access htf data
if OpenHTF=nil then begin
HeightData.DataState:=hdsNone;
Exit;
end else Assert(FHTF.TileSize=HeightData.Size,
'HTF TileSize and HeightData size don''t match.('+IntToStr(FHTF.TileSize)+' and '+Inttostr(HeightData.Size)+')');
heightdata.DataState := hdsPreparing;
// retrieve data and place it in the HeightData
with HeightData do begin
if Inverted then YPos:=YTop
else YPos:=FHTF.SizeY-YTop-size+1;
if InfiniteWrap then begin
x:=XLeft mod FHTF.SizeX;
if x<0 then x:=x+FHTF.SizeX;
y:=YPos mod FHTF.SizeY;
if y<0 then y:=y+FHTF.SizeY;
htfTile:=FHTF.GetTile(x, y, @htfTileInfo);
end else begin
htfTile:=FHTF.GetTile(XLeft, YPos, @htfTileInfo);
end;
if (htfTile=nil) or (htfTileInfo.max<=FMinElevation) then begin
// non-aligned tiles aren't handled (would be slow anyway)
DataState:=hdsNone;
end else begin
oldType:=DataType;
Allocate(hdtSmallInt);
if Inverted then Move(htfTile.data[0], SmallIntData^, DataSize)
else begin // invert the terrain (top to bottom) To compensate for the inverted terrain renderer
LineDataSize:=DataSize div size;
for y:=0 to size-1 do begin
inY:=y*HeightData.Size;
outY:=((size-1)-y)*HeightData.Size;
PLineIn :=@htfTile.data[inY];
PLineOut:=@HeightData.SmallIntData[outY];
Move(PLineIn^,PLineOut^,LineDataSize);
end;
end;
//---Move(htfTile.data[0], SmallIntData^, DataSize);---
if oldType<>hdtSmallInt then DataType:=oldType;
TextureCoordinates(HeightData);
inherited;
HeightMin:=htfTileInfo.min;
HeightMax:=htfTileInfo.max;
end;
end;
end;
function TGLHeightTileFileHDS.Width :integer;
begin
if OpenHTF=nil then result:=0
else result:=FHTF.SizeX;
end;
function TGLHeightTileFileHDS.Height:integer;
begin
if OpenHTF=nil then result:=0
else result:=FHTF.SizeY;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
Classes.RegisterClasses([TGLHeightTileFileHDS]);
end.
|
{******************************************}
{ TeeChart. TChart Component }
{ Copyright (c) 1995-2001 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit uaxislab;
interface
{ This Sample Project shows how to set the Axis Labels at specific Axis
positions.
The key is the Chart.OnGetNextAxisLabel event.
This event is called continuosly for each Axis Label until user decides
to stop.
At each call, you can specify the exact Axis value where a Label must be
drawn.
In this example, this event is used to set the BottomAxis labels to the
first (1) day in month: 1/1/96, 2/1/96, 3/1/96..... 12/1/96
This don't needs necessarily to be datetime values.
You can also set the Axis Labels in non-datetime axis.
WARNING:
Remember to set the Stop boolean variable to TRUE when no more labels are
needed.
Remember also that using this event will NOT calculate Label used space or
any Font size adjustment.
TeeChart Axis will draw all labels you specify.
}
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, StdCtrls, Teengine, Buttons,
TeeProcs;
type
TAxisLabelsForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
Panel1: TPanel;
RadioGroup1: TRadioGroup;
PointSeries1: TPointSeries;
BitBtn3: TBitBtn;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure Chart1GetNextAxisLabel(Sender: TChartAxis;
LabelIndex: Longint; var LabelValue: Double; var Stop: Boolean);
private
{ Private declarations }
public
{ Public declarations }
DefaultLabels:Boolean;
end;
implementation
{$R *.dfm}
procedure TAxisLabelsForm.FormCreate(Sender: TObject);
var t:Longint;
begin
DefaultLabels:=False; { <-- boolean variable to show or not the demo }
LineSeries1.Clear;
PointSeries1.Clear;
for t:=1 to 100 do
Begin
LineSeries1.AddXY( Date+t, 200+Random(700),'',clTeeColor); { <-- some random points }
PointSeries1.AddXY( Date+t, 200+Random(700),'',clTeeColor);
end;
end;
procedure TAxisLabelsForm.RadioGroup1Click(Sender: TObject);
begin
{ Choose between default and custom labeling. }
DefaultLabels:=RadioGroup1.ItemIndex=0;
Chart1.Repaint; { <-- repaint chart to see changes }
end;
procedure TAxisLabelsForm.Chart1GetNextAxisLabel(Sender: TChartAxis;
LabelIndex: Longint; var LabelValue: Double; var Stop: Boolean);
var year,month,day:Word;
begin
if not DefaultLabels then
Begin
if Sender=Chart1.BottomAxis then
Begin
{ ***************************** }
{ WARNING:
Setting this axis increment:
Chart1.BottomAxis.Increment := DateTimeStep[ dtOneMonth ];
and...
Chart1.BottomAxis.ExactDateTime := True ;
Eliminates the need for the following code.
}
{ ***************************** }
{ LabelValue has the "candidate" value where the Axis label will be painted. }
DecodeDate(LabelValue,year,month,day);
{ we force that value to be the first day in month }
Day:=1;
Month:=Month+1;
if Month>12 then
Begin
Month:=1;
Year:=Year+1;
end;
{ Then we set the preferred Label value }
LabelValue:=EncodeDate(year,month,day);
end
else
if Sender=Chart1.LeftAxis then
Begin
{ In this example, we want the Vertical Left Axis to show
labels only for positive values, starting at zero and
with 250 label increment.
}
if LabelValue>=250 then LabelValue:=LabelValue+250
else LabelValue:=250;
End;
{ we want more labels !! }
Stop:=False;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_Memo;
{$I FMX_Defines.inc}
interface
uses
Classes, Contnrs, Types, UITypes,
FMX_Types, FMX_Controls, FMX_Layouts, FMX_Platform, FMX_Menus;
{$SCOPEDENUMS ON}
type
TInsertOption = (ioSelected, ioMoveCaret, ioCanUndo, ioUndoPairedWithPrev);
TInsertOptions = set of TInsertOption;
TDeleteOption = (doMoveCaret, doCanUndo);
TDeleteOptions = set of TDeleteOption;
TActionType = (atDelete, atInsert);
TLinesBegins = array of Integer;
PLinesBegins = ^TLinesBegins;
TCaretPosition = record
Line, Pos: Integer;
end;
TEditAction = record
ActionType: TActionType;
PairedWithPrev: Boolean;
StartPosition: Integer;
DeletedFragment: WideString; { For atDelete }
Length: Integer; { For atInsert }
end;
PEditAction = ^TEditAction;
TMemo = class;
{ TEditActionStack }
TEditActionStack = class(TStack)
private
FOwner: TMemo;
public
constructor Create(AOwner: TMemo);
destructor Destroy; override;
procedure FragmentInserted(StartPos, FragmentLength: Integer;
IsPairedWithPrev: Boolean);
procedure FragmentDeleted(StartPos: Integer; const Fragment: WideString);
procedure CaretMovedBy(Shift: Integer);
function RollBackAction: Boolean;
end;
{ TMemo }
TSelArea = array of TRectF;
TMemo = class(TScrollBox, ITextServiceControl, IVirtualKeyboardControl)
private
FNeedChange: Boolean;
FTextService: TTextService;
FFontFill: TBrush;
FFont: TFont;
FTextAlign: TTextAlign;
FInternalMustUpdateLines: Boolean;
FLMouseSelecting: Boolean;
FOldMPt: TPointF;
FCaretPosition: TCaretPosition;
FFirstVisibleChar: Integer;
FUnwrapLines: TWideStrings;
FMemoPopupMenu: TPopupMenu;
FAutoSelect: Boolean;
FCharCase: TEditCharCase;
FHideSelection: Boolean;
FMaxLength: Integer;
FReadOnly: Boolean;
FOnChange: TNotifyEvent;
FActionStack: TEditActionStack;
FLines: TWideStrings;
FWordWrap: Boolean;
FLinesBegs: array of Integer;
FTextWidth: array of Single;
FCachedFillText: TFillTextFlags;
FSelStart: TCaretPosition;
FSelEnd: TCaretPosition;
FSelected: Boolean;
FOldSelStartPos, FOldSelEndPos, FOldCaretPos: Integer;
FSelectionFill: TBrush;
FOnChangeTracking: TNotifyEvent;
FContent: TControl;
FKeyboardType: TVirtualKeyboardType;
FEmptyFirstLine: boolean;
function GetSelBeg: TCaretPosition;
function GetSelEnd: TCaretPosition;
procedure StorePositions;
procedure ReadTextData(Reader: TReader);
procedure RestorePositions;
procedure SelectAtPos(APos: TCaretPosition);
procedure SetCaretPosition(const Value: TCaretPosition);
procedure SetSelLength(const Value: Integer);
procedure SetSelStart(const Value: Integer);
function GetSelStart: Integer;
function GetSelLength: Integer;
procedure UpdateHScrlBarByCaretPos;
procedure UpdateVScrlBarByCaretPos;
function GetSelText: WideString;
procedure SetAutoSelect(const Value: Boolean);
procedure SetCharCase(const Value: TEditCharCase);
procedure SetHideSelection(const Value: Boolean);
procedure SetMaxLength(const Value: Integer);
procedure SelectAtMousePoint;
function GetNextWordBegin(StartPosition: TCaretPosition): TCaretPosition;
function GetPrevWordBegin(StartPosition: TCaretPosition): TCaretPosition;
function GetPositionShift(APos: TCaretPosition; Delta: Integer { char count } ): TCaretPosition;
procedure MoveCareteBy(Delta: Integer);
procedure MoveCaretLeft;
procedure MoveCaretRight;
procedure MoveCaretVertical(LineDelta: Integer);
procedure MoveCaretDown;
procedure MoveCaretUp;
procedure MoveCaretPageUp;
procedure MoveCaretPageDown;
procedure UpdateCaretPosition(UpdateScrllBars: Boolean);
procedure SetLines(const Value: TWideStrings);
procedure GetLineBounds(LineIndex: Integer;
var LineBeg, LineLength: Integer);
function GetLineCount: Integer;
function GetLine(Index: Integer): WideString;
// Returns Line without special symbols at the end.
function GetLineInternal(Index: Integer): WideString;
// Returns Line with special symbols at the end.
procedure InsertLine(Index: Integer; const S: WideString);
procedure DeleteLine(Index: Integer);
procedure ClearLines;
procedure SetWordWrap(const Value: Boolean);
function GetPageSize: Single;
procedure ResetLineWidthCache;
function GetLineWidth(LineNum: Integer): Single;
function GetWidestLine: Integer;
function FillLocalLinesBegs(PText: PWideString; ABegChar, AEndChar: Integer;
TmpLinesBegs: PLinesBegins): Integer;
procedure UpdateRngLinesBegs(PText: PWideString;
AUpdBegLine, AUpdEndLine, AUpdBegChar, AUpdEndChar, ACharDelta,
AOldWidestLineWidth: Integer);
function GetShowSelection: Boolean;
function GetLineRealEnd(AStartPos: TCaretPosition; PText: PWideString)
: TCaretPosition;
procedure SetFont(const Value: TFont);
procedure SetFontFill( const Value: TBrush);
procedure SetTextAlign(const Value: TTextAlign);
function TextWidth(const Str: WideString): Single;
procedure HScrlBarChange(Sender: TObject);
procedure SetUpdateState(Updating: Boolean);
function GetUnwrapLines: TWideStrings;
function GetReadOnly: Boolean;
procedure SetReadOnly(Value: Boolean);
function GetImeMode: TImeMode; virtual;
procedure SetImeMode(const Value: TImeMode); virtual;
{ ITextServiceControl }
function GetTextService: TTextService; virtual;
procedure UpdateCaretPoint; virtual;
function GetTargetClausePointF: TPointF;
{ IVirtualKeyboardControl }
procedure SetKeyboardType(Value: TVirtualKeyboardType);
function GetKeyboardType: TVirtualKeyboardType;
protected
FOffScreenBitmap: TBitmap;
FInternalUpdating: Boolean;
FWidestLineIndex: Integer;
function CanObserve(const ID: Integer): Boolean; override;
function GetLineHeight: Single;
function GetPointPosition(Pt: TPointF): TCaretPosition;
function GetText: WideString; virtual;
procedure SetText(const Value: WideString); virtual;
function GetSelArea: TSelArea; virtual;
procedure DrawPasswordChar(SymbolRect: TRectF; Selected: Boolean); virtual;
procedure CreatePopupMenu; virtual;
procedure UpdatePopupMenuItems; virtual;
procedure ApplyStyle; override;
procedure FreeStyle; override;
function ContentPos: TPointF;
procedure Change; virtual;
procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
procedure DoContentPaintWithCache(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
function ValidText(const NewText: WideString): Boolean; virtual;
function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean;
// override;
procedure ContextMenu(const ScreenPosition: TPointF); override;
procedure DefineProperties(Filer: TFiler); override;
procedure HScrollChange(Sender: TObject); override;
procedure VScrollChange(Sender: TObject); override;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: Single); override;
procedure MouseMove(Shift: TShiftState; x, y: Single); override;
procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override;
procedure SelectWord;
procedure FontChanged(Sender: TObject);
procedure DoUndo(Sender: TObject);
procedure DoCut(Sender: TObject);
procedure DoCopy(Sender: TObject);
procedure DoPaste(Sender: TObject);
procedure DoDelete(Sender: TObject);
procedure DoSelectAll(Sender: TObject);
procedure UpdateLines;
procedure RepaintEdit;
{ inherited }
function GetData: Variant; override;
procedure SetData(const Value: Variant); override;
procedure DoEnter; override;
procedure DoExit; override;
function GetContentBounds: TRectF; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CopyToClipboard;
procedure PasteFromClipboard;
procedure CutToClipboard;
procedure ClearSelection;
procedure SelectAll;
procedure GoToTextEnd;
procedure GoToTextBegin;
procedure GotoLineEnd;
procedure GoToLineBegin;
function GetPositionPoint(ACaretPos: TCaretPosition): TPointF;
procedure UnDo;
procedure InsertAfter(Position: TCaretPosition; const S: WideString; Options: TInsertOptions);
procedure DeleteFrom(Position: TCaretPosition; ALength: Integer; Options: TDeleteOptions);
function TextPosToPos(APos: Integer): TCaretPosition;
function PosToTextPos(APostion: TCaretPosition): Integer;
property SelStart: Integer read GetSelStart write SetSelStart;
property SelLength: Integer read GetSelLength write SetSelLength;
property SelText: WideString read GetSelText;
property Text: WideString read GetText write SetText;
property CaretPosition: TCaretPosition read FCaretPosition write SetCaretPosition;
property LineWidth[LineNum: Integer]: Single read GetLineWidth;
{ return unwrapped lines }
property UnwrapLines: TWideStrings read GetUnwrapLines;
{ custom colors - only work when style was loaded }
property FontFill: TBrush read FFontFill write setFontFill;
property SelectionFill: TBrush read FSelectionFill;
published
property Cursor default crIBeam;
property CanFocus default True;
property DisableFocusEffect;
property TabOrder;
property AutoSelect: Boolean read FAutoSelect write SetAutoSelect default True;
property CharCase: TEditCharCase read FCharCase write SetCharCase default TEditCharCase.ecNormal;
property Enabled;
property HideSelection: Boolean read FHideSelection write SetHideSelection default True;
property Lines: TWideStrings read FLines write SetLines;
property MaxLength: Integer read FMaxLength write SetMaxLength default 0;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChangeTracking: TNotifyEvent read FOnChangeTracking write FOnChangeTracking;
property WordWrap: Boolean read FWordWrap write SetWordWrap default False;
property Font: TFont read FFont write SetFont;
property TextAlign: TTextAlign read FTextAlign write SetTextAlign default TTextAlign.taLeading;
property StyleLookup;
property KeyboardType: TVirtualKeyboardType read GetKeyboardType write SetKeyboardType;
property ImeMode: TImeMode read GetImeMode write SetImeMode default TImeMode.imDontCare;
end;
function ComposeCaretPos(ALine, APos: Integer): TCaretPosition;
implementation
uses
SysUtils, Variants, FMX_Consts;
type
{ TMemoLines }
TMemoLines = class(TWideStrings)
private
FMemo: TMemo;
protected
{$IFDEF FPCCOMP}function Get(Index: Integer): string; override;{$ELSE}function Get(Index: Integer): WideString; override;{$ENDIF}
function GetCount: Integer; override;
procedure SetUpdateState(Updating: Boolean); override;
public
procedure Clear; override;
procedure Delete(Index: Integer); override;
{$IFDEF FPCCOMP}procedure Insert(Index: Integer; const S: string); override;{$ELSE}procedure Insert(Index: Integer; const S: WideString); override;{$ENDIF}
end;
procedure TMemoLines.Clear;
begin
FMemo.ClearLines;
FMemo.Change;
end;
procedure TMemoLines.Delete(Index: Integer);
begin
FMemo.DeleteLine(Index);
FMemo.Change;
end;
procedure TMemoLines{$IFDEF FPCCOMP}.Insert(Index: Integer; const S: string);{$ELSE}.Insert(Index: Integer; const S: WideString);{$ENDIF}
begin
FMemo.InsertLine(Index, S);
FMemo.Change;
end;
function TMemoLines{$IFDEF FPCCOMP}.Get(Index: Integer): string;{$ELSE}.Get(Index: Integer): WideString;{$ENDIF}
begin
Result := FMemo.GetLine(Index);
end;
function TMemoLines.GetCount: Integer;
begin
Result := FMemo.GetLineCount;
end;
procedure TMemoLines.SetUpdateState(Updating: Boolean);
begin
inherited;
FMemo.SetUpdateState(Updating);
end;
function ComposeCaretPos(ALine, APos: Integer): TCaretPosition;
begin
with Result do
begin
Line := ALine;
Pos := APos;
end;
end;
{ TMemo }
constructor TMemo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTextService := Platform.GetTextServiceClass.Create(self, True);
FTextAlign := TTextAlign.taLeading;
FFont := TFont.Create;
FFont.OnChanged := FontChanged;
FFontFill := TBrush.Create(TBrushKind.bkSolid, $FF000000);
FFontFill.OnChanged := FontChanged;
FSelectionFill := TBrush.Create(TBrushKind.bkSolid, $802A8ADF);
FLines := TMemoLines.Create;
FKeyboardType := TVirtualKeyboardType.vktDefault;
(FLines as TMemoLines).FMemo := Self;
CanFocus := True;
Cursor := crIBeam;
FInternalMustUpdateLines := True;
CreatePopupMenu;
FActionStack := TEditActionStack.Create(Self);
FAutoSelect := True;
FCharCase := TEditCharCase.ecNormal;
FHideSelection := True;
FMaxLength := 0;
FReadOnly := False;
FLMouseSelecting := False;
FOldMPt := PointF(0, 0);
FInternalUpdating := False;
with FCaretPosition do
begin
Line := 0;
Pos := 0;
end;
FTextService.ImeMode := TImeMode.imDontCare;
FSelStart := ComposeCaretPos(0, 0);
FSelEnd := ComposeCaretPos(0, 0);
FSelected := False;
FOldSelStartPos := -1;
FOldSelEndPos := -1;
FOldCaretPos := -1;
AutoCapture := True;
FWidestLineIndex := 0;
FCachedFillText := [];
SetLength(FTextWidth, 0);
Width := 100;
SetAcceptsControls(False);
end;
destructor TMemo.Destroy;
begin
FreeAndNil(FOffScreenBitmap);
if FUnwrapLines <> nil then
FUnwrapLines.Free;
FSelectionFill.Free;
FFontFill.Free;
FFont.Free;
FActionStack.Free;
{$IFNDEF NOVCL}
FMemoPopupMenu.Free;
{$ENDIF}
FLines.Free;
FTextService.Free;
inherited;
end;
procedure TMemo.DoEnter;
begin
inherited;
FNeedChange := False;
UpdateCaretPosition(False);
ShowCaretProc;
if Platform.ShowVirtualKeyboard(Self) then
begin
CaretPosition := TextPosToPos(Length(Text));
end
else
begin
with FCaretPosition do
begin
Line := 0;
Pos := 0;
end;
if AutoSelect then
SelectAll;
end;
end;
procedure TMemo.DoExit;
begin
Platform.HideVirtualKeyboard;
inherited;
HideCaret;
FreeAndNil(FOffScreenBitmap);
Change;
if Observers.IsObserving(TObserverMapping.EditLinkID) then
TLinkObservers.EditLinkUpdate(Observers);
end;
function TMemo.TextWidth(const Str: WideString): Single;
var
R: TRectF;
begin
R := ContentRect;
R.Right := 10000;
Canvas.Font.Assign(Font);
Canvas.MeasureText(R, Str, False, FillTextFlags, TextAlign, TTextAlign.taCenter);
Result := RectWidth(R);
end;
function TMemo.GetPositionPoint(ACaretPos: TCaretPosition): TPointF;
var
WholeTextWidth: Single;
EditRectWidth: Single;
LineText: WideString;
begin
Result.x := ContentRect.Left;
Result.y := ContentRect.Top + (GetLineHeight * ACaretPos.Line) -
VScrollBarValue;
WholeTextWidth := 0;
if Canvas = nil then
Exit;
if ((ACaretPos.Line < Lines.Count) and (Lines.Count > 0)) or FTextService.HasMarkedText then
begin
if FTextService.HasMarkedText then
begin
LineText := Lines[ACaretPos.Line];
LineText := Copy(LineText, 1, FCaretPosition.Pos) + FTextService.InternalGetMarkedText + Copy(LineText, FCaretPosition.Pos + 1, MaxInt);
WholeTextWidth := TextWidth(LineText);
end
else
begin
LineText := Lines[ACaretPos.Line];
WholeTextWidth := LineWidth[ACaretPos.Line];
end;
if ACaretPos.Pos > 0 then
begin
if ACaretPos.Pos <= Length(LineText) then
Result.x := Result.x + TextWidth(Copy(LineText, 1, ACaretPos.Pos))
else
Result.x := Result.x + WholeTextWidth;
end;
end;
EditRectWidth := ContentRect.Right - ContentRect.Left;
if WholeTextWidth < EditRectWidth then
case FTextAlign of
TTextAlign.taTrailing:
Result.x := Result.x + (EditRectWidth - WholeTextWidth);
TTextAlign.taCenter:
Result.x := Result.x + ((EditRectWidth - WholeTextWidth) / 2);
end;
Result.x := Result.x - HScrollBarValue;
end;
function TMemo.GetPointPosition(Pt: TPointF): TCaretPosition;
var
CurX: double;
TmpX, WholeTextWidth, EditRectWidth: Single;
LineText: WideString;
LLine: Integer;
LPos: Integer;
TmpPt: TPointF;
LEdiTRect: TRectF;
begin
with Result do
begin
Line := 0;
Pos := 0;
end;
if Lines.Count <= 0 then
Exit;
LEdiTRect := ContentRect;
with LEdiTRect, Pt do
begin
if x < Left then
TmpPt.x := Left
else if x > Right then
TmpPt.x := Right
else
TmpPt.x := x;
if y < Top then
TmpPt.y := Top
else if y > Bottom then
TmpPt.y := Bottom
else
TmpPt.y := y;
end;
LLine := Trunc((TmpPt.y - ContentRect.Top + VScrollBarValue) / GetLineHeight);
LPos := 0;
if LLine > Lines.Count - 1 then
LLine := Lines.Count - 1;
LineText := Lines[LLine];
if Length(LineText) > 0 then
begin
WholeTextWidth := LineWidth[LLine];
EditRectWidth := ContentRect.Right - ContentRect.Left;
TmpX := TmpPt.x;
if WholeTextWidth < EditRectWidth then
case TextAlign of
TTextAlign.taTrailing:
TmpX := TmpPt.x - (EditRectWidth - WholeTextWidth);
TTextAlign.taCenter:
TmpX := TmpPt.x - ((EditRectWidth - WholeTextWidth) / 2);
end;
TmpX := TmpX + HScrollBarValue;
CurX := ContentRect.Left + TextWidth(LineText[1]) / 2;
while (CurX < TmpX) and (LPos + 1 <= Length(LineText)) and
(CurX < ContentRect.Right + HScrollBarValue) do
begin
CurX := ContentRect.Left + TextWidth(Copy(LineText, 1, LPos + 1)) +
(Font.Size / 4);
Inc(LPos);
end;
end;
with Result do
begin
Line := LLine;
Pos := LPos;
end;
end;
procedure TMemo.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
var
TmpS: WideString;
OldCaretPosition: TCaretPosition;
WasSelection: Boolean;
LTmpOptions: TInsertOptions;
begin
if Observers.IsObserving(TObserverMapping.EditLinkID) then
begin
if (Key = vkBack) or (Key = vkDelete) or ((Key = vkInsert) and (ssShift in Shift)) then
if TLinkObservers.EditLinkEdit(Observers) then
TLinkObservers.EditLinkModified(Observers)
else
begin
TLinkObservers.EditLinkReset(Observers);
Exit;
end;
if (KeyChar >= #32) and
not TLinkObservers.EditLinkIsValidChar(Observers, KeyChar) then
begin
// MessageBeep(0);
KeyChar := #0;
Exit;
end;
case KeyChar of
^H, ^V, ^X, #32..High(Char):
if not TLinkObservers.EditLinkEdit(Observers) then
begin
KeyChar := #0;
TLinkObservers.EditLinkReset(Observers);
Exit;
end
else
TLinkObservers.EditLinkModified(Observers);
#27:
begin
TLinkObservers.EditLinkReset(Observers);
SelectAll;
KeyChar := #0;
Exit;
end;
end;
end;
inherited KeyDown(Key, KeyChar, Shift);
OldCaretPosition := CaretPosition;
if (Key = vkReturn) then
begin
WasSelection := SelLength > 0;
if WasSelection then
DeleteFrom(GetSelBeg, SelLength,
[TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo] { True,True, False } );
if WasSelection then
LTmpOptions := [TInsertOption.ioUndoPairedWithPrev]
else
LTmpOptions := [];
TmpS := sLineBreak;
InsertAfter(CaretPosition, TmpS, LTmpOptions + [TInsertOption.ioMoveCaret, TInsertOption.ioCanUndo]
{ False, True, True, WasSelection } );
SelLength := 0;
Key := 0;
end;
case Key of
vkEnd:
if ssCtrl in Shift then
GoToTextEnd
else
GotoLineEnd;
vkHome:
if ssCtrl in Shift then
GoToTextBegin
else
GoToLineBegin;
vkLeft:
if ssCtrl in Shift then
// CaretPosition := TextPosToPos(FTextService.GetPrevWordBeginPosition(PosToTextPos(CaretPosition)))
CaretPosition := GetPrevWordBegin(CaretPosition)
else
// CaretPosition := TextPosToPos(FTextService.GetPrevCharacterPosition(PosToTextPos(CaretPosition)));
MoveCaretLeft;
vkRight:
if ssCtrl in Shift then
// CaretPosition := TextPosToPos(FTextService.GetNextWordBeginPosition(PosToTextPos(CaretPosition)))
CaretPosition := GetNextWordBegin(CaretPosition)
else
// CaretPosition := TextPosToPos(FTextService.GetNextCharacterPosition(PosToTextPos(CaretPosition)));
MoveCaretRight;
vkUp:
MoveCaretUp;
vkDown:
MoveCaretDown;
vkPrior:
MoveCaretPageUp;
vkNext:
MoveCaretPageDown;
vkDelete, 8: { Delete or BackSpace key was pressed }
if not ReadOnly then
begin
if SelLength <> 0 then
begin
if ssShift in Shift then
CutToClipboard
else
ClearSelection;
end
else
begin
TmpS := Text;
if Key = vkDelete then
DeleteFrom(CaretPosition, 1, [TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo])
else { BackSpace key was pressed }
if PosToTextPos(CaretPosition) > 0 then
DeleteFrom(GetPositionShift(CaretPosition, -1), 1,
[TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo]);
end;
end;
vkInsert:
if ssCtrl in Shift then
CopyToClipboard
else if ssShift in Shift then
PasteFromClipboard;
end;
if Shift = [ssCtrl] then
case KeyChar of
^A:
begin
SelectAll;
KeyChar := #0;
end;
^C:
begin
CopyToClipboard;
KeyChar := #0;
end;
^V:
begin
PasteFromClipboard;
KeyChar := #0;
end;
^X:
begin
CutToClipboard;
KeyChar := #0;
end;
^Z:
begin
KeyChar := #0;
end;
end;
{$IFNDEF FPC}
if Shift = [ssCommand] then
case KeyChar of
'a','A':
begin
SelectAll;
KeyChar := #0;
end;
'c','C':
begin
CopyToClipboard;
KeyChar := #0;
end;
'v','V':
begin
PasteFromClipboard;
KeyChar := #0;
end;
'x','X':
begin
CutToClipboard;
KeyChar := #0;
end;
'z','Z':
begin
KeyChar := #0;
end;
end;
{$ENDIF}
if (Ord(KeyChar) >= 32) and not ReadOnly then
begin
WasSelection := SelLength > 0;
if WasSelection then
DeleteFrom(GetSelBeg, SelLength,
[TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo] { True,True, False } );
if WasSelection then
LTmpOptions := [TInsertOption.ioUndoPairedWithPrev]
else
LTmpOptions := [];
if KeyChar <> #13 then
begin
InsertAfter(CaretPosition, KeyChar, LTmpOptions + [TInsertOption.ioMoveCaret, TInsertOption.ioCanUndo]
{ False, True, True, WasSelection } );
end;
SelLength := 0;
KeyChar := #0;
end;
if Key in [vkEnd, vkHome, vkLeft, vkRight, vkUp, vkDown, vkPrior, vkNext] then
begin
if ssShift in Shift then
begin
if not FSelected then
SelectAtPos(OldCaretPosition);
SelectAtPos(CaretPosition);
RepaintEdit;
end
else if FSelected then
begin
FSelected := False;
RepaintEdit;
end;
end;
UpdateCaretPosition(True);
end;
procedure TMemo.MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: Single);
begin
inherited;
if (Button = TMouseButton.mbLeft) and (ssDouble in Shift) then
begin
if PointInRect(PointF(x, y), ContentRect) then
begin
FLMouseSelecting := False;
SelectWord;
end;
end;
if (Button = TMouseButton.mbLeft) and PointInRect(PointF(x, y), ContentRect) then
begin
FLMouseSelecting := True;
CaretPosition := GetPointPosition(PointF(x, y));
FSelected := False;
SelectAtPos(CaretPosition);
RepaintEdit;
end;
end;
function TMemo.ContentPos: TPointF;
var
T: TFmxObject;
begin
T := FindStyleResource('content');
if (T <> nil) and (T is TControl) then
begin
Result := TControl(T).Position.Point;
end;
end;
procedure TMemo.DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
var
// BeforeCaret: WideString;
// BeforeCaretSize: Single;
// MarketSize: Single;
R, TmpRect: TRectF;
LSelArea: TSelArea;
CurSelRect: Integer;
State: TCanvasSaveState;
// CurChar,
CurLine, LEndLine: Integer;
TmpPt: TPointF;
LLeftTopCharPt: TPointF;
P: TPoint;
S: WideString;
begin
with Canvas do
begin
State := Canvas.SaveState;
try
Canvas.IntersectClipRect(ARect);
Font.Assign(FFont);
Fill.Assign(FFontFill);
Stroke.Assign(FFontFill);
// text
R := ContentRect;
TmpRect := ARect;
//Canvas.Font.Assign(Font);
LLeftTopCharPt.x := TmpRect.Left;
LLeftTopCharPt.y := TmpRect.Top;
CurLine := Trunc(VScrollBarValue / GetLineHeight);
LEndLine := Trunc((VScrollBarValue + ContentRect.Height) / GetLineHeight);
if LEndLine >= Lines.Count then
LEndLine := Lines.Count - 1;
if (LEndLine < 0) and FTextService.HasMarkedText then
begin
// only if text is empty
// TmpPt := GetPositionPoint(ComposeCaretPos(0, 0));
FTextService.DrawSingleLine( Canvas,
RectF(
TmpPt.x - R.Left,
TmpPt.y - R.Top,
$FFFF,
TmpPt.y - R.Top + (GetLineHeight * 1.25)),
0,
Font,
AbsoluteOpacity, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
end;
while CurLine <= LEndLine do
begin
TmpPt := GetPositionPoint(ComposeCaretPos(CurLine, 0));
if (CurLine = CaretPosition.Line) and FTextService.HasMarkedText then
begin
{$IFDEF __}
S := Copy(Lines[CurLine], 1, CaretPosition.Pos) +
FTextService.InternalGetMarkedText +
Copy(Lines[CurLine], CaretPosition.Pos + 1, $FFFF);
FillText(RectF(TmpPt.x - R.Left, TmpPt.y - R.Top, $FFFF,
TmpPt.y - R.Top + (GetLineHeight * 1.25)), S,
False, AbsoluteOpacity, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
FTextService.DrawStatusInformation(Canvas,
S, TmpPt,
Font, ARect, ContentRect,
GetLineHeight,
self);
{$ELSE !__}
S := Copy(Lines[CurLine], 1, CaretPosition.Pos) +
FTextService.InternalGetMarkedText +
Copy(Lines[CurLine], CaretPosition.Pos + 1, $FFFF);
P.X := CaretPosition.Pos;
P.Y := CaretPosition.Line;
FTextService.CaretPosition := P;
FTextService.DrawSingleLine2( Canvas, S,
RectF(
TmpPt.x - R.Left,
TmpPt.y - R.Top,
$FFFF,
TmpPt.y - R.Top + (GetLineHeight * 1.25)),
Font,
AbsoluteOpacity, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
{$ENDIF __}
end
else
FillText(RectF(TmpPt.x - R.Left, TmpPt.y - R.Top, $FFFF,
TmpPt.y - R.Top + (GetLineHeight * 1.25)), Lines[CurLine],
False, AbsoluteOpacity, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
Inc(CurLine);
end;
// selection
if IsFocused then
begin
LSelArea := GetSelArea;
if GetShowSelection then
begin
Fill.Assign(FSelectionFill);
for CurSelRect := Low(LSelArea) to High(LSelArea) do
begin
IntersectRect(TmpRect, LSelArea[CurSelRect], RectF(0, 0, 1000, 1000));
OffsetRect(TmpRect, -R.Left, -R.Top);
FillRect(TmpRect, 0, 0, [], 1);
end;
end;
end;
finally
Canvas.RestoreState(State);
end;
end;
end;
procedure TMemo.DoContentPaintWithCache(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
var
State: TCanvasSaveState;
R: TRectF;
begin
if not IsFocused then
DoContentPaint(Sender, Canvas, ARect)
else
begin
State := Canvas.SaveState;
try
R := RectF(0, 0, ARect.Width, ARect.Height);
with GetAbsoluteScale do
MultiplyRect(R, X, Y);
if (FOffScreenBitmap <> nil) and (
(FOffScreenBitmap.Width <> trunc(RectWidth(R))) or
(FOffScreenBitmap.Height <> trunc(RectHeight(R)))) then
begin
FreeAndNil(FOffScreenBitmap);
end;
if FOffScreenBitmap = nil then
begin
{ create }
FOffScreenBitmap := TBitmap.Create(trunc(RectWidth(R)), trunc(RectHeight(R)));
{ Paint Self }
if FOffScreenBitmap.Canvas.BeginScene then
try
FOffScreenBitmap.Canvas.Clear(Canvas.Fill.Color);
FOffScreenBitmap.Canvas.SetMatrix(CreateScaleMatrix(Scale.X, Scale.Y));
DoContentPaint(Sender, FOffScreenBitmap.Canvas, R);
finally
FOffScreenBitmap.Canvas.EndScene;
end;
end;
Canvas.SetMatrix(AbsoluteMatrix);
Canvas.DrawBitmap(FOffScreenBitmap,
RectF(0, 0, FOffScreenBitmap.Width, FOffScreenBitmap.Height),
ContentRect,
AbsoluteOpacity, RotationAngle = 0);
finally
Canvas.RestoreState(State);
end;
end;
end;
procedure TMemo.HScrollChange(Sender: TObject);
begin
FreeAndNil(FOffScreenBitmap);
inherited;
end;
procedure TMemo.VScrollChange(Sender: TObject);
begin
FreeAndNil(FOffScreenBitmap);
inherited;
UpdateCaretPosition(False);
end;
procedure TMemo.ApplyStyle;
var
T: TFmxObject;
begin
inherited;
T := FindStyleResource('content');
if (T <> nil) and (T is TControl) then
begin
FContent := TControl(T);
FContent.OnPaint := DoContentPaintWithCache;
end;
T := FindStyleResource('selection');
if (T <> nil) and (T is TBrushObject) then
begin
FSelectionFill.Assign(TBrushObject(T).Brush);
end;
{ from style }
T := FindStyleResource('foreground');
if (T <> nil) and (T is TBrushObject) then
FFontFill.Assign(TBrushObject(T).Brush);
end;
procedure TMemo.RepaintEdit;
begin
FreeAndNil(FOffScreenBitmap);
if FContent <> nil then
begin
FContent.Repaint;
end;
end;
procedure TMemo.UpdateHScrlBarByCaretPos;
var
LEdiTRect: TRectF;
LCaretLinePos: Integer;
LCaretLine: Integer;
CurCaretX: Integer;
TempStr: WideString;
LMarkedPos: integer;
EditWidth, VisWidth, FirstVisWidth, LastvisWidth: Single;
begin
if (Lines.Count <= 0) and (not FTextService.HasMarkedText) then
Exit;
if Canvas = nil then
Exit;
LEdiTRect := ContentRect;
// CurCaretX := round(GetPositionPoint(CaretPosition+Length(FMarkedText)).x);
// CurCaretX := round(GetPositionPoint(ComposeCaretPos(CaretPosition.Line, CaretPosition.Pos + Length(FTextService._InternaGetMarkedText))).X);
CurCaretX := round(GetPositionPoint(
ComposeCaretPos(
FTextService.TargetClausePosition.X,
FTextService.TargetClausePosition.Y )).X);
if not((CurCaretX < LEdiTRect.Left) or (CurCaretX > LEdiTRect.Right)) then
Exit;
LCaretLinePos := CaretPosition.Pos;
LCaretLine := CaretPosition.Line;
TempStr := Lines[LCaretLine];
TempStr := Copy(TempStr, 1, LCaretLinePos) + FTextService.InternalGetMarkedText+ Copy(TempStr, LCaretLinePos+1, MaxInt);
if FFirstVisibleChar >= (LCaretLinePos + Length(FTextService.InternalGetMarkedText) + 1) then
begin
FFirstVisibleChar := LCaretLinePos;
if FFirstVisibleChar < 1 then
FFirstVisibleChar := 1;
end
else
begin // caret
LMarkedPos := LCaretLinePos + Length(FTextService.InternalGetMarkedText);
EditWidth := LEdiTRect.Right - LEdiTRect.Left - 5;
VisWidth := TextWidth(Copy(TempStr, FFirstVisibleChar, LMarkedPos - FFirstVisibleChar + 1));
while (VisWidth > EditWidth) and (FFirstVisibleChar < Length(TempStr)) do
begin
// Get the width of the first character
FirstVisWidth := TextWidth(Copy(TempStr, FFirstVisibleChar, 1));
// Move the first visible pointer to the right
Inc(FFirstVisibleChar);
// Get the width of the new last visible character
LastVisWidth := TextWidth(Copy(TempStr, LMarkedPos - FFirstVisibleChar + 1, 1));
// Calculate the new visible width
VisWidth := VisWidth - FirstVisWidth + LastVisWidth;
end;
end;
if (HScrollBar <> nil) and (HScrollBar.Visible) then
HScrollBar.Value := TextWidth(Copy(TempStr, 1,
FFirstVisibleChar - 1));
end;
procedure TMemo.MouseMove(Shift: TShiftState; x, y: Single);
var
LEdiTRect: TRectF;
begin
inherited;
FOldMPt := PointF(x, y);
if FLMouseSelecting then
begin
LEdiTRect := ContentRect;
{ if y < LEdiTRect.Top then
VScrollBar.AutoScrollUp := True
else
if y > LEdiTRect.Bottom then
VScrollBar.AutoScrollDown := True
else begin
VScrollBar.AutoScrollDown := False;
VScrollBar.AutoScrollUp := False;
end; }
SelectAtMousePoint;
end;
end;
procedure TMemo.MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: Single);
begin
inherited;
FLMouseSelecting := False;
if SelLength = 0 then
FSelected := False;
end;
procedure TMemo.CopyToClipboard;
begin
if SelText <> '' then
Platform.SetClipboard(SelText);
end;
procedure TMemo.PasteFromClipboard;
var
WasSelection: Boolean;
begin
if ReadOnly then
Exit;
if Observers.IsObserving(TObserverMapping.EditLinkID) then
if not TLinkObservers.EditLinkEdit(Observers) then
begin
TLinkObservers.EditLinkReset(Observers);
Exit;
end
else
TLinkObservers.EditLinkModified(Observers);
try
if not VarIsStr(Platform.GetClipboard) then Exit;
WasSelection := SelLength >0;
if WasSelection then
begin
DeleteFrom(GetSelBeg, SelLength, [TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo]);
InsertAfter(GetSelBeg, Platform.GetClipboard, [TInsertOption.ioMoveCaret,
TInsertOption.ioCanUndo, TInsertOption.ioUndoPairedWithPrev]);
end
else
InsertAfter(CaretPosition, Platform.GetClipboard, [TInsertOption.ioMoveCaret,
TInsertOption.ioCanUndo{, ioUndoPairedWithPrev}]);
Change;
finally
end;
end;
procedure TMemo.CreatePopupMenu;
begin
FMemoPopupMenu := TPopupMenu.Create(Self);
FMemoPopupMenu.Stored := False;
FMemoPopupMenu.Parent := Self;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := SEditCut;
StyleName := 'cut';
OnClick := DoCut;
end;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := SEditCopy;
StyleName := 'copy';
OnClick := DoCopy;
end;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := SEditPaste;
StyleName := 'paste';
OnClick := DoPaste;
end;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := SEditDelete;
StyleName := 'delete';
OnClick := DoDelete;
end;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := '-';
end;
with TMenuItem.Create(FMemoPopupMenu) do
begin
Parent := FMemoPopupMenu;
Text := SEditSelectAll;
StyleName := 'selectall';
OnClick := DoSelectAll;
end;
end;
procedure TMemo.DoCut(Sender: TObject);
begin
CutToClipboard;
end;
procedure TMemo.DoCopy(Sender: TObject);
begin
CopyToClipboard;
end;
procedure TMemo.DoDelete(Sender: TObject);
begin
if Observers.IsObserving(TObserverMapping.EditLinkID) then
if not TLinkObservers.EditLinkEdit(Observers) then
begin
TLinkObservers.EditLinkReset(Observers);
Exit;
end
else
TLinkObservers.EditLinkModified(Observers);
ClearSelection;
end;
procedure TMemo.DoPaste(Sender: TObject);
begin
PasteFromClipboard;
end;
procedure TMemo.UpdatePopupMenuItems;
var
SelTextEmpty: Boolean;
begin
SelTextEmpty := SelText <> '';
TMenuItem(FMemoPopupMenu.FindStyleResource('cut')).Enabled := SelTextEmpty and not ReadOnly;
TMenuItem(FMemoPopupMenu.FindStyleResource('copy')).Enabled := SelTextEmpty;
TMenuItem(FMemoPopupMenu.FindStyleResource('paste')).Enabled := VarIsStr(Platform.GetClipboard) and not ReadOnly;
TMenuItem(FMemoPopupMenu.FindStyleResource('delete')).Enabled := SelTextEmpty and not ReadOnly;
TMenuItem(FMemoPopupMenu.FindStyleResource('selectall')).Enabled := SelText <> Text;
end;
function TMemo.GetNextWordBegin(StartPosition: TCaretPosition): TCaretPosition;
var
SpaceFound, WordFound: Boolean;
LLineText: WideString;
CurPos: Integer;
CurLine: Integer;
begin
CurPos := StartPosition.Pos;
CurLine := StartPosition.Line;
if StartPosition.Pos < Length(GetLine(StartPosition.Line)) then
begin
LLineText := GetLine(StartPosition.Line);
SpaceFound := False;
WordFound := False;
while (CurPos + 2 <= Length(LLineText)) and
((not((LLineText[CurPos + 1] <> ' ') and SpaceFound)) or not WordFound) do
begin
if LLineText[CurPos + 1] = ' ' then
SpaceFound := True;
if LLineText[CurPos + 1] <> ' ' then
begin
WordFound := True;
SpaceFound := False;
end;
CurPos := CurPos + 1;
end;
if not SpaceFound then
CurPos := CurPos + 1;
end
else if StartPosition.Line < Lines.Count - 1 then
begin
CurLine := CurLine + 1;
CurPos := 0;
end;
with Result do
begin
Line := CurLine;
Pos := CurPos;
end
end;
function TMemo.GetPrevWordBegin(StartPosition: TCaretPosition): TCaretPosition;
var
WordFound: Boolean;
LLineText: WideString;
CurPos: Integer;
CurLine: Integer;
begin
Result := StartPosition;
CurPos := StartPosition.Pos;
CurLine := StartPosition.Line;
if StartPosition.Pos > 0 then
begin
LLineText := GetLine(StartPosition.Line);
WordFound := False;
while (CurPos > 0) and ((LLineText[CurPos] <> ' ') or not WordFound) do
begin
if LLineText[CurPos] <> ' ' then
WordFound := True;
CurPos := CurPos - 1;
end;
end
else if (StartPosition.Line - 1 >= 0) and
(StartPosition.Line - 1 <= Lines.Count - 1) then
begin
CurLine := CurLine - 1;
CurPos := Length(GetLine(CurLine));
end;
with Result do
begin
Line := CurLine;
Pos := CurPos;
end
end;
function TMemo.GetReadOnly: Boolean;
begin
if Observers.IsObserving(TObserverMapping.EditLinkID) then
Result := TLinkObservers.EditLinkIsReadOnly(Observers)
else
Result := FReadOnly;
end;
procedure TMemo.ClearSelection;
begin
if not ReadOnly then
DeleteFrom(GetSelBeg, SelLength, [TDeleteOption.doMoveCaret, TDeleteOption.doCanUndo]);
end;
procedure TMemo.CutToClipboard;
begin
if Observers.IsObserving(TObserverMapping.EditLinkID) then
if not TLinkObservers.EditLinkEdit(Observers) then
begin
TLinkObservers.EditLinkReset(Observers);
Exit;
end
else
TLinkObservers.EditLinkModified(Observers);
CopyToClipboard;
ClearSelection;
end;
procedure TMemo.SelectAll;
begin
FSelStart := ComposeCaretPos(0, 0);
FSelEnd.Line := GetLineCount;
if FSelEnd.Line = 0 then
FSelEnd.Pos := 0
else
begin
Dec(FSelEnd.Line);
FSelEnd.Pos := Length(GetLine(FSelEnd.Line));
end;
FSelected := True;
GoToTextEnd;
RepaintEdit;
end;
procedure TMemo.DoSelectAll(Sender: TObject);
begin
SelectAll;
end;
procedure TMemo.DrawPasswordChar(SymbolRect: TRectF; Selected: Boolean);
var
LRect: TRectF;
begin
{ !!! Don't forget include clipping rountines
Char symbol image must not extend out of EdiTRect }
IntersectRect(LRect, SymbolRect, ContentRect);
Canvas.Font.Assign(Font);
// if Selected then
// Canvas.Font.Color := clHighlightText;
// Canvas.Brush.Style := bsClear;
// Canvas.TexTRect(LRect, SymbolRect.Left, SymbolRect.Top, PasswordChar);
end;
function TMemo.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean;
begin
Result := True;
NewHeight := round(GetLineHeight + ContentRect.Top * 2);
end;
procedure TMemo.SelectWord;
begin
// FSelStart := TextPosToPos(FTextService.GetPrevWordBeginPosition(PosToTextPos(CaretPosition)));
// FSelEnd := TextPosToPos(FTextService.GetNextWordBeginPosition(PosToTextPos(CaretPosition)));
FSelStart := GetPrevWordBegin(CaretPosition);
FSelEnd := GetNextWordBegin(CaretPosition);
FSelected := True;
RepaintEdit;
end;
procedure TMemo.Change;
begin
if FNeedChange then
begin
FreeAndNil(FOffScreenBitmap);
if Assigned(FBindingObjects) then
ToBindingObjects;
if not(csLoading in ComponentState) then
begin
if Assigned(FOnChangeTracking) then
FOnChangeTracking(Self);
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
end;
procedure TMemo.ContextMenu(const ScreenPosition: TPointF);
begin
inherited;
if csDesigning in ComponentState then
Exit;
if PopupMenu = nil then
begin
UpdatePopupMenuItems;
FMemoPopupMenu.PopupComponent := Self;
FMemoPopupMenu.Popup(round(ScreenPosition.X), round(ScreenPosition.Y));
end;
end;
procedure TMemo.FontChanged(Sender: TObject);
begin
ResetLineWidthCache;
RepaintEdit;
if not(csLoading in ComponentState) then
begin
UpdateLines;
UpdateCaretPosition(False);
if not FInternalUpdating then
Realign;
end;
inherited;
end;
procedure TMemo.FreeStyle;
begin
inherited;
FContent := nil;
end;
function TMemo.GetText: WideString;
begin
Result := FTextService.Text;
end;
procedure TMemo.SetText(const Value: WideString);
begin
if not ValidText(Value) then
Exit;
if Value <> Text then
begin
if (Value <> '') and (CharCase <> TEditCharCase.ecNormal) then
case CharCase of
{$IFDEF KS_COMPILER5}
ecUpperCase:
FText := UpperCase(Value);
ecLowerCase:
FText := LowerCase(Value);
{$ELSE}
TEditCharCase.ecUpperCase:
FTextService.Text := WideUpperCase(Value);
TEditCharCase.ecLowerCase:
FTextService.Text := WideLowerCase(Value);
{$ENDIF}
end
else
FTextService.Text := Value;
if FInternalMustUpdateLines then
begin
UpdateLines;
if not FInternalUpdating then
Realign;
end;
// if not(csLoading in ComponentState) and Assigned(OnChange) then
// OnChange(Self);
FNeedChange := True;
Change;
end;
end;
procedure TMemo.SetCaretPosition(const Value: TCaretPosition);
begin
if Value.Line > Lines.Count - 1 then
FCaretPosition.Line := Lines.Count - 1
else
FCaretPosition.Line := Value.Line;
if FCaretPosition.Line < 0 then
FCaretPosition.Line := 0;
if Value.Pos < 0 then
FCaretPosition.Pos := 0
else if Value.Pos > Length(Lines[FCaretPosition.Line]) then
FCaretPosition.Pos := Length(Lines[FCaretPosition.Line])
else
FCaretPosition.Pos := Value.Pos;
UpdateCaretPosition(True);
end;
procedure TMemo.SetSelLength(const Value: Integer);
begin
FSelected := Value > 0;
FSelEnd := TextPosToPos(PosToTextPos(FSelStart) + Value);
RepaintEdit;
end;
procedure TMemo.SetSelStart(const Value: Integer);
begin
FSelStart := TextPosToPos(Value);
CaretPosition := FSelStart;
SelLength := 0;
end;
procedure TMemo.SetAutoSelect(const Value: Boolean);
begin
if FAutoSelect <> Value then
FAutoSelect := Value;
end;
function TMemo.GetSelStart: Integer;
begin
if FSelected then
Result := PosToTextPos(GetSelBeg)
else
Result := PosToTextPos(CaretPosition);
end;
function TMemo.GetSelArea: TSelArea;
var
BegLine, EndLine, CurLine: Integer;
SelBegLineVisible, SelEndLineVisible: Boolean;
begin
if not FSelected then
begin
SetLength(Result, 0);
Exit;
end;
SelBegLineVisible := True;
SelEndLineVisible := True;
BegLine := GetSelBeg.Line;
if BegLine < Trunc(VScrollBarValue / GetLineHeight) then
begin
BegLine := Trunc(VScrollBarValue / GetLineHeight);
SelBegLineVisible := False;
end;
EndLine := GetSelEnd.Line;
if EndLine > Trunc((VScrollBarValue + ContentRect.Height) / GetLineHeight) then
begin
EndLine := Trunc((VScrollBarValue + ContentRect.Height) / GetLineHeight);
SelEndLineVisible := False;
end;
if EndLine < BegLine then
EndLine := BegLine - 1;
SetLength(Result, EndLine - BegLine + 1);
CurLine := BegLine;
while (CurLine <= EndLine) and (CurLine < Lines.Count) do
begin
with Result[CurLine - BegLine] do
begin
Left := GetPositionPoint(ComposeCaretPos(CurLine, 0)).x;
Right := GetPositionPoint(ComposeCaretPos(CurLine,
Length(Lines[CurLine]))).x;
Top := GetPositionPoint(ComposeCaretPos(CurLine, 0)).y;
Bottom := GetPositionPoint(ComposeCaretPos(CurLine, 0)).y + GetLineHeight;
end;
Inc(CurLine);
end;
if EndLine - BegLine >= 0 then
begin
if SelBegLineVisible then
Result[0].Left := GetPositionPoint(ComposeCaretPos(BegLine,
GetSelBeg.Pos)).x;
if SelEndLineVisible then
Result[EndLine - BegLine].Right :=
GetPositionPoint(ComposeCaretPos(EndLine, GetSelEnd.Pos)).x;
end;
end;
function TMemo.GetSelLength: Integer;
begin
if FSelected then
Result := PosToTextPos(GetSelEnd) - PosToTextPos(GetSelBeg)
else
Result := 0;
end;
procedure TMemo.ReadTextData(Reader: TReader);
begin
Text := Reader.ReadString;
end;
procedure TMemo.defineproperties(Filer: TFiler);
begin
Filer.DefineProperty('Text', ReadTextData, nil, False);
end;
function TMemo.GetSelText: WideString;
var
LSelStart, LSelLength: Integer;
begin
if FSelected then
begin
LSelStart := SelStart;
LSelLength := SelLength;
Result := Copy(Text, LSelStart + 1, LSelLength);
end
else
Result := '';
end;
procedure TMemo.SetCharCase(const Value: TEditCharCase);
var
tempS: WideString;
begin
if FCharCase <> Value then
begin
FCharCase := Value;
if FTextService.Text <> '' then
begin
tempS:= FTextService.Text;
case FCharCase of
TEditCharCase.ecUpperCase: FTextService.Text:= WideUpperCase(tempS);
TEditCharCase.ecLowerCase: FTextService.Text:= WideLowerCase(temps);
end;
RepaintEdit;
end;
end;
end;
procedure TMemo.SetHideSelection(const Value: Boolean);
begin
if FHideSelection <> Value then
begin
FHideSelection := Value;
RepaintEdit;
end;
end;
procedure TMemo.SetKeyboardType(Value: TVirtualKeyboardType);
begin
FKeyboardType := Value;
end;
function TMemo.GetTextService: TTextService;
begin
Result := FTextService;
end;
procedure TMemo.UpdateCaretPoint;
begin
if not FInternalUpdating then
Realign;
UpdateCaretPosition(True);
RepaintEdit;
end;
function TMemo.GetTargetClausePointF: TPointF;
var
P: TCaretPosition;
TmpPt: TPointF;
TmpRect: TRectF;
begin
// Str := Copy(FTextService.CombinedText, 1, Round(FTextService.TargetClausePosition.X) );
// if FFirstVisibleChar > 1 then
// Str := Copy(Str, FFirstVisibleChar);
// Result.X := TextWidth(Str) + ContentRect.Left + Self.Position.Point.X;
// Result.Y := ((ContentRect.Height / 2) + Font.Size / 2 + 2) + ContentRect.Top + Self.Position.Y;
P := CaretPosition;
P.Line := P.Line + 1;
TmpRect := ContentRect;
TmpPt := GetPositionPoint(P);
TmpPt.Y := TmpPt.Y + 2; // small space between conrol and IME window
Result.X := TmpPt.x + HScrollBarValue - TmpRect.Left;
Result.Y := TmpPt.y + VScrollBarValue - TmpRect.Top;
Result.X := Result.X + ContentRect.Top + Self.Position.Point.X;
Result.Y := Result.Y + ContentRect.Left + Self.Position.Point.Y;
end;
function TMemo.GetImeMode: TImeMode;
begin
Result := FTextService.ImeMode;
end;
procedure TMemo.SetImeMode(const Value: TImeMode);
begin
if FTextService.ImeMode <> Value then
FTextService.ImeMode := Value;
end;
procedure TMemo.SetMaxLength(const Value: Integer);
begin
if FMaxLength <> Value then
begin
FMaxLength := Value;
end;
end;
procedure TMemo.SetReadOnly(Value: Boolean);
begin
if Observers.IsObserving(TObserverMapping.EditLinkID) then
TLinkObservers.EditLinkSetIsReadOnly(Observers, Value)
else
FReadOnly := Value;
end;
function TMemo.ValidText(const NewText: WideString): Boolean;
begin
Result := True;
end;
procedure TMemo.UpdateCaretPosition(UpdateScrllBars: Boolean);
var
TmpPt: TPointF;
TmpRect: TRectF;
begin
if UpdateScrllBars then
begin
UpdateVScrlBarByCaretPos;
UpdateHScrlBarByCaretPos;
end;
TmpRect := ContentRect;
TmpPt := GetPositionPoint(CaretPosition);
TmpPt.x := TmpPt.x + HScrollBarValue - TmpRect.Left;
TmpPt.y := TmpPt.y + VScrollBarValue - TmpRect.Top;
if FTextService.HasMarkedText then
TmpPt.x := TmpPt.x + TextWidth(FTextService.InternalGetMarkedText);
SetCaretSize(PointF(1, GetLineHeight));
SetCaretPos(TmpPt);
SetCaretColor(FFontFill.Color);
end;
function TMemo.GetLineRealEnd(AStartPos: TCaretPosition; PText: PWideString) : TCaretPosition;
begin
Result.Line := AStartPos.Line;
while (Result.Line + 1 <= Lines.Count - 1) and
(GetLineInternal(Result.Line) = GetLine(Result.Line)) do
Result.Line := Result.Line + 1;
if (Result.Line <= Lines.Count - 1) and (Lines.Count > 0) then
begin
Result.Pos := Length(GetLine(Result.Line)) + FLinesBegs[Result.Line] - 1
end
else
Result.Pos := 0;
end;
function TMemo.FillLocalLinesBegs(PText: PWideString; ABegChar, AEndChar: Integer;
TmpLinesBegs: PLinesBegins): Integer;
var
S: WideString;
TmpSWidth: Single;
LLongestLineWidth: Single;
i: Integer;
LMetrics: TLineMetricInfo;
begin
Result := 0;
SetLength(TmpLinesBegs^, 0);
if PText^ = '' then
Exit;
LMetrics := TLineMetricInfo.Create;
S := Copy(PText^, ABegChar, AEndChar - ABegChar + 1);
Canvas.Font.Assign(Font);
Canvas.MeasureLines(LMetrics, ContentRect,
S, FWordWrap, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
if LMetrics.Count = 0 then
begin
// no date??? Error??
// Result := 0;
// SetLength(TmpLinesBegs^, 0);
end
else
if LMetrics.Count = 1 then
begin
// Single line
Result := 0;
SetLength(TmpLinesBegs^, 0);
end
else
begin
// New lines are coming.
SetLength(TmpLinesBegs^, LMetrics.Count - 1);
LLongestLineWidth := TextWidth(Copy(S, 1, LMetrics.Metrics[0].Len));
Result := 0;
for i := 0 to LMetrics.Count - 2 do
begin
TmpLinesBegs^[i] := LMetrics.Metrics[i+1].Index - 1 + ABegChar;
TmpSWidth := TextWidth(Copy(S, LMetrics.Metrics[i+1].Index, LMetrics.Metrics[i+1].Len));
if TmpSWidth > LLongestLineWidth then
begin
LLongestLineWidth := TmpSWidth;
Result := i;
end;
end;
end;
LMetrics.Free;
end;
procedure TMemo.UpdateLines;
var
TmpS: WideString;
TmpSWidth: Single;
LLongestLineWidth: Single;
i: Integer;
LMetrics: TLineMetricInfo;
begin
FWidestLineIndex := 0;
SetLength(FLinesBegs, 0);
SetLength(FTextWidth, 0);
if Text = '' then
Exit;
SetLength(FLinesBegs, 1);
SetLength(FTextWidth, 1);
// with ContentRect do
// LEditRectWidth := Right - Left;
if Canvas = nil then
Exit;
LMetrics := TLineMetricInfo.Create;
Canvas.Font.Assign(Font);
Canvas.MeasureLines(LMetrics, ContentRect, Text, FWordWrap, FillTextFlags, TTextAlign.taLeading, TTextAlign.taLeading);
SetLength(FLinesBegs, LMetrics.Count);
LLongestLineWidth := 0;
for i := 0 to LMetrics.Count - 1 do
FLinesBegs[i] := LMetrics.Metrics[i].Index;
SetLength(FTextWidth, LMetrics.Count);
FCachedFillText := FillTextFlags;
for i := 0 to LMetrics.Count - 1 do
begin
TmpS := GetLineInternal(i);
FTextWidth[i] := TextWidth(TmpS);
if LLongestLineWidth < FTextWidth[i] then
begin
LLongestLineWidth := FTextWidth[i];
FWidestLineIndex := i;
end;
end;
LMetrics.Free;
end;
procedure TMemo.UpdateRngLinesBegs(PText: PWideString;
AUpdBegLine, AUpdEndLine, AUpdBegChar, AUpdEndChar, ACharDelta, AOldWidestLineWidth: Integer);
var
LUpdEndChar, LNewWidestLineIndex, LLineDelta, i: Integer;
LTmpLinesBegs: TLinesBegins;
begin
if (Length(FLinesBegs) = 0) and (PText^ <> '') then
begin
SetLength(FLinesBegs, 1);
SetLength(FTextWidth, 1);
FLinesBegs[0] := 1;
FTextWidth[0] := 0;
end;
LUpdEndChar := AUpdEndChar + ACharDelta;
LNewWidestLineIndex := FillLocalLinesBegs(PText, AUpdBegChar, LUpdEndChar,
@LTmpLinesBegs) + AUpdBegLine;
LLineDelta := Length(LTmpLinesBegs) - (AUpdEndLine - AUpdBegLine);
if LLineDelta > 0 then
begin
SetLength(FLinesBegs, Length(FLinesBegs) + LLineDelta);
SetLength(FTextWidth, Length(FTextWidth) + LLineDelta);
for i := Length(FLinesBegs) - 1 downto AUpdEndLine + 1 + LLineDelta do
FLinesBegs[i] := FLinesBegs[i - LLineDelta] + ACharDelta;
for i := Length(FTextWidth) - 1 downto AUpdEndLine + 1 + LLineDelta do
begin
FTextWidth[i] := FTextWidth[i - LLineDelta];
end;
for i := AUpdBegLine to AUpdEndLine + LLineDelta do
FTextWidth[i] := 0;
end
else if LLineDelta < 0 then
begin
for i := AUpdBegLine + 1 to Length(FLinesBegs) - 1 + LLineDelta do
FLinesBegs[i] := FLinesBegs[i - LLineDelta] + ACharDelta;
for i := AUpdBegLine to AUpdEndLine do
FTextWidth[i] := 0;
for i := AUpdBegLine + Length(LTmpLinesBegs) to Length(FTextWidth) + LLineDelta - 1 do
FTextWidth[i] := FTextWidth[i - LLineDelta];
SetLength(FLinesBegs, Length(FLinesBegs) + LLineDelta);
SetLength(FTextWidth, Length(FTextWidth) + LLineDelta);
end
else
begin
// LLineDelta = 0
for i := AUpdBegLine + 1 to Length(FLinesBegs) - 1 do
FLinesBegs[i] := FLinesBegs[i] + ACharDelta;
if AUpdEndLine < Length(FTextWidth) then
for i := AUpdBegLine to AUpdEndLine do
FTextWidth[i] := 0;
end;
for i := 0 to Length(LTmpLinesBegs) - 1 do
if AUpdBegLine + i + 1 <= Length(FLinesBegs) - 1 then
begin
FLinesBegs[AUpdBegLine + i + 1] := LTmpLinesBegs[i];
FTextWidth[AUpdBegLine + i + 1] := 0;
end;
if FWidestLineIndex > Length(FLinesBegs) - 1 then
FWidestLineIndex := round(GetWidestLine)
else if LineWidth[LNewWidestLineIndex] >= AOldWidestLineWidth then
FWidestLineIndex := LNewWidestLineIndex
else if not((FWidestLineIndex < AUpdBegLine) or (FWidestLineIndex > AUpdEndLine))
then
FWidestLineIndex := GetWidestLine;
if not FInternalUpdating then
Realign;
end;
procedure TMemo.InsertAfter(Position: TCaretPosition; const S: WideString; Options: TInsertOptions);
var
LText: WideString;
Insertion: WideString;
LUpdBegLine, LUpdBegChar, LUpdEndLine, LUpdEndChar: Integer;
R: Integer;
LInsertionLength: Integer;
LOldWidestLineWidth: Single;
begin
R := PosToTextPos(CaretPosition);
LText := Text;
Insertion := S;
if MaxLength > 0 then
Insertion := Copy(Insertion, 1, MaxLength - Length(LText));
if TInsertOption.ioCanUndo in Options then
FActionStack.FragmentInserted(PosToTextPos(Position), Length(S),
TInsertOption.ioUndoPairedWithPrev in Options);
LUpdBegLine := Position.Line;
if (Length(FLinesBegs) > 0) and (Position.Line <= Length(FLinesBegs) - 1) then
LUpdBegChar := FLinesBegs[Position.Line]
else
LUpdBegChar := 1;
with GetLineRealEnd(Position, @LText) do
begin
LUpdEndLine := Line;
LUpdEndChar := Pos;
end;
LInsertionLength := Length(Insertion);
LOldWidestLineWidth := LineWidth[FWidestLineIndex];
Insert(Insertion, LText, PosToTextPos(Position) + 1);
try
FInternalMustUpdateLines := False;
Text := LText;
finally
FInternalMustUpdateLines := True;
end;
UpdateRngLinesBegs(@LText, LUpdBegLine, LUpdEndLine, LUpdBegChar, LUpdEndChar,
LInsertionLength, round(LOldWidestLineWidth));
if TInsertOption.ioSelected in Options then
begin
FSelStart := Position;
FSelEnd := GetPositionShift(Position, Length(Insertion));
FSelected := True;
CaretPosition := FSelEnd;
end
else
begin
if not(csLoading in ComponentState) then
begin
CaretPosition := TextPosToPos(R + Length(Insertion));
UpdateCaretPosition(False);
end;
end;
if not FInternalUpdating then
Realign;
end;
procedure TMemo.DeleteFrom(Position: TCaretPosition; ALength: Integer;
Options: TDeleteOptions);
var
LUpdBegLine, LUpdEndLine, LUpdBegChar, LUpdEndChar: Integer;
LText: WideString;
LTmpPos, LTmpLength: Integer;
LOldWidestLineWidth: Integer;
begin
LText := Text;
LTmpLength := ALength;
LTmpPos := PosToTextPos(Position) + 1;
if (LTmpPos + ALength - 1 + 1 <= System.Length(LText)) and
(LTmpPos + ALength - 1 >= 1) and (LText[LTmpPos + ALength - 1] = #13) and
(LText[LTmpPos + ALength - 1 + 1] = #10) then
LTmpLength := LTmpLength + 1;
if (LTmpPos - 1 >= 0) and (LTmpPos <= System.Length(LText)) and
(LText[LTmpPos] = #10) and (LText[LTmpPos - 1] = #13) then
begin
LTmpLength := LTmpLength + 1;
LTmpPos := LTmpPos - 1;
end;
if (TDeleteOption.doCanUndo in Options) and (LTmpLength > 0) then
FActionStack.FragmentDeleted(LTmpPos, Copy(LText, LTmpPos, LTmpLength));
LUpdBegLine := Position.Line;
if Position.Line <= Length(FLinesBegs) - 1 then
LUpdBegChar := FLinesBegs[Position.Line]
else
LUpdBegChar := 1;
with GetLineRealEnd(GetPositionShift(Position, LTmpLength - 1), @LText) do
begin
LUpdEndLine := Line;
LUpdEndChar := Pos;
end;
LOldWidestLineWidth := round(LineWidth[FWidestLineIndex]);
Delete(LText, LTmpPos, LTmpLength);
try
FInternalMustUpdateLines := False;
Text := LText;
finally
FInternalMustUpdateLines := True;
end;
UpdateRngLinesBegs(@LText, LUpdBegLine, LUpdEndLine, LUpdBegChar, LUpdEndChar,
-LTmpLength, LOldWidestLineWidth);
if (TDeleteOption.doMoveCaret in Options) or (SelLength <> 0) then
begin
FSelected := False;
CaretPosition := Position;
end;
if not FInternalUpdating then
Realign;
end;
procedure TMemo.DoUndo(Sender: TObject);
begin
UnDo;
end;
procedure TMemo.UnDo;
begin
FActionStack.RollBackAction;
end;
function TMemo.GetContentBounds: TRectF;
var
S: WideString;
begin
Result := inherited GetContentBounds;
if FWordWrap then
begin
StorePositions;
UpdateLines;
RestorePositions;
end;
if Lines.Count > 0 then
Result.Bottom := Result.Top + (Lines.Count * GetLineHeight);
// Updating Horizontal scrollbar params
if not FWordWrap and FTextService.HasMarkedText and (Length(Lines[CaretPosition.Line] + FTextService.InternalGetMarkedText) > Length(Lines[FWidestLineIndex])) then
begin
S := Lines[CaretPosition.Line];
S := Copy(S, 1, CaretPosition.Pos) + FTextService.InternalGetMarkedText+ Copy(S, CaretPosition.Pos+1, MaxInt);
if not FWordWrap and (TextWidth(S) > (Result.Right - Result.Left)) then
Result.Right := Result.Left + TextWidth(S) + 10;
end
else
begin
if not FWordWrap and (TextWidth(Lines[FWidestLineIndex]) >
(Result.Right - Result.Left)) then
Result.Right := Result.Left + TextWidth(Lines[FWidestLineIndex]) + 10;
end;
// for caret
UpdateHScrlBarByCaretPos;
end;
procedure TMemo.SetLines(const Value: TWideStrings);
begin
FLines.Assign(Value);
end;
function TMemo.TextPosToPos(APos: Integer): TCaretPosition;
var
CurRangeBeg, CurRangeEnd: Integer;
TmpI: Integer;
begin
with Result do
begin
Line := 0;
Pos := 0;
end;
if Lines.Count <= 0 then
Exit;
CurRangeBeg := 0;
CurRangeEnd := Length(FLinesBegs) - 1;
repeat
if ((CurRangeBeg < Length(FLinesBegs) - 1) and
(APos + 1 >= FLinesBegs[CurRangeBeg]) and
(APos + 1 < FLinesBegs[CurRangeBeg + 1])) or
((CurRangeBeg = Length(FLinesBegs) - 1) and
(APos + 1 >= FLinesBegs[CurRangeBeg])) then
CurRangeEnd := CurRangeBeg
else
begin
if APos + 1 < FLinesBegs[CurRangeBeg] then
begin
TmpI := CurRangeEnd - CurRangeBeg + 1;
CurRangeEnd := CurRangeBeg;
CurRangeBeg := CurRangeBeg - TmpI div 2;
end
else if APos + 1 >= FLinesBegs[CurRangeEnd] then
begin
TmpI := CurRangeEnd - CurRangeBeg + 1;
CurRangeBeg := CurRangeEnd;
CurRangeEnd := CurRangeEnd + TmpI div 2;
end
else
CurRangeEnd := (CurRangeBeg + CurRangeEnd) div 2;
if CurRangeBeg < 0 then
CurRangeBeg := 0;
if CurRangeEnd < 0 then
CurRangeEnd := 0;
if CurRangeEnd > Length(FLinesBegs) - 1 then
CurRangeEnd := Length(FLinesBegs) - 1;
if CurRangeBeg > Length(FLinesBegs) - 1 then
CurRangeBeg := Length(FLinesBegs) - 1;
end;
until CurRangeBeg = CurRangeEnd;
Result.Line := CurRangeBeg;
if Result.Line <= Length(FLinesBegs) - 1 then
Result.Pos := APos - FLinesBegs[Result.Line] + 1;
end;
procedure TMemo.MoveCaretLeft;
begin
MoveCareteBy(-1);
end;
procedure TMemo.MoveCaretRight;
begin
MoveCareteBy(1);
end;
procedure TMemo.MoveCareteBy(Delta: Integer);
begin
CaretPosition := GetPositionShift(CaretPosition, Delta);
end;
function TMemo.GetLineHeight: Single;
begin
Result := round(FFont.Size * (1.25));
end;
procedure TMemo.HScrlBarChange(Sender: TObject);
begin
RepaintEdit;
UpdateCaretPosition(False);
end;
procedure TMemo.UpdateVScrlBarByCaretPos;
var
LCaretPosLine: Integer;
begin
if (VScrollBar <> nil) then
begin
LCaretPosLine := CaretPosition.Line;
if (LCaretPosLine + 1) * GetLineHeight > VScrollBarValue + ContentRect.Height then
VScrollBar.Value := (LCaretPosLine + 1) * GetLineHeight - ContentRect.Height;
if LCaretPosLine * GetLineHeight < VScrollBarValue then
VScrollBar.Value := LCaretPosLine * GetLineHeight;
end;
end;
procedure TMemo.SetWordWrap(const Value: Boolean);
begin
if FWordWrap <> Value then
begin
FWordWrap := Value;
UpdateLines;
if not FInternalUpdating then
Realign;
UpdateCaretPosition(False);
end;
end;
procedure TMemo.GetLineBounds(LineIndex: Integer;
var LineBeg, LineLength: Integer);
begin
if Length(FLinesBegs) = 0 then
begin
LineBeg := 1;
LineLength := 0;
Exit;
end;
if (LineIndex <= Length(FLinesBegs) - 1) and (LineIndex >= 0) then
begin
LineBeg := FLinesBegs[LineIndex];
if (LineIndex + 1 < Length(FLinesBegs)) then
LineLength := FLinesBegs[LineIndex + 1] - LineBeg
else
LineLength := Length(Text) - LineBeg + 1;
end
else
begin
LineBeg := 0;
LineLength := 0;
end;
end;
function TMemo.GetLineCount: Integer;
begin
if Text <> '' then
Result := Length(FLinesBegs)
else
Result := 0;
end;
function TMemo.GetLine(Index: Integer): WideString;
begin
Result := GetLineInternal(Index);
if Length(Result) > 0 then
if Result[Length(Result)] = #10 then
Delete(Result, Length(Result), 1);
if Length(Result) > 0 then
if Result[Length(Result)] = #13 then
Delete(Result, Length(Result), 1);
end;
procedure TMemo.InsertLine(Index: Integer; const S: WideString);
var NewS: WideString;
begin
if (Text = '') and (S = '') and (not FEmptyFirstLine) then
FEmptyFirstLine := True
else
begin
if FEmptyFirstLine then
begin
NewS := sLineBreak + S;
FEmptyFirstLine := False;
end
else
NewS := S;
if Index < GetLineCount then
InsertAfter(ComposeCaretPos(Index, 0), NewS + sLineBreak, [])
else if (Index > 0) and (GetLineCount > 0) then
begin
InsertAfter(ComposeCaretPos(Index - 1, Length(GetLineInternal(Index - 1))),
sLineBreak + NewS, [])
end
else
InsertAfter(ComposeCaretPos(Index, 0), NewS, []);
end;
end;
procedure TMemo.DeleteLine(Index: Integer);
begin
if GetLineCount > 0 then
begin
if Index = GetLineCount - 1 then
DeleteFrom(ComposeCaretPos(Index - 1, Length(GetLineInternal(Index - 1))),
Length(GetLineInternal(Index)),
[])
else
DeleteFrom(ComposeCaretPos(Index, 0),
Length(GetLineInternal(Index)),
[]);
end;
end;
procedure TMemo.ClearLines;
begin
Text := '';
if FTextService.Text = '' then
FEmptyFirstLine := False;
end;
procedure TMemo.SelectAtMousePoint;
var
TmpPt: TPointF;
LEdiTRect: TRectF;
begin
LEdiTRect := ContentRect;
TmpPt := FOldMPt;
with TmpPt, LEdiTRect do
begin
if y < Top then
y := Top
else if y > Bottom then
y := Bottom;
if x < Left then
x := Left
else if x > Right then
x := Right;
end;
CaretPosition := GetPointPosition(TmpPt);
SelectAtPos(CaretPosition);
RepaintEdit;
end;
function TMemo.GetPageSize: Single;
begin
with ContentRect do
Result := (Bottom - Top) / GetLineHeight;
end;
procedure TMemo.ResetLineWidthCache;
begin
if Length(FTextWidth) > 0 then
fillchar( FTextWidth[0], Length(FTextWidth) * sizeof(Single), 0);
end;
function TMemo.GetLineWidth(LineNum: Integer): Single;
begin
if (LineNum >= 0) and (LineNum <= Lines.Count - 1) then
begin
if FCachedFillText <> FillTextFlags then
ResetLineWidthCache;
Result := FTextWidth[LineNum];
if Result = 0 then
begin
Result := TextWidth(Lines[LineNum]);
FTextWidth[LineNum] := Result;
end;
end
else
Result := 0;
end;
function TMemo.PosToTextPos(APostion: TCaretPosition): Integer;
var
LTmpLine: Integer;
begin
Result := 0;
if Text = '' then
Exit;
with APostion do
begin
if Line <= Length(FLinesBegs) - 1 then
LTmpLine := Line
else
LTmpLine := Length(FLinesBegs) - 1;
if LTmpLine < 0 then
Exit;
Result := FLinesBegs[LTmpLine];
if Pos <= Length(GetLineInternal(LTmpLine)) then
Result := Result + Pos - 1
else
Result := Result + Length(GetLineInternal(LTmpLine)) - 1;
end;
end;
function TMemo.GetLineInternal(Index: Integer): WideString;
var
LLineBeg, LLineLength: Integer;
begin
GetLineBounds(Index, LLineBeg, LLineLength);
Result := Copy(Text, LLineBeg, LLineLength);
end;
procedure TMemo.GoToTextBegin;
begin
with FCaretPosition do
begin
Line := 0;
Pos := 0;
end;
end;
procedure TMemo.GoToTextEnd;
begin
with FCaretPosition do
begin
Line := Lines.Count - 1;
if Line >= 0 then
Pos := Length(Lines[Line])
else
Pos := 0;
end;
end;
procedure TMemo.GotoLineEnd;
begin
with FCaretPosition do
begin
if Line <= Lines.Count - 1 then
Pos := Length(GetLine(CaretPosition.Line));
end;
end;
procedure TMemo.GoToLineBegin;
begin
with FCaretPosition do
begin
Pos := 0;
end;
end;
function TMemo.GetSelBeg: TCaretPosition;
begin
if FSelStart.Line < FSelEnd.Line then
Result := FSelStart
else if FSelEnd.Line < FSelStart.Line then
Result := FSelEnd
else if FSelStart.Pos < FSelEnd.Pos then
Result := FSelStart
else
Result := FSelEnd;
end;
function TMemo.GetSelEnd: TCaretPosition;
begin
if FSelStart.Line > FSelEnd.Line then
Result := FSelStart
else if FSelEnd.Line > FSelStart.Line then
Result := FSelEnd
else if FSelStart.Pos > FSelEnd.Pos then
Result := FSelStart
else
Result := FSelEnd;
end;
procedure TMemo.SelectAtPos(APos: TCaretPosition);
begin
if not FSelected then
begin
FSelStart := APos;
FSelEnd := APos;
FSelected := True;
end
else
begin
FSelEnd := APos;
end;
end;
function TMemo.GetPositionShift(APos: TCaretPosition; Delta: Integer)
: TCaretPosition;
var
LNewPos: TCaretPosition;
LNewTextPos: Integer;
i: Integer;
CurLineText: WideString;
begin
LNewPos := APos;
with LNewPos do
if Delta >= 14 then
begin
LNewTextPos := PosToTextPos(CaretPosition) + Delta;
if Delta > 0 then
begin
if (LNewTextPos + 1 <= Length(Text)) and (Text[LNewTextPos + 1] = #10)
then
Inc(LNewTextPos);
end
else if Delta < 0 then
begin
if (LNewTextPos + 1 - 1 >= Length(Text)) and
(Text[LNewTextPos + 1 - 1] = #10) then
Dec(LNewTextPos);
end;
LNewPos := TextPosToPos(LNewTextPos);
end
else
begin
CurLineText := GetLineInternal(Line);
if Delta > 0 then
begin
i := 1;
while i <= Delta do
begin
Pos := Pos + 1;
if (Pos + 1 <= Length(CurLineText)) and (CurLineText[Pos + 1] = #10)
then
begin
Inc(Pos);
Inc(i);
end;
if Pos + 1 > Length(CurLineText) then
begin
if Line + 1 <= Lines.Count - 1 then
begin
Line := Line + 1;
CurLineText := GetLineInternal(Line);
Pos := 0;
end
else
Pos := Length(CurLineText);
end;
Inc(i);
end;
end
else
begin { Delta < 0 }
i := 1;
while i <= Abs(Delta) do
begin
if Pos - 1 >= 0 then
Pos := Pos - 1
else
begin
if Line - 1 >= 0 then
begin
Line := Line - 1;
CurLineText := GetLineInternal(Line);
if CurLineText[Length(CurLineText)] = #10 then
Pos := Length(CurLineText) - 2
else
Pos := Length(CurLineText) - 1;
end;
end;
Inc(i);
end;
end;
end;
Result := LNewPos;
end;
procedure TMemo.RestorePositions;
begin
if FOldCaretPos >= 0 then
CaretPosition := TextPosToPos(FOldCaretPos);
if FSelected and (FOldSelStartPos >= 0) then
begin
FSelStart := TextPosToPos(FOldSelStartPos);
FSelEnd := TextPosToPos(FOldSelEndPos);
FOldSelStartPos := -1;
end;
end;
procedure TMemo.StorePositions;
begin
FOldCaretPos := PosToTextPos(CaretPosition);
if FSelected then
begin
FOldSelStartPos := PosToTextPos(FSelStart);
FOldSelEndPos := PosToTextPos(FSelEnd);
end;
end;
procedure TMemo.MoveCaretVertical(LineDelta: Integer);
var
NewLine, NewY, OldX: Integer;
begin
with FCaretPosition do
begin
NewLine := Line + LineDelta;
if NewLine < 0 then
NewLine := 0
else if NewLine > Lines.Count - 1 then
NewLine := Lines.Count - 1;
NewY := round(GetPositionPoint(ComposeCaretPos(NewLine, Pos)).y);
OldX := round(GetPositionPoint(CaretPosition).x);
Line := NewLine;
Pos := round(GetPointPosition(PointF(OldX, NewY)).Pos);
end;
end;
function TMemo.CanObserve(const ID: Integer): Boolean;
begin
Result := False;
if ID = TObserverMapping.EditLinkID then
Result := True;
end;
procedure TMemo.MoveCaretDown;
begin
MoveCaretVertical(1);
end;
procedure TMemo.MoveCaretUp;
begin
MoveCaretVertical(-1);
end;
procedure TMemo.MoveCaretPageDown;
var
ScrollLineNumber: Integer;
begin
ScrollLineNumber := Trunc(GetPageSize);
if ScrollLineNumber < 1 then
ScrollLineNumber := 1;
MoveCaretVertical(ScrollLineNumber);
end;
procedure TMemo.MoveCaretPageUp;
var
ScrollLineNumber: Integer;
begin
ScrollLineNumber := Trunc(GetPageSize);
if ScrollLineNumber < 1 then
ScrollLineNumber := 1;
MoveCaretVertical(-ScrollLineNumber);
end;
function TMemo.GetWidestLine: Integer;
var
i: Integer;
LWidth, LMaxWidth: Single;
begin
Result := -1;
LMaxWidth := -1;
for i := 0 to Lines.Count - 1 do
begin
LWidth := LineWidth[i];
if LWidth > LMaxWidth then
begin
Result := i;
LMaxWidth := LWidth;
end;
end;
end;
function TMemo.GetShowSelection: Boolean;
begin
Result := IsFocused or not HideSelection;
end;
procedure TMemo.MouseWheel(Shift: TShiftState; WheelDelta: Integer;
var Handled: Boolean);
begin
inherited;
if (VScrollBar <> nil) and (VScrollBar.Visible) then
begin
VScrollBar.Value := VScrollBar.Value - (WheelDelta / 30);
end;
end;
function TMemo.GetData: Variant;
begin
Result := Text;
end;
function TMemo.GetKeyboardType: TVirtualKeyboardType;
begin
Result := FKeyboardType;
end;
procedure TMemo.SetData(const Value: Variant);
begin
Text := Value;
end;
procedure TMemo.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
procedure TMemo.SetFontFill(const Value: TBrush);
begin
FFontFill.Assign(Value);
end;
procedure TMemo.SetTextAlign(const Value: TTextAlign);
begin
if FTextAlign <> Value then
begin
FTextAlign := Value;
ResetLineWidthCache;
RepaintEdit;
end;
end;
procedure TMemo.SetUpdateState(Updating: Boolean);
begin
FInternalUpdating := Updating;
if not Updating then
Realign;
end;
function TMemo.GetUnwrapLines: TWideStrings;
begin
if FUnwrapLines = nil then
FUnwrapLines := TWideStringList.Create;
FUnwrapLines.Text := FTextService.Text;
Result := FUnwrapLines;
end;
{ TEditActionStack }
constructor TEditActionStack.Create(AOwner: TMemo);
begin
inherited Create;
FOwner := AOwner;
end;
destructor TEditActionStack.Destroy;
var
TmpItem: PEditAction;
begin
while AtLeast(1) do
begin
TmpItem := Pop;
Finalize(TmpItem^);
FreeMem(TmpItem);
end;
inherited;
end;
procedure TEditActionStack.FragmentDeleted(StartPos: Integer; const Fragment: WideString);
var
TmpItem: PEditAction;
begin
if Fragment = '' then
Exit;
if (not AtLeast(1)) or not((PEditAction(Peek)^.ActionType = TActionType.atDelete) and
(PEditAction(Peek)^.StartPosition - StartPos - Length(Fragment) <= 1) and
(PEditAction(Peek)^.StartPosition - StartPos >= 0)) then
begin
New(TmpItem);
Initialize(TmpItem^);
Push(TmpItem);
with TmpItem^ do
begin
ActionType := TActionType.atDelete;
StartPosition := StartPos;
DeletedFragment := Fragment;
PairedWithPrev := False;
end;
end
else
case PEditAction(Peek)^.ActionType of
TActionType.atDelete:
begin
if StartPos > 0 then
begin
if StartPos < PEditAction(Peek)^.StartPosition then
PEditAction(Peek)^.DeletedFragment := Fragment + PEditAction(Peek)
^.DeletedFragment
else
PEditAction(Peek)^.DeletedFragment := PEditAction(Peek)
^.DeletedFragment + Fragment;
PEditAction(Peek)^.StartPosition := StartPos;
end;
end;
end;
end;
procedure TEditActionStack.FragmentInserted(StartPos, FragmentLength: Integer; IsPairedWithPrev: Boolean);
var
TmpItem: PEditAction;
begin
if FragmentLength = 0 then
Exit;
if (not AtLeast(1)) or not((PEditAction(Peek)^.ActionType = TActionType.atInsert) and
(PEditAction(Peek)^.StartPosition + PEditAction(Peek)^.Length = StartPos))
then
begin
New(TmpItem);
Initialize(TmpItem^);
Push(TmpItem);
with TmpItem^ do
begin
ActionType := TActionType.atInsert;
StartPosition := StartPos;
Length := FragmentLength;
PairedWithPrev := IsPairedWithPrev;
end;
end
else
case PEditAction(Peek)^.ActionType of
TActionType.atInsert:
PEditAction(Peek)^.Length := PEditAction(Peek)^.Length + FragmentLength;
end;
end;
procedure TEditActionStack.CaretMovedBy(Shift: Integer);
begin
end;
function TEditActionStack.RollBackAction: Boolean;
var
TmpItem: PEditAction;
WasPaired: Boolean;
LTmpOptions: TInsertOptions;
begin
Result := AtLeast(1);
if not(Result and Assigned(FOwner)) then
Exit;
repeat
TmpItem := Pop;
with TmpItem^, FOwner do
begin
if DeletedFragment <> sLineBreak then
LTmpOptions := [TInsertOption.ioSelected]
else
LTmpOptions := [];
case ActionType of
TActionType.atDelete:
InsertAfter(TextPosToPos(StartPosition - 1), DeletedFragment,
LTmpOptions + [TInsertOption.ioMoveCaret]
{ DeletedFragment<>#13+#10, True, False, False } );
TActionType.atInsert:
DeleteFrom(TextPosToPos(StartPosition), Length, [TDeleteOption.doMoveCaret]);
end;
end;
WasPaired := TmpItem^.PairedWithPrev;
Finalize(TmpItem^);
Dispose(TmpItem);
until (not AtLeast(1)) or (not WasPaired);
end;
initialization
RegisterFmxClasses([TMemo]);
end.
|
unit uGraphicPrimitive;
interface
uses uBase, uEventModel, Graphics, Windows, uExceptions, uExceptionCodes,
SysUtils, GdiPlus, uDrawingSupport, Classes, System.Generics.Collections;
{$M+}
type
TPrimitiveType = ( ptNone, ptBox ); // примитивы
TPrimitiveDrawMode = ( pdmNormal, pdmIndex ); // режим рисования примитива
TGraphicPrimitiveClass = class of TGraphicPrimitive;
TGraphicPrimitive = class ( TBaseSubscriber )
strict private
FParentPrimitive : TGraphicPrimitive;
FChilds : TObjectList<TGraphicPrimitive>;
FDrawingBox, FIndexDrawingBox : TDrawingBox;
FIndexColor : TColor;
FDrawMode : TPrimitiveDrawMode;
FPoints : TPoints;
FName : string;
FSelected : boolean;
function GetChild(aIndex: integer): TGraphicPrimitive;
function GetChildCount: integer;
function GetbackgroundColor: TColor;
procedure SetBackgroundColor(const Value: TColor);
function GetBorderColor: TColor;
procedure SetBorderColor(const Value: TColor);
function GetBorderWidth: byte;
procedure SetBorderWidth(const Value: byte);
protected
procedure AddChild( const aPrimitive : TGraphicPrimitive );
function GetDrawingBox : TDrawingBox;
procedure Draw( const aGraphics : IGPGraphics ); virtual;
// точки описанного вокруг прямоугольника
function GetTopLeftPoint : TPoint; virtual;
function GetBottomRightPoint : TPoint; virtual;
property NormalDrawingBox : TDrawingBox read FDrawingBox;
public
constructor Create( const aParent : TGraphicPrimitive ); virtual;
destructor Destroy; override;
// рисование
procedure DrawNormal( const aGraphics : IGPGraphics );
procedure DrawIndex( const aGraphics : IGPGraphics );
// работа с патомками
procedure RemoveAllChildren;
procedure DelChild( const aIndex : integer ); overload;
procedure DelChild( const aPrimitive : TGraphicPrimitive ); overload;
// положение
procedure ChangePos( const aNewX, aNewY : integer ); virtual;
procedure InitCoord( const aCenterX, aCenterY : integer ); virtual;
property Child[ aIndex : integer ] : TGraphicPrimitive read GetChild;
property ChildCount : integer read GetChildCount;
// точки
property Points : TPoints read FPoints;
property Parent : TGraphicPrimitive read FParentPrimitive;
property IndexColor : TColor read FIndexColor;
property Selected : boolean read FSelected write FSelected;
// графические свойства примитива
property BackgroundColor : TColor read GetbackgroundColor write SetBackgroundColor;
property BorderColor : TColor read GetBorderColor write SetBorderColor;
property BorderWidth : byte read GetBorderWidth write SetBorderWidth;
published
property Name : string read FName write FName;
end;
TGraphicPrimitives = array of TGraphicPrimitive;
// фон
TBackground = class( TGraphicPrimitive )
protected
procedure Draw( const aGraphics : IGPGraphics ); override;
function GetTopLeftPoint : TPoint; override;
function GetBottomRightPoint : TPoint; override;
published
property BackgroundColor;
end;
TSelectArea = class( TGraphicPrimitive )
protected
procedure Draw( const aGraphics : IGPGraphics ); override;
function GetTopLeftPoint : TPoint; override;
function GetBottomRightPoint : TPoint; override;
public
constructor Create( const aParent : TGraphicPrimitive ); override;
published
property BorderColor;
end;
TBox = class( TGraphicPrimitive )
protected
procedure Draw( const aGraphics : IGPGraphics ); override;
function GetTopLeftPoint : TPoint; override;
function GetBottomRightPoint : TPoint; override;
public
procedure ChangePos( const aNewX, aNewY : integer ); override;
procedure InitCoord( const aCenterX, aCenterY : integer ); override;
published
property BorderColor;
property BackgroundColor;
property BorderWidth;
end;
TBorder = class( TGraphicPrimitive )
protected
procedure Draw( const aGraphics : IGPGraphics ); override;
function GetTopLeftPoint : TPoint; override;
function GetBottomRightPoint : TPoint; override;
end;
implementation
const
SELECT_DASHES_PATTERN : array [0..1] of single = ( 1, 1 );
DEFAULT_WIDTH = 100;
DEFAULT_HEIGHT = 100;
{ TGraphicPrimitive }
procedure TGraphicPrimitive.AddChild(const aPrimitive: TGraphicPrimitive);
begin
if aPrimitive = nil then ContractFailure;
FChilds.Add( aPrimitive );
end;
procedure TGraphicPrimitive.ChangePos(const aNewX, aNewY: integer);
begin
//
end;
constructor TGraphicPrimitive.Create(const aParent: TGraphicPrimitive);
begin
inherited Create;
FChilds := TObjectList<TGraphicPrimitive>.Create;
FParentPrimitive := aParent;
if Assigned( aParent ) then aParent.AddChild( Self ); // Идем на риск
FDrawMode := pdmNormal;
FDrawingBox := TDrawingBox.Create;
FIndexDrawingBox := TDrawingBox.Create;
FIndexColor := GetNextIndexColor;
FIndexDrawingBox.SetColor( FIndexColor );
FPoints := TPoints.Create;
FSelected := false;
FName := '';
end;
procedure TGraphicPrimitive.DelChild(const aPrimitive: TGraphicPrimitive);
var
i : integer;
begin
i := FChilds.IndexOf( aPrimitive );
if i >= 0 then DelChild( i );
end;
procedure TGraphicPrimitive.DelChild(const aIndex: integer);
begin
if ( aIndex < 0 ) or ( aIndex >= FChilds.Count ) then ContractFailure;
FChilds.Delete( aIndex );
end;
destructor TGraphicPrimitive.Destroy;
begin
FreeAndNil( FChilds );
FreeAndNil( FPoints );
inherited;
end;
procedure TGraphicPrimitive.Draw(const aGraphics: IGPGraphics);
begin
//
end;
procedure TGraphicPrimitive.DrawIndex(const aGraphics: IGPGraphics);
begin
FDrawMode := pdmIndex;
Draw( aGraphics );
end;
procedure TGraphicPrimitive.DrawNormal(const aGraphics: IGPGraphics);
begin
FDrawMode := pdmNormal;
Draw( aGraphics );
end;
function TGraphicPrimitive.GetbackgroundColor: TColor;
begin
Result := NormalDrawingBox.BackgroundColor
end;
function TGraphicPrimitive.GetBorderColor: TColor;
begin
Result := NormalDrawingBox.BorderColor
end;
function TGraphicPrimitive.GetBorderWidth: byte;
begin
Result := NormalDrawingBox.BorderWidth
end;
function TGraphicPrimitive.GetBottomRightPoint: TPoint;
begin
//
end;
function TGraphicPrimitive.GetChild(aIndex: integer): TGraphicPrimitive;
begin
if ( aIndex < 0 ) or ( aIndex >= FChilds.Count ) then ContractFailure;
Result := FChilds[ aIndex ];
end;
function TGraphicPrimitive.GetChildCount: integer;
begin
Result := FChilds.Count;
end;
function TGraphicPrimitive.GetDrawingBox: TDrawingBox;
begin
if FDrawMode = pdmNormal then Result := FDrawingBox
else Result := FIndexDrawingBox;
end;
function TGraphicPrimitive.GetTopLeftPoint: TPoint;
begin
//
end;
procedure TGraphicPrimitive.InitCoord(const aCenterX, aCenterY: integer);
begin
//
end;
procedure TGraphicPrimitive.RemoveAllChildren;
begin
FChilds.Clear;
end;
procedure TGraphicPrimitive.SetBackgroundColor(const Value: TColor);
begin
NormalDrawingBox.BackgroundColor := Value;
end;
procedure TGraphicPrimitive.SetBorderColor(const Value: TColor);
begin
NormalDrawingBox.BorderColor := Value;
end;
procedure TGraphicPrimitive.SetBorderWidth(const Value: byte);
begin
NormalDrawingBox.BorderWidth := Value;
end;
{ TBackground }
procedure TBackground.Draw(const aGraphics: IGPGraphics);
var
DBox : TDrawingBox;
PTL, PBR : TPoint;
begin
DBox := GetDrawingBox;
DBox.SolidBrush.Color := GPColor( DBox.BackgroundColor );
PTL := GetTopLeftPoint;
PBR := GetBottomRightPoint;
aGraphics.FillRectangle( DBox.SolidBrush, PTL.X , PTL.Y, PBR.X, PBR.Y );
end;
function TBackground.GetBottomRightPoint: TPoint;
begin
Result := Points.Point[0];
end;
function TBackground.GetTopLeftPoint: TPoint;
begin
Result := TPoint.Create( 0, 0 );
end;
{ TSelect }
constructor TSelectArea.Create(const aParent: TGraphicPrimitive);
begin
inherited;
NormalDrawingBox.Pen.SetDashPattern( SELECT_DASHES_PATTERN );
Points.Add( 0, 0 );
Points.Add( 0, 0 );
end;
procedure TSelectArea.Draw(const aGraphics: IGPGraphics);
var
DBox : TDrawingBox;
X, Y, W, H : integer;
begin
if Points.Count < 2 then ContractFailure;
DBox := GetDrawingBox;
DBox.Pen.Color := GPColor( DBox.BorderColor );
DBox.Pen.Width := 1;
GetXYHW( GetTopLeftPoint, GetBottomRightPoint, true, X, Y, H, W);
aGraphics.DrawRectangle( DBox.Pen, X, Y, W, H );
end;
function TSelectArea.GetBottomRightPoint: TPoint;
begin
Result := Points.Point[1];
end;
function TSelectArea.GetTopLeftPoint: TPoint;
begin
Result := Points.Point[0];
end;
{ TBox }
procedure TBox.ChangePos(const aNewX, aNewY: integer);
var
P : TPoint;
begin
P := Points.Point[0];
P.X := P.X + aNewX;
P.Y := P.Y + aNewY;
Points.Point[0] := P;
P := Points.Point[1];
P.X := P.X + aNewX;
P.Y := P.Y + aNewY;
Points.Point[1] := P;
end;
procedure TBox.Draw( const aGraphics: IGPGraphics );
var
DBox : TDrawingBox;
X, Y, H, W : integer;
begin
DBox := GetDrawingBox;
DBox.Pen.Alignment := PenAlignmentInset;
DBox.Pen.Width := DBox.BorderWidth;
DBox.Pen.Color := GPColor( DBox.BorderColor );
DBox.SolidBrush.Color := GPColor( DBox.BackgroundColor );
GetXYHW( GetTopLeftPoint, GetBottomRightPoint, true, X, Y, H, W );
aGraphics.FillRectangle( DBox.SolidBrush, X, Y, W, H );
aGraphics.DrawRectangle( DBOx.Pen, X, Y, W, H );
end;
function TBox.GetBottomRightPoint: TPoint;
begin
Result := Points.Point[1];
end;
function TBox.GetTopLeftPoint: TPoint;
begin
Result := Points.Point[0];
end;
procedure TBox.InitCoord(const aCenterX, aCenterY: integer);
begin
Points.Clear;
Points.Add( aCenterX - DEFAULT_WIDTH div 2, aCenterY - DEFAULT_HEIGHT div 2 );
Points.Add( aCenterX + DEFAULT_WIDTH div 2, aCenterY + DEFAULT_HEIGHT div 2 );
end;
{ TBorder }
procedure TBorder.Draw(const aGraphics: IGPGraphics);
var
X, Y, H, W : integer;
DBox : TDrawingBox;
begin
GetXYHW( GetTopLeftPoint, GetBottomRightPoint, false, X, Y, H, W );
DBox := GetDrawingBox;
DBox.Pen.Color := GPColor( DBox.BorderColor );
DBox.Pen.Width := 1;
aGraphics.DrawRectangle( DBox.Pen, X - 5, Y - 5, W + 10, H + 10 );
end;
function TBorder.GetBottomRightPoint: TPoint;
begin
Result := Parent.GetBottomRightPoint;
end;
function TBorder.GetTopLeftPoint: TPoint;
begin
Result := Parent.GetTopLeftPoint;
end;
end.
|
unit BrickCamp.Resources.TQuestion;
interface
uses
System.Classes,
System.SysUtils,
system.JSON,
Spring.Container.Common,
Spring.Container,
MARS.Core.Registry,
MARS.Core.Attributes,
MARS.Core.MediaType,
MARS.Core.JSON,
MARS.Core.MessageBodyWriters,
MARS.Core.MessageBodyReaders,
BrickCamp.Repositories.IQuestion,
BrickCamp.Resources.IQuestion,
BrickCamp.Model.IQuestion,
BrickCamp.Model.TQuestion;
type
[Path('/question'), Produces(TMediaType.APPLICATION_JSON_UTF8)]
TQuestionResource = class(TInterfacedObject, IQuestionResurce)
protected
function GetQuestionFromJSON(const Value: TJSONValue): TQuestion;
public
[GET, Path('/getone/{Id}')]
function GetOne(const [PathParam] Id: Integer): TQuestion;
[GET, Path('/getlist/')]
function GetList: TJSONArray;
[POST]
procedure Insert(const [BodyParam] Value: TJSONValue);
[PUT]
procedure Update(const [BodyParam] Value: TJSONValue);
[DELETE, Path('/{Id}')]
procedure Delete(const [PathParam] Id: Integer);
[GET, Path('/getlistbyproductid/{ProductId}')]
function GetListByProductId(const [PathParam] ProductId: Integer): TJSONArray;
end;
implementation
{ THelloWorldResource }
function TQuestionResource.GetQuestionFromJSON(const Value: TJSONValue): TQuestion;
var
JSONObject: TJSONObject;
begin
Result := GlobalContainer.Resolve<TQuestion>;
JSONObject := TJSONObject.ParseJSONValue(Value.ToJSON) as TJSONObject;
try
Result.ProductId := JSONObject.ReadIntegerValue('PRODUCTID', -1);
Result.UserId := JSONObject.ReadIntegerValue('USERID', -1);
Result.Text := JSONObject.ReadStringValue('TEXT', '');
Result.IsOpen := JSONObject.ReadIntegerValue('ISOPEN', -1);
finally
JSONObject.Free;
end;
end;
function TQuestionResource.GetOne(const Id: Integer): TQuestion;
begin
Result := GlobalContainer.Resolve<IQuestionRepository>.GetOne(Id);
end;
procedure TQuestionResource.Delete(const Id: Integer);
begin
GlobalContainer.Resolve<IQuestionRepository>.Delete(Id);
end;
procedure TQuestionResource.Insert(const Value: TJSONValue);
var
Question: TQuestion;
begin
Question := GetQuestionFromJSON(Value);
try
if Assigned(Question) then
GlobalContainer.Resolve<IQuestionRepository>.Insert(Question);
finally
Question.Free;
end;
end;
procedure TQuestionResource.Update(const Value: TJSONValue);
var
Question: TQuestion;
begin
Question := GetQuestionFromJSON(Value);
try
if Assigned(Question) then
GlobalContainer.Resolve<IQuestionRepository>.Update(Question);
finally
Question.Free;
end;
end;
function TQuestionResource.GetList: TJSONArray;
begin
result := GlobalContainer.Resolve<IQuestionRepository>.GetList;
end;
function TQuestionResource.GetListByProductId(const ProductId: Integer): TJSONArray;
begin
Result := GlobalContainer.Resolve<IQuestionRepository>.GetListByProductId(ProductId);
end;
initialization
TMARSResourceRegistry.Instance.RegisterResource<TQuestionResource>;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC InterBase/Firebird driver base classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.IBBase;
interface
uses
System.Types, System.SysUtils, System.Classes, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.SQLGenerator, FireDAC.Phys.IBCli,
FireDAC.Phys.IBWrapper, FireDAC.Phys.IBMeta, FireDAC.Phys.IBDef;
type
TFDPhysIBBaseDriverLink = class;
TFDIBService = class;
TFDIBBackup = class;
TFDIBRestore = class;
TFDIBValidate = class;
TFDIBSecurity = class;
TFDIBConfig = class;
TFDIBInfo = class;
TFDPhysIBDriverBase = class;
TFDPhysIBConnectionBase = class;
TFDPhysIBTransactionBase = class;
TFDPhysIBEventAlerterBase = class;
TFDPhysIBCommandBase = class;
TFDPhysIBCliHandles = array [0..1] of PPointer;
PFDPhysIBCliHandles = ^TFDPhysIBCliHandles;
TFDPhysIBBaseDriverLink = class(TFDPhysDriverLink)
private
FThreadSafe: Boolean;
protected
function IsConfigured: Boolean; override;
procedure ApplyTo(const AParams: IFDStanDefinition); override;
published
property ThreadSafe: Boolean read FThreadSafe write FThreadSafe default False;
end;
TFDIBService = class (TFDPhysDriverService)
private
FConnectTimeout: LongWord;
FQueryTimeout: LongWord;
FProtocol: TIBProtocol;
FPassword: String;
FSEPassword: String;
FHost: String;
FPort: Integer;
FUserName: String;
FOnProgress: TFDPhysServiceProgressEvent;
FSqlRoleName: String;
FInstanceName: String;
function GetDriverLink: TFDPhysIBBaseDriverLink;
procedure SetDriverLink(const AValue: TFDPhysIBBaseDriverLink);
procedure SetHost(const AValue: String);
protected
// TFDPhysDriverService
procedure InternalExecute; override;
// introduced
function CreateService(AEnv: TIBEnv): TIBService; virtual; abstract;
procedure SetupService(AService: TIBService); virtual;
procedure QueryService(AService: TIBService); virtual;
procedure DeleteService(var AService: TIBService); virtual;
procedure DoProgress(AService: TIBService; const AMessage: String); virtual;
// other
function GetConnection(const ADatabase: String): IFDPhysConnection;
function ExecSQL(const ADatabase, ASQL: String): TFDDatSTable; overload;
function ExecSQL(const AConn: IFDPhysConnection; const ASQL: String): TFDDatSTable; overload;
published
property DriverLink: TFDPhysIBBaseDriverLink read GetDriverLink write SetDriverLink;
property Protocol: TIBProtocol read FProtocol write FProtocol default ipLocal;
property Host: String read FHost write SetHost;
property Port: Integer read FPort write FPort default 0;
property InstanceName: String read FInstanceName write FInstanceName;
property UserName: String read FUserName write FUserName;
property Password: String read FPassword write FPassword;
property SqlRoleName: String read FSqlRoleName write FSqlRoleName;
property ConnectTimeout: LongWord read FConnectTimeout write FConnectTimeout default 0;
property QueryTimeout: LongWord read FQueryTimeout write FQueryTimeout default 0;
property OnProgress: TFDPhysServiceProgressEvent read FOnProgress write FOnProgress;
// Interbase encryption
property SEPassword: String read FSEPassword write FSEPassword;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDIBBackup = class (TFDIBService)
private
FMode: TIBBackupMode;
FBackupFiles: TStrings;
FVerbose: Boolean;
FDatabase: String;
FOptions: TIBBackupOptions;
FEncryptKeyName: String;
FStatistics: TIBBackupStatistics;
procedure SetBackupFiles(const AValue: TStrings);
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure SetupService(AService: TIBService); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Backup;
procedure ArchiveDatabase;
procedure ArchiveJournals;
published
property Database: String read FDatabase write FDatabase;
property BackupFiles: TStrings read FBackupFiles write SetBackupFiles;
property Verbose: Boolean read FVerbose write FVerbose default False;
property Options: TIBBackupOptions read FOptions write FOptions default [];
// Interbase encryption
property EncryptKeyName: String read FEncryptKeyName write FEncryptKeyName;
// Firebird 3
property Statistics: TIBBackupStatistics read FStatistics write FStatistics default [];
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDIBRestore = class (TFDIBService)
private
FMode: TIBRestoreMode;
FBackupFiles: TStrings;
FVerbose: Boolean;
FPageSize: LongWord;
FDatabase: String;
FOptions: TIBRestoreOptions;
FPageBuffers: LongWord;
FEUAPassword: String;
FEUAUserName: String;
FFixCharSet: String;
FDecryptPassword: String;
FUntilTimestamp: TDateTime;
FStatistics: TIBBackupStatistics;
procedure SetBackupFiles(const AValue: TStrings);
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure SetupService(AService: TIBService); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Restore;
procedure ArchiveRecover;
published
property Database: String read FDatabase write FDatabase;
property BackupFiles: TStrings read FBackupFiles write SetBackupFiles;
property Verbose: Boolean read FVerbose write FVerbose default False;
property Options: TIBRestoreOptions read FOptions write FOptions default [];
property PageSize: LongWord read FPageSize write FPageSize default 0;
property PageBuffers: LongWord read FPageBuffers write FPageBuffers default 0;
property FixCharSet: String read FFixCharSet write FFixCharSet;
// Interbase encryption
property EUAUserName: String read FEUAUserName write FEUAUserName;
property EUAPassword: String read FEUAPassword write FEUAPassword;
property DecryptPassword: String read FDecryptPassword write FDecryptPassword;
// Interbase point-in-time recovery
property UntilTimestamp: TDateTime read FUntilTimestamp write FUntilTimestamp;
// Firebird 3
property Statistics: TIBBackupStatistics read FStatistics write FStatistics default [];
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDIBValidate = class(TFDIBService)
private
FMode: TIBRepairMode;
FDatabase: String;
FOptions: TIBRepairOptions;
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure SetupService(AService: TIBService); override;
public
procedure CheckOnly;
procedure Repair;
procedure Sweep;
procedure Analyze(const ATable: String = ''; const AIndex: String = '');
published
property Database: String read FDatabase write FDatabase;
property Options: TIBRepairOptions read FOptions write FOptions default [];
end;
TIBEncryptionType = (ecDES, ecAES);
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDIBSecurity = class (TFDIBService)
private
FAction: TIBSecurityAction;
FValues: array [Low(TIBSecurityValue) .. High(TIBSecurityValue)] of String;
FModified: TIBSecurityValues;
FUsers: TFDDatSTable;
FEUADatabase: String;
FKeyName: String;
function GetInt(const AIndex: Integer): Integer;
function GetStr(const AIndex: Integer): String;
procedure SetInt(const AIndex, AValue: Integer);
procedure SetStr(const AIndex: Integer; const AValue: String);
function IsStored(const AIndex: Integer): Boolean;
function GetEUAActive: Boolean;
procedure SetEUAActive(const AValue: Boolean);
function GetDBEncrypted: Boolean;
procedure SetDBEncrypted(const AValue: Boolean);
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure SetupService(AService: TIBService); override;
procedure QueryService(AService: TIBService); override;
procedure DeleteService(var AService: TIBService); override;
public
destructor Destroy; override;
// Users management
procedure AddUser;
procedure DeleteUser;
procedure ModifyUser;
procedure DisplayUser;
procedure DisplayUsers;
property Users: TFDDatSTable read FUsers;
// Interbase encryption
// Basic operations
procedure CreateSYSDSO(const APassword: String);
procedure CreateSEPassword(const APassword: String; AExternal: Boolean);
procedure CreateKey(ADefault: Boolean; AType: TIBEncryptionType;
ALength: Integer; const APassword: String; ARandomVect, ARandomPad: Boolean;
const ADesc: String);
procedure DropKey(ACascade: Boolean);
procedure GrantKey(const AUserName: String);
procedure RevokeKey(const AUserName: String);
procedure EncryptColumn(const ATableName, AColumnName: String);
procedure DecryptColumn(const ATableName, AColumnName: String);
// High level operations
procedure SetEncryption(const ADSOPassword, ASEPassword: String;
AAlwaysUseSEP: Boolean; AType: TIBEncryptionType; ALength: Integer);
procedure RemoveEncryption(const ADSOPassword: String);
procedure ChangeEncryption(const ADSOPassword, ASEPassword,
ANewSEPassword: String; ANewAlwaysUseSEP: Boolean);
property EUAActive: Boolean read GetEUAActive write SetEUAActive;
property DBEncrypted: Boolean read GetDBEncrypted write SetDBEncrypted;
published
property Modified: TIBSecurityValues read FModified write FModified default [];
property AUserName: String index ord(svUserName) read GetStr write SetStr stored IsStored;
property APassword: String index ord(svPassword) read GetStr write SetStr stored IsStored;
property AFirstName: String index ord(svFirstName) read GetStr write SetStr stored IsStored;
property AMiddleName: String index ord(svMiddleName) read GetStr write SetStr stored IsStored;
property ALastName: String index ord(svLastName) read GetStr write SetStr stored IsStored;
property AUserID: Integer index ord(svUserID) read GetInt write SetInt stored IsStored;
property AGroupID: Integer index ord(svGroupID) read GetInt write SetInt stored IsStored;
property AGroupName: String index ord(svGroupName) read GetStr write SetStr stored IsStored;
property ARoleName: String index ord(svRoleName) read GetStr write SetStr stored IsStored;
// Interbase encryption
property EUADatabase: String read FEUADatabase write FEUADatabase;
property KeyName: String read FKeyName write FKeyName;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDIBConfig = class (TFDIBService)
private type
TMode = (cmPageBuffers, cmSQLDialect, cmSweepInterval,
cmReserveSpace, cmWriteMode, cmAccessMode, cmShutdown, cmOnline,
cmActivateShadow, cmArchiveDumps, cmArchiveSweep);
private
FDatabase: String;
FMode: TMode;
FValue: LongWord;
FShutdownMode: TIBShutdownMode;
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure SetupService(AService: TIBService); override;
public
// properties
procedure SetPageBuffers(const AValue: LongWord);
procedure SetSQLDialect(const AValue: LongWord);
procedure SetSweepInterval(const AValue: LongWord);
procedure SetReserveSpace(const AValue: TIBReserveSpace);
procedure SetWriteMode(const AValue: TIBWriteMode);
procedure SetAccessMode(const AValue: TIBAccessMode);
procedure SetArchiveDumps(const AValue: LongWord);
procedure SetArchiveSweep(const AValue: LongWord);
// actions
procedure ShutdownDB(AMode: TIBShutdownMode; ATimeout: LongWord);
procedure OnlineDB;
procedure ActivateShadow;
published
property Database: String read FDatabase write FDatabase;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
/// <summary> This component is responsible for querying InterBase / Firebird
/// service manager. It provides access to server version, license,
/// configuration and usage information. </summary>
TFDIBInfo = class (TFDIBService)
private type
TMode = (imVersion, imLicense, imConfig, imUsage);
private
FMode: TMode;
FpData: Pointer;
protected
function CreateService(AEnv: TIBEnv): TIBService; override;
procedure QueryService(AService: TIBService); override;
public
/// <summary> Returns database server version information. </summary>
procedure GetVersion(out AVersion: TIBInfo.TVersion);
/// <summary> Returns database server license information. </summary>
procedure GetLicense(out ALicenses: TIBInfo.TLicense);
/// <summary> Returns database server configuration information. </summary>
procedure GetConfig(out AConfig: TIBInfo.TConfig);
/// <summary> Returns database server usage information. </summary>
procedure GetUsage(out AUsage: TIBInfo.TUsage);
end;
TFDPhysIBDriverBase = class(TFDPhysDriver)
protected
FLib: TIBLib;
procedure InternalUnload; override;
function GetThreadSafe: Boolean;
function GetCliObj: Pointer; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
end;
TFDPhysIBConnectionBase = class(TFDPhysConnection)
private
FEnv: TIBEnv;
FDatabase: TIBDatabase;
FServerVersion: TFDVersion;
FServerBrand: TFDPhysIBBrand;
FDialect: Word;
FGUIDEndian: TEndian;
FCliHandles: TFDPhysIBCliHandles;
FSharedTxHandle: isc_tr_handle;
FMetaTransaction: IFDPhysTransaction;
FExtendedMetadata: Boolean;
protected
procedure InternalConnect; override;
procedure InternalDisconnect; override;
procedure InternalPing; override;
function InternalCreateTransaction: TFDPhysTransaction; override;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateMetaInfoCommand: TFDPhysCommand; override;
function InternalCreateMetadata: TObject; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; override;
{$ENDIF}
procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override;
procedure GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override;
function GetItemCount: Integer; override;
function GetMessages: EFDDBEngineException; override;
function GetCliObj: Pointer; override;
function InternalGetCliHandle: Pointer; override;
procedure InternalAnalyzeSession(AMessages: TStrings); override;
procedure BuildIBConnectParams(AParams: TStrings;
const AConnectionDef: IFDStanConnectionDef); virtual;
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
destructor Destroy; override;
property IBEnv: TIBEnv read FEnv;
property IBDatabase: TIBDatabase read FDatabase;
property ServerVersion: TFDVersion read FServerVersion;
property ServerBrand: TFDPhysIBBrand read FServerBrand;
end;
TFDPhysIBTransactionBase = class(TFDPhysTransaction)
private
FParams: TStrings;
FTransaction: TIBTransaction;
function GetIBConnection: TFDPhysIBConnectionBase;
protected
// IFDMoniAdapter
function GetItemCount: Integer; override;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); override;
// TFDPhysTransaction
procedure InternalStartTransaction(AID: LongWord); override;
procedure InternalCommit(AID: LongWord); override;
procedure InternalRollback(AID: LongWord); override;
procedure InternalChanged; override;
procedure InternalAllocHandle; override;
procedure InternalReleaseHandle; override;
procedure InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand); override;
function GetCliObj: Pointer; override;
public
property IBConnection: TFDPhysIBConnectionBase read GetIBConnection;
property IBTransaction: TIBTransaction read FTransaction;
end;
TFDPhysIBEventAlerterBase = class(TFDPhysEventAlerter)
private
FEvents: TIBEvents;
FEventsConnection: IFDPhysConnection;
procedure DoFired(AEvents: TIBEvents; ABaseIndex: Integer;
const ACounts: TISCEventCounts);
protected
// TFDPhysEventAlerter
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalUnregister; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
PFDIBColInfoRec = ^TFDIBColInfoRec;
TFDIBColInfoRec = record
FVar: TIBVariable;
FName: String;
FOriginTabName,
FOriginColName: String;
FPos: Integer;
FLen,
FPrec,
FScale: SmallInt;
FSrcSQLDataType,
FSrcSQLSubType: SmallInt;
FSrcDataType,
FDestDataType: TFDDataType;
FSrcTypeName: String;
FAttrs: TFDDataAttributes;
FFDLen: LongWord;
FInPK: Boolean;
FItemInfos: array of TFDIBColInfoRec;
end;
PFDIBParInfoRec = ^TFDIBParInfoRec;
TFDIBParInfoRec = record
FVar: TIBVariable;
FParamIndex: Integer;
FLen,
FPrec,
FScale: SmallInt;
FDestSQLDataType,
FDestSQLSubType: SmallInt;
FDestDataType,
FSrcDataType: TFDDataType;
FDestTypeName: String;
FFDLen: LongWord;
FSrcFieldType: TFieldType;
FSrcSize: LongWord;
FSrcPrec: Integer;
FSrcScale: Integer;
FParamType: TParamType;
end;
TFDPhysIBCommandBase = class(TFDPhysCommand)
private
FColumnIndex: Integer;
FCurrentArrInfo: PFDIBColInfoRec;
FSPParsedName: TFDPhysParsedName;
FCursorCanceled: Boolean;
FMaxInputPos: Integer;
FRetWithOut: Boolean;
function GetConnection: TFDPhysIBConnectionBase; inline;
procedure CreateColInfos;
procedure DestroyColInfos;
procedure CreateParamInfos(AVars: TIBVariables; AInput, AFB2Batch: Boolean);
procedure DestroyParamInfos;
procedure SQL2FDDataType(ASQLDataType, ASQLSubType, ASQLLen, ASQLPrec,
ASQLScale: Smallint; out AType: TFDDataType; var AAttrs: TFDDataAttributes;
out ALen: LongWord; out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions);
procedure FD2SQLDataType(AType: TFDDataType; ALen: LongWord; APrec,
AScale: Integer; out ASQLDataType, ASQLSubType, ASQLLen, ASQLPrec,
ASQLScale: Smallint; AFmtOpts: TFDFormatOptions);
procedure FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
function UseExecDirect: Boolean;
function IsReturning: Boolean;
procedure CheckColInfos;
procedure PrepareBase;
protected
FStmt: TIBStatement;
FColInfos: array of TFDIBColInfoRec;
FParInfos: array of TFDIBParInfoRec;
FHasIntStreams: Boolean;
// TFDPhysCommand
procedure InternalAbort; override;
procedure InternalClose; override;
function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord; override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
function InternalNextRecordSet: Boolean; override;
procedure InternalPrepare; override;
function InternalUseStandardMetadata: Boolean; override;
function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override;
function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override;
procedure InternalCloseStreams; override;
procedure InternalUnprepare; override;
function GetCliObj: Pointer; override;
function GetItemCount: Integer; override;
procedure GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override;
// introduced
procedure ProcessColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions;
AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer;
var AUpdates: TIBUpdateStatus); virtual;
procedure ProcessMetaColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions;
AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer); virtual;
function CharLenInBytes: Boolean; virtual;
// other
procedure SetupStatement(AStmt: TIBStatement);
procedure CheckSPPrepared(ASPUsage: TFDPhysCommandKind);
procedure CheckParamInfos;
procedure DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter;
AFlush: Boolean);
procedure SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
AVar: TIBVariable; ApInfo: PFDIBParInfoRec; AVarIndex, AParIndex: Integer);
procedure GetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
AVar: TIBVariable; ApInfo: PFDIBParInfoRec; AVarIndex,
AParIndex: Integer);
procedure SetParamValues(ATimes, AOffset: Integer);
procedure GetParamValues(ATimes, AOffset: Integer);
public
property IBConnection: TFDPhysIBConnectionBase read GetConnection;
property IBStatement: TIBStatement read FStmt;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.Variants, System.Generics.Collections, System.Math,
FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Stan.ResStrs;
const
S_FD_UTF8 = 'UTF8';
S_FD_UnicodeFSS = 'UNICODE_FSS';
S_FD_CharacterSets = 'NONE;ASCII;BIG_5;CYRL;DOS437;DOS850;DOS852;DOS857;' +
'DOS860;DOS861;DOS863;DOS865;EUCJ_0208;GB_2312;ISO8859_1;' +
'ISO8859_2;KSC_5601;NEXT;OCTETS;SJIS_0208;' + S_FD_UnicodeFSS + ';' +
'WIN1250;WIN1251;WIN1252;WIN1253;WIN1254;' +
// FB 1.5
'DOS737;DOS775;DOS858;DOS862;DOS864;DOS866;DOS869;' +
'WIN1255;WIN1256;WIN1257;ISO8859_3;ISO8859_4;ISO8859_5;' +
'ISO8859_6;ISO8859_7;ISO8859_8;ISO8859_9;ISO8859_13;' +
// IB 7.1
'ISO8859_15;' +
// FB 2.0
'KOI8R;KOI8U;' + S_FD_UTF8 + ';' +
// IB 2007
'UNICODE_LE;UNICODE_BE';
S_FD_Local = 'Local';
S_FD_NetBEUI = 'NetBEUI';
S_FD_NovelSPX = 'SPX';
S_FD_TCPIP = 'TCPIP';
S_FD_Open = 'Open';
S_FD_Create = 'Create';
S_FD_OpenCreate = 'OpenOrCreate';
{-------------------------------------------------------------------------------}
{ TFDPhysIBBaseDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysIBBaseDriverLink.IsConfigured: Boolean;
begin
Result := inherited IsConfigured or ThreadSafe;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBBaseDriverLink.ApplyTo(const AParams: IFDStanDefinition);
begin
inherited ApplyTo(AParams);
if ThreadSafe then
AParams.AsBoolean[S_FD_ConnParam_IB_ThreadSafe] := ThreadSafe;
end;
{-------------------------------------------------------------------------------}
{ TFDIBService }
{-------------------------------------------------------------------------------}
function TFDIBService.GetDriverLink: TFDPhysIBBaseDriverLink;
begin
Result := inherited DriverLink as TFDPhysIBBaseDriverLink;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.SetDriverLink(const AValue: TFDPhysIBBaseDriverLink);
begin
inherited DriverLink := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.SetHost(const AValue: String);
begin
if FHost <> AValue then begin
FHost := AValue;
if (FHost <> '') and (Protocol = ipLocal) then
Protocol := ipTCPIP;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.SetupService(AService: TIBService);
begin
AService.Protocol := Protocol;
AService.Host := Host;
AService.Port := Port;
AService.InstanceName := InstanceName;
AService.UserName := UserName;
AService.Password := Password;
AService.SEPassword := SEPassword;
AService.SqlRoleName := SqlRoleName;
AService.ConnectTimeout := ConnectTimeout;
AService.QueryTimeout := QueryTimeout;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.DeleteService(var AService: TIBService);
begin
FDFree(AService);
AService := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.DoProgress(AService: TIBService; const AMessage: String);
begin
if Assigned(FOnProgress) then
FOnProgress(Self, AMessage);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.QueryService(AService: TIBService);
var
sMsg: String;
begin
while not AService.QueryString(sMsg) do
DoProgress(AService, sMsg);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBService.InternalExecute;
var
oEnv: TIBEnv;
oSvc: TIBService;
begin
oEnv := TIBEnv.Create(CliObj as TIBLib, Self);
oSvc := CreateService(oEnv);
try
SetupService(oSvc);
oSvc.Attach;
try
oSvc.Start;
QueryService(oSvc);
finally
oSvc.Detach;
end;
finally
DeleteService(oSvc);
FDFree(oEnv);
end;
end;
{-------------------------------------------------------------------------------}
function TFDIBService.GetConnection(const ADatabase: String): IFDPhysConnection;
const
C_Prots: array [TIBProtocol] of String = (S_FD_Local, S_FD_TCPIP, S_FD_NetBEUI, S_FD_NovelSPX);
var
sConnStr: String;
procedure Add(const AParam, AValue: String);
begin
if AValue <> '' then begin
if sConnStr <> '' then
sConnStr := sConnStr + ';';
sConnStr := sConnStr + AParam + '=' + AValue;
end;
end;
begin
Add(S_FD_ConnParam_Common_DriverID, DriverLink.ActualDriverID);
Add(S_FD_ConnParam_IB_Protocol, C_Prots[Protocol]);
Add(S_FD_ConnParam_Common_Server, Host);
if Port <> 0 then
Add(S_FD_ConnParam_Common_Port, IntToStr(Port));
Add(S_FD_ConnParam_IB_InstanceName, InstanceName);
Add(S_FD_ConnParam_Common_UserName, UserName);
Add(S_FD_ConnParam_Common_Password, Password);
Add(S_FD_ConnParam_IB_SEPassword, SEPassword);
Add(S_FD_ConnParam_Common_Database, FDExpandStr(ADatabase));
Add(S_FD_ConnParam_IB_SQLDialect, '3');
FDPhysManager.CreateConnection(sConnStr, Result);
Result.ErrorHandler := Self as IFDStanErrorHandler;
Result.Open;
Result.Options.ResourceOptions.CmdExecMode := amBlocking;
Result.Options.ResourceOptions.PreprocessCmdText := False;
end;
{-------------------------------------------------------------------------------}
function TFDIBService.ExecSQL(const AConn: IFDPhysConnection; const ASQL: String): TFDDatSTable;
var
oCmd: IFDPhysCommand;
begin
AConn.CreateCommand(oCmd);
oCmd.CommandText := ASQL;
oCmd.Prepare;
if oCmd.CommandKind in [skSelect, skSelectForLock, skSelectForUnLock, skStoredProcWithCrs] then begin
Result := oCmd.Define();
oCmd.Open();
oCmd.Fetch(Result, True);
end
else begin
Result := nil;
oCmd.Execute;
end;
end;
{-------------------------------------------------------------------------------}
function TFDIBService.ExecSQL(const ADatabase, ASQL: String): TFDDatSTable;
var
oConn: IFDPhysConnection;
begin
oConn := GetConnection(ADatabase);
Result := ExecSQL(oConn, ASQL);
end;
{-------------------------------------------------------------------------------}
{ TFDIBBackup }
{-------------------------------------------------------------------------------}
constructor TFDIBBackup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBackupFiles := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDIBBackup.Destroy;
begin
FDFreeAndNil(FBackupFiles);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBBackup.SetBackupFiles(const AValue: TStrings);
begin
FBackupFiles.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDIBBackup.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBBackup.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBBackup.SetupService(AService: TIBService);
begin
inherited SetupService(AService);
TIBBackup(AService).Mode := FMode;
TIBBackup(AService).DatabaseName := FDExpandStr(Database);
TIBBackup(AService).BackupFiles := BackupFiles;
FDExpandStrs(TIBBackup(AService).BackupFiles);
TIBBackup(AService).Verbose := Verbose;
TIBBackup(AService).Options := Options;
TIBBackup(AService).EncryptKeyName := EncryptKeyName;
TIBBackup(AService).Statistics := Statistics;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBBackup.Backup;
begin
FMode := bmBackup;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBBackup.ArchiveDatabase;
begin
FMode := bmArchiveDatabase;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBBackup.ArchiveJournals;
begin
FMode := bmArchiveJournals;
Execute;
end;
{-------------------------------------------------------------------------------}
{ TFDIBRestore }
{-------------------------------------------------------------------------------}
constructor TFDIBRestore.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBackupFiles := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDIBRestore.Destroy;
begin
FDFreeAndNil(FBackupFiles);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBRestore.SetBackupFiles(const AValue: TStrings);
begin
FBackupFiles.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDIBRestore.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBRestore.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBRestore.SetupService(AService: TIBService);
begin
inherited SetupService(AService);
TIBRestore(AService).Mode := FMode;
TIBRestore(AService).DatabaseName := FDExpandStr(Database);
TIBRestore(AService).BackupFiles := BackupFiles;
FDExpandStrs(TIBRestore(AService).BackupFiles);
TIBRestore(AService).Verbose := Verbose;
TIBRestore(AService).Options := Options;
TIBRestore(AService).FixCharSet := FixCharSet;
TIBRestore(AService).PageSize := PageSize;
TIBRestore(AService).PageBuffers := PageBuffers;
TIBRestore(AService).EUAUserName := EUAUserName;
TIBRestore(AService).EUAPassword := EUAPassword;
TIBRestore(AService).DecryptPassword := DecryptPassword;
TIBRestore(AService).UntilTimestamp := UntilTimestamp;
TIBRestore(AService).Statistics := Statistics;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBRestore.Restore;
begin
FMode := rmRestore;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBRestore.ArchiveRecover;
begin
FMode := rmArchiveRecover;
Execute;
end;
{-------------------------------------------------------------------------------}
{ TFDIBValidate }
{-------------------------------------------------------------------------------}
function TFDIBValidate.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBRepair.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBValidate.SetupService(AService: TIBService);
begin
inherited SetupService(AService);
TIBRepair(AService).DatabaseName := FDExpandStr(Database);
TIBRepair(AService).Mode := FMode;
TIBRepair(AService).Options := Options;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBValidate.CheckOnly;
begin
FMode := rmCheckOnly;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBValidate.Repair;
begin
FMode := rmRepair;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBValidate.Sweep;
begin
FMode := rmSweep;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBValidate.Analyze(const ATable, AIndex: String);
var
oTab: TFDDatSTable;
oConn: IFDPhysConnection;
i: Integer;
sIndex: String;
begin
DoBeforeExecute;
CheckActive(False, False);
if AIndex <> '' then begin
ExecSQL(Database, 'SET STATISTICS INDEX ' + AIndex);
DoProgress(nil, Format(S_FD_IBBIndexProg, [AIndex]));
end
else begin
oConn := GetConnection(Database);
if ATable <> '' then
oTab := ExecSQL(oConn, 'SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$RELATION_NAME = ''' + ATable + '''')
else
oTab := ExecSQL(oConn, 'SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$RELATION_NAME NOT LIKE ''RDB$%''');
try
for i := 0 to oTab.Rows.Count - 1 do begin
sIndex := oTab.Rows[i].GetData(0);
ExecSQL(oConn, 'SET STATISTICS INDEX "' + sIndex + '"');
DoProgress(nil, Format(S_FD_IBBIndexProg, [sIndex]));
end;
finally
FDFree(oTab);
end;
end;
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
{ TFDIBSecurity }
{-------------------------------------------------------------------------------}
destructor TFDIBSecurity.Destroy;
begin
if FUsers <> nil then
FUsers.RemRef;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.GetInt(const AIndex: Integer): Integer;
begin
Result := StrToIntDef(GetStr(AIndex), 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetInt(const AIndex, AValue: Integer);
begin
SetStr(AIndex, IntToStr(AValue));
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.GetStr(const AIndex: Integer): String;
begin
Result := FValues[TIBSecurityValue(AIndex)];
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetStr(const AIndex: Integer; const AValue: String);
begin
Include(FModified, TIBSecurityValue(AIndex));
FValues[TIBSecurityValue(AIndex)] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.IsStored(const AIndex: Integer): Boolean;
begin
Result := TIBSecurityValue(AIndex) in FModified;
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBSecurity.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetupService(AService: TIBService);
var
i: TIBSecurityValue;
begin
inherited SetupService(AService);
TIBSecurity(AService).Action := FAction;
TIBSecurity(AService).EUADatabase := FDExpandStr(EUADatabase);
TIBSecurity(AService).Modified := [];
for i := Low(TIBSecurityValue) to High(TIBSecurityValue) do
if i in Modified then
TIBSecurity(AService).SetStr(Integer(i), FValues[i]);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.QueryService(AService: TIBService);
begin
if TIBSecurity(AService).Action in [saDisplayUser, saDisplayUsers] then
TIBSecurity(AService).QuerySecurity
else
inherited QueryService(AService);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DeleteService(var AService: TIBService);
var
i: TIBSecurityValue;
begin
case TIBSecurity(AService).Action of
saDisplayUser:
begin
for i := Low(TIBSecurityValue) to High(TIBSecurityValue) do
SetStr(Integer(i), TIBSecurity(AService).GetStr(Integer(i)));
Modified := [];
end;
saDisplayUsers:
begin
if FUsers <> nil then
FUsers.RemRef;
FUsers := TIBSecurity(AService).Users;
if FUsers <> nil then
FUsers.AddRef;
end;
end;
inherited DeleteService(AService);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.AddUser;
begin
FAction := saAddUser;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DeleteUser;
begin
FAction := saDeleteUser;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.ModifyUser;
begin
FAction := saModifyUser;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DisplayUser;
begin
FAction := saDisplayUser;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DisplayUsers;
begin
FAction := saDisplayUsers;
Execute;
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.GetEUAActive: Boolean;
var
oConn: IFDPhysConnection;
begin
DoBeforeExecute;
CheckActive(False, False);
oConn := GetConnection(EUADatabase);
Result := TIBDatabase(oConn.CliObj).db_eua_active <> 0;
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetEUAActive(const AValue: Boolean);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'ALTER DATABASE';
if AValue then
sSQL := sSQL + ' ADD ADMIN OPTION'
else
sSQL := sSQL + ' DROP ADMIN OPTION';
ExecSQL(EUADatabase, sSQL);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
function TFDIBSecurity.GetDBEncrypted: Boolean;
var
oConn: IFDPhysConnection;
begin
oConn := GetConnection(EUADatabase);
Result := TIBDatabase(oConn.CliObj).db_encrypted <> 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetDBEncrypted(const AValue: Boolean);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'ALTER DATABASE';
if AValue then begin
sSQL := sSQL + ' ENCRYPT';
if KeyName <> '' then
sSQL := sSQL + ' WITH ' + KeyName;
end
else
sSQL := sSQL + ' DECRYPT';
ExecSQL(EUADatabase, sSQL);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.CreateSYSDSO(const APassword: String);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'CREATE USER SYSDSO';
if APassword <> '' then
sSQL := sSQL + ' SET PASSWORD ' + QuotedStr(APassword);
ExecSQL(EUADatabase, sSQL);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.CreateSEPassword(const APassword: String; AExternal: Boolean);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'ALTER DATABASE SET';
if APassword = '' then
sSQL := sSQL + ' NO SYSTEM ENCRYPTION PASSWORD'
else begin
sSQL := sSQL + ' SYSTEM ENCRYPTION PASSWORD ' + QuotedStr(APassword);
if AExternal then
sSQL := sSQL + ' EXTERNAL';
end;
ExecSQL(EUADatabase, sSQL);
SEPassword := APassword;
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.CreateKey(ADefault: Boolean; AType: TIBEncryptionType;
ALength: Integer; const APassword: String; ARandomVect, ARandomPad: Boolean;
const ADesc: String);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'CREATE ENCRYPTION ' + KeyName;
if ADefault then
sSQL := sSQL + ' AS DEFAULT';
if AType = ecDES then
sSQL := sSQL + ' FOR DES'
else
sSQL := sSQL + ' FOR AES';
if ALength <> 0 then
sSQL := sSQL + ' WITH LENGTH ' + IntToStr(ALength);
if APassword <> '' then
sSQL := sSQL + ' PASSWORD ' + QuotedStr(APassword);
if ARandomVect then
sSQL := sSQL + ' INIT_VECTOR RANDOM';
if ARandomPad then
sSQL := sSQL + ' PAD RANDOM';
if ADesc <> '' then
sSQL := sSQL + ' DESCRIPTION ' + QuotedStr(ADesc);
ExecSQL(EUADatabase, sSQL);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DropKey(ACascade: Boolean);
var
sSQL: String;
begin
DoBeforeExecute;
CheckActive(False, False);
sSQL := 'DROP ENCRYPTION ' + KeyName;
if ACascade then
sSQL := sSQL + ' CASCADE';
ExecSQL(EUADatabase, sSQL);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.GrantKey(const AUserName: String);
begin
DoBeforeExecute;
CheckActive(False, False);
ExecSQL(EUADatabase, 'GRANT ENCRYPT ON ENCRYPTION ' + KeyName +
' TO ' + AUserName);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.RevokeKey(const AUserName: String);
begin
DoBeforeExecute;
CheckActive(False, False);
ExecSQL(EUADatabase, 'REVOKE ENCRYPT ON ENCRYPTION ' + KeyName +
' FROM ' + AUserName);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.EncryptColumn(const ATableName, AColumnName: String);
begin
DoBeforeExecute;
CheckActive(False, False);
ExecSQL(EUADatabase, 'ALTER TABLE ' + ATableName + ' ALTER COLUMN ' +
AColumnName + ' ENCRYPT WITH ' + KeyName);
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.DecryptColumn(const ATableName, AColumnName: String);
begin
DoBeforeExecute;
CheckActive(False, False);
ExecSQL(EUADatabase, 'ALTER TABLE ' + ATableName + ' ALTER COLUMN ' +
AColumnName + ' DECRYPT');
DoAfterExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.SetEncryption(const ADSOPassword, ASEPassword: String;
AAlwaysUseSEP: Boolean; AType: TIBEncryptionType; ALength: Integer);
var
sPrevUser, sPrevPwd: String;
begin
sPrevUser := UserName;
sPrevPwd := Password;
try
// 1. Ensure that Embedded User Authentication (EUA) is enabled
if EUAActive = False then
EUAActive := True;
// 2. Create a System Database Security Owner (SYSDSO) account
CreateSYSDSO(ADSOPassword);
// -- login as SYSDSO
UserName := 'sysdso';
Password := ADSOPassword;
// 3. Create a System Encryption Password (SEP)
// and set SEPassword to ASEPassword
CreateSEPassword(ASEPassword, AAlwaysUseSEP);
// 4. Create an encryption key for the database
CreateKey(True, AType, ALength, '', True, True, '');
// 5. Grant the database owner privileges to use key
GrantKey(sPrevUser);
finally
// -- login as SYSDBA
UserName := sPrevUser;
Password := sPrevPwd;
end;
// 6. Encrypt the database
DBEncrypted := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.RemoveEncryption(const ADSOPassword: String);
var
sPrevUser, sPrevPwd: String;
begin
// 1. Unencrypt the database
DBEncrypted := False;
sPrevUser := UserName;
sPrevPwd := Password;
try
// -- login as SYSDSO
UserName := 'sysdso';
Password := ADSOPassword;
// 2. Drop encryption key
DropKey(True);
// 3. Remove a System Encryption Password (SEP)
CreateSEPassword('', False);
finally
// -- login as SYSDBA
UserName := sPrevUser;
Password := sPrevPwd;
end;
// 4. Drop a System Database Security Owner (SYSDSO) account
ExecSQL(EUADatabase, 'DROP USER SYSDSO');
// 5. Turn off Embedded User Authentication (EUA)
EUAActive := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBSecurity.ChangeEncryption(const ADSOPassword, ASEPassword: String;
const ANewSEPassword: String; ANewAlwaysUseSEP: Boolean);
var
sPrevUser, sPrevPwd: String;
begin
sPrevUser := UserName;
sPrevPwd := Password;
try
// -- login as SYSDSO
UserName := 'sysdso';
Password := ADSOPassword;
SEPassword := ASEPassword;
// Create a System Encryption Password (SEP)
// and set SEPassword to ASEPassword
CreateSEPassword(ANewSEPassword, ANewAlwaysUseSEP);
finally
// -- login as SYSDBA
UserName := sPrevUser;
Password := sPrevPwd;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDIBConfig }
{-------------------------------------------------------------------------------}
function TFDIBConfig.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBConfig.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetupService(AService: TIBService);
begin
inherited SetupService(AService);
TIBConfig(AService).DatabaseName := FDExpandStr(Database);
case FMode of
cmPageBuffers: TIBConfig(AService).SetPageBuffers(FValue);
cmSQLDialect: TIBConfig(AService).SetSQLDialect(FValue);
cmSweepInterval: TIBConfig(AService).SetSweepInterval(FValue);
cmReserveSpace: TIBConfig(AService).SetReserveSpace(TIBReserveSpace(FValue));
cmWriteMode: TIBConfig(AService).SetWriteMode(TIBWriteMode(FValue));
cmAccessMode: TIBConfig(AService).SetAccessMode(TIBAccessMode(FValue));
cmArchiveDumps: TIBConfig(AService).SetArchiveDumps(FValue);
cmArchiveSweep: TIBConfig(AService).SetArchiveSweep(FValue);
cmShutdown: TIBConfig(AService).ShutdownDB(FShutdownMode, FValue);
cmOnline: TIBConfig(AService).OnlineDB;
cmActivateShadow: TIBConfig(AService).ActivateShadow;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetAccessMode(const AValue: TIBAccessMode);
begin
FMode := cmAccessMode;
FValue := LongWord(AValue);
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetPageBuffers(const AValue: LongWord);
begin
FMode := cmPageBuffers;
FValue := AValue;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetReserveSpace(const AValue: TIBReserveSpace);
begin
FMode := cmReserveSpace;
FValue := LongWord(AValue);
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetSQLDialect(const AValue: LongWord);
begin
FMode := cmSQLDialect;
FValue := AValue;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetSweepInterval(const AValue: LongWord);
begin
FMode := cmSweepInterval;
FValue := AValue;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetWriteMode(const AValue: TIBWriteMode);
begin
FMode := cmWriteMode;
FValue := LongWord(AValue);
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetArchiveDumps(const AValue: LongWord);
begin
FMode := cmArchiveDumps;
FValue := AValue;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.SetArchiveSweep(const AValue: LongWord);
begin
FMode := cmArchiveSweep;
FValue := AValue;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.ShutdownDB(AMode: TIBShutdownMode; ATimeout: LongWord);
begin
FMode := cmShutdown;
FShutdownMode := AMode;
FValue := ATimeout;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.OnlineDB;
begin
FMode := cmOnline;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBConfig.ActivateShadow;
begin
FMode := cmActivateShadow;
Execute;
end;
{-------------------------------------------------------------------------------}
{ TFDIBInfo }
{-------------------------------------------------------------------------------}
function TFDIBInfo.CreateService(AEnv: TIBEnv): TIBService;
begin
Result := TIBInfo.Create(AEnv, Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDIBInfo.QueryService(AService: TIBService);
begin
case FMode of
imVersion: TIBInfo(AService).GetVersion(TIBInfo.TVersion(FpData^));
imLicense: TIBInfo(AService).GetLicense(TIBInfo.TLicense(FpData^));
imConfig: TIBInfo(AService).GetConfig(TIBInfo.TConfig(FpData^));
imUsage: TIBInfo(AService).GetUsage(TIBInfo.TUsage(FpData^));
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBInfo.GetVersion(out AVersion: TIBInfo.TVersion);
begin
FMode := imVersion;
FpData := @AVersion;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBInfo.GetLicense(out ALicenses: TIBInfo.TLicense);
begin
FMode := imLicense;
FpData := @ALicenses;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBInfo.GetConfig(out AConfig: TIBInfo.TConfig);
begin
FMode := imConfig;
FpData := @AConfig;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDIBInfo.GetUsage(out AUsage: TIBInfo.TUsage);
begin
FMode := imUsage;
FpData := @AUsage;
Execute;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBDriverBase }
{-------------------------------------------------------------------------------}
constructor TFDPhysIBDriverBase.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FLib := TIBLib.Create(GetBaseDriverID, FDPhysManagerObj);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysIBDriverBase.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FLib);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBDriverBase.InternalUnload;
begin
FLib.Unload;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBDriverBase.GetThreadSafe: Boolean;
begin
Result := (Params <> nil) and Params.AsBoolean[S_FD_ConnParam_IB_ThreadSafe];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBDriverBase.GetCliObj: Pointer;
begin
Result := FLib;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBDriverBase.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 2);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', '', S_FD_ConnParam_Common_OSAuthent, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_Protocol, S_FD_Local + ';' + S_FD_TCPIP + ';' + S_FD_NetBEUI + ';' + S_FD_NovelSPX, S_FD_Local, S_FD_ConnParam_IB_Protocol, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, '@S', '', S_FD_ConnParam_Common_Server, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', '', S_FD_ConnParam_Common_Port, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_SQLDialect, '@I', '3', S_FD_ConnParam_IB_SQLDialect, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_RoleName, '@S', '', S_FD_ConnParam_IB_RoleName, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, S_FD_CharacterSets, 'NONE', S_FD_ConnParam_Common_CharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_GUIDEndian, S_FD_Little + ';' + S_FD_Big, S_FD_Little, S_FD_ConnParam_Common_GUIDEndian, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ExtendedMetadata, '@L', S_FD_False, S_FD_ConnParam_Common_ExtendedMetadata, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_OpenMode, S_FD_Open + ';' + S_FD_Create + ';' + S_FD_OpenCreate, S_FD_Open, S_FD_ConnParam_IB_OpenMode, -1]);
if (AKeys <> nil) and (
(CompareText(AKeys.Values[S_FD_ConnParam_IB_OpenMode], S_FD_Create) = 0) or
(CompareText(AKeys.Values[S_FD_ConnParam_IB_OpenMode], S_FD_OpenCreate) = 0)) then begin
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_PageSize, '1024;2048;4096;8192;16384', '4096', S_FD_ConnParam_IB_PageSize, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_DropDatabase, '@Y', S_FD_No, S_FD_ConnParam_IB_DropDatabase, -1]);
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_IBAdvanced, '@S', '', S_FD_ConnParam_IB_IBAdvanced, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBConnectionBase }
{-------------------------------------------------------------------------------}
constructor TFDPhysIBConnectionBase.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
var
oOpts: TFDTxOptions;
begin
FEnv := TIBEnv.Create(TFDPhysIBDriverBase(ADriverObj).FLib, Self);
inherited Create(ADriverObj, AConnHost);
CreateTransaction(FMetaTransaction);
_Release;
oOpts := FMetaTransaction.Options;
oOpts.AutoCommit := True;
oOpts.ReadOnly := True;
oOpts.Isolation := xiReadCommitted;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysIBConnectionBase.Destroy;
begin
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
ForceDisconnect;
_AddRef;
FMetaTransaction := nil;
FDFreeAndNil(FEnv);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalCreateTransaction: TFDPhysTransaction;
begin
Result := TFDPhysIBTransactionBase.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_IB_Events) = 0 then
Result := TFDPhysIBEventAlerterBase.Create(Self, AEventKind)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalCreateMetaInfoCommand: TFDPhysCommand;
begin
Result := inherited InternalCreateMetaInfoCommand;
TFDPhysIBCommandBase(Result).SetTransaction(FMetaTransaction);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysIBCommandGenerator.Create(ACommand,
FEnv.Lib.IDUTF8, FDatabase.Encoder.Encoding)
else
Result := TFDPhysIBCommandGenerator.Create(Self,
FEnv.Lib.IDUTF8, FDatabase.Encoder.Encoding);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalCreateMetadata: TObject;
begin
Result := TFDPhysIBMetadata.Create(Self, FEnv.Lib.Brand, ServerVersion,
FEnv.Lib.Version, FDialect,
(FDatabase <> nil) and (FDatabase.Encoder.Encoding in [ecUTF8, ecUTF16]));
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalTracingChanged;
begin
if FEnv <> nil then begin
FEnv.Monitor := FMonitor;
FEnv.Tracing := FTracing;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.BuildIBConnectParams(AParams: TStrings;
const AConnectionDef: IFDStanConnectionDef);
var
oParams: TFDPhysIBConnectionDefParams;
i: Integer;
sAdv: String;
sCharSet: String;
begin
oParams := TFDPhysIBConnectionDefParams(ConnectionDef.Params);
i := 1;
sAdv := oParams.IBAdvanced;
while i <= Length(sAdv) do
AParams.Add(FDExtractFieldName(sAdv, i));
if oParams.OSAuthent then
AParams.Add('trusted_auth')
else begin
if ConnectionDef.HasValue(S_FD_ConnParam_Common_UserName) then
AParams.Add('user_name=' + oParams.UserName);
if ConnectionDef.HasValue(S_FD_ConnParam_Common_Password) then
AParams.Add('password=' + oParams.Password);
end;
if ConnectionDef.HasValue(S_FD_ConnParam_IB_RoleName) then
AParams.Add('sql_role_name=' + oParams.RoleName);
sCharSet := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if (sCharSet <> '') and (CompareText(sCharSet, 'none') <> 0) then
AParams.Add('lc_ctype=' + sCharSet);
if ConnectionDef.HasValue(S_FD_ConnParam_IB_PageSize) then
AParams.Add('page_size=' + ConnectionDef.AsString[S_FD_ConnParam_IB_PageSize]);
AParams.Add('sql_dialect=' + IntToStr(FDialect));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalConnect;
var
oParams: TFDPhysIBConnectionDefParams;
oIBParams: TFDStringList;
sCharSet: String;
pCliHandles: PFDPhysIBCliHandles;
i: Integer;
oStrs: TStrings;
sDB, sSrv: String;
eProto: TIBProtocol;
function GetInstance(const APrefix: String): String;
begin
if ConnectionDef.HasValue(S_FD_ConnParam_Common_Port) then
Result := APrefix + IntToStr(oParams.Port)
else if ConnectionDef.HasValue(S_FD_ConnParam_IB_InstanceName) then
Result := APrefix + oParams.InstanceName
else
Result := '';
end;
begin
oParams := TFDPhysIBConnectionDefParams(ConnectionDef.Params);
if InternalGetSharedCliHandle() <> nil then begin
pCliHandles := PFDPhysIBCliHandles(InternalGetSharedCliHandle());
FDatabase := TIBDatabase.CreateUsingHandle(FEnv, pCliHandles^[0], Self);
FSharedTxHandle := pCliHandles^[1];
end
else begin
FDatabase := TIBDatabase.Create(FEnv, Self);
FSharedTxHandle := nil;
end;
{$IFDEF FireDAC_MONITOR}
InternalTracingChanged;
{$ENDIF}
sCharSet := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if (CompareText(sCharSet, S_FD_UTF8) = 0) or (CompareText(sCharSet, S_FD_UnicodeFSS) = 0) then
FDatabase.Encoder.Encoding := ecUTF8
else
FDatabase.Encoder.Encoding := ecANSI;
FExtendedMetadata := oParams.ExtendedMetadata;
FDialect := Word(oParams.SQLDialect);
FGUIDEndian := oParams.GUIDEndian;
sDB := oParams.ExpandedDatabase;
sSrv := oParams.Server;
if ConnectionDef.HasValue(S_FD_ConnParam_IB_Protocol) or (sSrv <> '') then begin
eProto := oParams.Protocol;
if eProto = ipNetBEUI then
sDB := '\\' + sSrv + GetInstance('@') + '\' + sDB
else if eProto = ipSPX then
sDB := sSrv + '@' + sDB
else if (eProto = ipTCPIP) or (sSrv <> '') then
sDB := sSrv + GetInstance('/') + ':' + sDB
else if (eProto = ipLocal) and
(FEnv.Lib.Brand = ibFirebird) and (FEnv.Lib.Version >= ivFB030000) and not FEnv.Lib.FEmbedded then
{$IFDEF MSWINDOWS}
sDB := 'xnet://' + sDB
{$ENDIF}
{$IFDEF POSIX}
sDB := 'inet://' + sDB
{$ENDIF}
;
end;
if InternalGetSharedCliHandle() = nil then begin
oIBParams := TFDStringList.Create;
try
BuildIBConnectParams(oIBParams, ConnectionDef);
case oParams.OpenMode of
omOpen:
FDatabase.Attach(sDB, oIBParams, False);
omCreate:
FDatabase.CreateDatabase(sDB, oIBParams);
omOpenOrCreate:
if not FDatabase.Attach(sDB, oIBParams, True) then
FDatabase.CreateDatabase(sDB, oIBParams);
end;
finally
FDFree(oIBParams);
end;
end;
if FEnv.Lib.Brand in [ibFirebird, ibYaffil] then
oStrs := FDatabase.firebird_version
else
oStrs := FDatabase.isc_version;
if oStrs.Count >= 2 then
i := 1
else
i := 0;
FServerVersion := FDVerStr2Int(oStrs[i]);
if Pos('Firebird', oStrs[i]) > 0 then
FServerBrand := ibFirebird
else if (Pos('Interbase', oStrs[i]) > 0) or
(Pos('WI-V', oStrs[i]) > 0) or
(Pos('LI-V', oStrs[i]) > 0) or
(Pos('DW-V', oStrs[i]) > 0) or
(Pos('SO-V', oStrs[i]) > 0) or
(Pos('WE-V', oStrs[i]) > 0) or
(Pos('DE-V', oStrs[i]) > 0) or
(Pos('IO-V', oStrs[i]) > 0) or
(Pos('AA-V', oStrs[i]) > 0) then
FServerBrand := ibInterbase
else
FServerBrand := ibYaffil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalDisconnect;
begin
if ConnectionDef.AsYesNo[S_FD_ConnParam_IB_DropDatabase] then
FDatabase.Drop;
FDFreeAndNil(FDatabase);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalPing;
begin
FDatabase.Ping;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalExecuteDirect(const ASQL: String;
ATransaction: TFDPhysTransaction);
var
oStmt: TIBStatement;
oTX: TIBTransaction;
lCommit: Boolean;
begin
oTX := TFDPhysIBTransactionBase(ATransaction).IBTransaction;
lCommit := oTX.FTRHandle = nil;
if lCommit then
oTX.StartTransaction;
try
oStmt := TIBStatement.Create(FDatabase, oTX, Self);
try
oStmt.InVars.VarCount := 0;
oStmt.ExecuteImmediate(ASQL);
finally
FDFree(oStmt);
end;
finally
if lCommit then
oTX.Commit;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if FEnv <> nil then begin
Inc(Result, 3);
if (FDatabase <> nil) and (FDatabase.FDBHandle <> nil) then
Inc(Result, 1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else
case AIndex - inherited GetItemCount of
0:
begin
AName := 'Brand';
case FEnv.Lib.Brand of
ibInterbase: AValue := 'InterBase';
ibFirebird: AValue := 'Firebird';
ibYaffil: AValue := 'Yaffil';
end;
AKind := ikClientInfo;
end;
1:
begin
AName := 'Client version';
AValue := Integer(FEnv.Lib.Version);
AKind := ikClientInfo;
end;
2:
begin
AName := 'Client DLL name';
AValue := FEnv.Lib.DLLName;
AKind := ikClientInfo;
end;
3:
begin
AName := 'Server version';
if FEnv.Lib.Brand in [ibFirebird, ibYaffil] then
AValue := AdjustLineBreaks(FDatabase.firebird_version.Text, tlbsCRLF)
else
AValue := AdjustLineBreaks(FDatabase.isc_version.Text, tlbsCRLF);
AKind := ikSessionInfo;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.GetMessages: EFDDBEngineException;
begin
if FEnv <> nil then
Result := FEnv.Error.Info
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.GetCliObj: Pointer;
begin
Result := FDatabase;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBConnectionBase.InternalGetCliHandle: Pointer;
begin
if FDatabase <> nil then begin
FCliHandles[0] := FDatabase.FDBHandle;
FCliHandles[1] := TFDPhysIBTransactionBase(TransactionObj).FTransaction.FTRHandle;
Result := @FCliHandles;
end
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBConnectionBase.InternalAnalyzeSession(AMessages: TStrings);
begin
inherited InternalAnalyzeSession(AMessages);
// 2. Use FB client for FB server, and IB client for IB server
if (ServerBrand = ibFirebird) and (FEnv.Lib.Brand = ibInterbase) then
AMessages.Add(S_FD_IBBWarnGDSFB)
else if (ServerBrand = ibInterbase) and (FEnv.Lib.Brand = ibFirebird) then
AMessages.Add(S_FD_IBBWarnFBCIB);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBTransactionBase }
{-------------------------------------------------------------------------------}
function TFDPhysIBTransactionBase.GetIBConnection: TFDPhysIBConnectionBase;
begin
Result := TFDPhysIBConnectionBase(ConnectionObj);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalAllocHandle;
begin
FParams := TFDStringList.Create;
if IBConnection.FSharedTxHandle <> nil then begin
FTransaction := TIBTransaction.CreateUsingHandle(IBConnection.FEnv,
IBConnection.FSharedTxHandle, Self);
IBConnection.FSharedTxHandle := nil;
end
else
FTransaction := TIBTransaction.Create(IBConnection.FEnv, Self);
FTransaction.AddDatabase(IBConnection.FDatabase);
InternalChanged;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalReleaseHandle;
begin
FDFreeAndNil(FParams);
if FTransaction <> nil then begin
FTransaction.RemoveDatabase(IBConnection.FDatabase);
FDFreeAndNil(FTransaction);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalChanged;
var
i, j: Integer;
oCustom, oParams: TStrings;
begin
oParams := FTransaction.Params;
oParams.BeginUpdate;
try
oParams.Clear;
oCustom := GetOptions.Params;
if (oCustom.IndexOf('read') = -1) and (oCustom.IndexOf('write') = -1) then
if GetOptions.ReadOnly then
oParams.Add('read')
else
oParams.Add('write');
if (oCustom.IndexOf('read_committed') = -1) and (oCustom.IndexOf('rec_version') = -1) and
(oCustom.IndexOf('concurrency') = -1) and (oCustom.IndexOf('consistency') = -1) then
case GetOptions.Isolation of
xiUnspecified:
;
xiDirtyRead,
xiReadCommitted:
begin
oParams.Add('read_committed');
oParams.Add('rec_version');
end;
xiRepeatableRead,
xiSnapshot:
oParams.Add('concurrency');
xiSerializible:
oParams.Add('consistency');
end;
if (oCustom.IndexOf('wait') = -1) and (oCustom.IndexOf('nowait') = -1) then
if IBConnection.GetOptions.UpdateOptions.LockWait then
oParams.Add('wait')
else
oParams.Add('nowait');
for i := 0 to oCustom.Count - 1 do begin
j := oParams.IndexOfName(oCustom.KeyNames[i]);
if j = -1 then
j := oParams.IndexOf(oCustom[i]);
if j = -1 then
oParams.Add(oCustom[i])
else
oParams.Strings[j] := oCustom[i];
end;
finally
oParams.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalStartTransaction(AID: LongWord);
begin
FTransaction.StartTransaction();
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalCommit(AID: LongWord);
begin
if Retaining then
FTransaction.CommitRetaining()
else begin
DisconnectCommands(nil, dmOffline);
FTransaction.Commit();
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalRollback(AID: LongWord);
begin
if Retaining then
FTransaction.RollbackRetaining()
else begin
DisconnectCommands(nil, dmOffline);
FTransaction.Rollback();
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBTransactionBase.GetCliObj: Pointer;
begin
Result := FTransaction;
end;
{-------------------------------------------------------------------------------}
function DisconnectionBeforeStart(ACmdObj: TObject): Boolean;
var
oCmd: TFDPhysIBCommandBase;
begin
oCmd := TFDPhysIBCommandBase(TIBStatement(ACmdObj).OwningObj);
Result := not ((oCmd.GetCommandKind in [skCommit, skRollback]) and
(oCmd.GetState = csExecuting));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
begin
if ANotification = cpAfterCmdPrepareSuccess then
Exit;
ConnectionObj.Lock;
try
case ANotification of
cpBeforeCmdPrepare:
if not (TFDPhysIBCommandBase(ACommandObj).GetCommandKind in [skStartTransaction, skCommit, skRollback]) then
if GetOptions.AutoStart and not GetActive then begin
StartTransaction;
FIDAutoCommit := GetSerialID;
end;
cpBeforeCmdExecute:
if TFDPhysIBCommandBase(ACommandObj).GetCommandKind in [skCommit, skRollback] then
DisconnectCommands(DisconnectionBeforeStart, dmOffline);
cpAfterCmdPrepareFailure,
cpAfterCmdUnprepare,
cpAfterCmdExecuteSuccess,
cpAfterCmdExecuteFailure:
if not (TFDPhysIBCommandBase(ACommandObj).GetCommandKind in [skStartTransaction, skCommit, skRollback]) then begin
if GetOptions.AutoStop and GetActive and
(not (xoIfAutoStarted in GetOptions.StopOptions) or
(FIDAutoCommit <> 0) and (FIDAutoCommit = GetSerialID)) then
// allowunprepare, force, success
CheckStoping(not (ANotification in [cpAfterCmdUnprepare, cpAfterCmdPrepareFailure]),
not (xoIfCmdsInactive in GetOptions.StopOptions),
not (ANotification in [cpAfterCmdPrepareFailure, cpAfterCmdExecuteFailure]));
end
else if ANotification = cpAfterCmdExecuteSuccess then
InternalCheckState(ACommandObj, True);
end;
finally
ConnectionObj.UnLock;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBTransactionBase.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if FTransaction <> nil then
Inc(Result);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBTransactionBase.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else
case AIndex - inherited GetItemCount of
0:
begin
AName := '@Params';
AValue := FTransaction.Params.Text;
AKind := ikSQL;
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysIBEventMessage = class(TFDPhysEventMessage)
private
FBaseIndex: Integer;
FCounts: TISCEventCounts;
public
constructor Create(ABaseIndex: Integer; const ACounts: TISCEventCounts);
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysIBEventMessage.Create(ABaseIndex: Integer;
const ACounts: TISCEventCounts);
begin
inherited Create;
FBaseIndex := ABaseIndex;
FCounts := ACounts;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBEventAlerterBase }
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalAllocHandle;
begin
FEventsConnection := GetConnection.Clone;
if FEventsConnection.State = csDisconnected then
FEventsConnection.Open;
FEvents := TIBEvents.Create(TIBDatabase(FEventsConnection.CliObj), Self);
FEvents.Names.SetStrings(GetNames);
FEvents.OnFired := DoFired;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.DoFired(AEvents: TIBEvents; ABaseIndex: Integer;
const ACounts: TISCEventCounts);
begin
if IsRunning then
FMsgThread.EnqueueMsg(TFDPhysIBEventMessage.Create(ABaseIndex, ACounts));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
i, iFrom, iTo: Integer;
begin
iFrom := TFDPhysIBEventMessage(AEventMessage).FBaseIndex;
iTo := iFrom + 15 - 1;
if iTo >= GetNames.Count then
iTo := GetNames.Count - 1;
for i := iFrom to iTo do
if TFDPhysIBEventMessage(AEventMessage).FCounts[i - iFrom] <> 0 then
InternalHandleEvent(GetNames[i],
TFDPhysIBEventMessage(AEventMessage).FCounts[i - iFrom]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalRegister;
begin
FEvents.Start;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalUnregister;
begin
FEvents.Stop;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalReleaseHandle;
begin
FDFreeAndNil(FEvents);
FEventsConnection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBEventAlerterBase.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oCmd: IFDPhysCommand;
begin
if TFDPhysIBConnectionBase(ConnectionObj).FEnv.Lib.Brand <> ibFirebird then
FDCapabilityNotSupported(Self, [S_FD_LPhys, ConnectionObj.DriverID]);
GetConnection.CreateCommand(oCmd);
SetupCommand(oCmd);
oCmd.Prepare('EXECUTE BLOCK AS BEGIN POST_EVENT ' + QuotedStr(AEvent) + '; END');
oCmd.Execute();
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBCommandBase }
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.GetConnection: TFDPhysIBConnectionBase;
begin
Result := TFDPhysIBConnectionBase(FConnectionObj);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.GetCliObj: Pointer;
begin
Result := IBStatement;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.CharLenInBytes: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.SetupStatement(AStmt: TIBStatement);
var
oFmtOpts: TFDFormatOptions;
begin
oFmtOpts := FOptions.FormatOptions;
if GetMetaInfoKind <> mkNone then begin
AStmt.StrsTrim := True;
AStmt.StrsEmpty2Null := True;
AStmt.StrsTrim2Len := False;
AStmt.GUIDEndian := Little;
end
else begin
AStmt.StrsTrim := oFmtOpts.StrsTrim;
AStmt.StrsEmpty2Null := oFmtOpts.StrsEmpty2Null;
AStmt.StrsTrim2Len := oFmtOpts.StrsTrim2Len;
AStmt.GUIDEndian := IBConnection.FGUIDEndian;
end;
AStmt.Dialect := IBConnection.FDialect;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.SQL2FDDataType(ASQLDataType, ASQLSubType, ASQLLen,
ASQLPrec, ASQLScale: Smallint; out AType: TFDDataType; var AAttrs: TFDDataAttributes;
out ALen: LongWord; out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions);
begin
AType := dtUnknown;
ALen := 0;
APrec := 0;
AScale := 0;
Exclude(AAttrs, caFixedLen);
Exclude(AAttrs, caBlobData);
Include(AAttrs, caSearchable);
case ASQLDataType of
SQL_TEXT,
SQL_VARYING,
SQL_NULL:
if LongWord(ASQLLen) <= AFmtOpts.MaxStringSize then begin
if ASQLSubType = csIDOctets then begin
AType := dtByteString;
ALen := ASQLLen;
end
else if IBConnection.FEnv.Lib.IsUTF8(ASQLSubType) then begin
AType := dtWideString;
// Workaround for InterBase describing the SELECT item:
// select ('abc' || 'de') from "Region" where RegionID=1
// as SQLSubType = 59, and SQLLen = 5 instead of 5 * 4
if not CharLenInBytes() then
ALen := ASQLLen div IBConnection.FEnv.Lib.GetBytesPerChar(ASQLSubType)
else
ALen := ASQLLen;
if (ALen = 0) and (ASQLLen > 0) then
ALen := 1;
end
else begin
AType := dtAnsiString;
ALen := ASQLLen div SizeOf(TFDAnsiChar);
end;
if (ASQLDataType = SQL_TEXT) or (ASQLDataType = SQL_NULL) then
Include(AAttrs, caFixedLen);
end
else begin
if ASQLSubType = csIDOctets then
AType := dtBlob
else if IBConnection.FDatabase.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo;
Include(AAttrs, caBlobData);
end;
SQL_SHORT:
if ASQLScale = 0 then
AType := dtInt16
else begin
APrec := 4;
AScale := -ASQLScale;
if AScale <= 4 then
AType := dtCurrency
else if AFmtOpts.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
SQL_LONG:
if ASQLScale = 0 then
AType := dtInt32
else begin
APrec := 9;
AScale := -ASQLScale;
if AScale <= 4 then
AType := dtCurrency
else if AFmtOpts.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
SQL_INT64,
SQL_QUAD:
if ASQLScale = 0 then
AType := dtInt64
else begin
APrec := 18;
AScale := -ASQLScale;
if AFmtOpts.IsFmtBcd(APrec, AScale) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
SQL_FLOAT:
begin
AType := dtSingle;
APrec := 8;
end;
SQL_DOUBLE,
SQL_D_FLOAT:
begin
AType := dtDouble;
APrec := 16;
end;
SQL_TIMESTAMP:
AType := dtDateTimeStamp;
SQL_TYPE_TIME:
AType := dtTime;
SQL_TYPE_DATE:
AType := dtDate;
SQL_BOOLEAN_IB,
SQL_BOOLEAN_FB:
AType := dtBoolean;
SQL_BLOB:
begin
if ASQLSubType = isc_blob_text then
if IBConnection.FDatabase.Encoder.Encoding = ecUTF8 then
AType := dtWideMemo
else
AType := dtMemo
else
AType := dtBlob;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_ARRAY:
begin
AType := dtArrayRef;
Exclude(AAttrs, caSearchable);
end;
else
AType := dtUnknown;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.FD2SQLDataType(AType: TFDDataType;
ALen: LongWord; APrec, AScale: Integer; out ASQLDataType, ASQLSubType,
ASQLLen, ASQLPrec, ASQLScale: Smallint; AFmtOpts: TFDFormatOptions);
begin
ASQLSubType := 0;
ASQLPrec := 0;
ASQLScale := 0;
case AType of
dtSByte,
dtInt16,
dtByte:
ASQLDataType := SQL_SHORT;
dtInt32,
dtUInt16:
ASQLDataType := SQL_LONG;
dtInt64,
dtUInt32,
dtUInt64:
ASQLDataType := SQL_INT64;
dtSingle:
ASQLDataType := SQL_FLOAT;
dtDouble,
dtExtended:
ASQLDataType := SQL_DOUBLE;
dtCurrency:
begin
ASQLDataType := SQL_INT64;
ASQLPrec := 18;
ASQLScale := -4;
end;
dtBCD,
dtFmtBCD:
begin
ASQLDataType := SQL_INT64;
if APrec = 0 then
APrec := AFmtOpts.MaxBcdPrecision;
if AScale = 0 then
AScale := AFmtOpts.MaxBcdScale;
ASQLPrec := APrec;
ASQLScale := -AScale;
end;
dtDateTime,
dtDateTimeStamp:
ASQLDataType := SQL_TIMESTAMP;
dtTime:
ASQLDataType := SQL_TYPE_TIME;
dtDate:
ASQLDataType := SQL_TYPE_DATE;
dtAnsiString:
begin
ASQLDataType := SQL_VARYING;
ASQLSubType := csIDNone;
end;
dtWideString:
begin
ASQLDataType := SQL_VARYING;
ASQLSubType := csIDUnicodeFSS;
end;
dtByteString:
begin
ASQLDataType := SQL_VARYING;
ASQLSubType := csIDOctets;
end;
dtBlob,
dtHBlob,
dtHBFile:
begin
ASQLDataType := SQL_BLOB;
ASQLSubType := isc_blob_untyped;
end;
dtMemo,
dtHMemo,
dtWideMemo,
dtXML,
dtWideHMemo:
begin
ASQLDataType := SQL_BLOB;
ASQLSubType := isc_blob_text;
end;
dtGUID:
begin
ASQLDataType := SQL_VARYING;
ASQLSubType := csIDNone;
ALen := 38;
end;
dtBoolean:
if IBConnection.FEnv.Lib.Brand = ibInterbase then
ASQLDataType := SQL_BOOLEAN_IB
else
ASQLDataType := SQL_BOOLEAN_FB;
dtArrayRef:
ASQLDataType := SQL_ARRAY;
else
ASQLDataType := 0;
end;
ASQLLen := TIBVariable.GetDataTypeSize(ASQLDataType, ALen);
if ASQLDataType = SQL_VARYING then
Dec(ASQLLen, SizeOf(ISC_USHORT));
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.CreateColInfos;
var
i, j, k: Integer;
oVar: TIBVariable;
oFmtOpts: TFDFormatOptions;
oFetchOpts: TFDFetchOptions;
iPrec, iScale: Integer;
oTabs: TFDStringList;
sTableNames: String;
lGetDSInfo: Boolean;
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
pColInfo, pItemInfo: PFDIBColInfoRec;
oRow: TFDDatSRow;
oArr: TIBArray;
begin
oFmtOpts := FOptions.FormatOptions;
oFetchOpts := FOptions.FetchOptions;
sTableNames := '';
oTabs := nil;
lGetDSInfo := (GetMetaInfoKind = mkNone) and (fiMeta in oFetchOpts.Items) and
IBConnection.FExtendedMetadata;
SetLength(FColInfos, FStmt.OutVars.VarCount);
for i := 0 to Length(FColInfos) - 1 do begin
oVar := FStmt.OutVars[i];
pColInfo := @FColInfos[i];
pColInfo^.FVar := oVar;
pColInfo^.FName := oVar.aliasname;
pColInfo^.FOriginTabName := oVar.relname;
if pColInfo^.FOriginTabName <> '' then
pColInfo^.FOriginColName := oVar.sqlname;
pColInfo^.FPos := i + 1;
if lGetDSInfo and (pColInfo^.FOriginTabName <> '') and
(pColInfo^.FOriginColName <> '') then begin
// If there is only a single table, then GetSelectMetaInfo will use a
// parameter to substitute a table name. So, oTabs must be unquoted.
// Otherwise - oTabs must be a list of quoted table names. And will
// be concatenated with the mkResultSetFields SQL query.
if oTabs = nil then
oTabs := TFDStringList.Create(dupIgnore, True, False);
if oTabs.IndexOf(pColInfo^.FOriginTabName) = -1 then
oTabs.Add(pColInfo^.FOriginTabName);
end;
pColInfo^.FLen := oVar.sqllen;
pColInfo^.FPrec := oVar.sqlprecision;
pColInfo^.FScale := oVar.sqlscale;
pColInfo^.FSrcSQLDataType := oVar.SQLDataType;
pColInfo^.FSrcSQLSubType := oVar.sqlsubtype;
pColInfo^.FAttrs := [];
pColInfo^.FInPK := False;
if oVar.IsNullable then
Include(pColInfo^.FAttrs, caAllowNull);
if CompareText(pColInfo^.FOriginColName, 'DB_KEY') = 0 then
pColInfo^.FOriginColName := 'RDB$DB_KEY';
if CompareText(pColInfo^.FOriginColName, 'RDB$DB_KEY') = 0 then begin
Include(pColInfo^.FAttrs, caROWID);
Include(pColInfo^.FAttrs, caAllowNull);
end;
SQL2FDDataType(pColInfo^.FSrcSQLDataType, pColInfo^.FSrcSQLSubType,
pColInfo^.FLen, pColInfo^.FPrec, pColInfo^.FScale, pColInfo^.FSrcDataType,
pColInfo^.FAttrs, pColInfo^.FFDLen, iPrec, iScale, oFmtOpts);
pColInfo^.FPrec := iPrec;
pColInfo^.FScale := iScale;
if pColInfo^.FSrcSQLDataType = SQL_ARRAY then begin
oArr := TIBArray.Create(IBConnection.FDatabase,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
oArr.RelationName := oVar.relname;
oArr.FieldName := oVar.sqlname;
oArr.Lookup;
pColInfo^.FSrcTypeName := pColInfo^.FOriginTabName + '.' + pColInfo^.FOriginColName;
pColInfo^.FFDLen := oArr.TotalCount;
SetLength(pColInfo^.FItemInfos, 1);
pItemInfo := @pColInfo^.FItemInfos[0];
pItemInfo^.FAttrs := pColInfo^.FAttrs;
SQL2FDDataType(oArr.sqltype, oArr.sqlsubtype, oArr.sqllen, 0, oArr.sqlscale,
pItemInfo^.FSrcDataType, pItemInfo^.FAttrs, pItemInfo^.FFDLen, iPrec,
iScale, oFmtOpts);
pItemInfo^.FSrcSQLDataType := oArr.sqltype;
pItemInfo^.FSrcSQLSubType := oArr.sqlsubtype;
pItemInfo^.FLen := oArr.sqllen;
pItemInfo^.FPrec := iPrec;
pItemInfo^.FScale := iScale;
pItemInfo^.FDestDataType := pItemInfo^.FSrcDataType;
pItemInfo^.FAttrs := pItemInfo^.FAttrs - [caSearchable] + [caAllowNull];
finally
FDFree(oArr);
end;
end;
end;
if lGetDSInfo and (oTabs <> nil) and (oTabs.Count > 0) then begin
GetConnection.CreateMetadata(oConnMeta);
if oTabs.Count = 1 then
sTableNames := oTabs[0]
else
for k := 0 to oTabs.Count - 1 do begin
if sTableNames <> '' then
sTableNames := sTableNames + ', ';
sTableNames := sTableNames + QuotedStr(oTabs[k]);
end;
FDFree(oTabs);
oView := oConnMeta.GetResultSetFields(sTableNames);
try
for i := 0 to Length(FColInfos) - 1 do begin
pColInfo := @FColInfos[i];
if (pColInfo^.FOriginTabName <> '') and
(pColInfo^.FOriginColName <> '') and
(pColInfo^.FSrcSQLDataType <> SQL_ARRAY) then begin
j := oView.Find([pColInfo^.FOriginTabName, pColInfo^.FOriginColName],
'TABLE_NAME;COLUMN_NAME', []);
if j <> -1 then begin
oRow := oView.Rows[j];
pColInfo^.FSrcTypeName := AnsiUpperCase(oRow.AsString['DOMAIN_NAME']);
if StrLComp(PChar(pColInfo^.FSrcTypeName), PChar('RDB$'), 4) = 0 then
pColInfo^.FSrcTypeName := '';
if Pos('BOOL', pColInfo^.FSrcTypeName) <> 0 then
pColInfo^.FDestDataType := dtBoolean
else if Pos('GUID', pColInfo^.FSrcTypeName) <> 0 then
pColInfo^.FDestDataType := dtGUID;
if not VarIsNull(oRow.ValueS['IN_PKEY']) then
pColInfo^.FInPK := True;
if not VarIsNull(oRow.ValueS['GENERATOR_NAME']) then begin
Include(pColInfo^.FAttrs, caAutoInc);
Include(pColInfo^.FAttrs, caAllowNull);
end;
if oRow.ValueS['ISCOMPUTED'] = 1 then begin
Include(pColInfo^.FAttrs, caReadOnly);
Include(pColInfo^.FAttrs, caCalculated);
end;
if oRow.ValueS['HASDEFAULT'] = 1 then
Include(pColInfo^.FAttrs, caDefault);
if (IBConnection.ServerBrand = ibFirebird) and (IBConnection.ServerVersion >= ivFB030000) then
if not VarIsNull(oRow.ValueS['IDENT_TYPE']) and (oRow.ValueS['IDENT_TYPE'] >= 1) then
Include(pColInfo^.FAttrs, caAutoInc);
end;
end;
end;
finally
FDClearMetaView(oView, oFetchOpts);
end;
end;
for i := 0 to Length(FColInfos) - 1 do begin
pColInfo := @FColInfos[i];
// mapping data types
if pColInfo^.FDestDataType = dtUnknown then
if GetMetaInfoKind = mkNone then
oFmtOpts.ResolveDataType(pColInfo^.FName, pColInfo^.FSrcTypeName,
pColInfo^.FSrcDataType, pColInfo^.FFDLen, pColInfo^.FPrec,
pColInfo^.FScale, pColInfo^.FDestDataType, pColInfo^.FFDLen, True)
else
pColInfo^.FDestDataType := pColInfo^.FSrcDataType;
if pColInfo^.FDestDataType = dtGUID then
pColInfo^.FVar.FDDataType := dtGUID
else
pColInfo^.FVar.FDDataType := pColInfo^.FSrcDataType;
if not CheckFetchColumn(pColInfo^.FSrcDataType, pColInfo^.FAttrs) then
pColInfo^.FVar := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.DestroyColInfos;
begin
SetLength(FColInfos, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.CreateParamInfos(AVars: TIBVariables; AInput, AFB2Batch: Boolean);
var
iBase, iPar, i: Integer;
oVar: TIBVariable;
oFmtOpts: TFDFormatOptions;
iPrec, iScale, iLen: Integer;
eAttrs: TFDDataAttributes;
oParams: TFDParams;
oParam: TFDParam;
pInfo: PFDIBParInfoRec;
procedure SetupStringVariable(AParam: TFDParam; var AInfo: TFDIBParInfoRec;
var AVar: TIBVariable);
begin
if caFixedLen in eAttrs then
AVar.SQLDataType := SQL_TEXT
else
AVar.SQLDataType := SQL_VARYING;
case AInfo.FSrcDataType of
dtAnsiString: AVar.sqlsubtype := csIDNone;
dtByteString: AVar.sqlsubtype := csIDOctets;
dtWideString: AVar.sqlsubtype := FStmt.Lib.IDUTF8;
end;
if AParam.Size <> 0 then
AVar.sqllen := AParam.Size
else
AVar.sqllen := C_FD_DefStrSize;
AVar.sqlprecision := 0;
AVar.sqlscale := 0;
AInfo.FLen := AVar.sqllen;
AInfo.FPrec := AVar.sqlprecision;
AInfo.FScale := AVar.sqlscale;
AInfo.FDestSQLDataType := AVar.SQLDataType;
AInfo.FDestSQLSubType := AVar.sqlsubtype;
AInfo.FDestDataType := AInfo.FSrcDataType;
end;
begin
oFmtOpts := FOptions.FormatOptions;
oParams := GetParams;
iBase := Length(FParInfos);
iPar := iBase - 1;
SetLength(FParInfos, iBase + AVars.VarCount);
for i := 0 to AVars.VarCount - 1 do begin
if iPar >= oParams.Markers.Count - 1 then
if AFB2Batch then
iPar := -1
else
Break;
oParam := nil;
while iPar < oParams.Markers.Count - 1 do begin
Inc(iPar);
case GetParams.BindMode of
pbByName: oParam := oParams.FindParam(oParams.Markers[iPar]);
pbByNumber: oParam := oParams.FindParam(iPar + 1);
end;
if (oParam = nil) or
(oParam.DataType <> ftCursor) and (
AInput and (oParam.ParamType in [ptUnknown, ptInput, ptInputOutput]) or
not AInput and (oParam.ParamType in [ptOutput, ptInputOutput, ptResult])) then
Break;
end;
pInfo := @FParInfos[iBase + i];
if oParam = nil then begin
pInfo^.FParamIndex := -1;
Continue;
end;
oVar := AVars[i];
pInfo^.FVar := oVar;
pInfo^.FParamIndex := oParam.Index;
if AInput and not oVar.IsNullable then
oVar.IsNullable := True;
if (oVar.DumpLabel = '') or (oVar.DumpLabel[1] = '#') then
oVar.DumpLabel := oParam.DisplayName;
pInfo^.FParamType := oParam.ParamType;
pInfo^.FLen := oVar.sqllen;
pInfo^.FPrec := oVar.sqlprecision;
pInfo^.FScale := oVar.sqlscale;
pInfo^.FDestSQLDataType := oVar.SQLDataType;
pInfo^.FDestSQLSubType := oVar.sqlsubtype;
pInfo^.FDestTypeName := oParam.DataTypeName;
eAttrs := [];
SQL2FDDataType(pInfo^.FDestSQLDataType, pInfo^.FDestSQLSubType, pInfo^.FLen,
pInfo^.FPrec, pInfo^.FScale, pInfo^.FDestDataType, eAttrs, pInfo^.FFDLen,
iPrec, iScale, oFmtOpts);
if oParam.DataType = ftUnknown then begin
oFmtOpts.ResolveDataType('', pInfo^.FDestTypeName, pInfo^.FDestDataType,
pInfo^.FFDLen, iPrec, iScale, pInfo^.FSrcDataType, pInfo^.FFDLen, False);
if pInfo^.FDestDataType <> pInfo^.FSrcDataType then
eAttrs := [];
oFmtOpts.ColumnDef2FieldDef(pInfo^.FSrcDataType, pInfo^.FFDLen, iPrec,
iScale, eAttrs, pInfo^.FSrcFieldType, pInfo^.FSrcSize, pInfo^.FSrcPrec,
pInfo^.FSrcScale);
oParam.DataType := pInfo^.FSrcFieldType;
oParam.Size := pInfo^.FSrcSize;
oParam.Precision := pInfo^.FSrcPrec;
oParam.NumericScale := pInfo^.FSrcScale;
end
else begin
pInfo^.FSrcFieldType := oParam.DataType;
pInfo^.FSrcSize := oParam.Size;
pInfo^.FSrcPrec := oParam.Precision;
pInfo^.FSrcScale := oParam.NumericScale;
oFmtOpts.FieldDef2ColumnDef(pInfo^.FSrcFieldType, pInfo^.FSrcSize,
pInfo^.FSrcPrec, pInfo^.FSrcScale, pInfo^.FSrcDataType, pInfo^.FFDLen,
iPrec, iScale, eAttrs);
if pInfo^.FDestSQLDataType = SQL_ARRAY then begin
if (pInfo^.FSrcDataType in C_FD_StrTypes) and (pInfo^.FFDLen = 0) then
pInfo^.FFDLen := C_FD_DefStrSize;
end
else
case pInfo^.FSrcDataType of
dtAnsiString,
dtByteString,
dtWideString:
if (pInfo^.FDestSQLDataType <> SQL_VARYING) and
(pInfo^.FDestSQLDataType <> SQL_TEXT) and
(pInfo^.FDestSQLDataType <> SQL_BLOB) then
// When assigning a textual parameter value to a non-textual parameter,
// then let FB handle conversion, because it depends on FB data format.
// For example, assign '1996-07-05' to a DATE parameter. In other cases
// the conversion will be performed by FireDAC.
SetupStringVariable(oParam, pInfo^, oVar)
else if pInfo^.FFDLen <> 0 then
if not CharLenInBytes() and
((pInfo^.FDestSQLDataType = SQL_VARYING) or
(pInfo^.FDestSQLDataType = SQL_TEXT)) then begin
iLen := pInfo^.FFDLen * LongWord(IBConnection.FEnv.Lib.GetBytesPerChar(oVar.sqlsubtype));
if iLen > 32765 then
iLen := 32765;
oVar.sqllen := iLen;
end
else if not ((FStmt.Lib.Version >= ivFB030000) and
(oParam.ParamType in [ptOutput, ptInputOutput, ptResult])) then
oVar.sqllen := pInfo^.FFDLen;
dtBCD,
dtFmtBCD,
dtCurrency:
begin
if iPrec <> 0 then
oVar.sqlprecision := iPrec;
if (iScale <> 0) and (- oVar.sqlscale > iScale) then
oVar.sqlscale := - iScale;
end;
end;
end;
if pInfo^.FSrcDataType = dtGUID then
oVar.FDDataType := dtGUID
else
oVar.FDDataType := pInfo^.FDestDataType;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.DestroyParamInfos;
begin
SetLength(FParInfos, 0);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.UseExecDirect: Boolean;
begin
// ResourceOptions.DirectExecute is not used. Because then TIBStatement.GetRowCounts
// cannot be called and updated rows count will be zero.
Result := GetCommandKind in [skCreate, skAlter, skDrop, skStartTransaction,
skCommit, skRollback, skSet, skSetSchema];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.IsReturning: Boolean;
begin
Result := (FStmt.Lib.Brand = ibFirebird) and (FStmt.Lib.Version >= ivFB020000) and
(FStmt.sql_stmt_type = isc_info_sql_stmt_exec_procedure) and
(GetCommandKind in [skDelete, skInsert, skMerge, skUpdate]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.PrepareBase;
var
i: Integer;
begin
FStmt.Prepare(FDbCommandText);
FStmt.DescribeSelect;
FStmt.DescribeBind;
if FStmt.InVars.VarCount > 0 then
CreateParamInfos(FStmt.InVars, True, False);
// Do not create here column infos or output param infos, we does not
// know how programmer will use command - Execute or Open. If Execute,
// then create param infos, else column infos.
FRetWithOut := False;
if IsReturning then
for i := 0 to GetParams.Count - 1 do
if GetParams[i].ParamType in [ptOutput, ptInputOutput, ptResult] then begin
FRetWithOut := True;
Break;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.InternalPrepare;
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
begin
// generate metadata SQL command
if GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone then begin
GetSelectMetaInfoParams(rName);
GenerateSelectMetaInfo(rName);
if FDbCommandText = '' then
Exit;
end
// generate stored proc call SQL command
else if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
GetConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(Trim(GetCommandText()), FSPParsedName, Self, []);
FDbCommandText := '';
if fiMeta in FOptions.FetchOptions.Items then
GenerateStoredProcParams(FSPParsedName);
// If an exact stored proc kind is not specified, then do not build a stored
// proc call SQL, we does not know how a programmer will use a command - Execute
// or Open. If Execute, then - EXEC PROC, else - SELECT.
if (FDbCommandText = '') and (GetCommandKind <> skStoredProc) then
GenerateStoredProcCall(FSPParsedName, GetCommandKind);
end;
// adjust SQL command
GenerateLimitSelect();
GenerateParamMarkers();
FStmt := TIBStatement.Create(IBConnection.FDatabase,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
SetupStatement(FStmt);
if (GetCommandKind <> skStoredProc) and not UseExecDirect then
PrepareBase;
FCursorCanceled := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.CheckSPPrepared(ASPUsage: TFDPhysCommandKind);
begin
if (FDbCommandText <> '') or (GetCommandKind <> skStoredProc) then
Exit;
GenerateStoredProcCall(FSPParsedName, ASPUsage);
PrepareBase;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.CheckColInfos;
begin
if (FStmt.OutVars.VarCount > 0) and (Length(FColInfos) = 0) then
CreateColInfos;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.CheckParamInfos;
begin
if (FStmt.OutVars.VarCount > 0) and (FStmt.InVars.VarCount = Length(FParInfos)) then
CreateParamInfos(FStmt.OutVars, False, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.InternalUnprepare;
begin
if FStmt = nil then
Exit;
FStmt.Unprepare;
DestroyColInfos;
DestroyParamInfos;
FDFreeAndNil(FStmt);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalUseStandardMetadata: Boolean;
begin
Result := not IBConnection.FExtendedMetadata;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean;
var
pColInfo: PFDIBColInfoRec;
iCount: TFDCounter;
begin
// After Prepare call the columns are defined. But here a
// command is executing to make OpenOrExecute method working.
InitRowsAffected;
iCount := 0;
try
Result := InternalOpen(iCount);
finally
UpdateRowsAffected(iCount);
end;
if ATabInfo.FSourceID = -1 then begin
ATabInfo.FSourceName := GetCommandText;
ATabInfo.FSourceID := 1;
FColumnIndex := 0;
FCurrentArrInfo := nil;
end
else begin
pColInfo := @FColInfos[ATabInfo.FSourceID - 1];
ATabInfo.FSourceName := pColInfo^.FName;
ATabInfo.FSourceID := ATabInfo.FSourceID;
ATabInfo.FOriginName := pColInfo^.FName;
ATabInfo.FArraySize := pColInfo^.FFDLen;
FCurrentArrInfo := pColInfo;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean;
var
pColInfo: PFDIBColInfoRec;
begin
if FCurrentArrInfo <> nil then begin
pColInfo := @FCurrentArrInfo^.FItemInfos[0];
FCurrentArrInfo := nil;
end
else if FColumnIndex < Length(FColInfos) then begin
pColInfo := @FColInfos[FColumnIndex];
Inc(FColumnIndex);
end
else
Exit(False);
AColInfo.FSourceName := pColInfo^.FName;
AColInfo.FSourceID := pColInfo^.FPos;
AColInfo.FSourceType := pColInfo^.FSrcDataType;
AColInfo.FSourceTypeName := pColInfo^.FSrcTypeName;
AColInfo.FOriginTabName.FObject := pColInfo^.FOriginTabName;
AColInfo.FOriginColName := pColInfo^.FOriginColName;
AColInfo.FType := pColInfo^.FDestDataType;
AColInfo.FLen := pColInfo^.FFDLen;
AColInfo.FPrec := pColInfo^.FPrec;
AColInfo.FScale := Abs(pColInfo^.FScale);
AColInfo.FAttrs := pColInfo^.FAttrs;
AColInfo.FForceAddOpts := [];
if pColInfo^.FInPK then
Include(AColInfo.FForceAddOpts, coInKey);
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam;
AVar: TIBVariable; ApInfo: PFDIBParInfoRec; AVarIndex, AParIndex: Integer);
function CreateBlob(ADestDataType: TFDDataType): TIBBlob;
begin
Result := TIBBlob.Create(FStmt.Database,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
if ADestDataType in C_FD_CharTypes then
Result.sqlsubtype := isc_blob_text;
Result.Add;
except
FDFree(Result);
raise;
end;
end;
function CreateArray(ApInfo: PFDIBParInfoRec; ACount: Integer): TIBArray;
var
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
iSQLType, iSQLSubType, iSQLLen, iSQLPrec, iSQLScale: Smallint;
eDataType: TFDDataType;
eAttrs: TFDDataAttributes;
iLen: LongWord;
iPrec, iScale: Integer;
begin
Result := TIBArray.Create(FStmt.Database,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
GetConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(ApInfo^.FDestTypeName, rName, Self,
[doUnquote, doNormalize]);
if (rName.FBaseObject <> '') and (rName.FObject <> '') then begin
Result.RelationName := rName.FBaseObject;
Result.FieldName := rName.FObject;
Result.Lookup;
SQL2FDDataType(Result.sqltype, Result.sqlsubtype, Result.sqllen, 0,
Result.sqlscale, eDataType, eAttrs, iLen, iPrec, iScale,
FOptions.FormatOptions);
if (Result.sqlsubtype = 0) and
(eDataType = dtAnsiString) and (ApInfo^.FSrcDataType = dtWideString) then
Result.sqlsubtype := csIDUnicodeFSS;
if eDataType <> ApInfo^.FSrcDataType then
CheckParamMatching(AParam, ApInfo^.FSrcFieldType, ApInfo^.FParamType,
ApInfo^.FSrcPrec);
end
else begin
Result.RelationName := ' ';
Result.FieldName := ' ';
FD2SQLDataType(ApInfo^.FSrcDataType, ApInfo^.FFDLen, 0, 0,
iSQLType, iSQLSubType, iSQLLen, iSQLPrec, iSQLScale,
FOptions.FormatOptions);
Result.Init(iSQLType, iSQLLen, 1, [1, ACount]);
Result.sqlsubtype := iSQLSubType;
Result.sqlscale := iSQLScale;
end;
except
FDFree(Result);
raise;
end;
end;
var
pData: PByte;
iSize, iSrcSize: LongWord;
oBlob: TIBBlob;
oExtStr, oIntStr: TStream;
lExtStream: Boolean;
oArr: TIBArray;
iCount, i: Integer;
begin
pData := nil;
iSize := 0;
// null
if (AParam.DataType <> ftStream) and AParam.IsNulls[AParIndex] then
AVar.SetData(AVarIndex, nil, 0)
// assign BLOB stream
else if AParam.IsStreams[AParIndex] then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TIBBlobStream) and (TIBBlobStream(oExtStr).Blob.OwningObj = Self));
if (AParam.DataType <> ftStream) and not lExtStream or
(ApInfo^.FDestSQLDataType <> SQL_BLOB) then
UnsupParamObjError(AParam);
oBlob := CreateBlob(ApInfo^.FDestDataType);
oIntStr := TIBBlobStream.Create(oBlob);
try
if lExtStream then
oIntStr.CopyFrom(oExtStr, -1)
else begin
FHasIntStreams := True;
AParam.AsStreams[AParIndex] := oIntStr;
end;
AVar.SetData(AVarIndex, @oBlob.FBlobID, SizeOf(oBlob.FBlobID));
finally
if lExtStream then
FDFree(oIntStr);
end;
end
// assign constrained ARRAY
else if ApInfo^.FDestSQLDataType = SQL_ARRAY then begin
iCount := AParam.ArraySize;
oArr := CreateArray(ApInfo, iCount);
try
for i := 0 to iCount - 1 do begin
iSize := AParam.GetDataLength(i);
pData := FBuffer.Check(iSize);
AParam.GetData(pData, i);
oArr.SetData(oArr.GetDataPtr([i], True), pData, iSize);
end;
oArr.Write;
AVar.SetData(AVarIndex, @oArr.FArrayID, SizeOf(oArr.FArrayID));
finally
FDFree(oArr);
end;
end
// conversion is not required
else if ApInfo^.FSrcDataType = ApInfo^.FDestDataType then begin
// byte string data, then optimizing - get data directly
if ApInfo^.FDestSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(ApInfo^.FDestDataType);
try
AParam.GetBlobRawData(iSize, pData, AParIndex);
oBlob.Write(pData, iSize);
AVar.SetData(AVarIndex, @oBlob.FBlobID, SizeOf(oBlob.FBlobID));
finally
FDFree(oBlob);
end;
end
else if ApInfo^.FDestDataType in (C_FD_VarLenTypes {$IFDEF NEXTGEN} - C_FD_AnsiTypes {$ENDIF}) then begin
AParam.GetBlobRawData(iSize, pData, AParIndex);
AVar.SetData(AVarIndex, pData, iSize);
end
else begin
iSize := AParam.GetDataLength(AParIndex);
FBuffer.Check(iSize);
AParam.GetData(FBuffer.Ptr, AParIndex);
AVar.SetData(AVarIndex, FBuffer.Ptr, iSize);
end;
end
// conversion is required
else begin
// calculate buffer size to move param values
iSrcSize := AParam.GetDataLength(AParIndex);
FBuffer.Extend(iSrcSize, iSize, ApInfo^.FSrcDataType, ApInfo^.FDestDataType);
// get, convert and set parameter value
AParam.GetData(FBuffer.Ptr, AParIndex);
AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FDestDataType,
FBuffer.Ptr, iSrcSize, FBuffer.FBuffer, FBuffer.Size, iSize,
IBConnection.FDatabase.Encoder);
if ApInfo^.FDestSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(ApInfo^.FDestDataType);
try
oBlob.Write(FBuffer.Ptr, iSize);
AVar.SetData(AVarIndex, @oBlob.FBlobID, SizeOf(oBlob.FBlobID));
finally
FDFree(oBlob);
end;
end
else
AVar.SetData(AVarIndex, FBuffer.Ptr, iSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.SetParamValues(ATimes, AOffset: Integer);
var
oParams: TFDParams;
oFmtOpts: TFDFormatOptions;
oParam: TFDParam;
iArraySize, i, j: Integer;
pParInfo: PFDIBParInfoRec;
begin
FHasIntStreams := False;
oParams := GetParams;
if oParams.Count = 0 then
Exit;
oFmtOpts := GetOptions.FormatOptions;
iArraySize := oParams.ArraySize;
if ATimes < iArraySize then
iArraySize := ATimes;
for i := 0 to Length(FParInfos) - 1 do begin
pParInfo := @FParInfos[i];
if pParInfo^.FParamIndex <> -1 then begin
oParam := oParams[pParInfo^.FParamIndex];
if (pParInfo^.FVar <> nil) and
(oParam.DataType <> ftCursor) and
(oParam.ParamType in [ptInput, ptInputOutput, ptUnknown]) then begin
CheckParamMatching(oParam, pParInfo^.FSrcFieldType, pParInfo^.FParamType,
pParInfo^.FSrcPrec);
for j := AOffset to iArraySize - 1 do
SetParamValue(oFmtOpts, oParam, pParInfo^.FVar, pParInfo, j - AOffset, j);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.GetParamValue(AFmtOpts: TFDFormatOptions;
AParam: TFDParam; AVar: TIBVariable; ApInfo: PFDIBParInfoRec;
AVarIndex, AParIndex: Integer);
function CreateBlob(const ABlobID: ISC_QUAD; ADestDataType: TFDDataType): TIBBlob;
begin
Result := TIBBlob.Create(FStmt.Database,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
Result.BlobID := ABlobID;
if ADestDataType in C_FD_CharTypes then
Result.sqlsubtype := isc_blob_text;
Result.Open;
except
FDFree(Result);
raise;
end;
end;
var
pData: Pointer;
iSize, iByteSize, iDestSize: LongWord;
oBlob: TIBBlob;
oExtStr, oIntStr: TStream;
lExtStream: Boolean;
begin
pData := nil;
iSize := 0;
// null
if not AVar.GetData(AVarIndex, pData, iSize, True) then
AParam.Clear(AParIndex)
// assign BLOB stream
else if AParam.IsStreams[AParIndex] then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TIBBlobStream) and (TIBBlobStream(oExtStr).Blob.OwningObj = Self));
if (AParam.DataType <> ftStream) and not lExtStream or
(ApInfo^.FDestSQLDataType <> SQL_BLOB) then
UnsupParamObjError(AParam);
oBlob := CreateBlob(PISC_QUAD(pData)^, ApInfo^.FDestDataType);
oIntStr := TIBBlobStream.Create(oBlob);
try
if lExtStream then
oExtStr.CopyFrom(oIntStr, -1)
else begin
AParam.AsStreams[AParIndex] := oIntStr;
oBlob.Close;
end;
finally
if lExtStream then
FDFree(oIntStr);
end;
end
// conversion is not required
else if ApInfo^.FDestDataType = ApInfo^.FSrcDataType then begin
// byte string data, then optimizing - get data directly
if ApInfo^.FDestSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(PISC_QUAD(pData)^, ApInfo^.FDestDataType);
try
iSize := oBlob.total_length;
pData := AParam.SetBlobRawData(iSize, nil, AParIndex);
if iSize > 0 then
oBlob.Read(pData, iSize);
finally
FDFree(oBlob);
end;
end
else if ApInfo^.FDestDataType in C_FD_VarLenTypes then
AParam.SetData(PByte(pData), iSize, AParIndex)
else begin
FBuffer.Check(iSize);
AVar.GetData(AVarIndex, FBuffer.FBuffer, iSize, False);
AParam.SetData(FBuffer.Ptr, iSize, AParIndex);
end;
end
// conversion is required
else begin
if ApInfo^.FDestSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(PISC_QUAD(pData)^, ApInfo^.FDestDataType);
try
iSize := oBlob.total_length;
iByteSize := iSize;
if oBlob.National then
iByteSize := iByteSize * SizeOf(WideChar);
pData := FBuffer.Check(iByteSize);
if iSize > 0 then
oBlob.Read(pData, iSize);
finally
FDFree(oBlob);
end;
end
else begin
FBuffer.Check(iSize);
AVar.GetData(AVarIndex, FBuffer.FBuffer, iSize, False);
end;
iDestSize := 0;
FBuffer.Extend(iSize, iDestSize, ApInfo^.FDestDataType, ApInfo^.FSrcDataType);
iDestSize := 0;
AFmtOpts.ConvertRawData(ApInfo^.FDestDataType, ApInfo^.FSrcDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
IBConnection.FDatabase.Encoder);
AParam.SetData(FBuffer.Ptr, iDestSize, AParIndex);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.GetParamValues(ATimes, AOffset: Integer);
var
oParams: TFDParams;
oFmtOpts: TFDFormatOptions;
iArraySize, i, j: Integer;
oParam: TFDParam;
pParInfo: PFDIBParInfoRec;
begin
oParams := GetParams;
if oParams.Count = 0 then
Exit;
oFmtOpts := FOptions.FormatOptions;
iArraySize := oParams.ArraySize;
if ATimes < iArraySize then
iArraySize := ATimes;
for i := 0 to Length(FParInfos) - 1 do begin
pParInfo := @FParInfos[i];
if pParInfo^.FParamIndex <> -1 then begin
oParam := oParams[pParInfo^.FParamIndex];
if (pParInfo^.FVar <> nil) and
(oParam.DataType <> ftCursor) and
(oParam.ParamType in [ptOutput, ptResult, ptInputOutput]) then begin
CheckParamMatching(oParam, pParInfo^.FSrcFieldType, pParInfo^.FParamType,
pParInfo^.FSrcPrec);
for j := AOffset to iArraySize - 1 do
GetParamValue(oFmtOpts, oParam, pParInfo^.FVar, pParInfo, j - AOffset, j);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.DoExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter; AFlush: Boolean);
var
i: Integer;
iCount: TFDCounter;
begin
if ATimes - AOffset > 1 then begin
for i := AOffset to ATimes - 1 do begin
iCount := 0;
DoExecute(i + 1, i, iCount, False);
Inc(ACount, iCount);
end;
end
else begin
if not AFlush then begin
FStmt.InVars.RowCount := 1;
SetParamValues(ATimes, AOffset);
CheckArrayDMLWithIntStr(FHasIntStreams, ATimes, AOffset);
end;
if FHasIntStreams xor AFlush then begin
ACount := -1;
Exit;
end;
try
try
if UseExecDirect then
FStmt.ExecuteImmediate(FDbCommandText)
else
// If it is INSERT / UPDATE ... RETURNING, then Firebird describes it
// as EXECUTE PROCEDURE. In this case force to count inserted / updated
// records.
FStmt.Execute(IsReturning);
except
on E: EIBNativeException do begin
E.Errors[0].RowIndex := AOffset;
raise;
end;
end;
finally
if FStmt <> nil then
Inc(ACount, FStmt.RowsAffected);
end;
if FStmt.OutVars.VarCount > 0 then
GetParamValues(ATimes, AOffset);
FStmt.Close;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.InternalCloseStreams;
var
iTmp: TFDCounter;
begin
if (FStmt <> nil) and FHasIntStreams then begin
GetParams.Close;
DoExecute(1, 0, iTmp, True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.InternalAbort;
begin
if FStmt <> nil then
FStmt.Cancel;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalOpen(var ACount: TFDCounter): Boolean;
var
oFetchOpts: TFDFetchOptions;
lExactFetch: Boolean;
begin
ACount := 0;
if not FCursorCanceled then begin
Result := True;
Exit;
end
else if (GetMetaInfoKind <> mkNone) and (FDbCommandText = '') then begin
Result := False;
Exit;
end
else if GetMetaInfoKind = mkProcArgs then
FMaxInputPos := 0;
if (GetCommandKind <> skStoredProc) and UseExecDirect then
PrepareBase
else
CheckSPPrepared(skStoredProcWithCrs);
CheckColInfos;
Result := Length(FColInfos) > 0;
if not Result then
InternalExecute(GetParams.ArraySize, 0, ACount)
else begin
oFetchOpts := FOptions.FetchOptions;
SetParamValues(1, 0);
lExactFetch := (oFetchOpts.Mode = fmExactRecsMax) and (oFetchOpts.RecsMax = 1) and
// isc_dsql_execute2 returns "Attempt to reopen an open cursor" on
// second call for SELECT FOR UPDATE statement. For simple SELECT - OK.
(FStmt.sql_stmt_type <> isc_info_sql_stmt_select_for_upd);
try
FStmt.Open(lExactFetch or (FStmt.sql_stmt_type = isc_info_sql_stmt_exec_procedure));
except
on E: EIBNativeException do begin
if lExactFetch and (E.Kind in [ekNoDataFound, ekTooManyRows]) then
// FDQA checks FDCode = er_FD_AccExactFetchMismatch in fmExactRecsMax tests
E.FDCode := er_FD_AccExactMismatch;
raise;
end;
end;
FCursorCanceled := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.InternalClose;
begin
if (FStmt <> nil) and not FCursorCanceled then begin
if FRetWithOut then begin
if not FStmt.Eof then
FStmt.Fetch;
CheckParamInfos;
GetParamValues(1, 0);
end;
FCursorCanceled := True;
FStmt.Close;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.ProcessColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions;
AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer;
var AUpdates: TIBUpdateStatus);
function CreateBlob(const ABlobID: ISC_QUAD; ASrcDataType: TFDDataType): TIBBlob;
begin
Result := TIBBlob.Create(FStmt.Database,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
Result.BlobID := ABlobID;
if ASrcDataType in C_FD_CharTypes then
Result.sqlsubtype := isc_blob_text;
Result.Open;
except
FDFree(Result);
raise;
end;
end;
function CreateArray(const AArrayID: ISC_QUAD; ApInfo: PFDIBColInfoRec): TIBArray;
begin
Result := TIBArray.Create(FStmt.Database,
TFDPhysIBTransactionBase(FTransactionObj).FTransaction, Self);
try
Result.RelationName := ApInfo^.FVar.relname;
Result.FieldName := ApInfo^.FVar.sqlname;
Result.Lookup;
Result.ArrayID := AArrayID;
Result.Read;
except
FDFree(Result);
raise;
end;
end;
var
pData: Pointer;
iSize, iByteSize, iDestSize: LongWord;
oBlob: TIBBlob;
oArr: TIBArray;
oNestedTable: TFDDatSTable;
oNestedRow: TFDDatSRow;
i: Integer;
begin
pData := nil;
iSize := 0;
if (FStmt.Lib.Brand = ibInterbase) and (FStmt.Lib.Version >= ivIB120000) then
AUpdates := AUpdates + ApInfo^.FVar.Updates[ARowIndex];
// null
if not ApInfo^.FVar.GetData(ARowIndex, pData, iSize, True) then
ARow.SetData(AColIndex, nil, 0)
// constrained array
else if ApInfo^.FSrcSQLDataType = SQL_ARRAY then begin
oArr := CreateArray(PISC_QUAD(pData)^, ApInfo);
try
oNestedTable := ARow.Table.Columns[AColIndex].NestedTable;
oNestedRow := oNestedTable.NewRow(False);
try
for i := 0 to Min(oNestedTable.Columns.Count - 1, oArr.TotalCount) - 1 do begin
pData := FBuffer.Check(oArr.sqllen);
oArr.GetData(oArr.GetDataPtr([i], True), pData, iSize);
oNestedRow.SetData(i, pData, iSize);
end;
oNestedRow.ParentRow := ARow;
oNestedTable.Rows.Add(oNestedRow);
except
FDFree(oNestedRow);
raise;
end;
ARow.Fetched[AColIndex] := True;
finally
FDFree(oArr);
end;
end
// conversion is not required
else if ApInfo^.FSrcDataType = ApInfo^.FDestDataType then
if ApInfo^.FSrcSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(PISC_QUAD(pData)^, ApInfo^.FSrcDataType);
try
iSize := oBlob.total_length;
pData := ARow.BeginDirectWriteBlob(AColIndex, iSize);
try
if iSize > 0 then
iSize := oBlob.Read(pData, iSize);
finally
ARow.EndDirectWriteBlob(AColIndex, iSize);
end;
finally
FDFree(oBlob);
end;
end
else if ApInfo^.FDestDataType in C_FD_VarLenTypes then
ARow.SetData(AColIndex, pData, iSize)
else begin
FBuffer.Check(iSize);
ApInfo^.FVar.GetData(ARowIndex, FBuffer.FBuffer, iSize, False);
ARow.SetData(AColIndex, FBuffer.Ptr, iSize);
end
// conversion is required
else begin
if ApInfo^.FSrcSQLDataType = SQL_BLOB then begin
oBlob := CreateBlob(PISC_QUAD(pData)^, ApInfo^.FSrcDataType);
try
iSize := oBlob.total_length;
iByteSize := iSize;
if oBlob.National then
iByteSize := iByteSize * SizeOf(WideChar);
pData := FBuffer.Check(iByteSize);
if iSize > 0 then
oBlob.Read(pData, iSize);
finally
FDFree(oBlob);
end;
end
else begin
iByteSize := iSize;
if ApInfo^.FVar.National then
iByteSize := iByteSize * SizeOf(WideChar);
FBuffer.Check(iByteSize);
ApInfo^.FVar.GetData(ARowIndex, FBuffer.FBuffer, iSize, False);
end;
iDestSize := 0;
AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FDestDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
IBConnection.FDatabase.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.ProcessMetaColumn(ATable: TFDDatSTable;
AFmtOpts: TFDFormatOptions; AColIndex: Integer; ARow: TFDDatSRow;
ApInfo: PFDIBColInfoRec; ARowIndex: Integer);
var
pData: Pointer;
iSize, iDestSize: Longword;
begin
pData := nil;
iSize := 0;
if AColIndex = 0 then
ARow.SetData(0, ATable.Rows.Count + 1)
else if not ApInfo^.FVar.GetData(ARowIndex, pData, iSize, True) then
ARow.SetData(AColIndex, nil, 0)
else if ApInfo^.FDestDataType in C_FD_VarLenTypes then begin
if iSize > ATable.Columns[AColIndex].Size then
iSize := ATable.Columns[AColIndex].Size;
if ApInfo^.FDestDatatype in C_FD_AnsiTypes then begin
FBuffer.Check(iSize * SizeOf(WideChar));
AFmtOpts.ConvertRawData(dtAnsiString, dtWideString,
pData, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
IBConnection.FDatabase.Encoder);
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end
else
ARow.SetData(AColIndex, pData, iSize);
end
else begin
FBuffer.Check(iSize);
ApInfo^.FVar.GetData(ARowIndex, FBuffer.FBuffer, iSize, False);
iDestSize := 0;
if ApInfo^.FDestDataType in C_FD_NumTypes then
AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ATable.Columns[AColIndex].DataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize,
IBConnection.FDatabase.Encoder)
else
iDestSize := iSize;
ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow);
var
oRow: TFDDatSRow;
oFmtOpts: TFDFormatOptions;
pColInfo: PFDIBColInfoRec;
j: Integer;
lMetadata: Boolean;
[unsafe] oCol: TFDDatSColumn;
eRowUpdates: TIBUpdateStatus;
procedure AdjustProcArgPos;
var
eParamType: TParamType;
iPos: Integer;
begin
eParamType := TParamType(oRow.GetData(8));
case eParamType of
ptInput:
begin
iPos := oRow.GetData(7);
if iPos > FMaxInputPos then
FMaxInputPos := iPos;
end;
ptOutput:
oRow.SetData(7, oRow.GetData(7) + FMaxInputPos);
end;
end;
begin
oFmtOpts := FOptions.FormatOptions;
oRow := ATable.NewRow(False);
lMetadata := GetMetaInfoKind <> mkNone;
eRowUpdates := [];
try
for j := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[j];
if (oCol.SourceID > 0) and CheckFetchColumn(oCol.SourceDataType, oCol.Attributes) then begin
pColInfo := @FColInfos[oCol.SourceID - 1];
if pColInfo^.FVar <> nil then
if lMetadata then
ProcessMetaColumn(ATable, oFmtOpts, j, oRow, pColInfo, 0)
else
ProcessColumn(ATable, oFmtOpts, j, oRow, pColInfo, 0, eRowUpdates);
end;
end;
if lMetadata and (GetMetaInfoKind = mkProcArgs) then
AdjustProcArgPos;
if AParentRow <> nil then begin
oRow.ParentRow := AParentRow;
AParentRow.Fetched[ATable.Columns.ParentCol] := True;
end;
ATable.Rows.Add(oRow);
if not lMetadata and (eRowUpdates <> []) then
if [iuDeleted, iuTruncated] * eRowUpdates <> [] then
oRow.ForceChange(rsDeleted)
else if iuInserted in eRowUpdates then
oRow.ForceChange(rsInserted)
else if [iuUpdated, iuModified] * eRowUpdates <> [] then
oRow.ForceChange(rsModified);
except
FDFree(oRow);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalFetchRowSet(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord;
var
i: LongWord;
begin
try
Result := 0;
if FStmt <> nil then
for i := 1 to ARowsetSize do begin
if (GetState <> csFetching) or not FStmt.Fetch then
Break;
FetchRow(ATable, AParentRow);
Inc(Result);
end;
except
if IBConnection.FEnv.Lib.Brand = ibInterbase then
InternalClose;
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.InternalNextRecordSet: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandBase.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if FStmt <> nil then
Inc(Result, 4);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBCommandBase.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else
case AIndex - inherited GetItemCount of
0:
begin
AName := 'Rows inserted';
AValue := FStmt.RowsInserted;
AKind := ikStat;
end;
1:
begin
AName := 'Rows updated';
AValue := FStmt.RowsUpdated;
AKind := ikStat;
end;
2:
begin
AName := 'Rows deleted';
AValue := FStmt.RowsDeleted;
AKind := ikStat;
end;
3:
begin
AName := 'Rows selected';
AValue := FStmt.RowsSelected;
AKind := ikStat;
end;
end;
end;
end.
|
unit IdTCPClient;
interface
uses
Classes,
IdException, IdGlobal, IdSocks, IdTCPConnection;
type
TProceduralEvent = procedure of object;
TIdTCPClient = class(TIdTCPConnection)
protected
FBoundIP: string;
FHost: string;
FOnConnected: TNotifyEvent;
FPort: Integer;
FSocksInfo: TSocksInfo;
FUseNagle: boolean;
//
procedure DoOnConnected; virtual;
procedure SetSocksInfo(ASocks: TSocksInfo);
public
procedure Connect; virtual;
function ConnectAndGetAll: string; virtual;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BoundIP: string read FBoundIP write FBoundIP;
property Host: string read FHost write FHost;
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
property Port: integer read FPort write FPort;
property UseNagle: boolean read FUseNagle write FUseNagle default True;
property SocksInfo: TSocksInfo read FSocksInfo write SetSocksInfo;
end;
EIdSocksError = class(EIdException);
EIdSocksRequestFailed = class(EIdSocksError);
EIdSocksRequestServerFailed = class(EIdSocksError);
EIdSocksRequestIdentFailed = class(EIdSocksError);
EIdSocksUnknownError = class(EIdSocksError);
EIdSocksServerRespondError = class(EIdSocksError);
EIdSocksAuthMethodError = class(EIdSocksError);
EIdSocksAuthError = class(EIdSocksError);
EIdSocksServerGeneralError = class(EIdSocksError);
EIdSocksServerPermissionError = class(EIdSocksError);
EIdSocksServerNetUnreachableError = class(EIdSocksError);
EIdSocksServerHostUnreachableError = class(EIdSocksError);
EIdSocksServerConnectionRefusedError = class(EIdSocksError);
EIdSocksServerTTLExpiredError = class(EIdSocksError);
EIdSocksServerCommandError = class(EIdSocksError);
EIdSocksServerAddressError = class(EIdSocksError);
implementation
uses
IdComponent, IdStack, IdResourceStrings, IdStackConsts,
SysUtils;
{ TIdTCPClient }
procedure TIdTCPClient.Connect;
var
req: TIdSocksRequest;
res: TIdSocksResponse;
len, pos: Integer;
tempBuffer: array[0..255] of Byte;
ReqestedAuthMethod,
ServerAuthMethod: Byte;
tempPort: Word;
begin
if Binding.HandleAllocated then
begin
raise EIdAlreadyConnected.Create(RSAlreadyConnected);
end;
ResetConnection;
Binding.AllocateSocket;
try
Binding.IP := FBoundIP;
Binding.Bind;
case SocksInfo.Version of
svSocks4, svSocks4A, svSocks5:
begin
if not GStack.IsIP(SocksInfo.Host) then
begin
DoStatus(hsResolving, [SocksInfo.Host]);
end;
Binding.SetPeer(GStack.ResolveHost(SocksInfo.Host), SocksInfo.Port);
end
else
begin
if not GStack.IsIP(Host) then
begin
DoStatus(hsResolving, [Host]);
end;
Binding.SetPeer(GStack.ResolveHost(Host), Port);
end;
end;
if not UseNagle then
begin
Binding.SetSockOpt(Id_IPPROTO_TCP, Id_TCP_NODELAY, PChar(@Id_SO_True),
SizeOf(Id_SO_True));
end;
DoStatus(hsConnecting, [Binding.PeerIP]);
GStack.CheckForSocketError(Binding.Connect);
except
on E: Exception do
begin
try
Disconnect;
except
end;
raise;
end;
end;
if InterceptEnabled then
begin
Intercept.Connect(Binding);
end;
case SocksInfo.Version of
svSocks4, svSocks4A:
begin
req.Version := 4;
req.OpCode := 1;
req.Port := GStack.WSHToNs(Port);
if SocksInfo.Version = svSocks4A then
begin
req.IpAddr := GStack.StringToTInAddr('0.0.0.1');
end
else
begin
req.IpAddr := GStack.StringToTInAddr(GStack.ResolveHost(Host));
end;
req.UserId := SocksInfo.UserID;
len := Length(req.UserId);
req.UserId[len + 1] := #0;
if SocksInfo.Version = svSocks4A then
begin
Move(Host[1], req.UserId[len + 2], Length(Host));
len := len + 1 + Length(Host);
req.UserId[len + 1] := #0;
end;
len := 8 + len + 1;
WriteBuffer(req, len);
try
ReadBuffer(res, 8);
except
on E: Exception do
begin
raise;
end;
end;
case res.OpCode of
90: ;
91: raise EIdSocksRequestFailed.Create(RSSocksRequestFailed);
92: raise
EIdSocksRequestServerFailed.Create(RSSocksRequestServerFailed);
93: raise
EIdSocksRequestIdentFailed.Create(RSSocksRequestIdentFailed);
else
raise EIdSocksUnknownError.Create(RSSocksUnknownError);
end;
end;
svSocks5:
begin
if SocksInfo.Authentication = saNoAuthentication then
begin
tempBuffer[2] := $0
end
else
begin
tempBuffer[2] := $2;
end;
ReqestedAuthMethod := tempBuffer[2];
tempBuffer[0] := $5;
tempBuffer[1] := $1;
len := 2 + tempBuffer[1];
WriteBuffer(tempBuffer, len);
try
ReadBuffer(tempBuffer, 2);
except
on E: Exception do
begin
raise EIdSocksServerRespondError.Create(RSSocksServerRespondError);
end;
end;
ServerAuthMethod := tempBuffer[1];
if (ServerAuthMethod <> ReqestedAuthMethod) or (ServerAuthMethod = $FF)
then
begin
raise EIdSocksAuthMethodError.Create(RSSocksAuthMethodError);
end;
if SocksInfo.Authentication = saUsernamePassword then
begin
tempBuffer[0] := 1;
tempBuffer[1] := Length(SocksInfo.UserID);
pos := 2;
if Length(SocksInfo.UserID) > 0 then
begin
Move(SocksInfo.UserID[1], tempBuffer[pos],
Length(SocksInfo.UserID));
end;
pos := pos + Length(SocksInfo.UserID);
tempBuffer[pos] := Length(SocksInfo.Password);
pos := pos + 1;
if Length(SocksInfo.Password) > 0 then
begin
Move(SocksInfo.Password[1], tempBuffer[pos],
Length(SocksInfo.Password));
end;
pos := pos + Length(SocksInfo.Password);
WriteBuffer(tempBuffer, pos);
try
ReadBuffer(tempBuffer, 2);
except
on E: Exception do
begin
raise
EIdSocksServerRespondError.Create(RSSocksServerRespondError);
end;
end;
if tempBuffer[1] <> $0 then
begin
raise EIdSocksAuthError.Create(RSSocksAuthError);
end;
end;
tempBuffer[0] := $5;
tempBuffer[1] := $1;
tempBuffer[2] := $0;
tempBuffer[3] := $3;
tempBuffer[4] := Length(Host);
pos := 5;
if Length(Host) > 0 then
Move(Host[1], tempBuffer[pos], Length(Host));
pos := pos + Length(Host);
tempPort := GStack.WSHToNs(Port);
Move(tempPort, tempBuffer[pos], SizeOf(tempPort));
pos := pos + 2;
WriteBuffer(tempBuffer, pos);
try
ReadBuffer(tempBuffer, 5);
except
on E: Exception do
begin
raise EIdSocksServerRespondError.Create(RSSocksServerRespondError);
end;
end;
case tempBuffer[1] of
0: ;
1: raise EIdSocksServerGeneralError.Create(RSSocksServerGeneralError);
2: raise
EIdSocksServerPermissionError.Create(RSSocksServerPermissionError);
3: raise
EIdSocksServerNetUnreachableError.Create(RSSocksServerNetUnreachableError);
4: raise
EIdSocksServerHostUnreachableError.Create(RSSocksServerHostUnreachableError);
5: raise
EIdSocksServerConnectionRefusedError.Create(RSSocksServerConnectionRefusedError);
6: raise
EIdSocksServerTTLExpiredError.Create(RSSocksServerTTLExpiredError);
7: raise EIdSocksServerCommandError.Create(RSSocksServerCommandError);
8: raise EIdSocksServerAddressError.Create(RSSocksServerAddressError);
else
raise EIdSocksUnknownError.Create(RSSocksUnknownError);
end;
case tempBuffer[3] of
1: len := 4 + 2;
3: len := tempBuffer[4] + 2;
4: len := 16 + 2;
end;
try
ReadBuffer(tempBuffer[5], len - 1);
except
on E: Exception do
begin
raise EIdSocksServerRespondError.Create(RSSocksServerRespondError);
end;
end;
end;
end;
DoStatus(hsConnected, [Binding.PeerIP]);
DoOnConnected;
end;
function TIdTCPClient.ConnectAndGetAll: string;
begin
Connect;
try
result := AllData;
finally Disconnect;
end;
end;
constructor TIdTCPClient.Create(AOwner: TComponent);
begin
inherited;
FSocksInfo := TSocksInfo.Create;
FUseNagle := True;
end;
destructor TIdTCPClient.Destroy;
begin
FreeAndNil(FSocksInfo);
inherited;
end;
procedure TIdTCPClient.DoOnConnected;
begin
if assigned(OnConnected) then
begin
OnConnected(Self);
end;
end;
procedure TIdTCPClient.SetSocksInfo(ASocks: TSocksInfo);
begin
FSocksInfo.Assign(ASocks);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSMrWizardCommon;
interface
uses
Windows, ToolsApi, Controls, Forms, SysUtils, Classes, Dialogs, ComObj,
WizardAPI,
Generics.Collections, WizardIniOptions,
Graphics;
type
IDsWizardImage = interface
['{6B5D8B03-6C84-4276-92A0-6F76D50E8315}']
function GetImage: TBitmap;
function LoadImage: TBitmap;
end;
TCustomPageMrWizard = class(TInterfacedObject, IMrWizard, IDsWizardImage)
strict private
{ Wizard Info }
FWizard: IWizard;
FPersonality: string;
FHelpContext: Integer;
FCaption: string;
FImageName: string;
FBitmap: TBitmap;
{ Ini info }
FUIOptions: TWizardIniOptions;
procedure InitOptions(const AOptionsFileName: string);
private
{ IMrWizard }
procedure Start;
function FirstPage: IWizardPage;
procedure Cancel;
function GetWizard: IWizard;
procedure SetWizard(const Value: IWizard);
function GetPersonality: string;
{ IDsWizardImage }
function GetImage: TBitmap;
function LoadImage: TBitmap; overload;
protected
function LoadImage(Instance: THandle; const ResourceName: string): TBitmap; overload;
function LoadImage(const ResourceName: string): TBitmap; overload; virtual; abstract;
{ Wizard Utility functions }
function CreatePage(const IID: TGUID; out Intf; const name: string = ''): Boolean;
function GetFirstPage: IWizardpage; virtual;
procedure Finish; virtual;
function Caption: string;
function GetHelpContext: Integer;
procedure AddFirstPage(out AID: TGuid; out AName: string); virtual;
procedure AddCustomPages(const ParentID: TGUID; const ParentName: string); virtual;
function HasCustomPages: Boolean; virtual;
function FirstCustomPage: IWizardpage; virtual;
function CanFinish: Boolean; virtual;
property Wizard: IWizard read GetWizard;
property Personality: string read FPersonality;
public
constructor Create(const APersonality: string; const ACaption: string;
AHelpContext: Integer; const AImage: string; const AOptionsFile: string);
destructor Destroy; override;
end;
TDSPageClass = class(TPersistent)
protected
procedure AssignTo(Dest: TPersistent); override;
public
Name: string;
Guid: TGUID;
end;
TDSPageListMrWizard = class(TCustomPageMrWizard, IWizardEvents)
private
function GetNextPageDictionary: TDictionary<string, TDSPageClass>;
procedure UpdatePageCount(AList: TList<TDSPageClass>); overload;
function GetSelectedPageList: TList<TDSPageClass>;
function ClonePage(APage: TDSPageClass): TDSPageClass;
protected
procedure UpdatePageCount; overload;
{ IWizardEvents }
procedure OnEnterPage(LastPage, CurrentPage: IWizardPage; PageTransition: TPageTransition); virtual;
procedure OnLeavePage(WizardPage: IWizardPage; PageTransition: TPageTransition); virtual;
procedure OnLeavingPage(WizardPage: IWizardPage; PageTransition: TPageTransition; var Allow: Boolean); virtual;
function IsPageSelected(APage: TDSPageClass): Boolean; virtual;
function CreateWizardPage(APage: TDSPageClass): IWizardPage; virtual;
procedure GetPageList(AList: TList<TDSPageClass>); virtual;
function HandleNextPage(const CurrentPage: IWizardPage): IWizardPage;
procedure AddCustomPages(const ParentID: TGUID; const ParentName: string); override;
function HasCustomPages: Boolean; override;
function FirstCustomPage: IWizardpage; override;
public
constructor Create(const APersonality: string; const ACaption: string;
AHelpContext: Integer; const AImageName: string; const AOptionsFileName: string);
end;
TDSWizardPage = class(TWizardPage, IWizardPage, IWizardPageEvents)
private
FID: TGuid;
{ IWizardPage }
function Close: Boolean;
procedure Clear;
{ IWizardPageEvents }
procedure OnEnterPage(PageTransition: TPageTransition);
procedure OnLeavePage(PageTransition: TPageTransition);
protected
procedure UpdateInfo; virtual;
{ IWizardPage }
function Page: TFrame; virtual;
{ IWizardPageEvents }
procedure OnLeavingPage(PageTransition: TPageTransition; var Allow: Boolean); virtual;
public
function PageID: TGUID; override;
constructor Create(AID: TGuid; const AName, ATitle, ADescription: string);
function GetImage: TBitmap; override;
end;
const
// Wizard control margins
cRadioLeftMargin = 10;
cLabelLeftMargin = 10;
implementation
{ TDSPageListMrWizard }
constructor TDSPageListMrWizard.Create(const APersonality: string; const ACaption: string;
AHelpContext: Integer; const AImageName: string; const AOptionsFileName: string);
begin
inherited;
end;
function TDSPageListMrWizard.IsPageSelected(APage: TDSPageClass): Boolean;
begin
Result := True;
end;
procedure TDSPageListMrWizard.OnEnterPage(LastPage, CurrentPage: IWizardPage;
PageTransition: TPageTransition);
begin
UpdatePageCount;
end;
procedure TDSPageListMrWizard.OnLeavePage(WizardPage: IWizardPage;
PageTransition: TPageTransition);
begin
end;
procedure TDSPageListMrWizard.OnLeavingPage(WizardPage: IWizardPage;
PageTransition: TPageTransition; var Allow: Boolean);
begin
end;
function TDSPageListMrWizard.CreateWizardPage(APage: TDSPageClass): IWizardPage;
begin
Result := nil;
end;
function TDSPageListMrWizard.GetNextPageDictionary: TDictionary<string, TDSPageClass>;
var
LList: TList<TDSPageClass>;
LPage: TDSPageClass;
LPrevPage: string;
begin
LPrevPage := GetFirstPage.Name;
LList := GetSelectedPageList;
try
Result := TObjectDictionary<string, TDSPageClass>.Create([doOwnsValues]);
for LPage in LList do
begin
Result.Add(LPrevPage, ClonePage(LPage));
LPrevPage := LPage.Name;
end;
finally
LList.Free;
end;
end;
function TDSPageListMrWizard.ClonePage(APage: TDSPageClass): TDSPageClass;
begin
Result := TDSPageClass(APage.ClassType.Create);
Result.Assign(APage);
end;
procedure TDSPageListMrWizard.GetPageList(AList: TList<TDSPageClass>);
begin
Assert(False);
end;
function TDSPageListMrWizard.GetSelectedPageList: TList<TDSPageClass>;
var
LList: TList<TDSPageClass>;
LPage: TDSPageClass;
begin
LList := TObjectList<TDSPageClass>.Create;
GetPageList(LList);
try
Result := TObjectList<TDSPageClass>.Create;
for LPage in LList do
if IsPageSelected(LPage) then
Result.Add(ClonePage(LPage));
finally
LList.Free;
end;
end;
function TDSPageListMrWizard.HandleNextPage(
const CurrentPage: IWizardPage): IWizardPage;
var
LNextPage: TDSPageClass;
LDictionary: TDictionary<string, TDSPageClass>;
LLastPage: Boolean;
begin
LLastPage := True;
Result := nil;
LDictionary := GetNextPageDictionary;
try
if LDictionary.TryGetValue(CurrentPage.Name, LNextPage) then
begin
Result := CreateWizardPage(LNextPage);
LLastPage := not LDictionary.ContainsKey(LNextPage.Name);
end;
finally
LDictionary.Free;
end;
Wizard.Finish := LLastPage;
Wizard.Next := not LLastPage;
end;
procedure TDSPageListMrWizard.UpdatePageCount;
var
LList: TList<TDSPageClass>;
begin
LList := GetSelectedPageList;
try
UpdatePageCount(LList);
finally
LList.Free;
end;
end;
procedure TDSPageListMrWizard.UpdatePageCount(AList: TList<TDSPageClass>);
var
LName: string;
I: Integer;
begin
Wizard.PageCount := AList.Count + 1;
if Wizard.CurrentPage <> nil then
begin
if Wizard.CurrentPage = GetFirstPage then
Wizard.PageIndex := 1
else
begin
LName := Wizard.CurrentPage.Name;
for I := 0 to AList.Count - 1 do
if AList[I].Name = LName then
begin
Wizard.PageIndex := I + 2;
break;
end;
end;
end;
end;
procedure TDSPageListMrWizard.AddCustomPages(const ParentID: TGUID; const ParentName: string);
var
LParentID: TGUID;
LParentName: string;
procedure AddPage(const ChildID: TGUID; const ChildName: string;
Callback: TWizardFunctionCallback; AllowBack: Boolean);
begin
Wizard.AddPage(LParentID, LParentName, ChildId,
ChildName, Callback, AllowBack);
LParentID := ChildId;
LParentName := ChildName;
end;
var
LList: TList<TDSPageClass>;
LPage: TDSPageClass;
begin
LParentID := ParentID;
LParentName := ParentName;
LList := TObjectList<TDSPageClass>.Create;
GetPageList(LList);
try
for LPage in LList do
AddPage(LPage.Guid, LPage.Name, HandleNextPage, True);
UpdatePageCount(LList);
finally
LList.Free;
end;
end;
function TDSPageListMrWizard.HasCustomPages: Boolean;
begin
Result := True;
end;
function TDSPageListMrWizard.FirstCustomPage: IWizardpage;
var
LList: TList<TDSPageClass>;
begin
LList := GetSelectedPageList;
try
Assert(LList.Count > 0);
Result := CreateWizardPage(LList[0]);
Wizard.Next := LList.Count > 1;
Wizard.Finish := LList.Count = 1;
finally
LList.Free;
end;
end;
{ TDSPageClass }
procedure TDSPageClass.AssignTo(Dest: TPersistent);
begin
if Dest is TDSPageClass then
begin
TDSPageClass(Dest).Name := Name;
TDSPageClass(Dest).Guid := Guid;
end
else
inherited;
end;
{ TDSProjectLocationWizardPage }
procedure TDSWizardPage.Clear;
begin
end;
function TDSWizardPage.Close: Boolean;
begin
Result := True;
end;
constructor TDSWizardPage.Create(AID: TGuid; const AName, ATitle, ADescription: string);
begin
inherited Create;
FID := AID;
Title := ATitle;
Description := ADescription;
Name := AName;
end;
function TDSWizardPage.GetImage: TBitmap;
var
Intf: IDsWizardImage;
begin
if Supports(Wizard.MrWizard, IDsWizardImage, Intf) then
Result := Intf.GetImage
else
Result := nil;
end;
procedure TDSWizardPage.OnEnterPage(PageTransition: TPageTransition);
begin
UpdateInfo;
end;
procedure TDSWizardPage.OnLeavePage(PageTransition: TPageTransition);
begin
end;
procedure TDSWizardPage.OnLeavingPage(PageTransition: TPageTransition;
var Allow: Boolean);
begin
end;
function TDSWizardPage.Page: TFrame;
begin
Assert(False);
Result := nil;
end;
procedure TDSWizardPage.UpdateInfo;
begin
end;
function TDSWizardPage.PageID: TGUID;
begin
Result := FID;
end;
const
{ Wizard State }
ivFormTop = 'FormTop';
ivFormLeft = 'FormLeft';
ivFormWidth = 'FormWidth';
ivFormHeight = 'FormHeight';
procedure TCustomPageMrWizard.InitOptions(const AOptionsFileName: string);
begin
TWizardIniOptions.InitOptions(AOptionsFileName, FUIOptions);
end;
function TCustomPageMrWizard.CreatePage(const IID: TGUID; out Intf; const name: string = ''): Boolean;
var
WizardPage: IWizardpage;
begin
Result := False;
WizardPage := BorlandWizards.CreatePage(IID);
Assert(WizardPage <> nil);
if name <> '' then
WizardPage.name := name;
if Supports(WizardPage, IID, Intf) then
Result := True;
end;
function TCustomPageMrWizard.LoadImage: TBitmap;
begin
if FImageName <> '' then
Result := LoadImage(FImageName)
else
Result := nil;
end;
function TCustomPageMrWizard.LoadImage(Instance: THandle; const ResourceName: string): TBitmap;
begin
Result := TBitmap.Create;
try
Result.LoadFromResourceName(Instance, ResourceName);
except
FreeAndNil(Result);
end;
end;
constructor TCustomPageMrWizard.Create(const APersonality: string; const ACaption: string;
AHelpContext: Integer; const AImage: string; const AOptionsFile: string);
begin
inherited Create;
FPersonality := APersonality;
FCaption := ACaption;
FHelpContext := AHelpContext;
FWizard := nil;
FImageName := AImage;
InitOptions(AOptionsFile);
end;
destructor TCustomPageMrWizard.Destroy;
begin
FWizard := nil;
FUIOPtions.Free;
FBitmap.Free;
inherited;
end;
function TCustomPageMrWizard.CanFinish: Boolean;
begin
Result := True;
end;
procedure TCustomPageMrWizard.AddFirstPage(out AID: TGuid; out AName: string);
begin
Assert(False);
end;
procedure TCustomPageMrWizard.Cancel;
begin
if FUIOptions <> nil then
begin
FUIOptions[ivFormLeft] := Wizard.WizardForm.Left;
FUIOptions[ivFormTop] := Wizard.WizardForm.Top;
FUIOptions[ivFormWidth] := Wizard.WizardForm.Width;
FUIOptions[ivFormHeight] := Wizard.WizardForm.Height;
end;
end;
procedure TCustomPageMrWizard.Start;
var
LID: TGUID;
LName: string;
begin
if Wizard <> nil then
begin
if FUIOptions <> nil then
begin
Wizard.WizardForm.Left := FUIOptions.GetOption(ivFormLeft, Wizard.WizardForm.Left);
Wizard.WizardForm.Top := FUIOptions.GetOption(ivFormTop, Wizard.WizardForm.Top);
Wizard.WizardForm.Width := FUIOptions.GetOption(ivFormWidth, Wizard.WizardForm.Width);
Wizard.WizardForm.Height := FUIOptions.GetOption(ivFormHeight, Wizard.WizardForm.Height);
end;
AddFirstPage(LID, LName);
if HasCustomPages then
AddCustomPages(LID,
LName);
end;
end;
function TCustomPageMrWizard.HasCustomPages: Boolean;
begin
Result := False;
end;
procedure TCustomPageMrWizard.AddCustomPages(const ParentID: TGUID; const ParentName: string);
begin
Assert(False);
end;
procedure TCustomPageMrWizard.Finish;
begin
if FUIOptions <> nil then
begin
FUIOptions[ivFormLeft] := Wizard.WizardForm.Left;
FUIOptions[ivFormTop] := Wizard.WizardForm.Top;
FUIOptions[ivFormWidth] := Wizard.WizardForm.Width;
FUIOptions[ivFormHeight] := Wizard.WizardForm.Height;
end;
end;
function TCustomPageMrWizard.FirstCustomPage: IWizardpage;
begin
Assert(False);
end;
function TCustomPageMrWizard.FirstPage: IWizardpage;
begin
Result := GetFirstPage as IWizardPage;
Wizard.Back := False;
Wizard.Next := True;
Wizard.Finish := False;
Wizard.Cancel := True;
end;
function TCustomPageMrWizard.GetFirstPage: IWizardpage;
begin
Assert(False); // Ancestor must override
end;
function TCustomPageMrWizard.GetHelpContext: Integer;
begin
Result := FHelpContext;
end;
function TCustomPageMrWizard.GetImage: TBitmap;
begin
if FBitmap = nil then
FBitmap := LoadImage;
Result := FBitmap;
end;
function TCustomPageMrWizard.Caption: string;
begin
Result := FCaption;
end;
function TCustomPageMrWizard.GetPersonality: string;
begin
Result := FPersonality;
end;
function TCustomPageMrWizard.GetWizard: IWizard;
begin
Result := FWizard;
end;
procedure TCustomPageMrWizard.SetWizard(const Value: IWizard);
begin
FWizard := Value;
end;
end.
|
unit UMessageController;
interface
uses UMessageResultType, UFMessage, ExtCtrls, SysUtils;
type
TMessageController = class
private
public
class procedure ShowMessageInformation(Msg: string);
class procedure ShowMessageSuccess(Msg: string);
class procedure ShowMessageError(Msg: string);
class procedure ShowMessageAlert(Msg: string);
class function ShowMessageConfirm(Msg: string; ShowCancelButton: Boolean): TMessageResultType;
end;
implementation
{ TMessageController }
class procedure TMessageController.ShowMessageAlert(Msg: string);
var
MessageView : TFMessage;
begin
MessageView := TFMessage.Create(nil);
MessageView.ShowMessageAlert(Msg);
FreeAndNil(MessageView);
end;
class function TMessageController.ShowMessageConfirm(Msg: string;
ShowCancelButton: Boolean): TMessageResultType;
var
MessageView : TFMessage;
begin
MessageView := TFMessage.Create(nil);
Result := MessageView.ShowMessageConfirm(Msg,ShowCancelButton);
FreeAndNil(MessageView);
end;
class procedure TMessageController.ShowMessageError(Msg: string);
var
MessageView : TFMessage;
begin
MessageView := TFMessage.Create(nil);
MessageView.ShowMessageError(Msg);
FreeAndNil(MessageView);
end;
class procedure TMessageController.ShowMessageInformation(Msg: string);
var
MessageView : TFMessage;
begin
MessageView := TFMessage.Create(nil);
MessageView.ShowMessageInformation(Msg);
FreeAndNil(MessageView);
end;
class procedure TMessageController.ShowMessageSuccess(Msg: string);
var
MessageView : TFMessage;
begin
MessageView := TFMessage.Create(nil);
MessageView.ShowMessageSuccess(Msg);
FreeAndNil(MessageView);
end;
end.
|
unit ucadTransField;
interface
uses
SysUtils,
classes,
ufmTranslator;
type
TFieldTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TBooleanFieldTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
implementation
uses
db;
// -----------------------------------------------------------------------------
class function TFieldTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom( TField);
end;
function TFieldTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TField(aObj) do begin
DisplayLabel := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'DisplayLabel', DisplayLabel, Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TBooleanFieldTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj is TBooleanField;
end;
function TBooleanFieldTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
P: Integer;
vFalse, vTrue : string;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TBooleanField(aObj) do begin
if DisplayValues<>'' then begin
P := Pos(';', DisplayValues);
if P = 0 then P := 256;
vFalse := Copy(DisplayValues, P + 1, 255);
vTrue := Copy(DisplayValues, 1, P - 1);
vFalse := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'DisplayValueFalse', vFalse, Translated);
vTrue := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'DisplayValueTrue', vTrue, Translated);
DisplayValues := vFalse+';'+vTrue;
end;
end;
end;
initialization
RegisterTranslators([TFieldTranslator, TBooleanFieldTranslator]);
end.
|
unit UUserController;
interface
uses UISearchController, UFSearchUser, Forms, Classes, SysUtils, Types, StrUtils, IniFiles,
UIRegisterController, UFUserRegister, UUser, UMessageController, FireDAC.Phys.MongoDBDataSet;
type
TUserController = class(TInterfacedObject, ISearchController, IRegisterController)
private
FView : TFSearchUser;
FViewRegister : TFUserRegister;
FHasFilters : Boolean;
function ValidateRegister: boolean;
function GetValuesFromRegisterView: TUser;
procedure AjustGrid;
procedure AjustViewToNew;
public
class procedure Execute;
procedure Initialize;
procedure Close;
procedure Search(Value : String);
procedure Add;
procedure Update(Id : String);
procedure Delete(Id : String);
procedure RegisterClose;
procedure RegisterSave;
procedure RegisterCancel;
procedure UpdateFilters;
end;
implementation
{ TUserController }
procedure TUserController.Add;
begin
FViewRegister := TFUserRegister.Create(nil);
FViewRegister.Controller := Self;
AjustViewToNew;
FViewRegister.ShowModal;
end;
procedure TUserController.AjustGrid;
begin
FView.dbgrdData.Columns[0].Visible := False;
FView.dbgrdData.Columns[1].Title.Caption := 'Nome';
FView.dbgrdData.Columns[1].Width := 380;
FView.dbgrdData.Columns[2].Title.Caption := 'Nome de Usuário';
FView.dbgrdData.Columns[2].Width := 380;
FView.dbgrdData.Columns[3].Visible := False;
FView.dbgrdData.Columns[4].Title.Caption := 'Ativo';
FView.dbgrdData.Columns[4].Width := 70;
end;
procedure TUserController.AjustViewToNew;
begin
FViewRegister.cbActive.Checked := True;
FViewRegister.cbActive.Visible := False;
end;
procedure TUserController.Close;
begin
FView.Close;
end;
procedure TUserController.Delete(Id: String);
begin
end;
class procedure TUserController.Execute;
var
UserController : TUserController;
begin
UserController := TUserController.Create;
UserController.Initialize;
end;
function TUserController.GetValuesFromRegisterView: TUser;
begin
Result := TUser.Create;
Result.Username := FViewRegister.Username;
Result.Name := FViewRegister.Name;
Result.Password := FViewRegister.Password;
Result.Active := FViewRegister.Active;
end;
procedure TUserController.Initialize;
begin
FView := TFSearchUser.Create(nil);
FView.SetController(self);
FView.imgTitle.Picture.LoadFromStream(TResourceStream.Create(HInstance,'User24px',RT_RCDATA));
FView.ShowModal;
end;
procedure TUserController.RegisterCancel;
begin
end;
procedure TUserController.RegisterClose;
begin
FViewRegister.Close;
end;
procedure TUserController.RegisterSave;
var
User: TUser;
begin
if not ValidateRegister then
Exit;
User := GetValuesFromRegisterView;
if User.Save then
TMessageController.ShowMessageSuccess('Registro salvo com sucesso.')
else
TMessageController.ShowMessageError('Houve um erro ao salvar o registro.');
end;
procedure TUserController.Search(Value: String);
var
User: TUser;
begin
User := TUser.Create;
if Value = EmptyStr then
begin
if FView.DSetMain.Active then
FView.DSetMain.Close;
FView.DSetMain.Cursor := User.GetAll;
FView.DSetMain.Active := True;
FView.DSMain.Enabled := True;
FView.dbgrdData.Update;
AjustGrid;
end
else
begin
end;
end;
procedure TUserController.Update(Id: String);
begin
end;
procedure TUserController.UpdateFilters;
begin
end;
function TUserController.ValidateRegister: boolean;
var
Passed: boolean;
begin
Passed := True;
if FViewRegister.Username = EmptyStr then
Passed := False;
if FViewRegister.Name = EmptyStr then
Passed := False;
if FViewRegister.Password = EmptyStr then
Passed := False;
if FViewRegister.ConfirmPassword = EmptyStr then
Passed := False;
if Passed then
begin
if CompareStr(FViewRegister.Password,FViewRegister.ConfirmPassword) <> 0 then
begin
FViewRegister.ShowMsgError('As senhas não conferem.');
Passed := False;
end
end
else
FViewRegister.ShowMsgError('Todos os campos são obrigatórios.');
Result := Passed;
end;
end.
|
{
License: modified LGPL with linking exception (like RTL, FCL and LCL)
See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution,
for details about the license.
See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL
}
unit mvTypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
TILE_SIZE = 256;
PALETTE_PAGE = 'Misc';
Type
{ TArea }
TArea = record
top, left, bottom, right: Int64;
end;
{ TRealPoint }
TRealPoint = Record
Lon : Double;
Lat : Double;
end;
{ TRealArea }
TRealArea = Record
TopLeft : TRealPoint;
BottomRight : TRealPoint;
end;
implementation
end.
|
unit ncSocketList;
/// ////////////////////////////////////////////////////////////////////////////
//
// TSocketList
// Written by Demos Bill, Tue 21/10/2004
//
// SocketList, the equivalent of TStringList
// but for the type of TSocket handles
//
/// ////////////////////////////////////////////////////////////////////////////
interface
uses System.Classes, System.SysUtils, System.RTLConsts, ncLines;
type
TSocketItem = record
FSocketHandle: TSocketHandle;
FLine: TncLine;
end;
PSocketItem = ^TSocketItem;
TSocketItemList = array of TSocketItem;
PSocketItemList = ^TSocketItemList;
TSocketList = class(TPersistent)
private
FList: TSocketItemList;
FCount: Integer;
FCapacity: Integer;
function GetSocketHandles(Index: Integer): TSocketHandle; register;
function GetLines(Index: Integer): TncLine; register;
procedure PutLines(Index: Integer; aLine: TncLine);
procedure SetCapacity(aNewCapacity: Integer);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure Insert(aIndex: Integer; const aSocketHandle: TSocketHandle; aLine: TncLine);
procedure Grow;
public
destructor Destroy; override;
function Add(const aSocketHandle: TSocketHandle; aLine: TncLine): Integer;
procedure Clear;
procedure Delete(aIndex: Integer); register;
function Find(const aSocketHandle: TSocketHandle; var aIndex: Integer): Boolean; register;
function IndexOf(const aSocketHandle: TSocketHandle): Integer; register;
property Count: Integer read FCount;
property SocketHandles[index: Integer]: TSocketHandle read GetSocketHandles; default;
property Lines[index: Integer]: TncLine read GetLines write PutLines;
end;
implementation
resourcestring
SDuplicateSocketHandle = 'Socket handle list does not allow duplicates';
{ TSocketList }
destructor TSocketList.Destroy;
begin
inherited Destroy;
FCount := 0;
SetCapacity(0);
end;
procedure TSocketList.AssignTo(Dest: TPersistent);
var
DestList: TSocketList;
begin
if Dest is TSocketList then
begin
DestList := TSocketList(Dest);
DestList.FCapacity := FCapacity;
DestList.FCount := FCount;
DestList.FList := Copy(FList);
end
else
raise EConvertError.CreateResFmt(@SAssignError, [ClassName, Dest.ClassName]);
end;
function TSocketList.Add(const aSocketHandle: TSocketHandle; aLine: TncLine): Integer;
begin
if Find(aSocketHandle, Result) then
raise Exception.Create(SDuplicateSocketHandle);
Insert(Result, aSocketHandle, aLine);
end;
procedure TSocketList.Clear;
begin
if FCount <> 0 then
begin
FCount := 0;
SetCapacity(0);
end;
end;
procedure TSocketList.Delete(aIndex: Integer);
begin
if (aIndex < 0) or (aIndex >= FCount) then
raise Exception.Create(Format(SListIndexError, [aIndex]));
Dec(FCount);
if aIndex < FCount then
System.Move(FList[aIndex + 1], FList[aIndex], (FCount - aIndex) * SizeOf(TSocketItem));
end;
// Binary Searching
function TSocketList.Find(const aSocketHandle: TSocketHandle; var aIndex: Integer): Boolean;
var
Low, High, Mid: Integer;
begin
Result := False;
Low := 0;
High := FCount - 1;
while Low <= High do
begin
Mid := (Low + High) shr 1;
if aSocketHandle > FList[Mid].FSocketHandle then
Low := Mid + 1
else
begin
High := Mid - 1;
if aSocketHandle = FList[Mid].FSocketHandle then
begin
Result := True;
Low := Mid;
end;
end;
end;
aIndex := Low;
end;
procedure TSocketList.Grow;
var
Delta: Integer;
begin
if FCapacity > 64 then
Delta := FCapacity div 4
else if FCapacity > 8 then
Delta := 16
else
Delta := 4;
SetCapacity(FCapacity + Delta);
end;
function TSocketList.IndexOf(const aSocketHandle: TSocketHandle): Integer;
begin
if not Find(aSocketHandle, Result) then
Result := -1;
end;
procedure TSocketList.Insert(aIndex: Integer; const aSocketHandle: TSocketHandle; aLine: TncLine);
begin
if FCount = FCapacity then
Grow;
if aIndex < FCount then
System.Move(FList[aIndex], FList[aIndex + 1], (FCount - aIndex) * SizeOf(TSocketItem));
with FList[aIndex] do
begin
FSocketHandle := aSocketHandle;
FLine := aLine;
end;
Inc(FCount);
end;
function TSocketList.GetSocketHandles(Index: Integer): TSocketHandle;
begin
if (index < 0) or (index >= FCount) then
raise Exception.Create(Format(SListIndexError, [index]));
Result := FList[index].FSocketHandle;
end;
function TSocketList.GetLines(Index: Integer): TncLine;
begin
if (index < 0) or (index >= FCount) then
raise Exception.Create(Format(SListIndexError, [index]));
Result := FList[index].FLine;
end;
procedure TSocketList.PutLines(Index: Integer; aLine: TncLine);
begin
if (index < 0) or (index >= FCount) then
raise Exception.Create(Format(SListIndexError, [index]));
FList[index].FLine := aLine;
end;
procedure TSocketList.SetCapacity(aNewCapacity: Integer);
begin
if aNewCapacity < FCount then
raise Exception.Create(Format(SListCapacityError, [aNewCapacity]));
if aNewCapacity <> FCapacity then
begin
SetLength(FList, aNewCapacity);
FCapacity := aNewCapacity;
end;
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ TArrowSeries Example }
{ Copyright (c) 1995-2001 by David Berneda }
{ All rights reserved }
{*********************************************}
unit uarrows;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Teengine, Series, ArrowCha, Chart, StdCtrls, ExtCtrls,
Buttons, TeeProcs;
type
TArrowsForm = class(TForm)
Panel1: TPanel;
CheckBox1: TCheckBox;
Chart1: TChart;
ArrowSeries1: TArrowSeries;
Timer1: TTimer;
BitBtn3: TBitBtn;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure AddRandomArrows;
end;
implementation
{$R *.dfm}
procedure TArrowsForm.FormCreate(Sender: TObject);
begin
With ArrowSeries1 do
Begin
ArrowWidth:=32;
ArrowHeight:=24;
ColorEachPoint:=True;
XValues.DateTime:=False;
YValues.DateTime:=False;
AddRandomArrows;
end;
end;
procedure TArrowsForm.AddRandomArrows;
var x0,y0,x1,y1:Double;
t:Longint;
begin
With ArrowSeries1 do
Begin
Clear;
for t:=1 to 40 do
begin
x0:=Random( 1000 );
y0:=Random( 1000 );
x1:=Random( 300 ) - 150.0;
if x1<50 then x1:=50;
x1:=x1+x0;
y1:=Random( 300 ) - 150.0;
if y1<50 then y1:=50;
y1:=y1+y0;
AddArrow( x0,y0,x1,y1, '', clTeeColor );
end;
end;
end;
procedure TArrowsForm.CheckBox1Click(Sender: TObject);
begin
Timer1.Enabled:=CheckBox1.Checked;
end;
procedure TArrowsForm.Timer1Timer(Sender: TObject);
var t:Longint;
begin
Timer1.Enabled:=False;
With ArrowSeries1 do
Begin
for t:=0 to Count-1 do
Begin
StartXValues[t]:=StartXValues[t]+Random(100)-50.0;
StartYValues[t]:=StartYValues[t]+Random(100)-50.0;
EndXValues[t] :=EndXValues[t]+Random(100)-50.0;
EndYValues[t] :=EndYValues[t]+Random(100)-50.0;
End;
Repaint;
End;
Timer1.Enabled:=True;
end;
end.
|
(* Syntaxtree Abstract: MM, 2020-05-20 *)
(* ------ *)
(* A unit to display syntax trees in abstract form *)
(* ========================================================================= *)
UNIT syntaxtree;
INTERFACE
USES CodeGen, CodeDef, SymTab;
TYPE SynTree = POINTER;
PROCEDURE NewTree(VAR t: SynTree);
PROCEDURE DisposeTree(VAR t: SynTree);
PROCEDURE WriteTree(t: SynTree);
PROCEDURE WriteTreePreOrder(t: SynTree);
PROCEDURE WriteTreeInOrder(t: SynTree);
PROCEDURE WriteTreePostOrder(t: SynTree);
FUNCTION TreeOf(s: STRING; t1, t2: SynTree): SynTree;
FUNCTION ValueOf(t: Syntree): INTEGER;
PROCEDURE EmitCodeForExprTree(t: SynTree);
IMPLEMENTATION
TYPE
NodePtr = ^Node;
Node = RECORD
left, right: NodePtr;
val: STRING;
END;
TreePtr = NodePtr;
(*-- Functions for Tree --*)
PROCEDURE NewTree(VAR t: SynTree);
BEGIN (* NewTree *)
TreePtr(t) := NIL;
END; (* NewTree *)
PROCEDURE DisposeTree(VAR t: SynTree);
BEGIN (* DisposeTree *)
IF (TreePtr(t) <> NIL) THEN BEGIN
DisposeTree(TreePtr(t)^.left);
DisposeTree(TreePtr(t)^.right);
Dispose(TreePtr(t));
END; (* IF *)
END; (* DisposeTree *)
FUNCTION NewNode(x: STRING): NodePtr;
VAR n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.val := x;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END; (* NewNode *)
PROCEDURE WriteTreeRec(t: SynTree; space: INTEGER);
VAR i: INTEGER;
BEGIN (* WriteTree *)
IF (t <> NIL) THEN BEGIN
space := space + 10;
WriteTreeRec(TreePtr(t)^.right, space);
WriteLn;
FOR i := 10 TO space DO BEGIN
Write(' ');
END; (* FOR *)
WriteLn(TreePtr(t)^.val);
WriteTreeRec(TreePtr(t)^.left, space);
END; (* IF *)
END; (* WriteTree *)
PROCEDURE WriteTree(t: Syntree);
BEGIN (* WriteTree *)
WriteTreeRec(t, 0);
END; (* WriteTree *)
FUNCTION TreeOfPtr(s: STRING; t1, t2: TreePtr): TreePtr;
VAR n: NodePtr;
BEGIN (* TreeOf *)
n := NewNode(s);
n^.left := t1;
n^.right := t2;
TreeOfPtr := n;
END; (* TreeOf *)
FUNCTION TreeOf(s: STRING; t1, t2: SynTree): SynTree;
BEGIN (* TreeOf *)
TreeOf := TreeOfPtr(s, TreePtr(t1), TreePtr(t2));
END; (* TreeOf *)
PROCEDURE WriteTreePreOrder(t: SynTree);
BEGIN (* WriteTreePreOrder *)
IF (TreePtr(t) <> NIL) THEN BEGIN
WriteLn(TreePtr(t)^.val);
WriteTreePreOrder(TreePtr(t)^.left);
WriteTreePreOrder(TreePtr(t)^.right);
END; (* IF *)
END; (* WriteTreePreOrder *)
PROCEDURE WriteTreeInOrder(t: SynTree);
BEGIN (* WriteTreeInOrder *)
IF (t <> NIL) THEN BEGIN
WriteTreeInOrder(TreePtr(t)^.left);
WriteLn(TreePtr(t)^.val);
WriteTreeInOrder(TreePtr(t)^.right);
END; (* IF *)
END; (* WriteTreeInOrder *)
PROCEDURE WriteTreePostOrder(t: SynTree);
BEGIN (* WriteTreePostOrder *)
IF (t <> NIL) THEN BEGIN
WriteTreePostOrder(TreePtr(t)^.left);
WriteTreePostOrder(TreePtr(t)^.right);
WriteLn(TreePtr(t)^.val);
END; (* IF *)
END; (* WriteTreePostOrder *)
FUNCTION ToInt(s: STRING): INTEGER;
VAR i, sum: INTEGER;
BEGIN (* ToInt *)
sum := 0;
FOR i := 1 TO Length(s) DO BEGIN
sum := sum * 10 + Ord(s[i]) - Ord('0');
END; (* FOR *)
ToInt := sum;
END; (* ToInt *)
FUNCTION IsConstant(s: STRING): BOOLEAN;
BEGIN (* IsConstant *)
IsConstant := s[1] IN ['0'..'9'];
END; (* IsConstant *)
PROCEDURE FoldConstants(VAR t: SynTree);
VAR i: INTEGER;
s: STRING;
BEGIN (* FoldConstants *)
IF (TreePtr(t)^.left <> NIL) AND (TreePtr(t)^.right <> NIL) THEN BEGIN
IF (IsConstant(TreePtr(t)^.left^.val) AND IsConstant(TreePtr(t)^.right^.val)) THEN BEGIN
CASE TreePtr(t)^.val[1] OF
'+': BEGIN i := ToInt(TreePtr(t)^.left^.val) + ToInt(TreePtr(t)^.right^.val); END;
'-': BEGIN i := ToInt(TreePtr(t)^.left^.val) - ToInt(TreePtr(t)^.right^.val); END;
'*': BEGIN i := ToInt(TreePtr(t)^.left^.val) * ToInt(TreePtr(t)^.right^.val); END;
'/': BEGIN i := ToInt(TreePtr(t)^.left^.val) DIV ToInt(TreePtr(t)^.right^.val); END;
END; (* CASE *)
Dispose(TreePtr(t)^.left);
Dispose(TreePtr(t)^.right);
TreePtr(t)^.left := NIL;
TreePtr(t)^.right := NIL;
Str(i, s);
TreePtr(t)^.val := s;
END; (* IF *)
END; (* IF *)
END; (* FoldConstants *)
PROCEDURE Optimize(VAR t: SynTree);
BEGIN (* Optimize *)
IF (TreePtr(t)^.left <> NIL) THEN
Optimize(TreePtr(t)^.left);
IF (TreePtr(t)^.right <> NIL) THEN
Optimize(TreePtr(t)^.right);
FoldConstants(TreePtr(t));
IF (TreePtr(t)^.val = '+') THEN BEGIN
IF (TreePtr(t)^.left^.val = '0') THEN BEGIN
Dispose(TreePtr(t)^.left);
TreePtr(t) := TreePtr(t)^.right;
END ELSE IF (TreePtr(t)^.right^.val = '0') THEN BEGIN
Dispose(TreePtr(t)^.right);
TreePtr(t) := TreePtr(t)^.left;
END; (* IF *)
END ELSE IF (TreePtr(t)^.val = '-') THEN BEGIN
IF (TreePtr(t)^.right^.val = '0') THEN BEGIN
Dispose(TreePtr(t)^.right);
TreePtr(t) := TreePtr(t)^.left;
END; (* IF *)
END ELSE IF (TreePtr(t)^.val = '*') THEN BEGIN
IF (TreePtr(t)^.left^.val = '1') THEN BEGIN
Dispose(TreePtr(t)^.left);
TreePtr(t) := TreePtr(t)^.right;
END ELSE IF (TreePtr(t)^.right^.val = '1') THEN BEGIN
Dispose(TreePtr(t)^.right);
TreePtr(t) := TreePtr(t)^.left;
END; (* IF *)
END ELSE IF (TreePtr(t)^.val = '/') THEN BEGIN
IF (TreePtr(t)^.right^.val = '1') THEN BEGIN
Dispose(TreePtr(t)^.right);
TreePtr(t) := TreePtr(t)^.left;
END; (* IF *)
END; (* IF *)
END; (* Optimize *)
PROCEDURE EmitOpCode(t: SynTree);
VAR s: STRING;
BEGIN (* EmitOpCode *)
IF t <> NIL THEN BEGIN
EmitCodeForExprTree(TreePtr(t)^.left);
EmitCodeForExprTree(TreePtr(t)^.right);
s := TreePtr(t)^.val;
CASE s[1] OF
'+': BEGIN Emit1(AddOpc); END;
'-': BEGIN Emit1(SubOpc); END;
'*': BEGIN Emit1(MulOpc); END;
'/': BEGIN Emit1(DivOpc); END;
'0'..'9': BEGIN Emit2(LoadConstOpc, ToInt(s)); END;
ELSE BEGIN Emit2(LoadValOpc, AddrOf(s)); END;
END;
END;
END; (* EmitOpCode *)
PROCEDURE EmitCodeForExprTree(t: SynTree);
BEGIN (* EmitCodeForExprTree *)
IF (t <> NIL) THEN BEGIN
WriteTree(t);
Optimize(t);
WriteLn('----------Optimized----------');
WriteTree(t);
WriteLn('#############################');
EmitOpCode(t);
END; (* IF *)
END; (* EmitCodeForExprTree *)
FUNCTION ValueOfTreePtr(t: TreePtr): INTEGER;
BEGIN (* ValueOfTreePtr *)
IF (t <> NIL) THEN BEGIN
CASE t^.val[1] OF
'+': BEGIN ValueOfTreePtr := ValueOfTreePtr(t^.left) + ValueOfTreePtr(t^.right); END;
'-': BEGIN ValueOfTreePtr := ValueOfTreePtr(t^.left) - ValueOfTreePtr(t^.right); END;
'*': BEGIN ValueOfTreePtr := ValueOfTreePtr(t^.left) * ValueOfTreePtr(t^.right); END;
'/': BEGIN ValueOfTreePtr := ValueOfTreePtr(t^.left) DIV ValueOfTreePtr(t^.right); END;
ELSE BEGIN
ValueOfTreePtr := ToInt(t^.val);
END; (* ELSE *)
END; (* CASE *)
END; (* IF *)
END; (* ValueOfTreePtr *)
FUNCTION ValueOf(t: SynTree): INTEGER;
BEGIN (* ValueOf *)
ValueOf := ValueOfTreePtr(TreePtr(t));
END; (* ValueOf *)
(*-- END Functions for Tree --*)
END. (* syntaxtree_canon *) |
unit SortExtendedArrayBenchmark2Unit;
{$mode delphi}
interface
uses Windows, BenchmarkClassUnit, Classes, Math;
type
TQuickSortExtendedArrayThreads = class(TFastcodeMMBenchmark)
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses SysUtils;
type
TSortExtendedArrayThread = class(TThread)
FBenchmark: TFastcodeMMBenchmark;
procedure Execute; override;
end;
TExtended = record
X : Extended;
Pad1, Pad2, Pad3, Pad4, Pad5, Pad6 : Byte;
end;
TExtendedArray = array[0..1000000] of TExtended;
PExtendedArray = ^TExtendedArray;
function SortCompareExtended(Item1, Item2: Pointer): Integer;
var
Diff: Extended;
begin
Diff := PExtended(Item1)^ - PExtended(Item2)^;
if Diff < 0 then
Result := -1
else
if Diff > 0 then
Result := 1
else
Result := 0;
end;
procedure TSortExtendedArrayThread.Execute;
var
ExtArray: PExtendedArray;
I, J, RunNo, Size: Integer;
List: TList;
const
MAXRUNNO: Integer = 8;
MAXELEMENTVALUE: Integer = MAXINT;
MINSIZE: Integer = 100;
MAXSIZE: Integer = 10000;
RepeatCount = 10;
begin
for J := 1 to RepeatCount do
begin
GetMem(ExtArray, MINSIZE * SizeOf(TExtended));
try
for RunNo := 1 to MAXRUNNO do
begin
Size := Random(MAXSIZE-MINSIZE) + MINSIZE;
ReallocMem(ExtArray, Size * SizeOf(TExtended));
List := TList.Create;
try
List.Count := Size;
for I := 0 to Size-1 do
begin
ExtArray[I].X := Random(MAXELEMENTVALUE);
List[I] := @ExtArray[I].X;
end;
List.Sort(SortCompareExtended);
finally
List.Free;
end;
end;
finally
FreeMem(ExtArray);
end;
FBenchmark.UpdateUsageStatistics;
end;
end;
class function TQuickSortExtendedArrayThreads.GetBenchmarkDescription:
string;
begin
Result := 'A benchmark that measures read and write speed to an array of Extendeds. '
+ 'The Extended type is padded to be 16 byte. '
+ 'Bonus is given for 16 byte alignment of array '
+ 'Will also reveil cache set associativity related issues. '
+ 'Access pattern is created by X sorting array of random values using the QuickSort algorithm implemented in TList. '
+ 'Measures memory usage after all blocks have been freed. '
+ 'Benchmark submitted by Avatar Zondertau, based on a benchmark by Dennis Kjaer Christensen.';
end;
class function TQuickSortExtendedArrayThreads.GetBenchmarkName: string;
begin
Result := 'QuickSortExtendedArrayBenchmark';
end;
class function TQuickSortExtendedArrayThreads.GetCategory:
TBenchmarkCategory;
begin
Result := bmMemoryAccessSpeed;
end;
class function TQuickSortExtendedArrayThreads.GetSpeedWeight: Double;
begin
Result := 0.75;
end;
procedure TQuickSortExtendedArrayThreads.RunBenchmark;
var
SortExtendedArrayThread1, SortExtendedArrayThread2 :
TSortExtendedArrayThread;
SortExtendedArrayThread3, SortExtendedArrayThread4 :
TSortExtendedArrayThread;
begin
inherited;
SortExtendedArrayThread1 := TSortExtendedArrayThread.Create(True);
SortExtendedArrayThread2 := TSortExtendedArrayThread.Create(True);
SortExtendedArrayThread3 := TSortExtendedArrayThread.Create(True);
SortExtendedArrayThread4 := TSortExtendedArrayThread.Create(True);
SortExtendedArrayThread1.FreeOnTerminate := False;
SortExtendedArrayThread2.FreeOnTerminate := False;
SortExtendedArrayThread3.FreeOnTerminate := False;
SortExtendedArrayThread4.FreeOnTerminate := False;
SortExtendedArrayThread1.Priority := tpLower;
SortExtendedArrayThread2.Priority := tpNormal;
SortExtendedArrayThread3.Priority := tpHigher;
SortExtendedArrayThread4.Priority := tpHighest;
SortExtendedArrayThread1.FBenchmark := Self;
SortExtendedArrayThread2.FBenchmark := Self;
SortExtendedArrayThread3.FBenchmark := Self;
SortExtendedArrayThread4.FBenchmark := Self;
SortExtendedArrayThread1.Resume;
SortExtendedArrayThread2.Resume;
SortExtendedArrayThread3.Resume;
SortExtendedArrayThread4.Resume;
SortExtendedArrayThread1.WaitFor;
SortExtendedArrayThread2.WaitFor;
SortExtendedArrayThread3.WaitFor;
SortExtendedArrayThread4.WaitFor;
SortExtendedArrayThread1.Free;
SortExtendedArrayThread2.Free;
SortExtendedArrayThread3.Free;
SortExtendedArrayThread4.Free;
end;
end.
|
unit Test.Devices.Streamlux700f;
interface
uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst,
Test.Devices.Base.ReqParser;
type
TStreamlux700fReqCreatorTest = class(TDeviceReqCreatorTestBase)
protected
function GetDevType(): int; override;
procedure DoCheckRequests(); override;
end;
TStreamlux700fParserTest = class(TDeviceReqParserTestBase)
protected
function GetDevType(): int; override;
function GetThreadClass(): TSQLWriteThreadForTestClass; override;
published
procedure CommonVal;
procedure Quality;
procedure ErrorCode;
end;
implementation
uses
Threads.ResponceParser, Devices.ModbusBase, SysUtils, System.Math;
{ TADCPChannelMasterReqCreatorTest }
procedure TStreamlux700fReqCreatorTest.DoCheckRequests;
begin
CheckReqString(0, 'DQD'#13);
CheckReqString(1, 'DQH'#13);
CheckReqString(2, 'DQS'#13);
CheckReqString(3, 'DV'#13);
CheckReqString(4, 'DS'#13);
CheckReqString(5, 'DC'#13);
CheckReqString(6, 'DL'#13);
CheckReqString(7, 'DI+'#13);
end;
function TStreamlux700fReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_STREAMLUX700F;
end;
{ TADCPChannelMasterParserTest }
function TStreamlux700fParserTest.GetDevType: int;
begin
Result := DEVTYPE_STREAMLUX700F;
end;
type
TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest);
function TStreamlux700fParserTest.GetThreadClass: TSQLWriteThreadForTestClass;
begin
Result := TLocalSQLWriteThreadForTest;
end;
procedure TStreamlux700fParserTest.Quality;
begin
gbv.ReqDetails.rqtp := rqtStreamlux700f;
gbv.gmTime := NowGM();
gbv.SetBufRec('UP:01.0,DN:34.5,Q=67'#13#10);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_STREAMLUX700F;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 7;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI1');
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI1');
Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 67), 'AI1');
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI1');
end;
procedure TStreamlux700fParserTest.ErrorCode;
begin
gbv.ReqDetails.rqtp := rqtStreamlux700f;
gbv.gmTime := NowGM();
gbv.SetBufRec('*I'#13#10);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_STREAMLUX700F;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 6;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'RecognizeAndCheckChannel');
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'count');
CheckEquals(ord('I'), TLocalSQLWriteThreadForTest(thread).Values[0].Val, 'val');
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'time');
gbv.SetBufRec('*M'#13#10);
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresUnknown, 'RecognizeAndCheckChannel wrong');
end;
procedure TStreamlux700fParserTest.CommonVal;
begin
gbv.ReqDetails.rqtp := rqtStreamlux700f;
gbv.gmTime := NowGM();
gbv.SetBufRec('+3.405755E+01m3/m'#13#10);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_STREAMLUX700F;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 1;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI1');
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI1');
Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 34.05755), 'AI1');
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI1');
gbv.gmTime := NowGM();
gbv.SetBufRec('+3.211965E+01 m3'#13#10);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_CNT_MTR;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := 1;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'MTR1');
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'MTR1');
Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 32.11965), 'MTR1');
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'MTR1');
end;
initialization
RegisterTest('GMIOPSrv/Devices/Streamlux700f', TStreamlux700fReqCreatorTest.Suite);
RegisterTest('GMIOPSrv/Devices/Streamlux700f', TStreamlux700fParserTest.Suite);
end.
|
unit MediaStream.Framer;
interface
uses Classes, SysUtils, MediaProcessing.Definitions;
type
TStreamFramerRandomAccess = class;
TInfoState =
(isNotSupported, //Получение сведений не поддерживается
isNotFound, //Сведения не найдены
isOK //Все хорошо, сведения доступны
);
TVideoInfo = record
State : TInfoState;
Width : integer;
Height: integer;
end;
TAudioInfo = record
State : TInfoState;
Channels: cardinal;
BitsPerSample: cardinal;
SamplesPerSec: cardinal;
end;
TStreamFramer = class
public
constructor Create; virtual;
procedure OpenStream(aStream: TStream); virtual; abstract;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; virtual; abstract;
function StreamInfo: TBytes; virtual; abstract;
function VideoStreamType: TStreamType; virtual; abstract;
function VideoInfo: TVideoInfo; virtual;
function AudioStreamType: TStreamType; virtual; abstract;
function AudioInfo: TAudioInfo; virtual;
function RandomAccess: TStreamFramerRandomAccess; virtual;
end;
TStreamInfo = record
//Длительность файла в миллисекундах
Length:int64;
//Кол-во кадров видео
VideoFrameCount: int64;
end;
//Расширение фреймера для поддержки произвольного доступа
TStreamFramerRandomAccess = class
protected
function GetPosition: int64; virtual; abstract;
procedure SetPosition(const Value: int64); virtual; abstract;
public
function StreamInfo: TStreamInfo; virtual; abstract;
//Переместиться на предыдущий опорный видео кадр, который затем можно будет получить с помощью GetNextFrame
function SeekToPrevVideoKeyFrame: boolean; virtual; abstract;
//Позиция в миллисекундах
property Position: int64 read GetPosition write SetPosition;
end;
TStreamFramerClass = class of TStreamFramer;
implementation
{ TStreamFramer }
function TStreamFramer.AudioInfo: TAudioInfo;
begin
result.State:=isNotSupported;
end;
constructor TStreamFramer.Create;
begin
end;
function TStreamFramer.RandomAccess: TStreamFramerRandomAccess;
begin
result:=nil;
end;
function TStreamFramer.VideoInfo: TVideoInfo;
begin
result.State:=isNotSupported;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
(*
PRNDRV.PAS
PROCEDURE AttachPrinter(Printer : Printers);
{-define the Lst device to print to the specified printer}
PROCEDURE ReleasePrinter;
{-deassign the Lst device and restore the printer timeout}
printer driver to provide clean error handling
modification of Kim Kokkonen's TUFPRT, to include his later
changes, some corrections to error handling, & restore of display
after error message
*)
Uses
Dos;
TYPE
Printers = (LPT1, LPT2, LPT3, LPT4, NoPrinter);
CONST
ActivePrinter : Printers = NoPrinter;
VAR
SavePrintTimeOut : Byte;
{
the following bytes normally equal $14, providing 20 retries on printer
busy calls. Set to 1 for a single retry (timeout takes about 2 seconds).
Do not set to 0 or system will retry forever.
}
PrintTimeOut : ARRAY[Printers] OF Byte ABSOLUTE $40 : $78;
PROCEDURE PrintChar(ch : Char);
{-print the character ch, handle errors & loop when busy }
{
**********************************************************************
CANNOT USE TURBO I/O FUNCTIONS INSIDE HERE DUE TO RE-ENTRANCY PROBLEMS
**********************************************************************
}
TYPE
PrintErrors =
(TimeOut, unused1, unused2, IOerror, Selected,
OutOfPaper, Acknowledge, Busy, NoError);
DisplayString = STRING[80];
registers =
RECORD
CASE Integer OF
1 : (ax, bx, cx, dx, bp, si, di, ds, es, flags : Integer);
{! 1. Instead use the Registers type from the Turbo 4.0 DOS unit. ^ }
2 : (al, ah, bl, bh, cl, ch, dl, dh : Byte);
END;
CONST
PrintErrorMsg : ARRAY[PrintErrors] OF DisplayString =
('Printer Timeout Error', '', '', 'Printer Not Selected',
'Printer Not Selected', 'Printer Out of Paper',
'Printer Acknowledge Error', 'Printer Busy', '');
EndStr : DisplayString = #13#10#36;
{maximum number of replies with busy before calling it a timeout error.
may need to be adjusted empirically to avoid false timeouts}
BusyMax = 100;
VAR
reg : registers;
Error : PrintErrors;
BusyCount : Integer;
VAR err : Byte;
PROCEDURE writestring(s : DisplayString);
{-write string to standard output}
VAR
reg : registers;
BEGIN
reg.ah := 9;
reg.ds := Seg(s);
reg.dx := Ofs(s[1]);
MsDos(Dos.Registers(reg));
{! 2. Paramete^r to MsDos must be of the type Registers defined in DOS unit.}
END; {displaystring}
PROCEDURE getchar(VAR response : Char);
{-get a character from the keyboard}
VAR
reg : registers;
BEGIN
reg.ah := 0;
Intr($16, Dos.Registers(reg));
response := Chr(reg.al);
END; {getchar}
PROCEDURE HandleError(Error : PrintErrors);
{-handle user-oriented error conditions}
TYPE
ScreenContents = ARRAY[1..4000] OF Byte;
VAR
CrtMode : Byte ABSOLUTE $0040 : $0049;
MonoBuffer : ScreenContents ABSOLUTE $B000 : $0000;
ColorBuffer : ScreenContents ABSOLUTE $B800 : $0000;
savescreen : ScreenContents;
response : Char;
BEGIN
IF CrtMode = 7 THEN
savescreen := MonoBuffer
ELSE
savescreen := ColorBuffer; { save screen contents }
writestring(PrintErrorMsg[Error]+EndStr);
writestring('Correct condition and then press <ENTER> '+#36);
REPEAT getchar(response) UNTIL (response IN [#13, #3]);
writestring(EndStr);
IF response = #3 THEN Halt; {Ctrl-C}
BusyCount := 0;
IF CrtMode = 7 THEN
MonoBuffer := savescreen
ELSE
ColorBuffer := savescreen; { restore screen contents }
END; {handleerror}
PROCEDURE int17(Printer : Printers; func : Byte;
CharToPrint : Byte; VAR err : Byte);
{-call the printer interrupt and return error information}
{-func =0 to print, =2 to just check status}
BEGIN
INLINE(
{! 3. Ne^w stack conventions require that many Inlines be rewritten.}
$8B/$56/$0C/ {MOV DX,[BP+0C] - get printer number}
$8A/$66/$0A/ {MOV AH,[BP+0A] - get printer function}
$8A/$46/$08/ {MOV AL,[BP+08] - get character to print}
$CD/$17/ {INT 17}
$C4/$7E/$04/ {LES DI,[BP+04] - get address of error}
$26/$88/$25); {MOV ES:[DI],AH - return error if any}
END; {int17}
BEGIN { PrintChar }
IF ActivePrinter = NoPrinter THEN BEGIN
writestring('program error: no printer is selected'+EndStr);
Exit;
END;
reg.dx := Ord(ActivePrinter); {equals 0..3}
BusyCount := 0;
REPEAT
{print the character}
int17(ActivePrinter, 0, Ord(ch), err);
{check for errors}
IF (err AND 128) <> 0 THEN BEGIN
{printer busy}
BusyCount := Succ(BusyCount);
IF BusyCount < BusyMax THEN
Error := Busy
ELSE BEGIN
{busy too long, call it a timeout}
HandleError(TimeOut);
Error := TimeOut;
END;
END ELSE IF (err AND 41) <> 0 THEN BEGIN
{a "hard" error}
IF (err AND 32) <> 0 THEN
HandleError(OutOfPaper)
ELSE IF (err AND 8) <> 0 THEN
HandleError(IOerror)
ELSE HandleError(TimeOut);
Error := IOerror;
END ELSE
Error := NoError;
UNTIL Error = NoError;
END; {printchar}
PROCEDURE AttachPrinter(Printer : Printers);
{-define the Lst device to print to the specified printer}
BEGIN
IF ActivePrinter = NoPrinter THEN BEGIN
ActivePrinter := Printer;
LstOutPtr := Ofs(PrintChar);
{! 4. Us^e new textfile device drivers to replace I/O Ptr references.}
{save current printer timeout}
SavePrintTimeOut := PrintTimeOut[Printer];
{set to minimum timeout period}
PrintTimeOut[Printer] := 1;
END ELSE
WriteLn(Con,
{! 5. Special de^vices Con, Trm, Aux, Usr are not supported in Turbo 4.0.}
'program error: only one printer can be protected at a time');
END; {protectprinter}
PROCEDURE ReleasePrinter;
{-deassign the Lst device and restore the printer timeout}
BEGIN
IF ActivePrinter <> NoPrinter THEN BEGIN
PrintTimeOut[ActivePrinter] := SavePrintTimeOut;
ActivePrinter := NoPrinter;
END;
END; {restoreprinter}
{end of include portion
***********************************************************************}
(*
{demonstration follows}
VAR
i : Integer;
prn : text;
BEGIN
assign(prn,'LST:');
WriteLn(prn, 'using TURBO list device'); {this doesn't print}
WriteLn(Lst, 'using DOS list device'); { this does not }
AttachPrinter(LPT1);
WriteLn(Lst, 'using PRNDRV.PAS device'); { this prints }
ReleasePrinter;
{ this generates the 'printer not selected' error }
{ I figured ReleasePrinter was supposed to give it back }
WriteLn(Lst, 'using DOS list device');
END.
*)
|
unit eSocial.Models.Entities.Operacao;
interface
uses
eSocial.Models.DAO.Interfaces;
type
TOperacao = class
private
[weak]
FParent : iModelDAOEntity<TOperacao>;
FCompetencia : String;
FInsercao ,
FAlteracao,
FExclusao : Boolean;
public
constructor Create(aParent : iModelDAOEntity<TOperacao>);
destructor Destroy; override;
function Competencia(Value : String) : TOperacao; overload;
function Competencia : String; overload;
function Insercao(Value : Boolean) : TOperacao; overload;
function Insercao : Boolean; overload;
function Alteracao(Value : Boolean) : TOperacao; overload;
function Alteracao : Boolean; overload;
function Exclusao(Value : Boolean) : TOperacao; overload;
function Exclusao : Boolean; overload;
function Processar : Boolean; overload;
function &End : iModelDAOEntity<TOperacao>;
end;
implementation
uses
System.SysUtils;
{ TOperacao }
constructor TOperacao.Create(aParent: iModelDAOEntity<TOperacao>);
begin
FParent := aParent;
FCompetencia := FormatDaTeTime('yyyymm', Date);
FInsercao := False;
FAlteracao := False;
FExclusao := False;
end;
destructor TOperacao.Destroy;
begin
inherited;
end;
function TOperacao.Alteracao(Value: Boolean): TOperacao;
begin
Result := Self;
FAlteracao := Value;
end;
function TOperacao.Alteracao: Boolean;
begin
Result := FAlteracao;
end;
function TOperacao.Competencia: String;
begin
Result := FCompetencia;
end;
function TOperacao.Competencia(Value: String): TOperacao;
begin
Result := Self;
FCompetencia := Copy(Value.Trim, 1, 6);
end;
function TOperacao.Exclusao: Boolean;
begin
Result := FExclusao;
end;
function TOperacao.Exclusao(Value: Boolean): TOperacao;
begin
Result := Self;
FExclusao := Value;
end;
function TOperacao.Insercao(Value: Boolean): TOperacao;
begin
Result := Self;
FInsercao := Value;
end;
function TOperacao.Insercao: Boolean;
begin
Result := FInsercao;
end;
function TOperacao.Processar: Boolean;
begin
Result := FInsercao or FAlteracao or FExclusao;
end;
function TOperacao.&End: iModelDAOEntity<TOperacao>;
begin
Result := FParent;
end;
end.
|
// A benchmark to measure raw performance and fragmentation resistance.
// Alternates large number of small string and small number of large string allocations.
// Pure GetMem / FreeMem benchmark without reallocations, similar to WildThreads Benchmark.
// 8-thread version that has approx. same memory footprint and CPU load as single-thread version.
unit RawPerformanceMultiThread;
interface
uses
Windows, BenchmarkClassUnit, Classes, Math;
type
TRawPerformanceMultiThread = class(TFastcodeMMBenchmark)
private
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses
SysUtils;
type
TRawPerformanceThread = class(TThread)
public
FBenchmark: TFastcodeMMBenchmark;
procedure Execute; override;
end;
const
THREADCOUNT = 8;
procedure TRawPerformanceThread.Execute;
const
POINTERS = 2039; // take prime just below 2048 (scaled down 8x from single-thread)
MAXCHUNK = 1024; // take power of 2
REPEATCOUNT = 4;
var
i, j, n, Size, LIndex: Cardinal;
s: array [0..POINTERS - 1] of string;
begin
for j := 1 to REPEATCOUNT do
begin
n := Low(s);
for i := 1 to 1 * 1024 * 1024 do begin
if i and $FF < $F0 then // 240 times out of 256 ==> chunk < 1 kB
Size := (4 * i) and (MAXCHUNK-1) + 1
else if i and $FF <> $FF then // 15 times out of 256 ==> chunk < 32 kB
Size := 16 * n + 1
else // 1 time out of 256 ==> chunk < 256 kB
Size := 128 * n + 1;
s[n] := '';
SetLength(s[n], Size);
//start and end of string are already assigned, access every 4K page in the middle
LIndex := 1;
while LIndex <= Size do
begin
s[n][LIndex] := #1;
Inc(LIndex, 4096);
end;
Inc(n);
if n > High(s) then
n := Low(s);
if i and $FFFF = 0 then
FBenchmark.UpdateUsageStatistics;
end;
FBenchmark.UpdateUsageStatistics;
for n := Low(s) to High(s) do
s[n] := '';
end;
end;
{ TRawPerformanceMultiThread }
class function TRawPerformanceMultiThread.GetBenchmarkDescription: string;
begin
Result := 'A benchmark to measure raw performance and fragmentation resistance. ' +
'Allocates large number of small strings (< 1 kB) and small number of larger ' +
'(< 32 kB) to very large (< 256 kB) strings. 8-thread version.';
end;
class function TRawPerformanceMultiThread.GetBenchmarkName: string;
begin
Result := 'Raw Performance 8 threads';
end;
class function TRawPerformanceMultiThread.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadAllocAndFree;
end;
procedure TRawPerformanceMultiThread.RunBenchmark;
var
Threads: array [0..THREADCOUNT - 1] of TRawPerformanceThread;
i: integer;
begin
inherited;
for i := 0 to THREADCOUNT - 1 do begin
Threads[i] := TRawPerformanceThread.Create(True);
Threads[i].FreeOnTerminate := False;
Threads[i].FBenchmark := Self;
end;
Sleep(0);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_ABOVE_NORMAL);
for i := 0 to THREADCOUNT - 1 do
Threads[i].Resume;
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_NORMAL);
for i := 0 to THREADCOUNT - 1 do begin
Threads[i].WaitFor;
Threads[i].Free;
end;
end;
end.
|
unit UGeometry;
{$mode objfpc}{$H+}
interface
uses
Classes, math;
type
TFloatPoint = record
X, Y: Double;
end;
TFloatRect = record
Left, Right, Top, Bottom: Double;
end;
function FloatPoint(X, Y: Double): TFloatPoint;
function FloatPoint(APoint: TPoint): TFloatPoint;
function Point(AFloatPoint: TFloatPoint): TPoint; overload;
function Rect(a, b: TPoint): TRect; overload;
function FloatRect(a, b: TFloatPoint): TFloatRect;
function Intersection(a, b, c, d: TPoint): Boolean;
function Intersection(ARect: TRect; p1, p2: TPoint): Boolean; overload;
function Intersection(ARect1, ARect2: TRect): Boolean; overload;
function IsPointIn(p, p1, p2: TPoint): Boolean;
function IsPointIn(p: TPoint; rect: TRect): Boolean; overload;
function IsRectIn(rect1, rect2: TRect): Boolean;
function CircleSegmentIntersection(p1, p2, center: TPoint; r: Integer): Boolean;
operator +(a, b: TFloatPoint): TFloatPoint;
operator -(a, b: TFloatPoint): TFloatPoint;
operator +(a, b: TPoint): TPoint;
operator -(a, b: TPoint): TPoint;
operator +(a: TPoint; b: TFloatPoint): TFloatPoint;
operator +(a: TFloatPoint; b: TPoint): TFloatPoint;
operator -(a: TFloatPoint; b: TPoint): TFloatPoint;
operator -(a: TPoint; b: TFloatPoint): TFloatPoint;
operator /(a: TFloatPoint; b: Double): TFloatPoint;
operator *(a: TFloatPoint; b: Double): TFloatPoint;
operator /(a: TPoint; b: Double): TFloatPoint;
operator div(a: TPoint; b: Integer): TPoint;
type
TFloatPoints = array of TFloatPoint;
type
TPoints = array of TPoint;
implementation
function FloatPoint(X, Y: Double): TFloatPoint;
begin
Result.X := X;
Result.Y := Y;
end;
function FloatPoint(APoint: TPoint): TFloatPoint;
begin
Result.X := APoint.X;
Result.Y := APoint.Y;
end;
function Point(AFloatPoint: TFloatPoint): TPoint;
begin
Result.X := round(AFloatPoint.X);
Result.Y := round(AFloatPoint.Y);
end;
function Rect(a, b: TPoint): TRect;
begin
Result.Left := Min(a.X, b.X);
Result.Top := Min(a.Y, b.Y);
Result.Right := Max(a.X, b.X);
Result.Bottom := Max(a.Y, b.Y);
end;
function FloatRect(a, b: TFloatPoint): TFloatRect;
begin
Result.Left := Min(a.X, b.X);
Result.Top := Min(a.Y, b.Y);
Result.Right := Max(a.X, b.X);
Result.Bottom := Max(a.Y, b.Y);
end;
function Intersection(a, b, c, d: TPoint): Boolean;
procedure swap(var a, b: Integer);
var t: Integer;
begin
t := a;
a := b;
b := t;
end;
function area(a, b, c: TPoint): Integer;
begin
Result := (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
end;
function intersect(a, b, c, d: Integer): Boolean;
begin
if (a > b) then
swap(a, b);
if (c > d) then
swap(c, d);
Result := Max(a, c) <= Min(b, d);
end;
begin
Result := intersect(a.x, b.x, c.x, d.x) and
intersect(a.y, b.y, c.y, d.y) and
(area(a,b,c) * area(a,b,d) <= 0) and
(area(c,d,a) * area(c,d,b) <= 0);
end;
function Intersection(ARect: TRect; p1, p2: TPoint): Boolean;
begin
Result := IsPointIn(p1, ARect) or IsPointIn(p2, ARect);
if Result then
exit;
Result :=
Intersection(Point(ARect.Left, ARect.Top), Point(ARect.Right, ARect.Top), p1, p2) or
Intersection(Point(ARect.Left, ARect.Bottom), Point(ARect.Right, ARect.Bottom), p1, p2) or
Intersection(Point(ARect.Left, ARect.Top), Point(ARect.Left, ARect.Bottom), p1, p2) or
Intersection(Point(ARect.Right, ARect.Top), Point(ARect.Right, ARect.Bottom), p1, p2);
end;
function Intersection(ARect1, ARect2: TRect): Boolean;
begin
Result := IsRectIn(ARect1, ARect2) or IsRectIn(ARect2, ARect1);
if Result then
exit;
Result :=
Intersection(ARect2, Point(ARect1.Left, ARect1.Top), Point(ARect1.Right, ARect1.Top)) or
Intersection(ARect2, Point(ARect1.Left, ARect1.Bottom), Point(ARect1.Right, ARect1.Bottom)) or
Intersection(ARect2, Point(ARect1.Left, ARect1.Top), Point(ARect1.Left, ARect1.Bottom)) or
Intersection(ARect2, Point(ARect1.Right, ARect1.Top), Point(ARect1.Right, ARect1.Bottom));
end;
function IsPointIn(p, p1, p2: TPoint): Boolean;
begin
Result :=
(p.X <= Max(p1.x, p2.x)) and (p.X >= Min(p1.x, p2.x)) and
(p.Y <= Max(p1.y, p2.y)) and (p.Y >= Min(p1.y, p2.y));
end;
function IsPointIn(p: TPoint; rect: TRect): Boolean;
begin
Result := IsPointIn(p, Point(rect.Left,rect.Top),
Point(rect.Right, rect.Bottom));
end;
function IsRectIn(rect1, rect2: TRect): Boolean;
begin
Result :=
IsPointIn(Point(rect1.left, rect1.top), rect2) or
IsPointIn(Point(rect1.right, rect1.top), rect2) or
IsPointIn(Point(rect1.left, rect1.bottom), rect2) or
IsPointIn(Point(rect1.right, rect1.bottom), rect2);
end;
function CircleSegmentIntersection(p1, p2, center: TPoint; r: Integer): Boolean;
var
x1, y1, x2, y2, dx, dy, a, b, c: Double;
begin
x1 := p1.X - center.X;
x2 := p2.X - center.X;
y1 := p1.Y - center.Y;
y2 := p2.Y - center.Y;
dx := x2 - x1;
dy := y2 - y1;
a := dx * dx + dy * dy;
b := 2 * (x1 * dx + y1 * dy);
c := x1 * x1 + y1 * y1 - R * R;
if -b < 0 then
begin
Result := c < 0;
exit;
end;
if -b < (2 * a) then
begin
Result := (4 * a * c - b * b) < 0;
exit;
end;
Result := a + b + c < 0;
end;
operator +(a, b: TFloatPoint): TFloatPoint;
begin
Result.X := a.X + b.X;
Result.Y := a.Y + b.Y;
end;
operator -(a, b: TFloatPoint): TFloatPoint;
begin
Result.X := a.X - b.X;
Result.Y := a.Y - b.Y;
end;
operator +(a, b: TPoint): TPoint;
begin
Result.X := a.X + b.X;
Result.Y := a.Y + b.Y;
end;
operator -(a, b: TPoint): TPoint;
begin
Result.X := a.X - b.X;
Result.Y := a.Y - b.Y;
end;
operator +(a: TPoint; b: TFloatPoint): TFloatPoint;
begin
Result.X := a.X + b.X;
Result.Y := a.Y + b.Y;
end;
operator +(a: TFloatPoint; b: TPoint): TFloatPoint;
begin
Result.X := a.X + b.X;
Result.Y := a.Y + b.Y;
end;
operator -(a: TFloatPoint; b: TPoint): TFloatPoint;
begin
Result.X := a.X - b.X;
Result.Y := a.Y - b.Y;
end;
operator -(a: TPoint; b: TFloatPoint): TFloatPoint;
begin
Result.X := a.X - b.X;
Result.Y := a.Y - b.Y;
end;
operator / (a: TFloatPoint; b: Double): TFloatPoint;
begin
Result.X := a.X / b;
Result.Y := a.Y / b;
end;
operator * (a: TFloatPoint; b: Double): TFloatPoint;
begin
Result.X := a.X * b;
Result.Y := a.Y * b;
end;
operator / (a: TPoint; b: Double): TFloatPoint;
begin
Result.X := a.X / b;
Result.Y := a.Y / b;
end;
operator div(a: TPoint; b: Integer): TPoint;
begin
Result.X := a.X div b;
Result.Y := a.Y div b;
end;
end.
|
unit EnterDateDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Db, DBTables, Mask;
type
TEnterDateDialogForm = class(TForm)
PromptLabel: TLabel;
OKButton: TBitBtn;
CancelButton: TBitBtn;
DateEdit: TMaskEdit;
procedure OKButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
DateEntered : TDateTime;
end;
var
EnterDateDialogForm: TEnterDateDialogForm;
implementation
{$R *.DFM}
uses GlblVars, WinUtils;
{===============================================}
Procedure TEnterDateDialogForm.OKButtonClick(Sender: TObject);
var
DateOK : Boolean;
begin
If (DateEdit.Text = ' / / ')
then
begin
MessageDlg('Please enter a date.', mtError,
[mbOK], 0);
DateEdit.SetFocus;
end
else
begin
DateOK := True;
try
DateEntered := StrToDate(DateEdit.Text);
except
MessageDlg(DateEdit.Text + ' is not a valid date.' + #13 +
'Please re-enter.', mtInformation, [mbOK], 0);
end;
If DateOK
then ModalResult := idOK;
end; {else of If (DateEdit.Text = ' / / ')}
end; {OKButtonClick}
end.
|
unit uOtherObjects;
interface
uses Buttons, Classes, SysUtils, Graphics, Types, Math, uMyTypes;
type
TMultiselectButton = class(TObject)
private
objID: integer; // ID feature
objCaption: string;
objTop: integer;
objLeft: Integer;
objWidth: Integer;
objHeight: Integer;
objPadding: Integer;
objBox: TRect;
objFontColor: TColor;
objHighlighted: Boolean;
procedure UpdateBoundingBox;
procedure SetTop(value: Integer);
procedure SetLeft(value: Integer);
procedure SetWidth(value: Integer);
procedure SetHeight(value: Integer);
published
property Caption: string read objCaption write objCaption;
constructor Create(parent: TObject); virtual;
procedure Draw;
property FontColor: TColor read objFontColor write objFontColor;
property Height: Integer read objHeight write SetHeight;
property Highlighted: Boolean read objHighlighted write objHighlighted;
property ID: integer read objID write objID;
property Left: Integer read objLeft write SetLeft;
function PointIsOnButton(X, Y: Integer): Boolean;
property Top: Integer read objTop write SetTop;
property Width: Integer read objWidth write SetWidth;
end;
type
TMultiselectButtonsContainer = class(TObject)
private
_boundingBox: TRect;
_buttons: array of TMultiselectButton;
_doubleClickWaiting: Boolean;
procedure SetDoubleClickWaiting(value: Boolean);
published
procedure Clear;
property DoubleClickWaiting: Boolean read _doubleClickWaiting write SetDoubleClickWaiting;
procedure Draw(copyCanvas: Boolean = True);
procedure Fill(objekty: TPoleIntegerov; X, Y: Integer);
function GetFeatureIdUnderMouse(X, Y: Integer): integer;
end;
type
TGuideObject = class(TObject)
private
objID: integer; // ID feature
objType: string; // vertical / horizontal / slanted = V / H / S
objParam1: double;
objParam2: double;
objParam3: double;
objSide: byte;
objSelected: Boolean;
published
constructor Create(typ: string); virtual;
property ID: integer read objID write objID;
property Typ: string read objType write objType;
property Param1: double read objParam1 write objParam1;
property Param2: double read objParam2 write objParam2;
property Param3: double read objParam3 write objParam3;
property Strana: byte read objSide write objSide;
property Selected: Boolean read objSelected write objSelected;
procedure Draw;
end;
// pre pouzitie v expression parseri
type
TMathOperationObject = class(TObject)
private
objTyp: string;
objOperand1: Byte;
objOperand2: Byte;
published
property Typ: string read objTyp write objTyp;
property Op1: byte read objOperand1 write objOperand1;
property Op2: byte read objOperand2 write objOperand2;
end;
implementation
uses Controls, uMain, uDebug, uConfig;
{ ============================= TMultiselectButton ================================= }
constructor TMultiselectButton.Create(parent: TObject);
begin
inherited Create;
objID := -1;
objTop := 0;
objLeft := 0;
objWidth := 200;
objHeight := 25;
objPadding := multiselectButtonPadding;
objCaption := 'Multiselect';
objFontColor := farbaMultiselectBoxText;
objHighlighted := False;
UpdateBoundingBox;
end;
procedure TMultiselectButton.Draw;
begin
with BackPlane.Canvas do begin
// najprv podkladovy obdlznik
Pen.Width := 0;
Brush.Style := bsSolid;
if objHighlighted then
Brush.Color := farbaMultiselectBoxBgndHighlighted
else
Brush.Color := farbaMultiselectBoxBgnd;
Pen.Color := Brush.Color;
Rectangle(objBox);
// teraz oddelovacia ciarka
Pen.Width := 1;
Pen.Color := $00999999;
Pen.Style := psSolid;
MoveTo(objLeft, objTop+objHeight-1);
LineTo(objLeft+objWidth, objTop+objHeight-1);
// na zaver text
Font.Height := multiselectButtonFontHeight;
Font.Color := objFontColor;
Brush.Style := bsClear;
TextRect(objBox, objLeft+objPadding, objTop+objPadding, objCaption);
end;
end;
function TMultiselectButton.PointIsOnButton(X, Y: Integer): Boolean;
begin
Result := ( (X >= objLeft) AND (X < objLeft+objWidth) ) AND ( (Y >= objTop) AND (Y < objTop+objHeight) );
end;
procedure TMultiselectButton.SetHeight(value: Integer);
begin
objHeight := value;
UpdateBoundingBox;
end;
procedure TMultiselectButton.SetLeft(value: Integer);
begin
objLeft := value;
UpdateBoundingBox;
end;
procedure TMultiselectButton.SetTop(value: Integer);
begin
objTop := value;
UpdateBoundingBox;
end;
procedure TMultiselectButton.SetWidth(value: Integer);
begin
objWidth := value;
UpdateBoundingBox;
end;
procedure TMultiselectButton.UpdateBoundingBox;
begin
objBox.Left := objLeft;
objBox.Top := objTop;
objBox.Width := objWidth;
objBox.Height := objHeight;
end;
{ ============================= TGuideObject ================================= }
constructor TGuideObject.Create(typ: string);
begin
inherited Create;
objType := typ;
objID := -1;
objParam1 := -1;
objParam2 := -1;
objParam3 := 0;
objSelected := False;
end;
procedure TGuideObject.Draw;
begin
if (objSide <> _PNL.StranaVisible) then Exit;
// vykresli guideline
with BackPlane.Canvas do begin
Pen.Width := 1;
if objSelected then
Pen.Color := $000000ff
else
Pen.Color := $0066ffff;
Pen.Style := psDot;
Pen.Mode := pmCopy;
Brush.Style := bsClear;
// vertikalne
if objType = 'V' then begin
MoveTo( PX(objParam1, 'x'), -9 );
LineTo( PX(objParam1, 'x'), BackPlane.Height+9 );
end;
// horizontalne
if objType = 'H' then begin
MoveTo( -9 , PX(objParam1, 'y') );
LineTo( BackPlane.Width+9 , PX(objParam1, 'y') );
end;
end; // with canvas
end;
{ ============================= TMultiselectButtonsContainer ================================= }
procedure TMultiselectButtonsContainer.Clear;
var
i: Integer;
begin
// skryje tlacitka pre vyber jedneho z viacerych nad sebou leziacich objektov
for i := 0 to High(_buttons) do
if Assigned(_buttons[i]) then
FreeAndNil(_buttons[i]);
_boundingBox.Top := 0;
_boundingBox.Left := 0;
_boundingBox.Width := 0;
_boundingBox.Height := 0;
SetLength(_buttons, 0);
multiselectShowing := False;
end;
procedure TMultiselectButtonsContainer.Draw(copyCanvas: Boolean = True);
var
i: Integer;
rect: TRect;
begin
fMain.Log('container drawing. dblclick: '+booltostr(_doubleClickWaiting, true));
for i := 0 to High(_buttons) do
_buttons[i].Draw;
// na zaver sa cele vykreslene tlacitko skopiruje na fMain.Canvas
if (copyCanvas) then begin
fMain.Canvas.CopyRect(_boundingBox, BackPlane.Canvas, _boundingBox);
end;
end;
procedure TMultiselectButtonsContainer.Fill(objekty: TPoleIntegerov; X, Y: Integer);
var
i, maxTextLength: Integer;
btn: TMultiselectButton;
tmp_y_diff: Integer;
begin
fMain.Log('container fill...');
_doubleClickWaiting := False;
if Length(objekty) = 0 then begin
multiselectShowing := false;
Exit;
end;
// trochu posunieme buttony od mysi prec
X := X + 5;
Y := Y + 5;
SetLength(_buttons, Length(objekty));
for i := 0 to High(_buttons) do begin
btn := TMultiselectButton.Create(Self);
btn.ID := objekty[i];
// ak klikol velmi vpravo, tlacitka zobrazime nalavo od mysi
if (fMain.ClientWidth-X) < btn.Width then begin
btn.Left := X-btn.Width;
end else begin
btn.Left := X+1;
end;
// ak klikol velmi dolu, tlacitka zobrazime vyssie
tmp_y_diff := ( Y + 22 + btn.Height*Length(objekty) ) - fMain.ClientHeight; // o kolko by tlacitka presahovali dolny okraj formulara
if tmp_y_diff > 0 then begin
btn.Top := Y+1 + i*btn.Height - tmp_y_diff;
end else begin
btn.Top := Y+1 + i*btn.Height;
end;
btn.Caption := _PNL.GetFeatureByID( btn.ID ).GetFeatureInfo;
BackPlane.Canvas.Font.Height := multiselectButtonFontHeight;
maxTextLength := Max(maxTextLength , BackPlane.Canvas.TextWidth(btn.Caption) + 2*multiselectButtonPadding);
// farbou pisma odlisime, kedy sa vyberom v multivybere objekt len vyberie a kedy sa caka na jeho editaciu
if doubleClickWaiting then btn.FontColor := clRed
else btn.Fontcolor := clBlack;
_buttons[i] := btn;
end;
// vsetky nastavime na velkost aby sa tam zmestil aj najdlhsi text
maxTextLength := Max(maxTextLength , 200); // ale urcime nejaku minimalnu hodnotu
for i := 0 to High(_buttons) do begin
_buttons[i].Width := maxTextLength;
end;
// este nastavime bounding box celeho containera
_boundingBox.Left := _buttons[0].Left;
_boundingBox.Top := _buttons[0].Top;
_boundingBox.Right := _buttons[ High(_buttons) ].Left + _buttons[ High(_buttons) ].Width;
_boundingBox.Bottom := _buttons[ High(_buttons) ].Top + _buttons[ High(_buttons) ].Height;
multiselectShowing := true;
end;
function TMultiselectButtonsContainer.GetFeatureIdUnderMouse(X, Y: Integer): integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to High(_buttons) do begin
_buttons[i].Highlighted := False;
end;
for i := 0 to High(_buttons) do begin
if _buttons[i].PointIsOnButton(X, Y) then begin
_buttons[i].Highlighted := True;
Result := _buttons[i].ID;
Break;
end;
end;
end;
procedure TMultiselectButtonsContainer.SetDoubleClickWaiting(value: Boolean);
var
i: Integer;
tmpColor: TColor;
begin
_doubleClickWaiting := value;
if _doubleClickWaiting then
tmpColor := farbaMultiselectBoxTextHighlight
else
tmpColor := farbaMultiselectBoxText;
for i := 0 to High(_buttons) do begin
_buttons[i].FontColor := tmpColor;
end;
end;
end.
|
unit testsvdunit;
interface
uses Math, Sysutils, Ap, hblas, reflections, creflections, sblas, ablasf, ablas, ortfac, blas, rotations, bdsvd, svd;
function TestSVD(Silent : Boolean):Boolean;
function testsvdunit_test_silent():Boolean;
function testsvdunit_test():Boolean;
implementation
var
FailCount : AlglibInteger;
SuccCount : AlglibInteger;
procedure FillSparseA(var A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
Sparcity : Double);forward;
procedure GetSVDError(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
const U : TReal2DArray;
const W : TReal1DArray;
const VT : TReal2DArray;
var MatErr : Double;
var OrtErr : Double;
var WSorted : Boolean);forward;
procedure TestSVDProblem(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var MatErr : Double;
var OrtErr : Double;
var OtherErr : Double;
var WSorted : Boolean;
var WFailed : Boolean);forward;
(*************************************************************************
Testing SVD decomposition subroutine
*************************************************************************)
function TestSVD(Silent : Boolean):Boolean;
var
A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
MaxMN : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
GPass : AlglibInteger;
Pass : AlglibInteger;
WasErrors : Boolean;
WSorted : Boolean;
WFailed : Boolean;
MatErr : Double;
OrtErr : Double;
OtherErr : Double;
Threshold : Double;
FailThreshold : Double;
FailR : Double;
begin
FailCount := 0;
SuccCount := 0;
MatErr := 0;
OrtErr := 0;
OtherErr := 0;
WSorted := True;
WFailed := False;
WasErrors := False;
MaxMN := 30;
Threshold := 5*100*MachineEpsilon;
FailThreshold := 5.0E-3;
SetLength(A, MaxMN-1+1, MaxMN-1+1);
//
// TODO: div by zero fail, convergence fail
//
GPass:=1;
while GPass<=1 do
begin
//
// zero matrix, several cases
//
I:=0;
while I<=MaxMN-1 do
begin
J:=0;
while J<=MaxMN-1 do
begin
A[I,J] := 0;
Inc(J);
end;
Inc(I);
end;
I:=1;
while I<=Min(5, MaxMN) do
begin
J:=1;
while J<=Min(5, MaxMN) do
begin
TestSVDProblem(A, I, J, MatErr, OrtErr, OtherErr, WSorted, WFailed);
Inc(J);
end;
Inc(I);
end;
//
// Long dense matrix
//
I:=0;
while I<=MaxMN-1 do
begin
J:=0;
while J<=Min(5, MaxMN)-1 do
begin
A[I,J] := 2*RandomReal-1;
Inc(J);
end;
Inc(I);
end;
I:=1;
while I<=MaxMN do
begin
J:=1;
while J<=Min(5, MaxMN) do
begin
TestSVDProblem(A, I, J, MatErr, OrtErr, OtherErr, WSorted, WFailed);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=Min(5, MaxMN)-1 do
begin
J:=0;
while J<=MaxMN-1 do
begin
A[I,J] := 2*RandomReal-1;
Inc(J);
end;
Inc(I);
end;
I:=1;
while I<=Min(5, MaxMN) do
begin
J:=1;
while J<=MaxMN do
begin
TestSVDProblem(A, I, J, MatErr, OrtErr, OtherErr, WSorted, WFailed);
Inc(J);
end;
Inc(I);
end;
//
// Dense matrices
//
M:=1;
while M<=Min(10, MaxMN) do
begin
N:=1;
while N<=Min(10, MaxMN) do
begin
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 2*RandomReal-1;
Inc(J);
end;
Inc(I);
end;
TestSVDProblem(A, M, N, MatErr, OrtErr, OtherErr, WSorted, WFailed);
Inc(N);
end;
Inc(M);
end;
//
// Sparse matrices, very sparse matrices, incredible sparse matrices
//
M:=1;
while M<=10 do
begin
N:=1;
while N<=10 do
begin
Pass:=1;
while Pass<=2 do
begin
FillSparseA(A, M, N, 0.8);
TestSVDProblem(A, M, N, MatErr, OrtErr, OtherErr, WSorted, WFailed);
FillSparseA(A, M, N, 0.9);
TestSVDProblem(A, M, N, MatErr, OrtErr, OtherErr, WSorted, WFailed);
FillSparseA(A, M, N, 0.95);
TestSVDProblem(A, M, N, MatErr, OrtErr, OtherErr, WSorted, WFailed);
Inc(Pass);
end;
Inc(N);
end;
Inc(M);
end;
Inc(GPass);
end;
//
// report
//
FailR := AP_Double(FailCount)/(SuccCount+FailCount);
WasErrors := AP_FP_Greater(MatErr,Threshold) or AP_FP_Greater(OrtErr,Threshold) or AP_FP_Greater(OtherErr,Threshold) or not WSorted or AP_FP_Greater(FailR,FailThreshold);
if not Silent then
begin
Write(Format('TESTING SVD DECOMPOSITION'#13#10'',[]));
Write(Format('SVD decomposition error: %5.4e'#13#10'',[
MatErr]));
Write(Format('SVD orthogonality error: %5.4e'#13#10'',[
OrtErr]));
Write(Format('SVD with different parameters error: %5.4e'#13#10'',[
OtherErr]));
Write(Format('Singular values order: ',[]));
if WSorted then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('Always converged: ',[]));
if not WFailed then
begin
Write(Format('YES'#13#10'',[]));
end
else
begin
Write(Format('NO'#13#10'',[]));
Write(Format('Fail ratio: %5.3f'#13#10'',[
FailR]));
end;
Write(Format('Threshold: %5.4e'#13#10'',[
Threshold]));
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
procedure FillSparseA(var A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
Sparcity : Double);
var
I : AlglibInteger;
J : AlglibInteger;
begin
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
if AP_FP_Greater_Eq(RandomReal,Sparcity) then
begin
A[I,J] := 2*RandomReal-1;
end
else
begin
A[I,J] := 0;
end;
Inc(J);
end;
Inc(I);
end;
end;
procedure GetSVDError(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
const U : TReal2DArray;
const W : TReal1DArray;
const VT : TReal2DArray;
var MatErr : Double;
var OrtErr : Double;
var WSorted : Boolean);
var
I : AlglibInteger;
J : AlglibInteger;
K : AlglibInteger;
MinMN : AlglibInteger;
LocErr : Double;
SM : Double;
i_ : AlglibInteger;
begin
MinMN := Min(M, N);
//
// decomposition error
//
LocErr := 0;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
SM := 0;
K:=0;
while K<=MinMN-1 do
begin
SM := SM+W[K]*U[I,K]*VT[K,J];
Inc(K);
end;
LocErr := Max(LocErr, AbsReal(A[I,J]-SM));
Inc(J);
end;
Inc(I);
end;
MatErr := Max(MatErr, LocErr);
//
// orthogonality error
//
LocErr := 0;
I:=0;
while I<=MinMN-1 do
begin
J:=I;
while J<=MinMN-1 do
begin
SM := 0.0;
for i_ := 0 to M-1 do
begin
SM := SM + U[i_,I]*U[i_,J];
end;
if I<>J then
begin
LocErr := Max(LocErr, AbsReal(SM));
end
else
begin
LocErr := Max(LocErr, AbsReal(SM-1));
end;
SM := APVDotProduct(@VT[I][0], 0, N-1, @VT[J][0], 0, N-1);
if I<>J then
begin
LocErr := Max(LocErr, AbsReal(SM));
end
else
begin
LocErr := Max(LocErr, AbsReal(SM-1));
end;
Inc(J);
end;
Inc(I);
end;
OrtErr := Max(OrtErr, LocErr);
//
// values order error
//
I:=1;
while I<=MinMN-1 do
begin
if AP_FP_Greater(W[I],W[I-1]) then
begin
WSorted := False;
end;
Inc(I);
end;
end;
procedure TestSVDProblem(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var MatErr : Double;
var OrtErr : Double;
var OtherErr : Double;
var WSorted : Boolean;
var WFailed : Boolean);
var
U : TReal2DArray;
VT : TReal2DArray;
U2 : TReal2DArray;
VT2 : TReal2DArray;
W : TReal1DArray;
W2 : TReal1DArray;
I : AlglibInteger;
J : AlglibInteger;
K : AlglibInteger;
UJob : AlglibInteger;
VTJob : AlglibInteger;
MemJob : AlglibInteger;
UCheck : AlglibInteger;
VTCheck : AlglibInteger;
V : Double;
MX : Double;
begin
//
// Main SVD test
//
if not RMatrixSVD(A, M, N, 2, 2, 2, W, U, VT) then
begin
FailCount := FailCount+1;
WFailed := True;
Exit;
end;
GetSVDError(A, M, N, U, W, VT, MatErr, OrtErr, WSorted);
//
// Additional SVD tests
//
UJob:=0;
while UJob<=2 do
begin
VTJob:=0;
while VTJob<=2 do
begin
MemJob:=0;
while MemJob<=2 do
begin
if not RMatrixSVD(A, M, N, UJob, VTJob, MemJob, W2, U2, VT2) then
begin
FailCount := FailCount+1;
WFailed := True;
Exit;
end;
UCheck := 0;
if UJob=1 then
begin
UCheck := Min(M, N);
end;
if UJob=2 then
begin
UCheck := M;
end;
VTCheck := 0;
if VTJob=1 then
begin
VTCheck := Min(M, N);
end;
if VTJob=2 then
begin
VTCheck := N;
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=UCheck-1 do
begin
OtherErr := Max(OtherErr, AbsReal(U[I,J]-U2[I,J]));
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=VTCheck-1 do
begin
J:=0;
while J<=N-1 do
begin
OtherErr := Max(OtherErr, AbsReal(VT[I,J]-VT2[I,J]));
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=Min(M, N)-1 do
begin
OtherErr := Max(OtherErr, AbsReal(W[I]-W2[I]));
Inc(I);
end;
Inc(MemJob);
end;
Inc(VTJob);
end;
Inc(UJob);
end;
//
// update counter
//
SuccCount := SuccCount+1;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testsvdunit_test_silent():Boolean;
begin
Result := TestSVD(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testsvdunit_test():Boolean;
begin
Result := TestSVD(False);
end;
end. |
PROGRAM air;
(* File : air.pas *)
(* menentukan fasa air pada suhu tertentu *)
// KAMUS
VAR
t : INTEGER;
// ALGORITMA
BEGIN
ReadLn(t);
IF (t < 0) THEN BEGIN
WriteLn('PADAT');
END ELSE IF (t = 0) THEN BEGIN
WriteLn('ANTARA PADAT-CAIR');
END ELSE IF ((t > 0) AND (t < 100)) THEN BEGIN
WriteLn('CAIR');
END ELSE IF (t = 100) THEN BEGIN
WriteLn('ANTARA CAIR-GAS');
END ELSE {- t > 100 -} BEGIN
WriteLn('GAS');
END;
END.
|
unit UPedido;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, UItem;
type
{ Pedido }
TPedido = Class
private
FLista: TList;
protected
function getValorTotal: double; virtual;
function getItem(Index: integer): TItem; virtual;
procedure setItem(Index: integer; AValue: TItem); virtual;
function getCount: Integer; virtual;
public
property ValorTotal: double read getValorTotal;
property Itens[Index: integer]: TItem read getItem write setItem;
property Count: Integer read getCount;
constructor Create;
destructor Destroy; override;
procedure Add(item: TItem);
end;
implementation
{ Pedido }
function TPedido.getItem(Index: integer): TItem;
begin
if (index <= FLista.Count - 1) then
result := TItem(FLista[Index])
else
result := nil;
end;
function TPedido.getCount: Integer;
begin
result := FLista.Count;
end;
function TPedido.getValorTotal: double;
var I: Integer;
begin
result := 0;
for I:=0 to Count -1 do
result := result + (Itens[i].Valor * Itens[i].Qtde);
end;
procedure TPedido.setItem(Index: integer; AValue: TItem);
begin
if (index <= FLista.Count - 1) then
FLista[Index] := AValue;
end;
constructor TPedido.Create;
begin
inherited Create;
FLista := TList.Create;
end;
destructor Pedido.Destroy;
begin
FLista.Destroy;
inherited Destroy;
end;
procedure Pedido.Add(item: TItem);
begin
FLista.Add(item);
end;
end.
|
{$mode objfpc}{$H+}{$J-}
program MyProgram;
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 е: ', A + 10);
end;
function MyFunction(const S: string): string;
begin
Result := S + 'низовете се управляват автоматично';
end;
var
X: Single;
begin
WriteLn(MyFunction('Забележка: '));
MyProcedure(5);
// Делението с "/" винаги дава резултат float,
// използвайте "div" за целочислено делене
X := 15 / 5;
WriteLn('X сега е: ', X); // научна нотация
WriteLn('X сега е: ', X:1:2); // 2 десетични знака
end.
|
unit fOptionsReminders;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ORCtrls, OrFn, fBase508Form, VA508AccessibilityManager;
type
TfrmOptionsReminders = class(TfrmBase508Form)
pnlBottom: TPanel;
btnOK: TButton;
btnCancel: TButton;
lstDisplayed: TORListBox;
lstNotDisplayed: TORListBox;
btnUp: TButton;
btnDown: TButton;
btnDelete: TButton;
btnAdd: TButton;
lblDisplayed: TLabel;
lblNotDisplayed: TLabel;
bvlBottom: TBevel;
radSort: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure lstDisplayedChange(Sender: TObject);
procedure lstNotDisplayedChange(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
function GetFirstSelection(aList: TORListBox): integer;
procedure SetItem(aList: TORListBox; index: integer);
procedure MoveSelected(aList: TORListBox; items: TStrings);
procedure btnOKClick(Sender: TObject);
procedure radSortClick(Sender: TObject);
private
{ Private declarations }
procedure CheckEnable;
public
{ Public declarations }
end;
var
frmOptionsReminders: TfrmOptionsReminders;
procedure DialogOptionsReminders(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
implementation
uses rOptions, fRemCoverSheet, rReminders, VAUtils;
{$R *.DFM}
procedure DialogOptionsReminders(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
// create the form and make it modal, return an action
var
frmOptionsReminders: TfrmOptionsReminders;
begin
if NewRemCoverSheetListActive then
EditCoverSheetReminderList(TRUE)
else
begin
frmOptionsReminders := TfrmOptionsReminders.Create(Application);
actiontype := 0;
try
with frmOptionsReminders do
begin
if (topvalue < 0) or (leftvalue < 0) then
Position := poScreenCenter
else
begin
Position := poDesigned;
Top := topvalue;
Left := leftvalue;
end;
ResizeAnchoredFormToFont(frmOptionsReminders);
ShowModal;
actiontype := btnOK.Tag;
end;
finally
frmOptionsReminders.Release;
end;
end;
end;
procedure TfrmOptionsReminders.FormCreate(Sender: TObject);
var
i: integer;
biglist, userlist: TStringList;
begin
biglist := TStringList.Create;
userlist := TStringList.Create;
try
rpcGetReminders(biglist);
for i := 0 to biglist.Count - 1 do
if strtointdef(Piece(biglist[i], '^', 2), 0) > 0 then
userlist.Add(biglist[i])
else
lstNotDisplayed.Items.Add(biglist[i]);
SortByPiece(userlist, '^', 2);
for i := 0 to userlist.Count - 1 do
lstDisplayed.Items.Add(userlist[i]);
finally
biglist.free;
userlist.free;
end;
CheckEnable;
end;
procedure TfrmOptionsReminders.CheckEnable;
// allow buttons to be enabled or not depending on selections
begin
with lstDisplayed do
begin
if Items.Count > 0 then
begin
if SelCount > 0 then
begin
btnUp.Enabled := (SelCount > 0)
and (not Selected[0])
and (radSort.ItemIndex = 0);
btnDown.Enabled := (SelCount > 0)
and (not Selected[Items.Count - 1])
and (radSort.ItemIndex = 0);
btnDelete.Enabled := true;
end
else
begin
btnUp.Enabled := false;
btnDown.Enabled := false;
btnDelete.Enabled := false;
end;
end
else
begin
btnUp.Enabled := false;
btnDown.Enabled := false;
btnDelete.Enabled := false;
end;
end;
with lstNotDisplayed do
begin
btnAdd.Enabled := SelCount > 0;
end;
end;
procedure TfrmOptionsReminders.lstDisplayedChange(Sender: TObject);
begin
CheckEnable;
end;
procedure TfrmOptionsReminders.lstNotDisplayedChange(Sender: TObject);
begin
CheckEnable;
end;
procedure TfrmOptionsReminders.btnUpClick(Sender: TObject);
var
newindex, i: integer;
begin
with lstDisplayed do
begin
i := 0;
while i < Items.Count do
begin
if Selected[i] then
begin
newindex := i - 1;
Items.Move(i, newindex);
Selected[newindex] := true;
end;
inc(i);
end;
end;
lstDisplayedChange(self);
end;
procedure TfrmOptionsReminders.btnDownClick(Sender: TObject);
var
newindex, i: integer;
begin
with lstDisplayed do
begin
i := Items.Count - 1;
while i > -1 do
begin
if Selected[i] then
begin
newindex := i + 1;
Items.Move(i, newindex);
Selected[newindex] := true;
end;
dec(i);
end;
end;
lstDisplayedChange(self);
end;
procedure TfrmOptionsReminders.btnDeleteClick(Sender: TObject);
var
index: integer;
begin
index := GetFirstSelection(lstDisplayed);
MoveSelected(lstDisplayed, lstNotDisplayed.Items);
SetItem(lstDisplayed, index);
CheckEnable;
end;
procedure TfrmOptionsReminders.btnAddClick(Sender: TObject);
var
index: integer;
begin
index := GetFirstSelection(lstNotDisplayed);
MoveSelected(lstNotDisplayed, lstDisplayed.Items);
SetItem(lstNotDisplayed, index);
if radSort.ItemIndex = 1 then radSortClick(self);
CheckEnable;
end;
function TfrmOptionsReminders.GetFirstSelection(aList: TORListBox): integer;
begin
for result := 0 to aList.Items.Count - 1 do
if aList.Selected[result] then exit;
result := LB_ERR;
end;
procedure TfrmOptionsReminders.SetItem(aList: TORListBox; index: integer);
var
maxindex: integer;
begin
with aList do
begin
SetFocus;
maxindex := aList.Items.Count - 1;
if Index = LB_ERR then
Index := 0
else if Index > maxindex then Index := maxindex;
Selected[index] := true;
end;
CheckEnable;
end;
procedure TfrmOptionsReminders.MoveSelected(aList: TORListBox; Items: TStrings);
var
i: integer;
begin
for i := aList.Items.Count - 1 downto 0 do
begin
if aList.Selected[i] then
begin
Items.AddObject(aList.Items[i], aList.Items.Objects[i]);
aList.Items.Delete(i);
end;
end;
end;
procedure TfrmOptionsReminders.btnOKClick(Sender: TObject);
var
i: integer;
values: string;
aList: TStringList;
begin
aList := TStringList.Create;
try
with lstDisplayed do
for i := 0 to Items.Count - 1 do
begin
values := inttostr(i + 1) + '^' + Piece(Items[i], '^', 1);
aList.Add(values);
end;
rpcSetReminders(aList);
finally
aList.free;
end;
end;
procedure TfrmOptionsReminders.radSortClick(Sender: TObject);
var
i: integer;
userlist: TStringList;
begin
userlist := TStringList.Create;
try
for i := 0 to lstDisplayed.Items.Count - 1 do
userlist.Add(lstDisplayed.Items[i]);
case radSort.ItemIndex of
0: SortByPiece(userlist, '^', 2);
else SortByPiece(userlist, '^', 3);
end;
lstDisplayed.Items.Clear;
for i := 0 to userlist.Count - 1 do
lstDisplayed.Items.Add(userlist[i]);
finally
userlist.free;
end;
CheckEnable;
end;
end.
|
program hello(output);
procedure WriteResponseHeader;
begin
writeln('content-type: text/html');
writeln
end;
begin
WriteResponseHeader;
writeln('<HTML>');
writeln('<HEAD>');
writeln('<TITLE>IriePascal Hello World Program</TITLE>');
writeln('</HEAD>');
writeln('<BODY>');
writeln('<BIG> Hello world!!! </BIG>');
writeln('</BODY>');
writeln('</HTML>')
end.
|
unit uDDThread;
interface
uses
System.Classes, SysUtils, ActiveX, IniFiles,
FireDAC.Stan.Option, uLogger, Vcl.ExtCtrls, FireDAC.Phys.MSSQL,
FireDAC.Phys.MSSQLDef, FireDAC.Phys.OracleDef, FireDAC.Phys.Oracle, DB, ADODB,
FireDAC.Stan.Intf, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Phys, Variants,
FireDAC.Phys.ODBCBase, FireDAC.UI.Intf, FireDAC.VCLUI.Wait, FireDAC.Comp.UI,
FireDAC.Stan.Async, FireDAC.Comp.Client, uVariants, uUpdateYZBH, uSQLHelper;
type
TDataType = (dtVeh, dtDrv, dtVio);
TDDThread = class(TThread)
private
FData: TData;
FSQLHelper: TSQLHelper;
FConnOra: TFDConnection;
function DownLoadData: Boolean;
function GetConn: boolean;
function GetFields(tableName: string): string;
function GetMaxGxsj: double;
function ImportData(qyOra: TFDQuery): boolean;
function QueryDataFromOracle: TFDQuery;
procedure SQLError(const SQL, Description: string);
protected
procedure Execute; override;
public
constructor Create(AData: TData); overload;
end;
implementation
{ TDDThread }
constructor TDDThread.Create(AData: TData);
begin
inherited Create;
FData := AData;
FreeOnTerminate := true;
ActiveX.CoInitialize(nil);
end;
procedure TDDThread.Execute;
begin
if GetConn then
begin
DownLoadData;
if (UpperCase(FData.TableName) = 'T_VIO_SURVEIL') then
TUpdateYZBH.Run(FSQLHelper);
end;
FConnOra.Free;
end;
function TDDThread.GetConn: boolean;
begin
result := true;
FConnOra := TFDConnection.Create(nil);
FConnOra.Params.Add('DriverID=Ora');
FConnOra.Params.Add(Format('Database=(DESCRIPTION = (ADDRESS_LIST = ' +
'(ADDRESS = (PROTOCOL = TCP)(HOST = %s)(PORT = %s)))' +
'(CONNECT_DATA = (SERVICE_NAME = %s)))', [oraHost, oraPort, oraSID]));
FConnOra.Params.Add('User_Name=' + oraUser);
FConnOra.Params.Add('Password=' + oraPwd);
FConnOra.Params.Add('CharacterSet=UTF8'); // ·ñÔòÖÐÎÄÂÒÂë
FConnOra.LoginPrompt := false;
FSQLHelper := TSQLHelper.Create(sqlServer, sqlDBName, sqlUser, sqlPwd);
FSQLHelper.OnError := SQLError;
try
FConnOra.Open();
except
on e: exception do
begin
logger.Error('GetConn:' + e.Message);
result := false;
end;
end;
end;
function TDDThread.GetMaxGxsj: double;
var
s: string;
begin
s := FSQLHelper.GetSinge('select Max(GXSJ) from ' + FData.TableName);
if s <> '' then
result := VarToDatetime(s)
else
result := 100;
end;
function TDDThread.QueryDataFromOracle: TFDQuery;
begin
result := TFDQuery.Create(nil);
result.DisableControls;
result.Connection := FConnOra;
result.SQL.Text := FData.SQL;
if result.FindParam('gxsj') <> nil then
result.Params.ParamByName('gxsj').AsDateTime := GetMaxGxsj-0.1;
try
logger.Info('QueryDataFromOracle ' + FData.TableName);
result.Open;
logger.Info('QueryDataFromOracle OK');
except
on e: exception do
begin
logger.Error('QueryDataFromOracle:' + e.Message);
end;
end;
end;
procedure TDDThread.SQLError(const SQL, Description: string);
begin
logger.Error(Description + #13 + SQL);
end;
function TDDThread.DownLoadData: Boolean;
var
qyOra: TFDQuery;
begin
qyOra := QueryDataFromOracle;
if not qyOra.Eof then
begin
try
Result:= ImportData(qyOra);
except
on e: exception do
begin
logger.Error(e.Message);
Result:= False;
end;
end;
end;
qyOra.Free;
end;
function TDDThread.GetFields(tableName: string): string;
var
i: integer;
begin
result := '';
with FSQLHelper.Query('select * from ' + tableName + ' where 1=0') do
begin
if Active then
begin
for i := 0 to FieldCount - 1 do
begin
if (uppercase(Fields[i].fieldname) <> 'SYSTEMID') and (uppercase(Fields[i].fieldname) <> 'BZ') then
begin
result := result + ',' + Fields[i].fieldname;
end;
end;
result := result.Substring(1);
end;
Free;
end;
end;
function TDDThread.ImportData(qyOra: TFDQuery): boolean;
var
ss: tstrings;
SQL, tmpTable, fieldNames, s: string;
i: integer;
fieldArr: TArray<string>;
gxsj: double;
begin
tmpTable := 'tmp_' + FData.TableName;
SQL := 'if exists(select 1 from sysobjects where name = ''' + tmpTable + ''')'
+' drop table ' + tmpTable
+' select * into ' + tmpTable + ' from ' + FData.TableName + ' where 1=0';
FSQLHelper.ExecuteSql(SQL);
SQL := 'if exists(select 1 from syscolumns '
+ 'where object_name(id) = ''' + tmpTable + ''' and name = ''systemid'') '
+ 'alter table ' + tmpTable + ' drop column systemid ';
FSQLHelper.ExecuteSQL(SQL);
fieldNames := GetFields(tmpTable);
fieldArr := fieldNames.Split([',']);
ss := TStringList.Create;
while not qyOra.Eof do
begin
s := '';
for i := 0 to length(fieldArr) - 1 do
begin
s := s + ',' + qyOra.FieldByName(fieldArr[i]).AsString.QuotedString
end;
ss.Add(',(' + s.Substring(1) + ')');
if ss.Count = 999 then
begin
if FSQLHelper.ExecuteSql('insert into ' + tmpTable + '(' + fieldNames + ')values' + ss.Text.Substring(1)) then
logger.Info('[InsertIntoTmp](' + ss.Count.ToString + ', 0) OK ');
ss.Clear;
end;
qyOra.Next;
end;
if ss.Count > 0 then
begin
if FSQLHelper.ExecuteSql('insert into ' + tmpTable + '(' + fieldNames + ')values' + ss.Text.Substring(1)) then
logger.Info('[InsertIntoTmp](' + ss.Count.ToString + ', 0) OK ');
ss.Clear;
ss.Add('delete a from ' + FData.TableName + ' a inner join ' + tmpTable + ' b ');
fieldArr := FData.KeyField.Split([',']);
for i := 0 to Length(fieldArr) - 1 do
begin
if i = 0 then
ss.Add('on a.' + fieldArr[i] + ' = b.' + fieldArr[i])
else
ss.Add(' and a.' + fieldArr[i] + ' = b.' + fieldArr[i]);
end;
ss.Add('insert into ' + FData.TableName + '(' + fieldNames + ')');
ss.Add('select ' + fieldNames + ' from ' + tmpTable);
if FSQLHelper.ExecuteSql(ss.Text) then
logger.Info('tmp to data OK ');
end;
//FSQLHelper.ExecuteSQL('drop table ' + tmpTable);
ss.Free;
result := true;
end;
end.
|
{*******************************************************************************
* *
* ksTypes - ksComponents Base classes and types *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* 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 forthe specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksTypes;
interface
{$I ksComponents.inc}
{$R glyphs.res}
uses Classes, FMX.Controls, FMX.Objects, FMX.Types, FMX.StdCtrls, FMX.Graphics, System.UITypes, Types,
System.UIConsts, System.Generics.Collections, FMX.InertialMovement;
type
TksSound = (ksMailNew, ksMailSent, ksVoiceMail, ksBeep, ksMessageReceived, ksMessageSent, ksCameraShutter);
IksBaseComponent = interface
['{23FAF7AC-205E-4F03-924D-DA5C7D663777}']
end;
IksSystemSound = interface(IKsBaseComponent)
['{CF3A9726-6F3B-4029-B5CD-EB763DB0D2C5}']
procedure Play(ASound: TksSound);
end;
TksControl = class(TControl, IksBaseComponent);
TksComponent = class(TFmxObject);
TksRoundRect = class(TRoundRect);
TksBaseSpeedButton = class(TSpeedButton);
TksBaseTabControl = class(TksComponent)
protected
procedure AddTab; virtual; abstract;
end;
TksAccessoryType = (atNone, atMore, atCheckmark, atDetail, atEllipses, atFlag, atBack, atRefresh,
atAction, atPlay, atRewind, atForward, atPause, atStop, atAdd, atPrior,
atNext, atArrowUp, atArrowDown, atArrowLeft, atArrowRight, atReply,
atSearch, atBookmarks, atTrash, atOrganize, atCamera, atCompose, atInfo,
atPagecurl, atDetails, atRadioButton, atRadioButtonChecked, atCheckBox,
atCheckBoxChecked, atUserDefined1, atUserDefined2, atUserDefined3);
TksStandardIcon = (Custom, AlarmClock, BarChart, Barcode, Bell, BookCover, BookCoverMinus, BookCoverPlus, BookMark, BookOpen,
Calendar, Camera, Car, Clock, CloudDownload, CloudUpload, Cross, Document, Download, Earth, Email,
Fax, FileList, FileMinus, FilePlus, Files, FileStar, FileTick, Flag, Folder, FolderMinus,
FolderPlus, FolderStar, Home, Inbox, Incoming, ListBullets, ListCheckBoxes, ListImages, ListNumbered, ListTicked,
Location, More, Note, Outgoing,
PaperClip, Photo, PieChart, Pin, Presentation, Search, Settings, Share, ShoppingCart, Spanner, Speaker,
Star, Tablet, Tag, Telephone, Telephone2, TelephoneBook, Tick, Timer, Trash, Upload,
User, UserEdit, UserGroup, Users, UserSearch,
VideoCamera, VideoPlayer, Viewer,
Wifi, Window, Write);
//---------------------------------------------------------------------------------------
TksTableViewAccessoryImage = class(TBitmap)
private
FColor: TAlphaColor;
procedure SetColor(const Value: TAlphaColor);
public
procedure SetBitmap(ASource: TBitmap);
procedure DrawToCanvas(ACanvas: TCanvas; ADestRect: TRectF; const AStretch: Boolean = True);
property Color: TAlphaColor read FColor write SetColor default claNull;
end;
//---------------------------------------------------------------------------------------
TksTableViewAccessoryImageList = class(TObjectList<TksTableViewAccessoryImage>)
private
FImageScale: single;
FImageMap: TBitmap;
FActiveStyle: TFmxObject;
procedure AddEllipsesAccessory;
procedure AddFlagAccessory;
function GetAccessoryFromResource(AStyleName: array of string; const AState: string = ''): TksTableViewAccessoryImage;
procedure Initialize;
public
constructor Create;
destructor Destroy; override;
function GetAccessoryImage(AAccessory: TksAccessoryType): TksTableViewAccessoryImage;
procedure DrawAccessory(ACanvas: TCanvas; ARect: TRectF; AAccessory: TksAccessoryType; AStroke, AFill: TAlphaColor);
property Images[AAccessory: TksAccessoryType]: TksTableViewAccessoryImage read GetAccessoryImage; default;
property ImageMap: TBitmap read FImageMap;
property ImageScale: single read FImageScale;
end;
TksAniCalc = class(TAniCalculations)
public
procedure UpdatePosImmediately;
end;
var
AUnitTesting: Boolean;
AAccessories: TksTableViewAccessoryImageList;
function SwitchWidth: single;
function SwitchHeight: single;
procedure SwitchImage(ACanvas: TCanvas; ARect: TRectF; AChecked: Boolean);
implementation
uses FMX.Forms, ksCommon, SysUtils,FMX.Styles, FMX.Styles.Objects, Math, ksSystemSound;
var
ASwitchSize: TSizeF;
ASwitchBmp: array[False..True] of TBitmap;
// ------------------------------------------------------------------------------
procedure InitializeSwitch(const AForce: Boolean = false); var ASwitch: TSwitch; i: Boolean;
begin
if not assigned(application.MainForm) then exit;
if (not AForce) and (not ASwitchSize.IsZero) then exit;
ASwitch := TSwitch.Create(nil);
try
ASwitch.Parent := application.MainForm;
ASwitch.Visible := False;
ASwitch.ApplyStyleLookup;
for i := Low(ASwitchBmp) to High(ASwitchBmp) do
begin
ASwitch.IsChecked := i;
ASwitchSize.Width := ASwitch.Width;
ASwitchSize.Height := ASwitch.Height;
ASwitchBmp[i].SetSize(Round(ASwitch.Width), Round(ASwitch.Height));
ASwitchBmp[i].Clear(0);
if ASwitchBmp[i].Canvas.BeginScene(nil) then
begin
ASwitch.PaintTo(ASwitchBmp[i].Canvas, RectF(0, 0, ASwitch.Width,
ASwitch.Height), nil);
ASwitchBmp[i].Canvas.EndScene;
end;
end;
finally
ASwitch.DisposeOf;
end;
end;
(*
procedure InitialiseSwitchSize;
var
ASwitch: TSwitch;
begin
ASwitch := TSwitch.Create(nil);
try
ASwitchSize.Width := ASwitch.Width;
ASwitchSize.Height := ASwitch.Height;
finally
ASwitch.DisposeOf;
end;
end; *)
function SwitchWidth: single;
begin
InitializeSwitch;
Result := ASwitchSize.Width;
end;
function SwitchHeight: single;
begin
InitializeSwitch;
Result := ASwitchSize.Height;
end;
procedure SwitchImage(ACanvas: TCanvas; ARect: TRectF; AChecked: Boolean);
var
ASaveState: TCanvasSaveState;
begin
InitializeSwitch;
ASaveState := ACanvas.SaveState;
try
ACanvas.DrawBitmap(ASwitchBmp[AChecked], RectF(0, 0, ASwitchBmp[AChecked].Width, ASwitchBmp[AChecked].Height), ARect, 1);
finally
ACanvas.RestoreState(ASaveState);
end;
end;
procedure PlaySystemSound(ASound: TksSound);
var
AObj: TksSystemSound;
begin
AObj := TksSystemSound.Create;
AObj.Play(ASound);
end;
{ TksTableViewAccessoryImageList }
function TksTableViewAccessoryImageList.GetAccessoryImage(AAccessory: TksAccessoryType): TksTableViewAccessoryImage;
begin
Result := nil;
if Count = 0 then
begin
Initialize;
end;
if Ord(AAccessory) < Count then
Result := Items[Ord(AAccessory)];
end;
procedure TksTableViewAccessoryImageList.AddEllipsesAccessory;
var
AAcc: TksTableViewAccessoryImage;
ARect: TRectF;
ASpacing: single;
ASize: single;
begin
AAcc := TksTableViewAccessoryImage.Create;
AAcc.SetSize(Round(32 * GetScreenScale), Round(32 * GetScreenScale));
ASize := 7 * GetScreenScale;
ASpacing := (AAcc.Width - (3 * ASize)) / 2;
AAcc.Clear(claNull);
AAcc.Canvas.BeginScene;
try
AAcc.Canvas.Fill.Color := claSilver;
ARect := RectF(0, 0, ASize, ASize);
OffsetRect(ARect, 0, (AAcc.Height - ARect.Height) / 2);
AAcc.Canvas.FillEllipse(ARect, 1);
OffsetRect(ARect, ASize+ASpacing, 0);
AAcc.Canvas.FillEllipse(ARect, 1);
OffsetRect(ARect, ASize+ASpacing, 0);
AAcc.Canvas.FillEllipse(ARect, 1);
finally
AAcc.Canvas.EndScene;
end;
Add(AAcc);
end;
procedure TksTableViewAccessoryImageList.AddFlagAccessory;
var
AAcc: TksTableViewAccessoryImage;
ARect: TRectF;
s: single;
r1, r2: TRectF;
begin
s := GetScreenScale;
AAcc := TksTableViewAccessoryImage.Create;
AAcc.SetSize(Round(32 * s), Round(32 * s));
AAcc.Clear(claNull);
ARect := RectF(0, 0, AAcc.Width, AAcc.Height);
ARect.Inflate(0-(AAcc.Width / 4), 0-(AAcc.Height / 7));
AAcc.Canvas.BeginScene;
try
r1 := ARect;
r2 := ARect;
r2.Top := ARect.Top+(ARect.Height/12);
r2.Left := r2.Left;
r2.Height := ARect.Height / 2;
AAcc.Canvas.stroke.Color := claSilver;
AAcc.Canvas.Stroke.Thickness := s*2;
AAcc.Canvas.Fill.Color := claSilver;
AAcc.Canvas.FillRect(r2, 0, 0, AllCorners, 1);
AAcc.Canvas.DrawLine(r1.TopLeft, PointF(r1.Left, r1.Bottom), 1);
finally
AAcc.Canvas.EndScene;
end;
Add(AAcc);
end;
constructor TksTableViewAccessoryImageList.Create;
begin
inherited Create(True);
FImageScale := 0;
FImageMap := TBitmap.Create;
end;
destructor TksTableViewAccessoryImageList.Destroy;
begin
FreeAndNil(FImageMap);
if FActiveStyle <> nil then
FreeAndNil(FActiveStyle);
inherited;
end;
procedure TksTableViewAccessoryImageList.DrawAccessory(ACanvas: TCanvas; ARect: TRectF; AAccessory: TksAccessoryType; AStroke, AFill: TAlphaColor);
var
AAcc: TksTableViewAccessoryImage;
begin
if AFill <> claNull then
begin
ACanvas.Fill.Color := AFill;
ACanvas.Fill.Kind := TBrushKind.Solid;
ACanvas.FillRect(ARect, 0, 0, AllCorners, 1);
end;
AAcc := GetAccessoryImage(AAccessory);
if AAcc <> nil then
AAcc.DrawToCanvas(ACanvas, ARect, False);
end;
function TksTableViewAccessoryImageList.GetAccessoryFromResource
(AStyleName: array of string; const AState: string = ''): TksTableViewAccessoryImage;
var
AStyleObj: TStyleObject;
AImgRect: TBounds;
r: TRectF;
ABitmapLink: TBitmapLinks;
AImageMap: TBitmap;
I: integer;
AScale: single;
ICount: integer;
begin
Result := TksTableViewAccessoryImage.Create;
if AUnitTesting then
begin
if FActiveStyle = nil then
FActiveStyle := TStyleManager.ActiveStyle(Nil);
AStyleObj := TStyleObject(FActiveStyle)
end
else
AStyleObj := TStyleObject(TStyleManager.ActiveStyle(nil));
for ICount := Low(AStyleName) to High(AStyleName) do
AStyleObj := TStyleObject(AStyleObj.FindStyleResource(AStyleName[ICount]));
if AStyleObj <> nil then
begin
if FImageMap.IsEmpty then
begin
FImageScale := GetScreenScale(False);
for i := 0 to (AStyleObj as TStyleObject).Source.MultiResBitmap.Count-1 do
begin
AScale := (AStyleObj as TStyleObject).Source.MultiResBitmap[i].Scale;
if Round(AScale) <= FImageScale then
begin
FImageScale := Round(AScale);
Break;
end;
end;
AImageMap := ((AStyleObj as TStyleObject).Source.MultiResBitmap.Bitmaps[FImageScale]);
FImageMap.SetSize(Round(AImageMap.Width), Round(AImageMap.Height));
FImageMap.Clear(claNull);
FImageMap.Canvas.BeginScene;
try
FImageMap.Canvas.DrawBitmap(AImageMap,
RectF(0, 0, AImageMap.Width, AImageMap.Height),
RectF(0, 0, FImageMap.Width, FImageMap.Height),
1,
True);
finally
FImageMap.Canvas.EndScene;
end;
end;
ABitmapLink := nil;
if AStyleObj = nil then
Exit;
if (AStyleObj.ClassType = TCheckStyleObject) then
begin
if AState = 'checked' then
ABitmapLink := TCheckStyleObject(AStyleObj).ActiveLink
else
ABitmapLink := TCheckStyleObject(AStyleObj).SourceLink
end;
if ABitmapLink = nil then
ABitmapLink := AStyleObj.SourceLink;
{$IFDEF XE8_OR_NEWER}
AImgRect := ABitmapLink.LinkByScale(FImageScale, True).SourceRect;
{$ELSE}
AImgRect := ABitmapLink.LinkByScale(FImageScale, False).SourceRect;
{$ENDIF}
Result.SetSize(Round(AImgRect.Width), Round(AImgRect.Height));
Result.Clear(claNull);
Result.Canvas.BeginScene;
r := AImgRect.Rect;
Result.Canvas.DrawBitmap(FImageMap, r, RectF(0, 0, Result.Width,
Result.Height), 1, True);
Result.Canvas.EndScene;
end;
end;
procedure TksTableViewAccessoryImageList.Initialize;
var
ICount: TksAccessoryType;
begin
for ICount := Low(TksAccessoryType) to High(TksAccessoryType) do
begin
case ICount of
atNone: Add(GetAccessoryFromResource(['none']));
atMore: Add(GetAccessoryFromResource(['listviewstyle','accessorymore']));
atCheckmark: Add(GetAccessoryFromResource(['listviewstyle','accessorycheckmark']));
atDetail: Add(GetAccessoryFromResource(['listviewstyle','accessorydetail']));
atEllipses: AddEllipsesAccessory;
atFlag: AddFlagAccessory;
atBack: Add(GetAccessoryFromResource(['backtoolbutton','icon']));
atRefresh: Add(GetAccessoryFromResource(['refreshtoolbutton','icon']));
atAction: Add(GetAccessoryFromResource(['actiontoolbutton','icon']));
atPlay: Add(GetAccessoryFromResource(['playtoolbutton','icon']));
atRewind: Add(GetAccessoryFromResource(['rewindtoolbutton','icon']));
atForward: Add(GetAccessoryFromResource(['forwardtoolbutton','icon']));
atPause: Add(GetAccessoryFromResource(['pausetoolbutton','icon']));
atStop: Add(GetAccessoryFromResource(['stoptoolbutton','icon']));
atAdd: Add(GetAccessoryFromResource(['addtoolbutton','icon']));
atPrior: Add(GetAccessoryFromResource(['priortoolbutton','icon']));
atNext: Add(GetAccessoryFromResource(['nexttoolbutton','icon']));
atArrowUp: Add(GetAccessoryFromResource(['arrowuptoolbutton','icon']));
atArrowDown: Add(GetAccessoryFromResource(['arrowdowntoolbutton','icon']));
atArrowLeft: Add(GetAccessoryFromResource(['arrowlefttoolbutton','icon']));
atArrowRight: Add(GetAccessoryFromResource(['arrowrighttoolbutton','icon']));
atReply: Add(GetAccessoryFromResource(['replytoolbutton','icon']));
atSearch: Add(GetAccessoryFromResource(['searchtoolbutton','icon']));
atBookmarks: Add(GetAccessoryFromResource(['bookmarkstoolbutton','icon']));
atTrash: Add(GetAccessoryFromResource(['trashtoolbutton','icon']));
atOrganize: Add(GetAccessoryFromResource(['organizetoolbutton','icon']));
atCamera: Add(GetAccessoryFromResource(['cameratoolbutton','icon']));
atCompose: Add(GetAccessoryFromResource(['composetoolbutton','icon']));
atInfo: Add(GetAccessoryFromResource(['infotoolbutton','icon']));
atPagecurl: Add(GetAccessoryFromResource(['pagecurltoolbutton','icon']));
atDetails: Add(GetAccessoryFromResource(['detailstoolbutton','icon']));
atRadioButton: Add(GetAccessoryFromResource(['radiobuttonstyle','background']));
atRadioButtonChecked: Add(GetAccessoryFromResource(['radiobuttonstyle','background'], 'checked'));
atCheckBox: Add(GetAccessoryFromResource(['checkboxstyle','background']));
atCheckBoxChecked: Add(GetAccessoryFromResource(['checkboxstyle','background'], 'checked'));
atUserDefined1: Add(GetAccessoryFromResource(['userdefined1']));
atUserDefined2: Add(GetAccessoryFromResource(['userdefined2']));
atUserDefined3: Add(GetAccessoryFromResource(['userdefined3']));
end;
end;
// generate our own ellipses accessory...
end;
// ------------------------------------------------------------------------------
{ TksAccessoryImage }
procedure TksTableViewAccessoryImage.DrawToCanvas(ACanvas: TCanvas;
ADestRect: TRectF; const AStretch: Boolean = True);
var
r: TRectF;
begin
r := ADestRect;
if AStretch = False then
begin
r := RectF(0, 0, Width / GetScreenScale, Height / GetScreenScale);
OffsetRect(r, ADestRect.Left, ADestRect.Top);
OffsetRect(r, (ADestRect.Width-r.Width)/2, (ADestRect.Height-r.Height)/2);
end;
ACanvas.DrawBitmap(Self, RectF(0, 0, Width, Height), r, 1, True);
end;
procedure TksTableViewAccessoryImage.SetBitmap(ASource: TBitmap);
var
AScale: single;
begin
AScale := Min(Trunc(GetScreenScale), 3);
Assign(ASource);
Resize(Round(32 * AScale), Round(32 * AScale));
end;
procedure TksTableViewAccessoryImage.SetColor(const Value: TAlphaColor);
begin
if FColor <> Value then
begin
FColor := Value;
ReplaceOpaqueColor(Value);
end;
end;
{ TksAniCalc }
procedure TksAniCalc.UpdatePosImmediately;
begin
inherited UpdatePosImmediately(True);
end;
initialization
AUnitTesting := False;
AAccessories := TksTableViewAccessoryImageList.Create;
ASwitchBmp[True] := TBitmap.Create;
ASwitchBmp[False] := TBitmap.Create;
finalization
FreeAndNil(AAccessories);
FreeAndNil(ASwitchBmp[True]);
FreeAndNil(ASwitchBmp[False]);
end.
|
unit SearchFamily;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, DSWrap;
type
TSearchFamilyW = class(TDSWrap)
private
FCategoryIDList: TFieldWrap;
FID: TFieldWrap;
FComponentGroup: TFieldWrap;
FDatasheet: TFieldWrap;
FDescription: TFieldWrap;
FDescriptionComponentName: TFieldWrap;
FDescriptionID: TFieldWrap;
FDiagram: TFieldWrap;
FDrawing: TFieldWrap;
FIDDatasheet: TFieldWrap;
FIDDiagram: TFieldWrap;
FIDDrawing: TFieldWrap;
FIDImage: TFieldWrap;
FIDProducer: TFieldWrap;
FImage: TFieldWrap;
FSubgroup: TFieldWrap;
FValue: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property CategoryIDList: TFieldWrap read FCategoryIDList;
property ID: TFieldWrap read FID;
property ComponentGroup: TFieldWrap read FComponentGroup;
property Datasheet: TFieldWrap read FDatasheet;
property Description: TFieldWrap read FDescription;
property DescriptionComponentName: TFieldWrap
read FDescriptionComponentName;
property DescriptionID: TFieldWrap read FDescriptionID;
property Diagram: TFieldWrap read FDiagram;
property Drawing: TFieldWrap read FDrawing;
property IDDatasheet: TFieldWrap read FIDDatasheet;
property IDDiagram: TFieldWrap read FIDDiagram;
property IDDrawing: TFieldWrap read FIDDrawing;
property IDImage: TFieldWrap read FIDImage;
property IDProducer: TFieldWrap read FIDProducer;
property Image: TFieldWrap read FImage;
property Subgroup: TFieldWrap read FSubgroup;
property Value: TFieldWrap read FValue;
end;
TQuerySearchFamily = class(TQueryBase)
private
FW: TSearchFamilyW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
function SearchByID(const AIDComponent: Integer; TestResult: Integer = -1)
: Integer; overload;
function SearchByValue(const AValue: string): Integer;
function SearchByValueAndProducer(const AValue, AProducer: string): Integer;
function SearchByValueSimple(const AValue: string): Integer;
property W: TSearchFamilyW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses DefaultParameters, StrHelper;
constructor TQuerySearchFamily.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchFamilyW.Create(FDQuery);
end;
function TQuerySearchFamily.SearchByID(const AIDComponent: Integer;
TestResult: Integer = -1): Integer;
var
ASQL: String;
begin
Assert(AIDComponent > 0);
ASQL := SQL;
// Добавляем поле ComponentGroup
ASQL := ASQL.Replace('/* ComponentGroup', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ComponentGroup */', '', [rfReplaceAll]);
// Добавляем значения параметров
ASQL := ASQL.Replace('/* ParametersValues', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ParametersValues */', '', [rfReplaceAll]);
// Добавляем описание
ASQL := ASQL.Replace('/* Description', '', [rfReplaceAll]);
ASQL := ASQL.Replace('Description */', '', [rfReplaceAll]);
// Добавляем условие
FDQuery.SQL.Text := ReplaceInSQL(ASQL,
Format('%s = :%s', [W.ID.FullName, W.ID.FieldName]), 0);
SetParamType(W.ID.FieldName);
SetParamType('ProducerParamSubParamID');
SetParamType('PackagePinsParamSubParamID');
SetParamType('DatasheetParamSubParamID');
SetParamType('DiagramParamSubParamID');
SetParamType('DrawingParamSubParamID');
SetParamType('ImageParamSubParamID');
Result := Search([W.ID.FieldName, 'ProducerParamSubParamID',
'PackagePinsParamSubParamID', 'DatasheetParamSubParamID',
'DiagramParamSubParamID', 'DrawingParamSubParamID', 'ImageParamSubParamID'],
[AIDComponent, TDefaultParameters.ProducerParamSubParamID,
TDefaultParameters.PackagePinsParamSubParamID,
TDefaultParameters.DatasheetParamSubParamID,
TDefaultParameters.DiagramParamSubParamID,
TDefaultParameters.DrawingParamSubParamID,
TDefaultParameters.ImageParamSubParamID], TestResult);
end;
function TQuerySearchFamily.SearchByValue(const AValue: string): Integer;
var
ASQL: String;
begin
Assert(not AValue.IsEmpty);
ASQL := SQL;
// Добавляем значения параметров
ASQL := ASQL.Replace('/* ParametersValues', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ParametersValues */', '', [rfReplaceAll]);
FDQuery.SQL.Text := ReplaceInSQL(ASQL, Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]), 0);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
SetParamType('ProducerParamSubParamID');
SetParamType('PackagePinsParamSubParamID');
SetParamType('DatasheetParamSubParamID');
SetParamType('DiagramParamSubParamID');
SetParamType('DrawingParamSubParamID');
SetParamType('ImageParamSubParamID');
Result := Search([W.Value.FieldName, 'ProducerParamSubParamID',
'PackagePinsParamSubParamID', 'DatasheetParamSubParamID',
'DiagramParamSubParamID', 'DrawingParamSubParamID', 'ImageParamSubParamID'],
[AValue, TDefaultParameters.ProducerParamSubParamID,
TDefaultParameters.PackagePinsParamSubParamID,
TDefaultParameters.DatasheetParamSubParamID,
TDefaultParameters.DiagramParamSubParamID,
TDefaultParameters.DrawingParamSubParamID,
TDefaultParameters.ImageParamSubParamID]);
end;
function TQuerySearchFamily.SearchByValueAndProducer(const AValue,
AProducer: string): Integer;
var
ASQL: String;
begin
Assert(not AValue.IsEmpty);
Assert(not AProducer.IsEmpty);
ASQL := SQL;
// Добавляем значения параметров
ASQL := ASQL.Replace('/* ParametersValues', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ParametersValues */', '', [rfReplaceAll]);
// Добавляем краткое описание
ASQL := ASQL.Replace('/* Description', '', [rfReplaceAll]);
ASQL := ASQL.Replace('Description */', '', [rfReplaceAll]);
// Добавляем условие по наименованию семейства и его производителю
ASQL := ReplaceInSQL(ASQL, Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]), 0);
FDQuery.SQL.Text := ReplaceInSQL(ASQL,
'upper(pv.Value) = upper(:Producer)', 1);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
SetParamType('Producer', ptInput, ftWideString);
SetParamType('ProducerParamSubParamID');
SetParamType('PackagePinsParamSubParamID');
SetParamType('DatasheetParamSubParamID');
SetParamType('DiagramParamSubParamID');
SetParamType('DrawingParamSubParamID');
SetParamType('ImageParamSubParamID');
Result := Search([W.Value.FieldName, 'Producer', 'ProducerParamSubParamID',
'PackagePinsParamSubParamID', 'DatasheetParamSubParamID',
'DiagramParamSubParamID', 'DrawingParamSubParamID', 'ImageParamSubParamID'],
[AValue, AProducer, TDefaultParameters.ProducerParamSubParamID,
TDefaultParameters.PackagePinsParamSubParamID,
TDefaultParameters.DatasheetParamSubParamID,
TDefaultParameters.DiagramParamSubParamID,
TDefaultParameters.DrawingParamSubParamID,
TDefaultParameters.ImageParamSubParamID]);
end;
function TQuerySearchFamily.SearchByValueSimple(const AValue: string): Integer;
begin
Assert(not AValue.IsEmpty);
Result := SearchEx([TParamRec.Create(W.Value.FullName, AValue,
ftWideString, True)]);
end;
constructor TSearchFamilyW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'p.ID', '', True);
FCategoryIDList := TFieldWrap.Create(Self, 'CategoryIDList');
FComponentGroup := TFieldWrap.Create(Self, 'ComponentGroup');
FDatasheet := TFieldWrap.Create(Self, 'Datasheet');
FDescription := TFieldWrap.Create(Self, 'Description');
FDescriptionComponentName := TFieldWrap.Create(Self,
'DescriptionComponentName');
FDescriptionID := TFieldWrap.Create(Self, 'DescriptionID');
FDiagram := TFieldWrap.Create(Self, 'Diagram');
FDrawing := TFieldWrap.Create(Self, 'Drawing');
FIDDatasheet := TFieldWrap.Create(Self, 'IDDatasheet');
FIDDiagram := TFieldWrap.Create(Self, 'IDDiagram');
FIDDrawing := TFieldWrap.Create(Self, 'IDDrawing');
FIDImage := TFieldWrap.Create(Self, 'IDImage');
FIDProducer := TFieldWrap.Create(Self, 'IDProducer');
FImage := TFieldWrap.Create(Self, 'Image');
FSubgroup := TFieldWrap.Create(Self, 'Subgroup');
FValue := TFieldWrap.Create(Self, 'p.Value');
end;
end.
|
unit ConnParamsStorage;
interface
type
TZConnectionParams = record
Port: integer;
Host: string;
Login: string;
Password: string;
Database: string;
LibraryLocation: string;
end;
procedure SetGlobalSQLConnectionParams(ConnectionParams: TZConnectionParams);
function GlobalSQLConnectionParams(): TZConnectionParams;
implementation
var SQLConnectionParams: TZConnectionParams;
procedure SetGlobalSQLConnectionParams(ConnectionParams: TZConnectionParams);
begin
SQLConnectionParams := ConnectionParams;
end;
function GlobalSQLConnectionParams(): TZConnectionParams;
begin
Result := SQLConnectionParams;
end;
end.
|
unit eSocial.Models.Entities.Competencia;
interface
uses
eSocial.Models.DAO.Interfaces,
eSocial.Models.ComplexTypes;
type
TCompetencia = class
private
[weak]
FParent : iModelDAOEntity<TCompetencia>;
FAno : String;
FCodigo : String;
FDescricao : String;
FEncerrado : Boolean;
FMes : String;
FOrigem : TOrigemDados;
public
constructor Create(aParent : iModelDAOEntity<TCompetencia>);
destructor Destroy; override;
function Ano(Value : String) : TCompetencia; overload;
function Ano : String; overload;
function Codigo(Value : String) : TCompetencia; overload;
function Codigo : String; overload;
function Descricao(Value : String) : TCompetencia; overload;
function Descricao : String; overload;
function Encerrado(Value : String) : TCompetencia; overload;
function Encerrado : Boolean; overload;
function Mes(Value : String) : TCompetencia; overload;
function Mes : String; overload;
function Origem(Value : TOrigemDados) : TCompetencia; overload;
function Origem : TOrigemDados; overload;
function &End : iModelDAOEntity<TCompetencia>;
end;
implementation
uses
System.SysUtils;
{ TCompetencia }
constructor TCompetencia.Create(aParent: iModelDAOEntity<TCompetencia>);
begin
FParent := aParent;
end;
destructor TCompetencia.Destroy;
begin
inherited;
end;
function TCompetencia.Ano(Value: String): TCompetencia;
begin
Result := Self;
FAno := Value.Trim;
end;
function TCompetencia.Ano: String;
begin
Result := FAno;
end;
function TCompetencia.Codigo(Value: String): TCompetencia;
begin
Result := Self;
FCodigo := Value.Trim;
end;
function TCompetencia.Codigo: String;
begin
Result := FCodigo;
end;
function TCompetencia.Descricao: String;
begin
Result := FDescricao;
end;
function TCompetencia.Descricao(Value: String): TCompetencia;
begin
Result := Self;
FDescricao := Value.Trim;
end;
function TCompetencia.Encerrado(Value: String): TCompetencia;
begin
Result := Self;
FEncerrado := (Value.Trim.ToUpper = 'S');
end;
function TCompetencia.Encerrado: Boolean;
begin
Result := FEncerrado;
end;
function TCompetencia.Mes: String;
begin
Result := FMes;
end;
function TCompetencia.Mes(Value: String): TCompetencia;
begin
Result := Self;
FMes := Value.Trim
end;
function TCompetencia.Origem(Value: TOrigemDados): TCompetencia;
begin
Result := Self;
FOrigem := Value;
end;
function TCompetencia.Origem: TOrigemDados;
begin
Result := FOrigem;
end;
function TCompetencia.&End: iModelDAOEntity<TCompetencia>;
begin
Result := FParent;
end;
end.
|
unit TestFormatPart;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestFormatPart
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
TestFrameWork,
BaseTestProcess, SettingsTypes;
type
TTestFormatPart = class(TBaseTestProcess)
private
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Test1;
procedure Test2;
end;
implementation
uses
JcfStringUtils,
BlockStyles, JcfSettings, SetReturns;
const
UNIT_IN = UNIT_HEADER +
'procedure fred; ' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_OUT_TOP = SPACED_UNIT_HEADER +
'procedure fred; ' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_OUT_TOP_MID = SPACED_UNIT_HEADER + NativeLineBreak +
'procedure fred; ' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
UNIT_OUT_MID = UNIT_HEADER +
'procedure fred; ' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
procedure TTestFormatPart.Setup;
begin
inherited;
end;
procedure TTestFormatPart.Teardown;
begin
inherited;
end;
procedure TTestFormatPart.Test1;
begin
TestFormatPartResult(UNIT_IN, UNIT_OUT_TOP, 10, 20);
end;
procedure TTestFormatPart.Test2;
begin
TestFormatPartResult(UNIT_IN, UNIT_OUT_TOP_MID, 20, 30);
end;
initialization
TestFramework.RegisterTest('Processes', TTestFormatPart.Suite);
end.
|
unit uBitly;
interface
uses System.Classes, System.SysUtils, IdHTTP, IdSSLOPenSSL;
type
TDataToShorten = record
Title: String;
LongURL: String;
end;
TBitly = class
private
FIdHTTP: TIdHTTP;
FIdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL;
public
function Shorten(DataToShorten: TDataToShorten): String;
constructor Create;
end;
implementation
{ TBitly }
const
BITLY_ACCESS_TOKEN = '';
URL_BITLINKS = 'https://api-ssl.bitly.com/v4/bitlinks';
JSON = '{"domain": "bit.ly", "title": "%s", "long_url": "%s"}';
constructor TBitly.Create;
begin
FIdHTTP := TIdHTTP.Create(nil);
FIdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FIdHTTP.IOHandler := FIdSSLIOHandlerSocketOpenSSL;
FIdHTTP.Request.Accept := 'application/json';
FIdHTTP.Request.ContentType := 'application/json';
FIdHTTP.Request.ContentEncoding := 'utf-8';
FIdHTTP.Request.UserAgent := 'Mozilla/3.0 (compatible;Indy Library)';
FIdHTTP.Request.BasicAuthentication := False;
FIdHTTP.Request.CustomHeaders.FoldLines := False;
FIdHTTP.Request.CustomHeaders.Add(
Format('Authorization:Bearer %s', [BITLY_ACCESS_TOKEN])
);
end;
function TBitly.Shorten(DataToShorten: TDataToShorten): String;
var
JsonToSend: TStringStream;
begin
Result := '';
JsonToSend := TStringStream.Create(
Format(JSON, [DataToShorten.Title, DataToShorten.LongURL])
);
try
Result := FIdHTTP.Post(URL_BITLINKS, JsonToSend);
finally
FreeAndNil(JsonToSend);
end;
end;
end.
|
{
@html(<b>)
Data Client Components
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
This unit implements a set of Client-side Data components. @Link(TRtcDataClient)
is the base class for all Request/Response based client connections. It implements the
mechanisms used by components like @Link(TRtcDataClientLink) @Link(TRtcDataRequest) and
@Link(TRtcClientModule) and so prepares the road for different connection providers,
which will all be able to use all higher-level RTC components. You won't be creating
TRtcDataClient components, since it only implements the mechanism for working with
other Data-related RTC components, but it doesn't implement a communication protocol.
First RTC component which implements the connection is @Link(TRtcHttpClient). You should
use that component if you want to communicate with a Http Server over TCP/IP.
}
unit rtcDataCli;
{$INCLUDE rtcDefs.inc}
interface
uses
Windows,Messages,
Classes,SysUtils,
{$IFNDEF FPC}
Forms,
{$ENDIF}
rtcInfo,
rtcConn,
memObjList,
rtcSyncObjs,
rtcThrPool;
type
{ @abstract(Basic Request Info)
Objects of this type (inherited) are created for every request passed to DataClient
and destroyed by DataClient after the Request has been processed or rejected.
@exclude }
TRtcClientRequestInfo=class
private
FWasInjected: boolean;
FWasAborted: boolean;
public
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); virtual; abstract;
// @exclude
function Get_Request:TRtcClientRequest; virtual; abstract;
// @exclude
property WasInjected:boolean read FWasInjected write FWasInjected default false;
// @exclude
property WasAborted:boolean read FWasAborted write FWasAborted default false;
end;
{ @abstract(Client Session) }
TRtcClientSession=class(TRtcSession)
protected
// @exclude
FCon:TRtcConnection;
public
// @exclude
procedure Init;
// Open a new session with this ID
procedure Open(const _ID:string); virtual;
procedure Close; virtual;
end;
// @abstract(All Components used by the DataClient are derived from this class)
TRtcClientComponent = class(TRtcComponent);
TRtcAbsDataClientLink = class; // forward
// @exclude
TRtcDataClientLinkList = class
private
FList:TList;
public
constructor Create;
destructor Destroy; override;
procedure Add(Value:TRtcAbsDataClientLink);
procedure Remove(Value:TRtcAbsDataClientLink);
procedure RemoveAll;
function Count:integer;
function Get(index:integer):TRtcAbsDataClientLink;
end;
{ @Abstract(Data Client Connection component)
Most of the events published by TRtcDataClient will NOT be defined directly on the
@Link(TRtcDataClient), but instead of that will be passed on to posted DataRequest components,
so that each DataRequest can process its request (send request out and accept response).
Posted requests will be processed one-by-one, even if they are posted all at the same time.
Properties to check first:
@html(<br>)
@Link(TRtcConnection.ServerAddr) - Address to connect to
@html(<br>)
@Link(TRtcConnection.ServerPort) - Port to connect to
@html(<br><br>)
Methods to check first:
@html(<br>)
@Link(TRtcClient.Connect) - Connect to Server
@html(<br>)
@Link(TRtcDataClient.Request), @Link(TRtcDataClient.WriteHeader), @Link(TRtcConnection.Write) - Write result to server
@html(<br>)
@Link(TRtcDataClient.Response), @Link(TRtcConnection.Read) - Read Server's response
@html(<br>)
@Link(TRtcConnection.Disconnect) - Disconnect from Server
@html(<br><br>)
Events to check first:
@html(<br>)
@Link(TRtcConnection.OnConnect) - Connected to Server
@html(<br>)
@Link(TRtcConnection.OnDataSent) - Data sent to server (buffer now empty)
@html(<br>)
@Link(TRtcDataClient.OnResponseAbort) - Connection Lost while receiving response, but Repost was not triggered.
@html(<br>)
@Link(TRtcConnection.OnDisconnect) - Disconnected from Server
@html(<br><br>)
Check @Link(TRtcClient) and @Link(TRtcConnection) for more info.
}
TRtcDataClient = class(TRtcClient)
private
FOnRepostCheck:TRtcNotifyEvent;
FOnBeginRequest:TRtcNotifyEvent;
FOnResponseDone:TRtcNotifyEvent;
FOnResponseData:TRtcNotifyEvent;
FOnResponseAbort:TRtcNotifyEvent;
FOnResponseReject:TRtcNotifyEvent;
FOnSessionOpen:TRtcNotifyEvent;
FOnSessionClose:TRtcNotifyEvent;
FMayInsertRequest:boolean;
FRequestInserted:boolean;
FRequestSkipped:integer;
FAutoConnect:boolean;
FCS:TRtcCritSec;
FSession:TRtcClientSession;
FRequestList:TList;
FActiveRequest:TRtcClientRequestInfo;
FIdle:boolean;
FDataClientLinks:TRtcDataClientLinkList;
FMyRequest, FRequest:TRtcClientRequest;
FMyResponse, FResponse:TRtcClientResponse;
procedure CheckRequestSkipped;
function GetAutoConnect: boolean;
procedure SetAutoConnect(const Value: boolean);
protected
// @exclude
function isConnectionRequired:boolean; override;
// @exclude
procedure AddDataClientLink(Value:TRtcAbsDataClientLink);
// @exclude
procedure RemoveDataClientLink(Value:TRtcAbsDataClientLink);
// @exclude
procedure RemoveAllDataClientLinks;
// @exclude
procedure SetRequest(const Value: TRtcClientRequest); virtual;
// @exclude
procedure SetResponse(const Value: TRtcClientResponse); virtual;
// @exclude
procedure CallConnect; override;
// @exclude
procedure CallDataReceived; override;
// @exclude
procedure CallDataOut; override;
// @exclude
procedure CallDataIn; override;
// @exclude
procedure CallDataSent; override;
// @exclude
procedure CallReadyToSend; override;
// @exclude
procedure CallConnectLost; override;
// @exclude
procedure CallConnectFail; override;
// @exclude
procedure CallConnectError(E: Exception); override;
// @exclude
procedure AddRequest(Req:TRtcClientRequestInfo);
// @exclude
procedure RemoveAllRequests;
// @exclude
procedure RemoveRequest;
// @exclude
procedure StartRequest;
// @exclude
procedure PrepareNextRequest;
// @exclude
function CheckRequestWork:boolean;
{ @exclude
Post a 'StartRequest' Job }
procedure PostStartRequest;
{ Check if connection is Idle (no requests waiting or disconnected)
@exclude }
function isIdle:boolean; virtual;
public
// @exclude
constructor Create(AOwner: TComponent); override;
// @exclude
destructor Destroy; override;
{ @exclude
Internal function: Post a new Request Object.
When posting from inside a RTC event or a remote function,
"FromInsideEvent" parameter has to be TRUE to avoid memory consumption. }
procedure PostRequest(Req:TRtcClientRequestInfo; FromInsideEvent:boolean=False); virtual;
{ @exclude
Internal function: Insert a Request before active request.
This procedure may ONLY be called from BeginRequest event
to place another request before the active request. }
procedure InsertRequest(Req:TRtcClientRequestInfo); virtual;
// @exclude
procedure CallBeginRequest; virtual;
// @exclude
procedure CallResponseDone; virtual;
// @exclude
procedure CallResponseData; virtual;
// @exclude
procedure CallResponseAbort; virtual;
// @exclude
procedure CallResponseReject; virtual;
// @exclude
procedure CallSessionOpen; virtual;
// @exclude
procedure CallSessionClose; virtual;
// @exclude
procedure CallRepostCheck; virtual;
{ Flush all buffered data.
@html(<br>)
When using 'Write' without calling 'WriteHeader' before, all data
prepared by calling 'Write' will be buffered until your event
returns to its caller (automatically upon your event completion) or
when you first call 'Flush'. Flush will check if Request.ContentLength is set
and if not, will set the content length to the number of bytes buffered.
@html(<br>)
Flush does nothing if WriteHeader was called for this response.
@exclude}
procedure Flush; virtual; abstract;
// You can call WriteHeader to send the Request header out.
procedure WriteHeader(SendNow:boolean=True); overload; virtual; abstract;
{ You can call WriteHeader with empty 'HeaderText' parameter to
tell the component that you do not want any HTTP header to be sent. }
procedure WriteHeader(const HeaderText: string; SendNow:boolean=True); overload; virtual; abstract;
// Skip all requests (RequestAborted events will NOT BE triggered!!!)
procedure SkipRequests; virtual;
// Cancel all requests (will fire all RequestAborted events)
procedure CancelRequests; virtual;
// Check request count (number of requests waiting to be processed)
function RequestCount:integer; virtual;
{ Wait for all posted requests and function calls to complete,
be aborted, be calceled, or for the connection to close. @html(<br>)
Using a timeout (seconds) you can specify how long you want to wait.
(0=forever). Returns TRUE only if there are no more requests waiting.
Returns FALSE if timed-out or terminating or connection can't be open
or connection closed on purpose. }
function WaitForCompletion(UserInteractionAllowed:boolean=False; _Timeout:cardinal=0):boolean; virtual;
{ This connection's Session info.
If you will be using multiple client connections and
need to store session information, you have to start a
separate session for every client connection.
@html(<br><br>)
There is a difference between this DataClient's Session object and
the DataServer's Session object. DataClient's Session object stays
permamently defined all the time, from the point of object creation to its destruction.
Different from the Server connection, }
property Session:TRtcClientSession read FSession;
// Another request has just been inserted before this one.
property RequestInserted:boolean read FRequestInserted;
{ Access to current request information.
Use Request property to prepare the request header.
Here you can set all header variables and parameters.
If there is no content body to send out (only header), you will at
least have to call 'WriteHeader', or 'Write' without parameters once. }
property Request:TRtcClientRequest read FRequest write SetRequest;
{ Access to current response information.
Use Response property to read the response information received.
Here is all the info that was available in response header.
To read response's body, use the Read function. }
property Response:TRtcClientResponse read FResponse write SetResponse;
published
{ You have two ways of working with connections. One is to open a connection
on application start by calling "Connect" and using "ReconnectOn" to keep the
connection open until your application closes, the other is to use implicit
connects when a connection is required (when you post a request of any kind). @html(<br>)
You should set AutoConnect to TRUE if you do not want your connection to remain
open all the time, but also do not want to call "Connect" when you need a connection.
For connection to remain open as long as there are requests waiting to be processed,
you will also need to set the appropriate ReconnectOn parameters. @html(<br><br>)
When AutoConnect is TRUE, connection will be automaticaly opened when you
post a request (no need to call Connect) and "ReconnectOn" parameters will be
used to reconnect only if there are requests waiting in the queue. By using Timeout
parameters, your connection will close after specified timeout and stay closed
until needed again, when a new connection will be automaticaly initiated. @html(<br><br>)
When AutoConnect is FALSE, connection has to be opened explicitly by calling "Connect"
and "ReconnectOn" parameters will be used to keep the connection open, even if there
are no requests waiting in the queue. }
property AutoConnect:boolean read GetAutoConnect write SetAutoConnect default False;
{ Called before each request start.
You can use this event to prepare the request. }
property OnBeginRequest:TRtcNotifyEvent read FOnBeginRequest write FOnBeginRequest;
{ Called after the last DataReceived event for the response, when a response is done.
You can use this event to react to the final response. }
property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone;
{ Called every time a data package comes from Server, immediatelly after OnDataReceived. }
property OnResponseData:TRtcNotifyEvent read FOnResponseData write FOnResponseData;
{ Called after OnConnectLost,OnConnectFail and OnConnectError if Request was not reposted. }
property OnRepostCheck:TRtcNotifyEvent read FOnRepostCheck write FOnRepostCheck;
{ Called after OnRepostCheck if Request was not reposted. }
property OnResponseAbort:TRtcNotifyEvent read FOnResponseAbort write FOnResponseAbort;
{ Called if response has been rejected by calling Response.Reject. }
property OnResponseReject:TRtcNotifyEvent read FOnResponseReject write FOnResponseReject;
{ Called after a new session has been opened. }
property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen;
{ Called before an existing session is about to get closed. }
property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose;
{ This event will be triggered every time a chunk of your data
prepared for sending has just been sent out. To know
exactly how much of it is on the way, use the @Link(TRtcConnection.DataOut) property.
@html(<br><br>)
NOTE: Even though data has been sent out, it doesn't mean that
the other side already received it. It could also be that connection will
break before this package reaches the other end. }
property OnDataOut;
{ This event will be triggered every time a chunk of data
has just come in (received). To know exactly how much of it
has just arrived, use the @Link(TRtcConnection.DataIn) property. }
property OnDataIn;
end;
TRtcDataClientLink=class; // forward
{ @abstract(DataClient Link wrapper) }
TRtcAbsDataClientLink=class(TRtcClientComponent)
private
FClient: TRtcDataClient;
FLink: TRtcDataClientLink;
FAutoSync: boolean;
protected
// @exclude
function CheckLink(Value:TRtcAbsDataClientLink):boolean; virtual;
// @exclude
procedure RemoveLink(Value:TRtcAbsDataClientLink); virtual;
// @exclude
procedure RemoveClient(Value:TRtcDataClient); virtual;
// @exclude
function GetClient: TRtcDataClient; virtual;
// @exclude
procedure SetClient(const Value: TRtcDataClient); virtual;
// @exclude
function GetLink: TRtcDataClientLink; virtual;
// @exclude
procedure SetLink(const Value: TRtcDataClientLink); virtual;
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); virtual; abstract;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); virtual; abstract;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
// Post a new Request Object
procedure PostRequest(Req:TRtcClientRequestInfo; FromInsideEvent:boolean=False); virtual;
{ Insert a Request before active request.
This procedure may ONLY be called from BeginRequest event
to place another request before the active request. }
procedure InsertRequest(Req:TRtcClientRequestInfo); virtual;
// Skip all requests posted to the Client Connection used (RequestAborted events will NOT BE triggered!!!)
procedure SkipRequests; virtual;
// Cancel all requests posted to the Client Connection used and fire RequestAborted events
procedure CancelRequests; virtual;
// Check request count at Client Connection used (number of requests waiting to be processed)
function RequestCount:integer; virtual;
{ Wait for all posted requests and function calls to complete,
be aborted, be calceled, or for the connection to close. @html(<br>)
Using a timeout (seconds) you can specify how long you want to wait.
(0=forever). Returns TRUE only if there are no more requests waiting.
Returns FALSE if timed-out or terminating or connection can't be open
or connection closed on purpose. }
function WaitForCompletion(UserInteractionAllowed:boolean=False; Timeout:cardinal=0):boolean; virtual;
published
{ If all events which your component implements have to access the GUI,
to avoid checking the "Sender.inMainThread" and calling Sender.Sync(Event)
for every event, you can se this AutoSyncEvent property to true,
which will ensure that any event assigned to this component will
be called from the main thread (synchronized, when needed). }
property AutoSyncEvents:boolean read FAutoSync write FAutoSync default false;
{ You can link your components (one or more) to a DataClientLink component
by assigning your @Link(TRtcDataClientLink) component to chind component's Link property.
Doing this, you only have to set the Client property for the master
DataClientLink component and don't need to do it for every single
DataRequest component. }
property Link:TRtcDataClientLink read GetLink write SetLink;
{ You can also link your components (one or more) directly to your
DataClient connection component by assigning your
@Link(TRtcDataClient) connection component to this child component's Client property.
This is useful if you don't want to use a DataClientLink. }
property Client:TRtcDataClient read GetClient write SetClient;
end;
{ @abstract(DataClient Link, used to group Data Requests)
You can use TRtcDataClientLink components to group several related
@Link(TRtcDataRequest) components. Simply set this component as the
Link property for all your RtcDataSource components, so that
you don't have to set the Client property for every single
TRtcDataRequest component separately. This is useful especially
when the component is used in a datamodule or a form without
DataClient and you need to link all the components to
a DataClient which is on another datamodule or form.
@html(<br><br>)
Check @Link(TRtcAbsDataClientLink) for more info. }
TRtcDataClientLink=class(TRtcAbsDataClientLink)
private
FOnBeginRequest:TRtcNotifyEvent;
FOnResponseDone:TRtcNotifyEvent;
FOnResponseData:TRtcNotifyEvent;
FOnResponseAbort:TRtcNotifyEvent;
FOnResponseReject:TRtcNotifyEvent;
FOnSessionOpen:TRtcNotifyEvent;
FOnSessionClose:TRtcNotifyEvent;
FOnRepostCheck:TRtcNotifyEvent;
protected
// @exclude
FDataClientLinks:TRtcDataClientLinkList;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); override;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); override;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); override;
// @exclude
procedure AddChildLink(Value:TRtcAbsDataClientLink);
// @exclude
procedure RemoveChildLink(Value:TRtcAbsDataClientLink);
// @exclude
procedure RemoveAllChildLinks;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); override;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); override;
published
{ Use this event to initialize child requests linked to this DataLink }
property OnBeginRequest:TRtcNotifyEvent read FOnBeginRequest write FOnBeginRequest;
{ Use this event to add additional control after each OnDataReceived package. }
property OnResponseData:TRtcNotifyEvent read FOnResponseData write FOnResponseData;
{ Use this event to finalize child requests linked to this DataLink }
property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone;
{ Called after OnConnectLost, OnConnectFail and OnConnectError if request is not finished and not marked for reposting }
property OnRepostCheck:TRtcNotifyEvent read FOnRepostCheck write FOnRepostCheck;
{ Called after OnRepostCheck if request is not finished and is not marked for reposting. }
property OnResponseAbort:TRtcNotifyEvent read FOnResponseAbort write FOnResponseAbort;
{ Called after Response has been rejected by calling Response.Reject }
property OnResponseReject:TRtcNotifyEvent read FOnResponseReject write FOnResponseReject;
{ Called after a new Session has been opened. }
property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen;
{ Called before an existing session is about to be closed. }
property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose;
end;
{ @abstract(Dual DataClient Link, used to create a connection pool)
You can use TRtcDualDataClientLink components to create a small pool
of client connections. When posting requests through this component,
you will never really know which connection the request will be posted
from, since the component itself will determine that, depending on
the number of currently active requests on each connection component.
@html(<br><br>)
Check @Link(TRtcDataClientLink) for more info. }
TRtcDualDataClientLink=class(TRtcDataClientLink)
private
FClient2: TRtcDataClient;
FLink2: TRtcDataClientLink;
protected
// @exclude
function CheckLink(Value:TRtcAbsDataClientLink):boolean; override;
// @exclude
procedure RemoveLink(Value:TRtcAbsDataClientLink); override;
// @exclude
procedure RemoveClient(Value:TRtcDataClient); override;
// @exclude
function GetClient2: TRtcDataClient; virtual;
// @exclude
procedure SetClient2(const Value: TRtcDataClient); virtual;
// @exclude
procedure SetClient(const Value: TRtcDataClient); override;
// @exclude
function GetLink2: TRtcDataClientLink; virtual;
// @exclude
procedure SetLink2(const Value: TRtcDataClientLink); virtual;
// @exclude
procedure SetLink(const Value: TRtcDataClientLink); override;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
// @exclude
procedure Call_ConnectLost(Sender: TRtcConnection); override;
// @exclude
procedure Call_DataReceived(Sender: TRtcConnection); override;
// @exclude
procedure Call_DataOut(Sender: TRtcConnection); override;
// @exclude
procedure Call_DataIn(Sender: TRtcConnection); override;
// @exclude
procedure Call_DataSent(Sender: TRtcConnection); override;
// @exclude
procedure Call_ReadyToSend(Sender: TRtcConnection); override;
// @exclude
procedure Call_BeginRequest(Sender: TRtcConnection); override;
// @exclude
procedure Call_ResponseData(Sender: TRtcConnection); override;
// @exclude
procedure Call_ResponseDone(Sender: TRtcConnection); override;
// @exclude
procedure Call_RepostCheck(Sender: TRtcConnection); override;
// @exclude
procedure Call_ResponseAbort(Sender: TRtcConnection); override;
// @exclude
procedure Call_ResponseReject(Sender: TRtcConnection); override;
// @exclude
procedure Call_SessionClose(Sender: TRtcConnection); override;
// @exclude
procedure Call_SessionOpen(Sender: TRtcConnection); override;
// Post a new Request Object
procedure PostRequest(Req:TRtcClientRequestInfo; FromInsideEvent:boolean=False); override;
{ Insert a Request before active request.
This procedure may ONLY be called from BeginRequest event
to place another request before the active request. }
procedure InsertRequest(Req:TRtcClientRequestInfo); override;
// Skip all requests posted to the Client Connection used (RequestAborted events will NOT BE triggered!!!)
procedure SkipRequests; override;
// Cancel all requests posted to the Client Connection used and fire RequestAborted events
procedure CancelRequests; override;
// Check request count at Client Connection used (number of requests waiting to be processed)
function RequestCount:integer; override;
{ Wait for all posted requests and function calls to complete,
be aborted, be calceled, or for the connection to close. @html(<br>)
Using a timeout (seconds) you can specify how long you want to wait.
(0=forever). Returns TRUE only if there are no more requests waiting.
Returns FALSE if timed-out or terminating or connection can't be open
or connection closed on purpose. }
function WaitForCompletion(UserInteractionAllowed:boolean=False; Timeout:cardinal=0):boolean; override;
published
{ You can link your components (one or more) to a DataClientLink component
by assigning your @Link(TRtcDataClientLink) component to child component's Link property.
Doing this, you only have to set the Client property for the master
DataClientLink component and don't need to do it for every single
DataRequest component. }
property Link2:TRtcDataClientLink read GetLink2 write SetLink2;
{ You can also link your components (one or more) directly to your
DataClient connection component by assigning your
@Link(TRtcDataClient) connection component to this child component's Client property.
This is useful if you don't want to use a DataClientLink. }
property Client2:TRtcDataClient read GetClient2 write SetClient2;
end;
{ @abstract(DataRequest Info Object)
This object is created and filled by TRtcDataRequest,
when you Post or Insert a DataRequest.
@exclude }
TRtcDataRequestInfo=class(TRtcClientRequestInfo)
protected
// @exclude
FRequest:TRtcClientRequest;
// @exclude
FEvents:TRtcAbsDataClientLink;
public
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); override;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); override;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); override;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); override;
// @exclude
function Get_Request:TRtcClientRequest; override;
public
// Standard constructor
constructor Create; virtual;
// @exclude
destructor Destroy; override;
{ Request Info, will be destroyed after the Request has been processed,
has to be assigned a valid TRtcClientRequest object before posting. }
property Request:TRtcClientRequest read FRequest write FRequest;
{ This DataClient Link component will be used to call events. }
property Events:TRtcAbsDataClientLink read FEvents write FEvents;
end;
// @exclude
TRtcDataRequestData=class
public
FRequest:TRtcClientRequest;
constructor Create; virtual;
destructor Destroy; override;
end;
{ @abstract(Data Request, used to Prepare+Post or Insert+Prepare Requests for DataClient)
This is the component you have to use to work with DataClient.
Put TRtcDataRequest on a form or a datamodule and define events
at design-time, which will be used for default request processing.
@html(<br><br>)
Then, at runtime, there are 2 ways you can use this DataRequest:
@html(<br>)
1.) From the Main thread, you can prepare the request using the
@Link(TRtcDataRequest.Request) property and call @link(TRtcDataRequest.Post)
to post the prepared request to its associated DataClient, or ...
@html(<br>)
2.) From inside a BeginRequest event handler (which is called by the DataClient
connection component), you can insert this DataRequest, so that your active
DataRequest is put on the 2nd position and this request is put on the first
place, by calling the @Link(TRtcDataRequest.Insert) method. After calling
@link(TRtcDataRequest.Insert), immediatelly a new @Link(TRtcDataClient.Request)
is created for this inserted DataRequest, so you can initialize the request
before exiting your event handler.
@html(<br><br>)
Check @Link(TRtcAbsDataClientLink) for more info. }
TRtcDataRequest=class(TRtcAbsDataClientLink)
private
FCS:TRtcCritSec;
FMyData:TObjList;
FMainThrData:TRtcDataRequestData;
FHyperThreading: boolean;
function CheckMyData:TRtcDataRequestData;
function GetMyData:TRtcDataRequestData;
procedure ClearMyData;
function GetRequest: TRtcClientRequest;
protected
// @exclude
FAutoRepost:integer;
// @exclude
FOnBeginRequest: TRtcNotifyEvent;
// @exclude
FOnResponseData: TRtcNotifyEvent;
// @exclude
FOnResponseDone: TRtcNotifyEvent;
// @exclude
FOnResponseAbort: TRtcNotifyEvent;
// @exclude
FOnResponseReject: TRtcNotifyEvent;
// @exclude
FOnSessionOpen: TRtcNotifyEvent;
// @exclude
FOnSessionClose: TRtcNotifyEvent;
// @exclude
FOnConnectLost: TRtcNotifyEvent;
// @exclude
FOnDataReceived: TRtcNotifyEvent;
// @exclude
FOnReadyToSend: TRtcNotifyEvent;
// @exclude
FOnDataOut: TRtcNotifyEvent;
// @exclude
FOnDataIn: TRtcNotifyEvent;
// @exclude
FOnDataSent: TRtcNotifyEvent;
// @exclude
FOnRepostCheck: TRtcNotifyEvent;
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); override;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); override;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); override;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); override;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
{ Post this DataRequest to assigned DataClient.
@html(<br><br>)
After a call to Post, an object will be created to hold the
prepared Request info, after which the Request property will be cleared,
so that you can prepare and post new requests immediatelly,
without waiting for the last request to complete.
@html(<br><br>)
When posting a new Request from inside an Event of a running request/response loop,
"FromInsideEvent" parameter has to be TRUE to avoid memory consumption and
always pass the Sender:TRtcConnection parameter through.
Events assigned to this TRtcDataRequest will not be removed nor cleared,
so you can define them at design-time and not worry about them at runtime. }
procedure Post(FromInsideEvent:boolean=False; Sender:TRtcConnection=nil); virtual;
{ Insert this request before the active request.
@html(<br><br>)
DataRequest objects which are used for automatic initialisation
can be inserted before the active request, but ONLY from inside
the active request's BeginRequest event handler. After calling
this Insert procedure, a new Request is created for the inserted
DataRequest and can/should be modified/prepared before exiting the
BeginRequest event. After BeginRequest event exists, the inserted
DataRequest's BeginRequest events will be called, as if this event
was posted before the one that inserted it.
To make sure the request will be inserted to same connection,
always pass the Sender:TRtcConnection parameter through. }
procedure Insert(Sender:TRtcConnection=nil); virtual;
{ ONLY use this Request property to prepare a request BEFORE posting.
@html(<br>)
DO NOT directly use this property when processing the request.
After a request has been posted, it is moved to the DataClient,
so you can access it (from events) using Sender's Request property. }
property Request:TRtcClientRequest read GetRequest;
published
{ If you want to enable the possibility to use this Data Request to send requests
from multiple threads AT THE SAME TIME, where this component will acs as if
it were X components, one for each thread, simply set HyperThreading to TRUE. @html(<br><br>)
This is useful if you need to send requests to another Server from
within your Server running in multi-threaded mode and want to use only one set of
rtcHttpClient/rtcDataRequest components for all clients connected to your Server.
Even in HyperThreading mode, only properties and methods needed to prepare and post
the request (Request and Post) will use a separate copy for each thread, while all
other properties and methods exist only once for all threads, so don't try to modify
them while your application is actively using the component in multi-threaded mode. @html(<br><br>)
Leave HyperThreading as FALSE to use this component "the stadard way" (for example,
when you're writing a client application where requests are posted from the main thread
or if you are creating a separate component for every thread that needs it). }
property HyperThreading:boolean read FHyperThreading write FHyperThreading default False;
{ Set this property to a value other than 0 (zero) if you want the DataRequest to
auto-repost any request up to "AutoRepost" times, in case the connection gets lost
while sending data to server or receiving data from server.
AutoRepost = -1 means that request should be reposted infinitely. }
property AutoRepost:integer read FAutoRepost write FAutoRepost default 0;
{ This event will be called when DataClient component is
ready to start sending the request out.
@html(<br><br>)
If the request is already in memory (not a large file on disk),
send it out using Sender's WriteHeader and/or Write methods.
If the request is too large to be sent out at once (maybe a big file
on disk), you should at least send the Request Header out in this event.
@html(<br><br>)
If you DO NOT call Write and/or WriteHeader from this event,
then this Request will be skipped by the DataClient. }
property OnBeginRequest:TRtcNotifyEvent read FOnBeginRequest write FOnBeginRequest;
{ This event will be called after each DataReceived event for this request
and can be used to access info prepared by the OnDataReceived event. }
property OnResponseData:TRtcNotifyEvent read FOnResponseData write FOnResponseData;
{ This event will be called after the last DataReceived event for this request,
read after the request has been sent out and a complete response was received (Response.Done). }
property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone;
{ This event will be called after ConnectLost, ConnectFail and ConnectError events if request was not marked for reposting.
If you want to re-post the request, you should call Request.Repost from
this event, or the Request will NOT be reposted and OnResponseAbort
event will be trigered. You can also use the AutoRepost property to tell the
component to repost requests automaticaly (for a specified number of times or unlimited). }
property OnRepostCheck:TRtcNotifyEvent read FOnRepostCheck write FOnRepostCheck;
{ This event will be called after the OnRepostCheck event if request was not marked for reposting. }
property OnResponseAbort:TRtcNotifyEvent read FOnResponseAbort write FOnResponseAbort;
{ This event will be called after the response has been rejected by calling Response.Reject }
property OnResponseReject:TRtcNotifyEvent read FOnResponseReject write FOnResponseReject;
{ This event will be called after a new Session has been opened. }
property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen;
{ This event will be called before an existing Session is about to close. }
property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose;
{ This event will be mapped as TRtcDataClient.OnDataReceived event
to the assigned DataClient component and called for all DataReceived
events until the request is processed in full, skipped or rejected. }
property OnDataReceived:TRtcNotifyEvent read FOnDataReceived write FOnDataReceived;
{ This event will be mapped as @Link(TRtcConnection.OnDataOut) event
to the assigned DataClient component and called for all DataOut
events until the request is processed in full, skipped or rejected. }
property OnDataOut:TRtcNotifyEvent read FOnDataOut write FOnDataOut;
{ This event will be mapped as @Link(TRtcConnection.OnDataIn) event
to the assigned DataClient component and called for all DataIn
events until the request is processed in full, skipped or rejected. }
property OnDataIn:TRtcNotifyEvent read FOnDataIn write FOnDataIn;
{ This event will be mapped as @Link(TRtcConnection.OnDataSent) event
to the assigned DataClient component and called for all DataSent
events until the request is processed in full, skipped or rejected. }
property OnDataSent:TRtcNotifyEvent read FOnDataSent write FOnDataSent;
{ This event will be mapped as @Link(TRtcConnection.OnReadyToSend) event
to the assigned DataClient component and called for all ReadyToSend
events until the request is processed in full, skipped or rejected. }
property OnReadyToSend:TRtcNotifyEvent read FOnReadyToSend write FOnReadyToSend;
{ This event will be mapped as @Link(TRtcClient.OnConnectLost) event
to the assigned DataClient component and called if your connection gets
closed while you are processing your request (sending or receiving data).
@html(<br><br>)
If you want to re-send the request, you can call Request.Repost from this event,
or use the OnRepostCheck or OnResponseAborted events to do so. }
property OnConnectLost:TRtcNotifyEvent read FOnConnectLost write FOnConnectLost;
end;
implementation
type
{ @abstract(DataRequest Job)
This Job is used by TRtcDataClient to post a signal to start a request
@exclude }
TRtcStartRequestJob=class(TRtcJob)
Client:TRtcDataClient;
procedure Kill; override;
procedure Run(Thr:TRtcThread); override;
end;
{ TRtcDataClientLinkList }
constructor TRtcDataClientLinkList.Create;
begin
inherited;
FList:=TList.Create;
end;
destructor TRtcDataClientLinkList.Destroy;
begin
FList.Free;
inherited;
end;
procedure TRtcDataClientLinkList.Add(Value: TRtcAbsDataClientLink);
var
idx:integer;
begin
idx:=FList.IndexOf(Value);
if idx<0 then
FList.Add(Value);
end;
function TRtcDataClientLinkList.Count: integer;
begin
Result:=FList.Count;
end;
function TRtcDataClientLinkList.Get(index:integer): TRtcAbsDataClientLink;
begin
if (index>=0) and (index<FList.Count) then
Result:=TRtcAbsDataClientLink(FList.Items[index])
else
Result:=nil;
end;
procedure TRtcDataClientLinkList.Remove(Value: TRtcAbsDataClientLink);
var
idx:integer;
begin
idx:=FList.IndexOf(Value);
if idx>=0 then
FList.Delete(idx);
end;
procedure TRtcDataClientLinkList.RemoveAll;
begin
FList.Clear;
end;
{ TRtcDataClient }
constructor TRtcDataClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMyRequest:=TRtcClientRequest.Create;
FMyResponse:=TRtcClientResponse.Create;
FRequest:=FMyRequest;
FResponse:=FMyResponse;
FCS:=TRtcCritSec.Create;
FSession:=TRtcClientSession.Create;
FSession.FCon:=self;
FMayInsertRequest:=False;
FRequestInserted:=False;
FDataClientLinks:=TRtcDataClientLinkList.Create;
FRequestList:=TList.Create;
FActiveRequest:=nil;
FIdle:=True;
FRequestSkipped:=0;
end;
destructor TRtcDataClient.Destroy;
begin
RemoveAllDataClientLinks;
FDataClientLinks.Free;
FDataClientLinks:=nil;
if assigned(FRequestList) then
begin
RemoveAllRequests;
RemoveRequest;
FRequestList.Free;
FRequestList:=nil;
end;
FActiveRequest:=nil;
FIdle:=True;
FMyRequest.Free; FRequest:=nil;
FMyResponse.Free; FResponse:=nil;
FSession.Free;
FCS.Free;
inherited;
end;
procedure TRtcDataClient.CallConnect;
begin
inherited;
if MultiThreaded then
PostStartRequest
else
StartRequest;
end;
procedure TRtcDataClient.CallReadyToSend;
begin
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_ReadyToSend(self);
Flush;
CheckRequestWork;
end
else
inherited;
end;
procedure TRtcDataClient.CallDataSent;
begin
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_DataSent(self);
Flush;
CheckRequestWork;
end
else
inherited;
end;
procedure TRtcDataClient.CallDataOut;
begin
if assigned(FActiveRequest) then
FActiveRequest.Call_DataOut(self);
inherited;
Flush;
end;
procedure TRtcDataClient.CallDataIn;
begin
if assigned(FActiveRequest) then
FActiveRequest.Call_DataIn(self);
inherited;
end;
procedure TRtcDataClient.CallDataReceived;
begin
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_DataReceived(self);
Flush;
if CheckRequestWork then Exit;
FActiveRequest.Call_ResponseData(self);
Flush;
if CheckRequestWork then Exit;
if assigned(Request.OnData) then
begin
Request.OnData(self);
Flush;
if CheckRequestWork then Exit;
end;
if Response.Done then
begin
FActiveRequest.Call_ResponseDone(self);
if CheckRequestWork then Exit;
if assigned(Request.OnDone) then
Request.OnDone(self);
if CheckRequestWork then Exit;
RemoveRequest;
if MultiThreaded then
PostStartRequest
else
StartRequest;
end;
end
else
inherited;
end;
procedure TRtcDataClient.CallConnectLost;
begin
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_ConnectLost(self);
if not Response.Done and not Request.Reposting then
begin
FActiveRequest.Call_RepostCheck(self);
if not Response.Done and not Request.Reposting then
begin
FActiveRequest.Call_ResponseAbort(self);
if assigned(Request.OnAbort) then
if not Request.Reposting then
Request.OnAbort(self);
end;
end;
inherited;
if Request.Skipped then
RemoveRequest
else if Response.Rejected then
begin
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
RemoveRequest;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Response.Clear;
end
else if Response.Done then
RemoveRequest
else
begin
RemoveRequest;
// We will skip all remaining requests
CancelRequests;
end;
// This will remove all skipped requests
PrepareNextRequest;
end
else
inherited;
end;
procedure TRtcDataClient.CallConnectFail;
begin
PrepareNextRequest;
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_RepostCheck(self);
if not Response.Done and not Request.Reposting then
begin
FActiveRequest.Call_ResponseAbort(self);
if assigned(Request.OnAbort) then
if not Request.Reposting then
Request.OnAbort(self);
end;
inherited;
if Request.Skipped then
RemoveRequest
else if Response.Rejected then
begin
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
RemoveRequest;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Response.Clear;
end
else if Response.Done then
RemoveRequest
else
begin
RemoveRequest;
// We will skip all remaining requests
CancelRequests;
end;
// This will remove all skipped requests
PrepareNextRequest;
end
else
inherited;
end;
procedure TRtcDataClient.CallConnectError(E:Exception);
begin
PrepareNextRequest;
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_RepostCheck(self);
if not Response.Done and not Request.Reposting then
begin
FActiveRequest.Call_ResponseAbort(self);
if assigned(Request.OnAbort) then
if not Request.Reposting then
Request.OnAbort(self);
end;
inherited;
if Request.Skipped then
RemoveRequest
else if Response.Rejected then
begin
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
RemoveRequest;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Response.Clear;
end
else if Response.Done then
RemoveRequest
else
begin
RemoveRequest;
// We will skip all remaining requests
CancelRequests;
end;
// This will remove all skipped requests
PrepareNextRequest;
end
else
inherited;
end;
{ Called from TRtcDataRequest to add a new request,
without interfering with other connection component operations. }
procedure TRtcDataClient.AddRequest(Req: TRtcClientRequestInfo);
begin
FCS.Enter;
try
FRequestList.Add(Req);
FIdle:=False;
finally
FCS.Leave;
end;
end;
{ Called from TRtcDataRequest to add a new request,
without interfering with other connection component operations. }
procedure TRtcDataClient.InsertRequest(Req: TRtcClientRequestInfo);
begin
FCS.Enter;
try
if not FMayInsertRequest then
raise Exception.Create('You are not allowed to insert requests.')
else if FRequestSkipped>0 then
raise Exception.Create('Operation Interrupted by a "RequestSkipped" call.');
FRequestInserted:=True;
if assigned(FActiveRequest) then
FRequestList.Insert(0,FActiveRequest);
FActiveRequest:=Req;
Req.WasInjected:=True;
Request:=FActiveRequest.Get_Request;
finally
FCS.Leave;
end;
end;
procedure TRtcDataClient.PrepareNextRequest;
var
endloop:boolean;
begin
if not assigned(FActiveRequest) then
begin
FCS.Enter;
try
repeat
endloop:=True;
if FRequestList.Count>0 then
begin
FActiveRequest:= TRtcClientRequestInfo(FRequestList.Items[0]);
Request:=FActiveRequest.Get_Request;
FRequestList.Delete(0);
end;
if FRequestSkipped>0 then
begin
FCS.Leave;
try
EnterEvent;
try
if assigned(FActiveRequest) then
FActiveRequest.Call_ResponseAbort(self)
else
CallResponseAbort;
finally
LeaveEvent;
end;
finally
FCS.Enter;
end;
RemoveRequest;
endloop:=False;
end;
until endloop;
finally
FCS.Leave;
end;
end;
end;
{ Start Request if no request active }
procedure TRtcDataClient.StartRequest;
var
endmainloop:boolean;
begin
if not isConnected then
begin
if AutoConnect then
Connect;
Exit;
end;
// if assigned(FActiveRequest) then Exit;
repeat
endmainloop:=True;
PrepareNextRequest;
EnterEvent;
try
if isConnected and assigned(FActiveRequest) and not Request.Active then
begin
if (Session.ID<>'') and
(Session.PeerAddr<>PeerAddr) then
begin
Session.Init;
end;
CheckRequestSkipped;
if not Request.Skipped then
begin
FMayInsertRequest:=True;
try
// use a loop to simplify repeating the BeginRequest calls if a new request has been inserted
repeat
FRequestInserted:=False;
if assigned(Request.OnBegin) then
Request.OnBegin(self);
if RequestInserted then
Continue;
FActiveRequest.Call_BeginRequest(self);
until not RequestInserted;
finally
FMayInsertRequest:=False;
end;
Flush;
end;
if not isConnected then
Exit
else if not Request.Active then
begin
if Response.Rejected then
begin
EnterEvent;
try
if assigned(FActiveRequest) then
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
finally
LeaveEvent;
end;
end;
RemoveRequest;
endmainloop:=False;
end
else if not Response.Done then
begin
{ Request has started sending something out }
CheckRequestSkipped;
if Request.Skipped then
begin
RemoveRequest;
// Need to Reset the connection
if isConnected then
begin
Disconnect;
Reconnect;
end;
end
else if Response.Rejected then
begin
EnterEvent;
try
if assigned(FActiveRequest) then
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
finally
LeaveEvent;
end;
RemoveRequest;
// Need to Reset the connection
if isConnected then
begin
Disconnect;
Reconnect;
end;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Response.Clear;
// Reset connection
if isConnected then
begin
Disconnect;
Reconnect;
end;
end;
end
else
begin
if Request.Skipped then
RemoveRequest
else if Response.Rejected then
begin
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
RemoveRequest;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Response.Clear;
end
else
endmainloop:=False;
end;
end;
finally
LeaveEvent;
end;
until endmainloop;
end;
{ Remove all requests from Memory }
procedure TRtcDataClient.RemoveAllRequests;
var
_MyRequest:TRtcClientRequestInfo;
begin
FCS.Enter;
try
FRequestSkipped:=0;
while FRequestList.Count>0 do
begin
_MyRequest := TRtcClientRequestInfo(FRequestList.Items[0]);
_MyRequest.Free;
FRequestList.Delete(0);
end;
if assigned(FActiveRequest) then
FRequestSkipped:=1
else
FIdle:=True;
finally
FCS.Leave;
end;
end;
{ Remove the active Request from Memory }
procedure TRtcDataClient.RemoveRequest;
var
Remove_Next:boolean;
begin
if assigned(FActiveRequest) then
begin
FCS.Enter;
try
if FRequestSkipped>0 then
Dec(FRequestSkipped);
Remove_Next:=FActiveRequest.WasInjected and FActiveRequest.WasAborted;
FActiveRequest.Free;
FActiveRequest:=nil;
if FRequestList.Count=0 then
FIdle:=True;
finally
FCS.Leave;
end;
Request:=nil;
Request.Clear;
Response.Clear;
if Remove_Next then
begin
PrepareNextRequest;
if assigned(FActiveRequest) then
begin
FActiveRequest.Call_ResponseAbort(self);
RemoveRequest;
end;
end;
end;
end;
{ Check the Request after any standard working event. }
function TRtcDataClient.CheckRequestWork:boolean;
begin
CheckRequestSkipped;
if Request.Skipped or Response.Rejected then
begin
Result:=True;
if Response.Rejected then
begin
EnterEvent;
try
if assigned(FActiveRequest) then
FActiveRequest.Call_ResponseReject(self);
if assigned(Request.OnReject) then
Request.OnReject(self);
finally
LeaveEvent;
end;
end;
if Request.Active then
begin
{ Request has started sending something out }
RemoveRequest;
// Need to Reconnect, to reset the connection
if isConnected then
begin
Disconnect;
Reconnect;
end;
end
else
begin
RemoveRequest;
// Check if there are more requests waiting
if MultiThreaded then
PostStartRequest
else
StartRequest;
end;
end
else if Request.Reposting then
begin
Request.Reposting:=False;
Result:=True;
if not Response.Done then
begin
Response.Clear;
if isConnected then
begin
Disconnect;
Reconnect;
end;
end
else
begin
Response.Clear;
if MultiThreaded then
PostStartRequest
else
StartRequest;
end;
end
else if not assigned(FActiveRequest) then
Result:=True
else
Result:=False;
end;
// Skip all requests (do not fire more RequestAborted events)
procedure TRtcDataClient.SkipRequests;
begin
RemoveAllRequests;
end;
// Cancel all requests (fire all RequestAborted events)
procedure TRtcDataClient.CancelRequests;
begin
FCS.Enter;
try
FRequestSkipped:=FRequestList.Count;
if assigned(FActiveRequest) then
Inc(FRequestSkipped)
else
FIdle:=True;
finally
FCS.Leave;
end;
end;
// Post a StartRequest job
procedure TRtcDataClient.PostStartRequest;
var
ReqJob:TRtcStartRequestJob;
begin
ReqJob:=TRtcStartRequestJob.Create;
ReqJob.Client:=self;
if not PostJob(ReqJob) then
begin
if AutoConnect then
Connect;
if not PostJob(ReqJob) then
begin
ReqJob.Client:=nil;
ReqJob.Free;
end;
end;
end;
// Post a new request
procedure TRtcDataClient.PostRequest(Req: TRtcClientRequestInfo;FromInsideEvent:boolean=False);
begin
AddRequest(Req);
if not FromInsideEvent then
PostStartRequest;
end;
function TRtcDataClient.RequestCount: integer;
begin
FCS.Enter;
try
if assigned(FRequestList) then
Result:=FRequestList.Count
else
Result:=0;
if assigned(FActiveRequest) then
Result:=Result+1;
finally
FCS.Leave;
end;
end;
procedure TRtcDataClient.CallBeginRequest;
begin
if assigned(FOnBeginRequest) then
FOnBeginRequest(self);
end;
procedure TRtcDataClient.CallResponseDone;
begin
if assigned(FOnResponseDone) then
FOnResponseDone(self);
end;
procedure TRtcDataClient.CallRepostCheck;
begin
if assigned(FOnRepostCheck) then
FOnRepostCheck(self);
end;
procedure TRtcDataClient.CallResponseData;
begin
if assigned(FOnResponseData) then
FOnResponseData(self);
end;
procedure TRtcDataClient.CallResponseAbort;
begin
if assigned(FActiveRequest) then
FActiveRequest.WasAborted:=True;
if assigned(FOnResponseAbort) then
FOnResponseAbort(self);
end;
procedure TRtcDataClient.CallResponseReject;
begin
if assigned(FOnResponseReject) then
FOnResponseReject(self);
end;
procedure TRtcDataClient.CallSessionClose;
begin
if assigned(FOnSessionClose) then
FOnSessionClose(self);
end;
procedure TRtcDataClient.CallSessionOpen;
begin
if assigned(FOnSessionOpen) then
FOnSessionOpen(self);
end;
procedure TRtcDataClient.AddDataClientLink(Value: TRtcAbsDataClientLink);
begin
FDataClientLinks.Add(Value);
end;
procedure TRtcDataClient.RemoveAllDataClientLinks;
var
Link:TRtcAbsDataClientLink;
begin
while FDataClientLinks.Count>0 do
begin
Link:=TRtcAbsDataClientLink(FDataClientLinks.Get(0));
Link.RemoveClient(self);
end;
end;
procedure TRtcDataClient.RemoveDataClientLink(Value: TRtcAbsDataClientLink);
begin
FDataClientLinks.Remove(Value);
end;
procedure TRtcDataClient.CheckRequestSkipped;
begin
FCS.Enter;
try
if FRequestSkipped>0 then
if assigned(FActiveRequest) then
Request.Skip;
finally
FCS.Leave;
end;
end;
procedure TRtcDataClient.SetRequest(const Value: TRtcClientRequest);
begin
FRequest := Value;
if FRequest=nil then
FRequest:=FMyRequest;
end;
procedure TRtcDataClient.SetResponse(const Value: TRtcClientResponse);
begin
FResponse := Value;
if FResponse=nil then
FResponse:=FMyResponse;
end;
function TRtcDataClient.isIdle: boolean;
begin
FCS.Enter;
try
Result:=FIdle;
finally
FCS.Leave;
end;
end;
function TRtcDataClient.WaitForCompletion(UserInteractionAllowed: boolean; _Timeout: cardinal): boolean;
var
Msg:TMsg;
MyTime:cardinal;
function PeekMsg:boolean;
begin
Result:=PeekMessage(Msg,0,WM_USER,$FFFF,PM_REMOVE) or
PeekMessage(Msg,0,0,WM_KEYFIRST-1,PM_REMOVE);
end;
begin
Result := isIdle;
if Result then
begin
Result:=RequestCount=0;
Exit;
end;
if _Timeout>0 then
MyTime:=GetTickCount+_Timeout*1000
else
MyTime:=0;
if not inMainThread then // When used from a Service
begin
{$IFDEF FPC}
while not Result do
{$ELSE}
while not (Result or Application.Terminated) do
{$ENDIF}
begin
while PeekMessage(Msg,0,0,WM_USER-1,PM_REMOVE) or
PeekMessage(Msg,0,WM_USER,$FFFF,PM_NOREMOVE) do
begin
if Msg.message>=WM_USER then
Exit
else if (Msg.message=WM_QUIT) then
begin
{$IFDEF FPC}
{$ELSE}
Application.Terminate;
{$ENDIF}
Exit;
end
else
begin
TranslateMessage( Msg );
DispatchMessage( Msg );
end;
end;
Result:=isIdle;
if not Result then
if (MyTime>0) and (GetTickCount>=MyTime) then
Exit
else
Sleep(10);
end;
if Result then
Result:=RequestCount=0;
end
else if UserInteractionAllowed then
begin
{$IFDEF FPC}
while not Result do
{$ELSE}
while not (Result or Application.Terminated) do
{$ENDIF}
begin
while PeekMessage(Msg,0,0,0,PM_REMOVE) do
begin
if (Msg.message=WM_QUIT) then
begin
{$IFDEF FPC}
{$ELSE}
Application.Terminate;
{$ENDIF}
Exit;
end
else
begin
TranslateMessage( Msg );
DispatchMessage( Msg );
end;
end;
Result:=isIdle;
if not Result then
if (MyTime>0) and (GetTickCount>=MyTime) then
Exit
else
Sleep(10);
end;
if Result then
Result:=RequestCount=0;
end
else
begin
{$IFDEF FPC}
while not Result do
{$ELSE}
while not (Result or Application.Terminated) do
{$ENDIF}
begin
while PeekMsg do
begin
if (Msg.message=WM_QUIT) then
begin
{$IFDEF FPC}
{$ELSE}
Application.Terminate;
{$ENDIF}
Exit;
end
else
begin
TranslateMessage( Msg );
DispatchMessage( Msg );
end;
end;
Result:=isIdle;
if not Result then
if (MyTime>0) and (GetTickCount>=MyTime) then
Exit
else
Sleep(10);
end;
if Result then
Result:=RequestCount=0;
end;
end;
function TRtcDataClient.isConnectionRequired: boolean;
begin
if not FAutoConnect then
Result:=True
else
Result:=RequestCount>0;
end;
function TRtcDataClient.GetAutoConnect: boolean;
begin
Result:=FAutoConnect;
end;
procedure TRtcDataClient.SetAutoConnect(const Value: boolean);
begin
if Value<>FAutoConnect then
begin
FAutoConnect:=Value;
if FAutoConnect and isConnectionRequired then
Connect;
end;
end;
{ TRtcAbsDataClientLink }
constructor TRtcAbsDataClientLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClient:=nil;
FLink:=nil;
end;
destructor TRtcAbsDataClientLink.Destroy;
begin
Client:=nil; // remove from DataClient
Link:=nil; // remove from parent DataClientLink
inherited;
end;
procedure TRtcAbsDataClientLink.SetLink(const Value: TRtcDataClientLink);
var
MyLink:TRtcDataClientLink;
begin
if Value<>FLink then
begin
if assigned(FLink) then
begin
FLink.RemoveChildLink(self);
FLink:=nil;
end;
if assigned(Value) then
begin
Client:=nil; // can not be maped to DataClient and to DataClientLink at the same time.
// Check for circular reference before assigning!
MyLink:=Value;
while (MyLink<>nil) and (MyLink<>self) do
MyLink:=MyLink.Link;
if MyLink=self then
raise Exception.Create('Circular DataClientLink reference!');
FLink:=Value;
FLink.AddChildLink(self);
end;
end;
end;
function TRtcAbsDataClientLink.GetLink: TRtcDataClientLink;
begin
Result:=FLink;
end;
procedure TRtcAbsDataClientLink.SetClient(const Value: TRtcDataClient);
begin
if Value<>FClient then
begin
if assigned(FClient) then
begin
FClient.RemoveDataClientLink(self);
FClient:=nil;
end;
if assigned(Value) then
begin
Link:=nil; // can not be linked to DataClientLink and DataClient at the same time.
FClient:=Value;
FClient.AddDataClientLink(self);
end;
end;
end;
function TRtcAbsDataClientLink.GetClient: TRtcDataClient;
begin
Result:=FClient;
end;
procedure TRtcAbsDataClientLink.PostRequest(Req: TRtcClientRequestInfo; FromInsideEvent:boolean=False);
begin
if assigned(FLink) then
FLink.PostRequest(Req,FromInsideEvent)
else if assigned(FClient) then
FClient.PostRequest(Req,FromInsideEvent)
else
raise Exception.Create('PostRequest: Client connection undefined.');
end;
procedure TRtcAbsDataClientLink.InsertRequest(Req: TRtcClientRequestInfo);
begin
if assigned(FLink) then
FLink.InsertRequest(Req)
else if assigned(FClient) then
FClient.InsertRequest(Req)
else
raise Exception.Create('InsertRequest: Client connection undefined.');
end;
function TRtcAbsDataClientLink.RequestCount: integer;
begin
if assigned(FLink) then
Result:=FLink.RequestCount
else if assigned(FClient) then
Result:=FClient.RequestCount
else
raise Exception.Create('RequestCount: Client connection undefined.');
end;
procedure TRtcAbsDataClientLink.SkipRequests;
begin
if assigned(FLink) then
FLink.SkipRequests
else if assigned(FClient) then
FClient.SkipRequests
else
raise Exception.Create('SkipRequests: Client connection undefined.');
end;
procedure TRtcAbsDataClientLink.CancelRequests;
begin
if assigned(FLink) then
FLink.CancelRequests
else if assigned(FClient) then
FClient.CancelRequests
else
raise Exception.Create('CancelRequests: Client connection undefined.');
end;
function TRtcAbsDataClientLink.WaitForCompletion(UserInteractionAllowed: boolean; Timeout: cardinal): boolean;
begin
if assigned(FLink) then
Result:=FLink.WaitForCompletion(UserInteractionAllowed, Timeout)
else if assigned(FClient) then
Result:=FClient.WaitForCompletion(UserInteractionAllowed, Timeout)
else
raise Exception.Create('WaitForCompletion: Client connection undefined.');
end;
function TRtcAbsDataClientLink.CheckLink(Value: TRtcAbsDataClientLink): boolean;
begin
if Value=FLink then
Result:=True
else if assigned(FLink) then
Result:=FLink.CheckLink(Value)
else
Result:=False;
end;
procedure TRtcAbsDataClientLink.RemoveClient(Value: TRtcDataClient);
begin
if Value=FClient then Client:=nil;
end;
procedure TRtcAbsDataClientLink.RemoveLink(Value: TRtcAbsDataClientLink);
begin
if Value=FLink then Link:=nil;
end;
{ TRtcDataRequest }
constructor TRtcDataRequestInfo.Create;
begin
inherited;
FEvents:=nil;
FRequest:=nil;
end;
destructor TRtcDataRequestInfo.Destroy;
begin
FEvents:=nil;
if assigned(FRequest) then
begin
FRequest.Free;
FRequest:=nil;
end;
inherited;
end;
procedure TRtcDataRequestInfo.Call_DataReceived(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_DataReceived(Sender);
end;
procedure TRtcDataRequestInfo.Call_DataOut(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_DataOut(Sender);
end;
procedure TRtcDataRequestInfo.Call_DataIn(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_DataIn(Sender);
end;
procedure TRtcDataRequestInfo.Call_DataSent(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_DataSent(Sender);
end;
procedure TRtcDataRequestInfo.Call_ConnectLost(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ConnectLost(Sender);
end;
procedure TRtcDataRequestInfo.Call_RepostCheck(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_RepostCheck(Sender);
end;
procedure TRtcDataRequestInfo.Call_ReadyToSend(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ReadyToSend(Sender);
end;
procedure TRtcDataRequestInfo.Call_BeginRequest(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_BeginRequest(Sender);
end;
procedure TRtcDataRequestInfo.Call_ResponseDone(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ResponseDone(Sender);
end;
procedure TRtcDataRequestInfo.Call_ResponseData(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ResponseData(Sender);
end;
procedure TRtcDataRequestInfo.Call_ResponseAbort(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ResponseAbort(Sender);
end;
procedure TRtcDataRequestInfo.Call_ResponseReject(Sender:TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_ResponseReject(Sender);
end;
procedure TRtcDataRequestInfo.Call_SessionClose(Sender: TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_SessionClose(Sender);
end;
procedure TRtcDataRequestInfo.Call_SessionOpen(Sender: TRtcConnection);
begin
if assigned(FEvents) then
FEvents.Call_SessionOpen(Sender);
end;
function TRtcDataRequestInfo.Get_Request: TRtcClientRequest;
begin
Result:=FRequest;
end;
{ TRtcDataRequestData }
constructor TRtcDataRequestData.Create;
begin
inherited;
FRequest:=nil;
end;
destructor TRtcDataRequestData.Destroy;
begin
if assigned(FRequest) then
begin
FRequest.Free;
FRequest:=nil;
end;
inherited;
end;
{ TRtcDataRequest }
procedure TRtcDataRequest.Call_ConnectLost(Sender: TRtcConnection);
begin
if assigned(FOnConnectLost) then
if AutoSyncEvents then
Sender.Sync(FOnConnectLost)
else
FOnConnectLost(Sender);
end;
procedure TRtcDataRequest.Call_DataReceived(Sender: TRtcConnection);
begin
if assigned(FOnDataReceived) then
if AutoSyncEvents then
Sender.Sync(FOnDataReceived)
else
FOnDataReceived(Sender);
end;
procedure TRtcDataRequest.Call_DataOut(Sender: TRtcConnection);
begin
if assigned(FOnDataOut) then
if AutoSyncEvents then
Sender.Sync(FOnDataOut)
else
FOnDataOut(Sender);
end;
procedure TRtcDataRequest.Call_DataIn(Sender: TRtcConnection);
begin
if assigned(FOnDataIn) then
if AutoSyncEvents then
Sender.Sync(FOnDataIn)
else
FOnDataIn(Sender);
end;
procedure TRtcDataRequest.Call_DataSent(Sender: TRtcConnection);
begin
if assigned(FOnDataSent) then
if AutoSyncEvents then
Sender.Sync(FOnDataSent)
else
FOnDataSent(Sender);
end;
procedure TRtcDataRequest.Call_ReadyToSend(Sender: TRtcConnection);
begin
if assigned(FOnReadyToSend) then
if AutoSyncEvents then
Sender.Sync(FOnReadyToSend)
else
FOnReadyToSend(Sender);
end;
procedure TRtcDataRequest.Call_BeginRequest(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_BeginRequest(Sender)
else if assigned(FClient) then
FClient.CallBeginRequest;
if not TRtcDataClient(Sender).RequestInserted and
not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FOnBeginRequest) then
if AutoSyncEvents then
Sender.Sync(FOnBeginRequest)
else
FOnBeginRequest(Sender);
end;
procedure TRtcDataRequest.Call_ResponseData(Sender: TRtcConnection);
begin
if assigned(FOnResponseData) then
if AutoSyncEvents then
Sender.Sync(FOnResponseData)
else
FOnResponseData(Sender);
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink) then
FLink.Call_ResponseData(Sender)
else if assigned(FClient) then
FClient.CallResponseData;
end;
procedure TRtcDataRequest.Call_ResponseDone(Sender: TRtcConnection);
begin
if assigned(FOnResponseDone) then
if AutoSyncEvents then
Sender.Sync(FOnResponseDone)
else
FOnResponseDone(Sender);
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink) then
FLink.Call_ResponseDone(Sender)
else if assigned(FClient) then
FClient.CallResponseDone;
end;
procedure TRtcDataRequest.Call_RepostCheck(Sender: TRtcConnection);
begin
if ((AutoRepost<0) or (TRtcDataClient(Sender).Request.Reposted<AutoRepost)) then
TRtcDataClient(Sender).Request.Repost
else
begin
if assigned(FOnRepostCheck) then
if not TRtcDataClient(Sender).Request.Reposting then
FOnRepostCheck(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink) then
FLink.Call_RepostCheck(Sender)
else if assigned(FClient) then
FClient.CallRepostCheck;
end;
end;
procedure TRtcDataRequest.Call_ResponseAbort(Sender: TRtcConnection);
begin
if assigned(FOnResponseAbort) then
if AutoSyncEvents then
Sender.Sync(FOnResponseAbort)
else
FOnResponseAbort(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink) then
FLink.Call_ResponseAbort(Sender)
else if assigned(FClient) then
FClient.CallResponseAbort;
end;
procedure TRtcDataRequest.Call_ResponseReject(Sender: TRtcConnection);
begin
if assigned(FOnResponseReject) then
if AutoSyncEvents then
Sender.Sync(FOnResponseReject)
else
FOnResponseReject(Sender);
if assigned(FLink) then
FLink.Call_ResponseReject(Sender)
else if assigned(FClient) then
FClient.CallResponseReject;
end;
procedure TRtcDataRequest.Call_SessionOpen(Sender: TRtcConnection);
begin
if assigned(FOnSessionOpen) then
if AutoSyncEvents then
Sender.Sync(FOnSessionOpen)
else
FOnSessionOpen(Sender);
if assigned(FLink) then
FLink.Call_SessionOpen(Sender)
else if assigned(FClient) then
FClient.CallSessionOpen;
end;
procedure TRtcDataRequest.Call_SessionClose(Sender: TRtcConnection);
begin
if assigned(FOnSessionClose) then
if AutoSyncEvents then
Sender.Sync(FOnSessionClose)
else
FOnSessionClose(Sender);
if assigned(FLink) then
FLink.Call_SessionClose(Sender)
else if assigned(FClient) then
FClient.CallSessionClose;
end;
constructor TRtcDataRequest.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCS:=TRtcCritSec.Create;
FMyData:=tObjList.Create(32);
FMainThrData:=TRtcDataRequestData.Create;
end;
destructor TRtcDataRequest.Destroy;
begin
if assigned(FMainThrData) then
begin
FMainThrData.Free;
FMainThrData:=nil;
end;
if assigned(FMyData) then
begin
FMyData.Free;
FMyData:=nil;
end;
FCS.Free;
inherited;
end;
function TRtcDataRequest.CheckMyData: TRtcDataRequestData;
var
id:longword;
obj:TObject;
begin
if not FHyperThreading then
Result:=FMainThrData
else
begin
id:=GetCurrentThreadId;
if id=MainThreadID then
Result:=FMainThrData
else
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj<>nil then
Result:=TRtcDataRequestData(obj)
else
Result:=nil;
finally
FCS.Leave;
end;
end;
end;
end;
procedure TRtcDataRequest.ClearMyData;
var
id:longword;
obj:TObject;
cli:TRtcDataRequestData;
begin
if FHyperThreading then
begin
id:=GetCurrentThreadId;
if id<>MainThreadID then
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj<>nil then
begin
cli:=TRtcDataRequestData(obj);
cli.Free;
FMyData.remove(id);
end;
finally
FCS.Leave;
end;
end;
end;
end;
function TRtcDataRequest.GetMyData: TRtcDataRequestData;
var
id:longword;
obj:TObject;
begin
if not FHyperThreading then
Result:=FMainThrData
else
begin
id:=GetCurrentThreadId;
if id=MainThreadID then
Result:=FMainThrData
else
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj=nil then
begin
obj:=TRtcDataRequestData.Create;
FMyData.insert(id, obj);
end;
Result:=TRtcDataRequestData(obj);
finally
FCS.Leave;
end;
end;
end;
end;
procedure TRtcDataRequest.Post(FromInsideEvent:boolean=False; Sender:TRtcConnection=nil);
var
myData:TRtcDataRequestData;
DataReq:TRtcDataRequestInfo;
begin
myData:=CheckMyData;
if myData=nil then
raise Exception.Create('Prepare your request using the "Request" property before callind "Post".');
if myData.FRequest=nil then
raise Exception.Create('Prepare your request using the "Request" property before callind "Post".');
with myData do
begin
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=FRequest;
DataReq.Events:=Self;
FRequest:=nil;
end;
try
if assigned(Sender) and (Sender is TRtcDataClient) then
TRtcDataClient(Sender).PostRequest(DataReq,FromInsideEvent)
else
PostRequest(DataReq,FromInsideEvent);
except
DataReq.Free;
raise;
end;
// Free temporary object from memory
ClearMyData;
end;
procedure TRtcDataRequest.Insert(Sender:TRtcConnection);
var
DataReq:TRtcDataRequestInfo;
begin
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=TRtcClientRequest.Create;
DataReq.Events:=Self;
try
if assigned(Sender) and (Sender is TRtcDataClient) then
TRtcDataClient(Sender).InsertRequest(DataReq)
else
InsertRequest(DataReq);
except
DataReq.Free;
raise;
end;
end;
function TRtcDataRequest.GetRequest: TRtcClientRequest;
var
myData:TRtcDataRequestData;
begin
myData:=GetMyData;
if not assigned(myData.FRequest) then
myData.FRequest:=TRtcClientRequest.Create;
Result:=myData.FRequest;
end;
{ TRtcStartRequestJob }
procedure TRtcStartRequestJob.Kill;
begin
Client:=nil;
Free;
end;
procedure TRtcStartRequestJob.Run(Thr:TRtcThread);
begin
try
Client.StartRequest;
except
// ignore exceptions
end;
Client:=nil;
Free;
end;
{ TRtcClientSession }
procedure TRtcClientSession.Init;
begin
Close;
Clear;
FID:='';
FCreated:=0;
FPeerAddr:='';
end;
procedure TRtcClientSession.Open(const _ID: string);
begin
if FID<>'' then Close;
Clear;
FID:=_ID;
FCreated:=Now;
if assigned(FCon) then
FPeerAddr:=FCon.PeerAddr
else
FPeerAddr:='';
if assigned(FCon) and (FCon is TRtcDataClient) then
with TRtcDataClient(FCon) do
if assigned(FActiveRequest) then
FActiveRequest.Call_SessionOpen(FCon)
else
CallSessionOpen;
end;
procedure TRtcClientSession.Close;
begin
if FID<>'' then
begin
if assigned(FCon) and (FCon is TRtcDataClient) then
with TRtcDataClient(FCon) do
if assigned(FActiveRequest) then
FActiveRequest.Call_SessionClose(FCon)
else
CallSessionClose;
FCreated:=0;
FID:='';
Clear;
end;
end;
{ TRtcDataClientLink }
constructor TRtcDataClientLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataClientLinks:=TRtcDataClientLinkList.Create;
end;
destructor TRtcDataClientLink.Destroy;
begin
RemoveAllChildLinks;
FDataClientLinks.Free;
FDataClientLinks:=nil;
inherited;
end;
procedure TRtcDataClientLink.AddChildLink(Value: TRtcAbsDataClientLink);
begin
FDataClientLinks.Add(Value);
end;
procedure TRtcDataClientLink.RemoveAllChildLinks;
var
_Link:TRtcAbsDataClientLink;
begin
while FDataClientLinks.Count>0 do
begin
_Link:=TRtcAbsDataClientLink(FDataClientLinks.Get(0));
_Link.RemoveLink(self);
end;
end;
procedure TRtcDataClientLink.RemoveChildLink(Value: TRtcAbsDataClientLink);
begin
FDataClientLinks.Remove(Value);
end;
procedure TRtcDataClientLink.Call_ConnectLost(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_ConnectLost(Sender);
end;
procedure TRtcDataClientLink.Call_DataReceived(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_DataReceived(Sender);
end;
procedure TRtcDataClientLink.Call_DataOut(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_DataOut(Sender);
end;
procedure TRtcDataClientLink.Call_DataIn(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_DataIn(Sender);
end;
procedure TRtcDataClientLink.Call_DataSent(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_DataSent(Sender);
end;
procedure TRtcDataClientLink.Call_ReadyToSend(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_ReadyToSend(Sender);
end;
procedure TRtcDataClientLink.Call_BeginRequest(Sender: TRtcConnection);
begin
if assigned(FLink) then
FLink.Call_BeginRequest(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallBeginRequest;
if not TRtcDataClient(Sender).RequestInserted then
if assigned(FOnBeginRequest) then
if AutoSyncEvents then
Sender.Sync(FOnBeginRequest)
else
FOnBeginRequest(Sender);
end;
procedure TRtcDataClientLink.Call_ResponseData(Sender: TRtcConnection);
begin
if assigned(FOnResponseData) then
if AutoSyncEvents then
Sender.Sync(FOnResponseData)
else
FOnResponseData(Sender);
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink) then
FLink.Call_ResponseData(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallResponseData;
end;
procedure TRtcDataClientLink.Call_ResponseDone(Sender: TRtcConnection);
begin
if assigned(FOnResponseDone) then
if AutoSyncEvents then
Sender.Sync(FOnResponseDone)
else
FOnResponseDone(Sender);
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink) then
FLink.Call_ResponseDone(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallResponseDone;
end;
procedure TRtcDataClientLink.Call_RepostCheck(Sender: TRtcConnection);
begin
if assigned(FOnRepostCheck) then
if AutoSyncEvents then
Sender.Sync(FOnRepostCheck)
else
FOnRepostCheck(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink) then
FLink.Call_RepostCheck(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallRepostCheck;
end;
procedure TRtcDataClientLink.Call_ResponseAbort(Sender: TRtcConnection);
begin
if assigned(FOnResponseAbort) then
if AutoSyncEvents then
Sender.Sync(FOnResponseAbort)
else
FOnResponseAbort(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink) then
FLink.Call_ResponseAbort(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallResponseAbort;
end;
procedure TRtcDataClientLink.Call_ResponseReject(Sender: TRtcConnection);
begin
if assigned(FOnResponseReject) then
if AutoSyncEvents then
Sender.Sync(FOnResponseReject)
else
FOnResponseReject(Sender);
if assigned(FLink) then
FLink.Call_ResponseReject(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallResponseReject;
end;
procedure TRtcDataClientLink.Call_SessionClose(Sender: TRtcConnection);
begin
if assigned(FOnSessionClose) then
if AutoSyncEvents then
Sender.Sync(FOnSessionClose)
else
FOnSessionClose(Sender);
if assigned(FLink) then
FLink.Call_SessionClose(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallSessionClose;
end;
procedure TRtcDataClientLink.Call_SessionOpen(Sender: TRtcConnection);
begin
if assigned(FOnSessionOpen) then
if AutoSyncEvents then
Sender.Sync(FOnSessionOpen)
else
FOnSessionOpen(Sender);
if assigned(FLink) then
FLink.Call_SessionOpen(Sender)
else if assigned(FClient) then
if Sender=FClient then FClient.CallSessionOpen;
end;
{ TRtcDualDataClientLink }
constructor TRtcDualDataClientLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClient2:=nil;
FLink2:=nil;
end;
destructor TRtcDualDataClientLink.Destroy;
begin
Client2:=nil; // remove from DataClient
Link2:=nil; // remove from parent DataClientLink
inherited;
end;
procedure TRtcDualDataClientLink.CancelRequests;
begin
inherited;
if assigned(FLink2) then
FLink2.CancelRequests
else if assigned(FClient2) then
FClient2.CancelRequests
else
raise Exception.Create('CancelRequests: 2nd Client connection undefined.');
end;
function TRtcDualDataClientLink.GetClient2: TRtcDataClient;
begin
Result:=FClient2;
end;
function TRtcDualDataClientLink.GetLink2: TRtcDataClientLink;
begin
Result:=FLink2;
end;
procedure TRtcDualDataClientLink.InsertRequest(Req: TRtcClientRequestInfo);
var
c1,c2:integer;
begin
if assigned(FLink) then
c1:=FLink.RequestCount
else if assigned(FClient) then
c1:=FClient.RequestCount
else
c1:=MaxLongInt;
if assigned(FLink2) then
c2:=FLink2.RequestCount
else if assigned(FClient2) then
c2:=FClient2.RequestCount
else
c2:=MaxLongInt;
if c1<=c2 then
begin
if assigned(FLink) then
FLink.InsertRequest(Req)
else if assigned(FClient) then
FClient.InsertRequest(Req)
else
raise Exception.Create('InsertRequest: Client connection undefined.');
end
else
begin
if assigned(FLink2) then
FLink2.InsertRequest(Req)
else if assigned(FClient2) then
FClient2.InsertRequest(Req)
else
raise Exception.Create('InsertRequest: 2nd Client connection undefined.');
end;
end;
procedure TRtcDualDataClientLink.PostRequest(Req: TRtcClientRequestInfo; FromInsideEvent: boolean);
var
c1,c2:integer;
begin
if assigned(FLink) then
c1:=FLink.RequestCount
else if assigned(FClient) then
c1:=FClient.RequestCount
else
c1:=MaxLongInt;
if assigned(FLink2) then
c2:=FLink2.RequestCount
else if assigned(FClient2) then
c2:=FClient2.RequestCount
else
c2:=MaxLongInt;
if c1<=c2 then
begin
if assigned(FLink) then
FLink.PostRequest(Req,FromInsideEvent)
else if assigned(FClient) then
FClient.PostRequest(Req,FromInsideEvent)
else
raise Exception.Create('PostRequest: Client connection undefined.');
end
else
begin
if assigned(FLink2) then
FLink2.PostRequest(Req,FromInsideEvent)
else if assigned(FClient2) then
FClient2.PostRequest(Req,FromInsideEvent)
else
raise Exception.Create('PostRequest: 2nd Client connection undefined.');
end;
end;
function TRtcDualDataClientLink.RequestCount: integer;
begin
Result:=inherited RequestCount;
if assigned(FLink2) then
Result:=Result+FLink2.RequestCount
else if assigned(FClient2) then
Result:=Result+FClient2.RequestCount;
end;
procedure TRtcDualDataClientLink.SetClient(const Value: TRtcDataClient);
begin
if Value<>FClient then
begin
if assigned(FClient2) and (FClient2=Value) then
Client2:=nil;
inherited SetClient(Value);
end;
end;
procedure TRtcDualDataClientLink.SetLink(const Value: TRtcDataClientLink);
begin
if Value<>FLink then
begin
if assigned(FLink2) and (FLink2=Value) then
Link2:=nil;
inherited SetLink(Value);
end;
end;
procedure TRtcDualDataClientLink.SetClient2(const Value: TRtcDataClient);
begin
if Value<>FClient2 then
begin
if assigned(FClient2) then
begin
FClient2.RemoveDataClientLink(self);
FClient2:=nil;
end;
if assigned(Value) then
begin
Link2:=nil; // can not be linked to DataClientLink and DataClient at the same time.
FClient2:=Value;
FClient2.AddDataClientLink(self);
end;
end;
end;
procedure TRtcDualDataClientLink.SetLink2(const Value: TRtcDataClientLink);
begin
if Value<>FLink2 then
begin
if assigned(FLink2) then
begin
FLink2.RemoveChildLink(self);
FLink2:=nil;
end;
if assigned(Value) then
begin
Client2:=nil; // can not be maped to DataClient and to DataClientLink at the same time.
// Check for circular reference before assigning!
if Value=self then
raise Exception.Create('Circular DataClientLink reference!');
if Value.CheckLink(self) then
raise Exception.Create('Circular DataClientLink reference!');
if CheckLink(Value) then
raise Exception.Create('Circular DataClientLink reference!');
FLink2:=Value;
FLink2.AddChildLink(self);
end;
end;
end;
procedure TRtcDualDataClientLink.SkipRequests;
begin
inherited;
if assigned(FLink2) then
FLink2.SkipRequests
else if assigned(FClient2) then
FClient2.SkipRequests
else
raise Exception.Create('SkipRequests: 2nd Client connection undefined.');
end;
function TRtcDualDataClientLink.WaitForCompletion(UserInteractionAllowed: boolean; Timeout: cardinal): boolean;
begin
Result:=inherited WaitForCompletion(UserInteractionAllowed,Timeout);
if Result then
begin
if assigned(FLink2) then
Result:=FLink2.WaitForCompletion(UserInteractionAllowed, Timeout)
else if assigned(FClient2) then
Result:=FClient2.WaitForCompletion(UserInteractionAllowed, Timeout)
else
raise Exception.Create('WaitForCompletion: 2nd Client connection undefined.');
end;
end;
function TRtcDualDataClientLink.CheckLink(Value: TRtcAbsDataClientLink): boolean;
begin
Result:=inherited CheckLink(Value);
if not Result then
if Value=FLink2 then
Result:=True
else if assigned(FLink2) then
Result:=FLink2.CheckLink(Value)
else
Result:=False;
end;
procedure TRtcDualDataClientLink.RemoveClient(Value: TRtcDataClient);
begin
inherited RemoveClient(Value);
if Value=FClient2 then Client2:=nil;
end;
procedure TRtcDualDataClientLink.RemoveLink(Value: TRtcAbsDataClientLink);
begin
inherited RemoveLink(Value);
if Value=FLink2 then Link2:=nil;
end;
procedure TRtcDualDataClientLink.Call_ConnectLost(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_ConnectLost(Sender);
end;
procedure TRtcDualDataClientLink.Call_DataReceived(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_DataReceived(Sender);
end;
procedure TRtcDualDataClientLink.Call_DataOut(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_DataOut(Sender);
end;
procedure TRtcDualDataClientLink.Call_DataIn(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_DataIn(Sender);
end;
procedure TRtcDualDataClientLink.Call_DataSent(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_DataSent(Sender);
end;
procedure TRtcDualDataClientLink.Call_ReadyToSend(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_ReadyToSend(Sender);
end;
procedure TRtcDualDataClientLink.Call_BeginRequest(Sender: TRtcConnection);
begin
if assigned(FLink2) then
FLink2.Call_BeginRequest(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallBeginRequest;
inherited;
end;
procedure TRtcDualDataClientLink.Call_ResponseData(Sender: TRtcConnection);
begin
inherited;
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink2) then
FLink2.Call_ResponseData(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallResponseData;
end;
procedure TRtcDualDataClientLink.Call_ResponseDone(Sender: TRtcConnection);
begin
inherited;
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(FLink2) then
FLink2.Call_ResponseDone(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallResponseDone;
end;
procedure TRtcDualDataClientLink.Call_RepostCheck(Sender: TRtcConnection);
begin
inherited;
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink2) then
FLink2.Call_RepostCheck(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallRepostCheck;
end;
procedure TRtcDualDataClientLink.Call_ResponseAbort(Sender: TRtcConnection);
begin
inherited;
if not TRtcDataClient(Sender).Request.Reposting then
if assigned(FLink2) then
FLink2.Call_ResponseAbort(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallResponseAbort;
end;
procedure TRtcDualDataClientLink.Call_ResponseReject(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_ResponseReject(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallResponseReject;
end;
procedure TRtcDualDataClientLink.Call_SessionClose(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_SessionClose(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallSessionClose;
end;
procedure TRtcDualDataClientLink.Call_SessionOpen(Sender: TRtcConnection);
begin
inherited;
if assigned(FLink2) then
FLink2.Call_SessionOpen(Sender)
else if assigned(FClient2) then
if Sender=FClient2 then FClient2.CallSessionOpen;
end;
end.
|
program Sample;
var c: Char;
begin
WriteLn('enter a character and press enter:');
Readln(c);
WriteLn('got chacter ''', c, '''');
end.
|
unit Vigilante.Infra.Compilacao.Builder.Impl;
interface
uses
Vigilante.Infra.Compilacao.Builder, Vigilante.Compilacao.Model, System.JSON,
Vigilante.Infra.Compilacao.JSONDataAdapter;
type
TCompilacaoBuilder = class(TInterfacedObject, ICompilacaoBuilder)
private
FJSON: TJSONObject;
public
constructor Create(const AJson: TJSONObject);
function PegarCompilacao: ICompilacaoModel;
end;
implementation
uses
Vigilante.Compilacao.Model.Impl, Vigilante.Infra.Compilacao.DataAdapter, Module.ValueObject.URL,
Module.ValueObject.URL.Impl;
constructor TCompilacaoBuilder.Create(const AJson: TJSONObject);
begin
FJSON := AJson;
end;
function TCompilacaoBuilder.PegarCompilacao: ICompilacaoModel;
var
_compilacao: ICompilacaoModel;
_adapter: ICompilacaoAdapter;
begin
_adapter := TCompilacaoJSONDataAdapter.Create(FJSON);
_compilacao := TCompilacaoModel.Create(_adapter.Numero, _adapter.Nome,
TURL.Create(_adapter.URL), _adapter.Situacao, _adapter.Building, _adapter.ChangesSet);
Result := _compilacao;
end;
end.
|
unit uConstants;
interface
uses UITypes;
const
// настройки таймеров
TIMER_LOGIC_INTERVAL = 1000;
TIMER_COOLDOWN_INTERVAL = 100;
TIMER_SCROLL_INTERVAL = 100;
// цветовые настройки
COLOR_PANEL_FILL_LIGHT = TAlphaColors.Gray;
COLOR_PANEL_FILL_NORMAL = $FFE0E0E0;
COLOR_PANEL_FILL_DARK = TAlphaColors.Gainsboro;
COLOR_PANEL_FILL_ACTIVE = TAlphaColors.Darkseagreen;
COLOR_PANEL_STROKE_LIGHT = $FFE0E0E0;
COLOR_PANEL_STROKE_NORMAL = TAlphaColors.Lightgrey;
COLOR_PANEL_STROKE_DARK = TAlphaColors.Gray;
COLOR_COMMON_PROGRESS_BG = TAlphaColors.Darkgray;
COLOR_COMMON_PROGRESS_FG = TAlphaColors.Aliceblue;
COLOR_COMMON_PROGRESS_FULL_FG = TAlphaColors.Darkseagreen;
COLOR_HP = TAlphaColors.Firebrick;
COLOR_MP = TAlphaColors.Cornflowerblue;
// размеры и положение компонентов
TOP_PANEL_HEIGHT = 43;
BOTTOM_PANEL_HEIGHT = 177;
// синонимы имен картинок из атласа
IMG_EMPTY = 'msc_empty';
PERS_WARRIOR = 'pers_warrior';
PERS_ARCHER = 'pers_archer';
PERS_BARBARIAN = 'pers_barbarian';
PERS_CLIRIC = 'pers_cliric';
PERS_DRUID = 'pers_druid';
PERS_MAGE = 'pers_mage';
PERS_MONK = 'pers_monk';
PERS_SNIPER = 'pers_sniper';
PERS_THEIF = 'pers_theif';
PERS_VALKYRIA = 'pers_valkyria';
PERS_VEDUNYA = 'pers_vedunya';
PERS_CHAOS = 'pers_chaos';
// картинки интерфейса
INT_WALK_1 = 'int_walk1';
INT_WALK_2 = 'int_walk2';
INT_WALK_3 = 'int_walk3';
INT_WALK_JUMP = 'int_walk_jump';
// указание на элемент прогресса конкретного объекта
KIND_PROGRESS_JUMP = 0;
KIND_PROGRESS_LEVEL = 1;
KIND_PROGRESS_WEIGHT = 2;
implementation
end.
|
unit u_xpl_application;
{$i xpl.inc}
{$M+}
interface
uses SysUtils
, Classes
, CustApp
, u_xpl_address
, u_xpl_folders
, u_xpl_settings
, u_xpl_common
, u_xpl_vendor_file
, u_timer_pool
;
type // TxPLApplication =======================================================
TxPLApplication = class(TComponent)
private
fSettings : TxPLSettings;
fFolders : TxPLFolders;
fAdresse : TxPLAddress;
fOnLogEvent : TStrParamEvent;
fPluginList : TxPLVendorSeedFile;
fVersion : string;
fTimerPool : TTimerPool;
function GetApplication: TCustomApplication;
public
constructor Create(const aOwner : TComponent); reintroduce;
destructor Destroy; override;
function AppName : string;
function FullTitle : string;
function SettingsFile : string;
procedure RegisterMe;
Procedure Log (const EventType : TEventType; const Msg : String); overload; dynamic;
Procedure Log (const EventType : TEventType; const Fmt : String; const Args : Array of const); overload;
property Settings : TxPLSettings read fSettings;
property Adresse : TxPLAddress read fAdresse;
property Folders : TxPLFolders read fFolders;
property Version : string read fVersion;
property OnLogEvent: TStrParamEvent read fOnLogEvent write fOnLogEvent;
property VendorFile: TxPLVendorSeedFile read fPluginList;
property TimerPool : TTimerPool read fTimerPool;
property Application : TCustomApplication read GetApplication;
end;
var xPLApplication : TxPLApplication;
InstanceInitStyle : TInstanceInitStyle;
implementation // =============================================================
uses lin_win_compat
, fpc_delphi_compat
;
// ============================================================================
const AppTitle = '%s v%s by %s (build %s)'{$IFDEF DEBUG} + ' - DEBUG' {$ENDIF};
// TxPLAppFramework ===========================================================
constructor TxPLApplication.Create(const aOwner : TComponent);
begin
inherited Create(aOwner);
Assert(aOwner is TCustomApplication,'Owner must be TCustomApplication type');
include(fComponentStyle,csSubComponent);
fAdresse := TxPLAddress.Create(GetVendor,GetDevice);
fVersion := GetVersion;
fFolders := TxPLFolders.Create(fAdresse);
Log(etInfo,FullTitle);
if TCustomApplication(Owner).HasOption('i') then
fSettings := TxPLCommandLineSettings.Create(self)
else
fSettings := TxPLRegistrySettings.Create(self);
fPluginList := TxPLVendorSeedFile.Create(self,Folders);
fTimerPool := TTimerPool.Create(self);
RegisterMe;
end;
destructor TxPLApplication.Destroy;
begin
if Assigned(fFolders) then fFolders.Free;
fAdresse.Free;
inherited;
end;
function TxPLApplication.GetApplication: TCustomApplication;
begin
Result := Owner as TCustomApplication;
end;
procedure TxPLApplication.RegisterMe;
var aPath, aVersion, aNiceName : string;
begin
if Settings is TxPLRegistrySettings then with TxPLRegistrySettings(Settings) do begin
GetAppDetail(Adresse.Vendor, Adresse.Device,aPath,aVersion, aNiceName);
if aVersion < Version
then SetAppDetail(Adresse.Vendor,Adresse.Device,Version)
end;
end;
function TxPLApplication.AppName : string;
begin
Result := GetProductName;
end;
function TxPLApplication.FullTitle : string;
begin
Result := Format(AppTitle,[AppName,fVersion ,Adresse.Vendor,BuildDate]);
end;
function TxPLApplication.SettingsFile: string;
begin
Result := Folders.DeviceDir + 'settings.xml';
end;
procedure TxPLApplication.Log(const EventType: TEventType; const Msg: String);
begin
LogInSystem(EventType,Msg);
if IsConsole then writeln(FormatDateTime('dd/mm hh:mm:ss',now),' ',EventTypeToxPLLevel(EventType),' ',Msg);
if EventType = etError then Halt;
if Assigned(fOnLogEvent) then OnLogEvent(Msg);
end;
procedure TxPLApplication.Log(const EventType: TEventType; const Fmt: String; const Args: array of const);
begin
Log(EventType,Format(Fmt,Args));
end;
initialization // =============================================================
InstanceInitStyle := iisHostName; // Will use hostname as instance default name
end.
|
unit uConexaoPadrao;
interface
uses Data.DB, System.SysUtils, System.Classes, Datasnap.DBClient, Vcl.Forms,
FireDAC.Phys.FB, FireDAC.Phys.MySQL, FireDAC.Comp.UI, FireDAC.DApt, FireDAC.Comp.Client, Datasnap.Provider,
uDM, Dialogs, FireDAC.Comp.DataSet, FireDAC.Phys.MSSQL;
type TConexaoPadrao = class
private
_fdCursor : TFDGUIxWaitCursor;
_fdDriverFB : TFDPhysFBDriverLink;
_FdDriverMySql : TFDPhysMySQLDriverLink;
_FdDriverSqlServer : TFDPhysMSSQLDriverLink;
_fdQuery : TFDQuery;
_dsProvider : TDataSetProvider;
function trataException(AException: Exception): Boolean;
public
procedure StartTransaction;
procedure Commit;
procedure RollBack;
function GetDataPacket(ASql: string): OleVariant;
function GetDataPacketFD(ASql: string): IFDDataSetReference;
function ExecSql(ASql: String): Boolean;
function ExecSqlAndCommit(ASql: String): Boolean;
function LeUltimoRegistro(TableName, FieldKey: String): Integer;
function insereUltimoRegistro(ATableName: string; ACodigo: Integer): Boolean;
constructor create;
destructor destroy;
end;
var
ConexaoPadrao : TConexaoPadrao;
implementation
{ TConexaoPadrao }
procedure TConexaoPadrao.Commit;
begin
DM.fdConn.Commit;
end;
constructor TConexaoPadrao.create;
begin
_fdCursor := TFDGUIxWaitCursor.Create(nil);
_fdDriverFB := TFDPhysFBDriverLink.Create(nil);
_FdDriverMySql := TFDPhysMySQLDriverLink.Create(nil);
_FdDriverSqlServer := TFDPhysMSSQLDriverLink.Create(nil);
_fdQuery := TFDQuery.Create(nil);
_fdQuery.FormatOptions.DataSnapCompatibility := True;
_fdQuery.Connection := DM.fdConn;
_dsProvider := TDataSetProvider.Create(nil);
_dsProvider.DataSet := _fdQuery;
//_FdDriverMySql.VendorLib := ExtractFilePath(Application.ExeName) + '\libmysql.dll';
_fdQuery.FormatOptions.FmtDisplayDateTime := 'YYYY-MM-DD';
_fdQuery.FormatOptions.FmtDisplayDate := 'YYYY-MM-DD';
end;
destructor TConexaoPadrao.destroy;
begin
if _fdQuery.Active then
_fdQuery.Close;
FreeAndNil(_dsProvider);
FreeAndNil(_fdQuery);
FreeAndNil(_fdDriverFB);
FreeAndNil(_FdDriverSqlServer);
FreeAndNil(_FdDriverMySql);
FreeAndNil(_fdCursor);
end;
function TConexaoPadrao.ExecSql(ASql: String): Boolean;
begin
result := False;
try
_fdQuery.SQL.Clear;
_fdQuery.SQL.Text := ASql;
_fdQuery.ExecSQL;
Result := True;
except
on e : Exception do
result := trataException(e);
end;
end;
function TConexaoPadrao.ExecSqlAndCommit(ASql: String): Boolean;
begin
Result := False;
StartTransaction;
Result := ExecSql(ASql);
if Result then
Commit
else
RollBack;
end;
function TConexaoPadrao.GetDataPacket(ASql: string): OleVariant;
begin
try
_fdQuery.Close;
_fdQuery.SQL.Text := ASql;
_fdQuery.Active := True;
result := _dsProvider.Data;
except
on e : Exception do
raise Exception.Create('Erro ao executar a instrução SQL: ' + Chr(13) + ASql + Chr(13) + e.Message);
end;
end;
function TConexaoPadrao.GetDataPacketFD(ASql: string): IFDDataSetReference;
begin
try
_fdQuery.Close;
_fdQuery.SQL.Text := ASql;
_fdQuery.Active := True;
result := _fdQuery.Data;
except
on e : Exception do
raise Exception.Create('Erro ao executar a instrução SQL: ' + Chr(13) + ASql + Chr(13) + e.Message);
end;
end;
function TConexaoPadrao.insereUltimoRegistro(ATableName: string; ACodigo: Integer): Boolean;
begin
if UpperCase( uDM.DM.fdConn.DriverName ) = 'MSSQL' then
Result := ExecSql('INSERT INTO CODIGOS (TABELA, CODIGO) VALUES (' + QuotedStr(ATableName) + ', ' + IntToStr(ACodigo) + ')');
end;
function TConexaoPadrao.LeUltimoRegistro(TableName, FieldKey: String): Integer;
var
cds : TClientDataSet;
sqlMySql : string;
sqlSqlServer : string;
sqlOracle : string;
sql : string;
begin
try
sqlSqlServer := 'SELECT MAX(CODIGO) AS CODIGO FROM CODIGOS WHERE TABELA = ' + QuotedStr(TableName);
sqlMySql := 'SELECT MAX(' + FieldKey + ') AS CODIGO FROM ' + TableName;
sqlOracle := 'SELECT SEQ' + TableName + '.NEXTVAL - 1 AS CODIGO FROM DUAL';
if UpperCase( uDM.DM.fdConn.DriverName ) = 'MYSQL' then
sql := sqlMySql
else
if UpperCase( uDM.DM.fdConn.DriverName ) = 'MSSQL' then
sql := sqlSqlServer
else
if UpperCase( uDM.DM.fdConn.DriverName ) = 'ORA' then
sql := sqlOracle;
cds := TClientDataSet.Create(nil);
cds.Data := GetDataPacket( sql );
if cds.FieldByName('CODIGO').AsString = '' then
result := 0
else
Result := cds.FieldByName('CODIGO').AsInteger;
cds.Free;
except
on e : Exception do
raise Exception.Create('Erro ao buscar Ultimo Registro. ' + e.Message);
end;
end;
procedure TConexaoPadrao.RollBack;
begin
DM.fdConn.Rollback;
end;
procedure TConexaoPadrao.StartTransaction;
begin
DM.fdConn.StartTransaction;
end;
function TConexaoPadrao.trataException(AException: Exception): Boolean;
begin
raise Exception.Create(AException.Message);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.