text
stringlengths
14
6.51M
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.DB2Def; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysDB2ConnectionDefParams // Generated for: FireDAC DB2 driver TFDDB2StringFormat = (sfChoose, sfUnicode); TFDDB2TxSupported = (tsYes, tsNo); /// <summary> TFDPhysDB2ConnectionDefParams class implements FireDAC DB2 driver specific connection definition class. </summary> TFDPhysDB2ConnectionDefParams = 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 GetAlias: String; procedure SetAlias(const AValue: String); function GetServer: String; procedure SetServer(const AValue: String); function GetPort: Integer; procedure SetPort(const AValue: Integer); function GetProtocol: String; procedure SetProtocol(const AValue: String); function GetOSAuthent: Boolean; procedure SetOSAuthent(const AValue: Boolean); function GetStringFormat: TFDDB2StringFormat; procedure SetStringFormat(const AValue: TFDDB2StringFormat); function GetExtendedMetadata: Boolean; procedure SetExtendedMetadata(const AValue: Boolean); function GetTxSupported: TFDDB2TxSupported; procedure SetTxSupported(const AValue: TFDDB2TxSupported); 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 Alias: String read GetAlias write SetAlias stored False; property Server: String read GetServer write SetServer stored False; property Port: Integer read GetPort write SetPort stored False; property Protocol: String read GetProtocol write SetProtocol stored False; property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False; property StringFormat: TFDDB2StringFormat read GetStringFormat write SetStringFormat stored False default sfChoose; property ExtendedMetadata: Boolean read GetExtendedMetadata write SetExtendedMetadata stored False; property TxSupported: TFDDB2TxSupported read GetTxSupported write SetTxSupported stored False default tsYes; property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False; property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False; end; implementation uses FireDAC.Stan.Consts; // TFDPhysDB2ConnectionDefParams // Generated for: FireDAC DB2 driver {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetODBCAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetODBCAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetLoginTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetLoginTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetAlias: String; begin Result := FDef.AsString[S_FD_ConnParam_DB2_Alias]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetAlias(const AValue: String); begin FDef.AsString[S_FD_ConnParam_DB2_Alias] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetServer: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_Server]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetServer(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_Server] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetPort: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Common_Port]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetPort(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetProtocol: String; begin Result := FDef.AsString[S_FD_ConnParam_DB2_Protocol]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetProtocol(const AValue: String); begin FDef.AsString[S_FD_ConnParam_DB2_Protocol] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetOSAuthent: Boolean; begin Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetOSAuthent(const AValue: Boolean); begin FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetStringFormat: TFDDB2StringFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_DB2_StringFormat]; if CompareText(s, 'Choose') = 0 then Result := sfChoose else if CompareText(s, 'Unicode') = 0 then Result := sfUnicode else Result := sfChoose; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetStringFormat(const AValue: TFDDB2StringFormat); const C_StringFormat: array[TFDDB2StringFormat] of String = ('Choose', 'Unicode'); begin FDef.AsString[S_FD_ConnParam_DB2_StringFormat] := C_StringFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetExtendedMetadata: Boolean; begin Result := FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetExtendedMetadata(const AValue: Boolean); begin FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetTxSupported: TFDDB2TxSupported; var s: String; begin s := FDef.AsString[S_FD_ConnParam_DB2_TxSupported]; if CompareText(s, 'Yes') = 0 then Result := tsYes else if CompareText(s, 'No') = 0 then Result := tsNo else Result := tsYes; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetTxSupported(const AValue: TFDDB2TxSupported); const C_TxSupported: array[TFDDB2TxSupported] of String = ('Yes', 'No'); begin FDef.AsString[S_FD_ConnParam_DB2_TxSupported] := C_TxSupported[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetMetaDefSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetMetaDefSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDB2ConnectionDefParams.GetMetaCurSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDB2ConnectionDefParams.SetMetaCurSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue; end; end.
// ************************************************************************************************** // Delphi Aio Library. // Unit AioIndy // https://github.com/Purik/AIO // The contents of this file are subject to the Apache License 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 // // // The Original Code is AioIndy.pas. // // Contributor(s): // Pavel Minenkov // Purik // https://github.com/Purik // // The Initial Developer of the Original Code is Pavel Minenkov [Purik]. // All Rights Reserved. // // ************************************************************************************************** unit AioIndy; interface uses IdIOHandler, IdServerIOHandler, IdComponent, IdIOHandlerSocket, IdGlobal, Aio, SysUtils, IdCustomTransparentProxy, IdYarn, IdSocketHandle, IdThread, IdSSLOpenSSL, IdSSLOpenSSLHeaders, IdCTypes; type { TIdIOHandlerSocket reintroducing } TAioIdIOHandlerSocket = class(TIdIOHandler) const CONN_TIMEOUT = 3000; protected FBinding: IAioProvider; FBoundIP: string; FBoundPort: TIdPort; FDefaultPort: TIdPort; FTransparentProxy: TIdCustomTransparentProxy; FUseNagle: Boolean; FConnected: Boolean; FIPVersion: TIdIPVersion; procedure ConnectClient; virtual; function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override; function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override; function SourceIsAvailable: Boolean; override; function CheckForError(ALastResult: Integer): Integer; override; procedure RaiseError(AError: Integer); override; function GetTransparentProxy: TIdCustomTransparentProxy; virtual; procedure SetTransparentProxy(AProxy: TIdCustomTransparentProxy); virtual; procedure InitComponent; override; public destructor Destroy; override; function BindingAllocated: Boolean; procedure Close; override; function Connected: Boolean; override; procedure Open; override; function WriteFile(const AFile: String; AEnableTransferFile: Boolean = False): Int64; override; // property Binding: IAioProvider read FBinding; // procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True; AIgnoreBuffer: Boolean = False); override; function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; override; published property IPVersion: TIdIPVersion read FIPVersion write FIPVersion default ID_DEFAULT_IP_VERSION; property BoundIP: string read FBoundIP write FBoundIP; property BoundPort: TIdPort read FBoundPort write FBoundPort default IdBoundPortDefault; property DefaultPort: TIdPort read FDefaultPort write FDefaultPort; property TransparentProxy: TIdCustomTransparentProxy read GetTransparentProxy write SetTransparentProxy; end; TAioIdIOHandlerStack = class(TAioIdIOHandlerSocket) protected procedure ConnectClient; override; function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override; function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override; public procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True; AIgnoreBuffer: Boolean = False); override; function Connected: Boolean; override; function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; override; end; implementation uses IdExceptionCore, IdResourceStringsCore, Classes, IdStack, IdTCPConnection, IdSocks, IdResourceStringsProtocols, IdStackConsts; type TAioIdSSLSocket = class(TIdSSLSocket) end; { TAioIdIOHandlerSocket } function TAioIdIOHandlerSocket.BindingAllocated: Boolean; begin Result := FBinding <> nil end; procedure TAioIdIOHandlerSocket.CheckForDisconnect( ARaiseExceptionIfDisconnected, AIgnoreBuffer: Boolean); begin if ARaiseExceptionIfDisconnected and not FConnected then RaiseConnClosedGracefully end; function TAioIdIOHandlerSocket.CheckForError(ALastResult: Integer): Integer; begin Result := GStack.CheckForSocketError(ALastResult, [Id_WSAESHUTDOWN, Id_WSAECONNABORTED, Id_WSAECONNRESET]); end; procedure TAioIdIOHandlerSocket.Close; begin if FBinding <> nil then begin if Supports(FBinding, IAioTcpSocket) then begin (FBinding as IAioTcpSocket).Disconnect end end; inherited Close; end; procedure TAioIdIOHandlerSocket.ConnectClient; begin IPVersion := Self.FIPVersion; if Supports(FBinding, IAioTcpSocket) then begin FConnected := (FBinding as IAioTcpSocket).Connect(Host, Port, CONN_TIMEOUT) end else if Supports(FBinding, IAioUdpSocket) then begin (FBinding as IAioUdpSocket).Bind(Host, Port); FConnected := True; end; end; function TAioIdIOHandlerSocket.Connected: Boolean; begin Result := (BindingAllocated and FConnected and inherited Connected) or (not InputBufferIsEmpty); end; destructor TAioIdIOHandlerSocket.Destroy; begin if Assigned(FTransparentProxy) then begin if FTransparentProxy.Owner = nil then begin FreeAndNil(FTransparentProxy); end; end; FBinding := nil; inherited Destroy; end; function TAioIdIOHandlerSocket.GetTransparentProxy: TIdCustomTransparentProxy; begin // Necessary at design time for Borland SOAP support if FTransparentProxy = nil then begin FTransparentProxy := TIdSocksInfo.Create(nil); //default end; Result := FTransparentProxy; end; procedure TAioIdIOHandlerSocket.InitComponent; begin inherited InitComponent; FIPVersion := ID_DEFAULT_IP_VERSION; end; procedure TAioIdIOHandlerSocket.Open; begin inherited Open; if not Assigned(FBinding) then begin FBinding := MakeAioTcpSocket end else begin FBinding := nil; end; FConnected := False; //if the IOHandler is used to accept connections then port+host will be empty if (Host <> '') and (Port > 0) then begin ConnectClient end; end; procedure TAioIdIOHandlerSocket.RaiseError(AError: Integer); begin GStack.RaiseSocketError(AError); end; function TAioIdIOHandlerSocket.Readable(AMSec: Integer): Boolean; begin Result := Connected end; function TAioIdIOHandlerSocket.ReadDataFromSource( var VBuffer: TIdBytes): Integer; begin Result := 0; if BindingAllocated and FBinding.ReadBytes(VBuffer) then Result := Length(VBuffer); end; procedure TAioIdIOHandlerSocket.SetTransparentProxy( AProxy: TIdCustomTransparentProxy); var LClass: TIdCustomTransparentProxyClass; begin // All this is to preserve the compatibility with old version // In the case when we have SocksInfo as object created in runtime without owner form it is treated as temporary object // In the case when the ASocks points to an object with owner it is treated as component on form. if Assigned(AProxy) then begin if not Assigned(AProxy.Owner) then begin if Assigned(FTransparentProxy) then begin if Assigned(FTransparentProxy.Owner) then begin FTransparentProxy.RemoveFreeNotification(Self); FTransparentProxy := nil; end; end; LClass := TIdCustomTransparentProxyClass(AProxy.ClassType); if Assigned(FTransparentProxy) and (FTransparentProxy.ClassType <> LClass) then begin FreeAndNil(FTransparentProxy); end; if not Assigned(FTransparentProxy) then begin FTransparentProxy := LClass.Create(nil); end; FTransparentProxy.Assign(AProxy); end else begin if Assigned(FTransparentProxy) then begin if not Assigned(FTransparentProxy.Owner) then begin FreeAndNil(FTransparentProxy); end else begin FTransparentProxy.RemoveFreeNotification(Self); end; end; FTransparentProxy := AProxy; FTransparentProxy.FreeNotification(Self); end; end else if Assigned(FTransparentProxy) then begin if not Assigned(FTransparentProxy.Owner) then begin FreeAndNil(FTransparentProxy); end else begin FTransparentProxy.RemoveFreeNotification(Self); FTransparentProxy := nil; //remove link end; end; end; function TAioIdIOHandlerSocket.SourceIsAvailable: Boolean; begin Result := BindingAllocated and FConnected end; function TAioIdIOHandlerSocket.WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; begin Result := 0; if BindingAllocated then begin Result := FBinding.Write(@ABuffer[AOffset], ALength) end; end; function TAioIdIOHandlerSocket.WriteFile(const AFile: String; AEnableTransferFile: Boolean): Int64; var F: IAioFile; FSize, RdSize: UInt64; Buffer: Pointer; begin Result := 0; if FileExists(AFile) and BindingAllocated then begin F := MakeAioFile(AFile, fmOpenRead or fmShareDenyWrite); FSize := f.Seek(0, soEnd); Buffer := AllocMem(FSize); try RdSize := F.Read(Buffer, FSize); // !!! Assert(RdSize = FSize); // FBinding.Write(Buffer, FSize); finally FreeMem(Buffer); end; end else raise EIdFileNotFound.CreateFmt(RSFileNotFound, [AFile]); end; { TAioIdIOHandlerStack } procedure TAioIdIOHandlerStack.CheckForDisconnect(ARaiseExceptionIfDisconnected, AIgnoreBuffer: Boolean); var LDisconnected: Boolean; begin // ClosedGracefully // Server disconnected // IOHandler = nil // Client disconnected if ClosedGracefully then begin if BindingAllocated then begin Close; // Call event handlers to inform the user that we were disconnected DoStatus(hsDisconnected); //DoOnDisconnected; end; LDisconnected := True; end else begin LDisconnected := not BindingAllocated; end; // Do not raise unless all data has been read by the user if LDisconnected then begin if (InputBufferIsEmpty or AIgnoreBuffer) and ARaiseExceptionIfDisconnected then begin RaiseConnClosedGracefully; end; end; end; procedure TAioIdIOHandlerStack.ConnectClient; var LHost: String; LPort: Integer; LIP: string; LIPVersion : TIdIPVersion; begin inherited ConnectClient; if Assigned(FTransparentProxy) then begin if FTransparentProxy.Enabled then begin LHost := FTransparentProxy.Host; LPort := FTransparentProxy.Port; LIPVersion := FTransparentProxy.IPVersion; end else begin LHost := Host; LPort := Port; LIPVersion := IPVersion; end; end else begin LHost := Host; LPort := Port; LIPVersion := IPVersion; end; if LIPVersion = Id_IPv4 then begin if not GStack.IsIP(LHost) then begin if Assigned(OnStatus) then begin DoStatus(hsResolving, [LHost]); end; LIP := GStack.ResolveHost(LHost, LIPVersion); end else begin LIP := LHost; end; end else begin //IPv6 LIP := MakeCanonicalIPv6Address(LHost); if LIP='' then begin //if MakeCanonicalIPv6Address failed, we have a hostname if Assigned(OnStatus) then begin DoStatus(hsResolving, [LHost]); end; LIP := GStack.ResolveHost(LHost, LIPVersion); end else begin LIP := LHost; end; end; // TODO: Binding.SetPeer(LIP, LPort, LIPVersion); // Connect if Assigned(OnStatus) then begin DoStatus(hsConnecting, [LIP]); end; if Assigned(FTransparentProxy) then begin if FTransparentProxy.Enabled then begin FTransparentProxy.Connect(Self, Host, Port, IPVersion); end; end; end; function TAioIdIOHandlerStack.Connected: Boolean; begin ReadFromSource(False, 0, False); Result := inherited Connected; end; function TAioIdIOHandlerStack.Readable(AMSec: Integer): Boolean; begin Result := inherited Readable(AMSec) end; function TAioIdIOHandlerStack.ReadDataFromSource( var VBuffer: TIdBytes): Integer; begin Assert(Binding<>nil); Result := inherited ReadDataFromSource(VBuffer) end; function TAioIdIOHandlerStack.WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; begin Assert(Binding<>nil); Result := inherited WriteDataToTarget(ABuffer, AOffset, ALength) end; end.
{ SynEdit plugin that automates the notifications between the LSP Client and the Server. (C) PyScripter 2020 } unit SynEditLsp; interface uses System.SysUtils, System.Classes, System.JSON, System.Generics.Collections, LspUtils, SynEditTypes, SynEdit; type TDiagnostic = record Severity: TDiagnositicSeverity; BlockBegin, BlockEnd: TBufferCoord; Source: string; Msg: string; end; TDiagnostics = TThreadList<TDiagnostic>; TLspSynEditPlugin = class(TSynEditPlugin) private FFileId: string; FIncChanges: TJSONArray; FVersion: Int64; FTransmitChanges: Boolean; FDiagnostics: TDiagnostics; procedure FOnLspInitialized(Sender: TObject); class var Instances: TThreadList<TLspSynEditPlugin>; class function FindPluginWithFileId(const AFileId: string): TLspSynEditPlugin; protected procedure LinesInserted(FirstLine, Count: Integer); override; procedure LinesDeleted(FirstLine, Count: Integer); override; procedure LinesPutted(aIndex: Integer; aCount: Integer); override; procedure LinesChanged; override; public constructor Create(AOwner: TCustomSynEdit); destructor Destroy; override; procedure FileOpened(const FileId, LangId: string); procedure FileClosed; procedure FileSaved; procedure FileSavedAs(const FileId, LangId: string); procedure InvalidateErrorLines; property TransmitChanges: boolean read fTransmitChanges write fTransmitChanges; property Diagnostics: TDiagnostics read FDiagnostics; class constructor Create; class destructor Destroy; class procedure HandleLspNotify(const Method: string; Params: TJsonValue); end; function LspPosition(const BC: TBufferCoord): TJsonObject; overload; function LspDocPosition(const FileName: string; const BC: TBufferCoord): TJsonObject; overload; function LspRange(const BlockBegin, BlockEnd: TBufferCoord): TJsonObject; procedure RangeFromJson(Json: TJsonObject; out BlockBegin, BlockEnd: TBufferCoord); implementation uses Winapi.Windows, System.StrUtils, System.Threading, LspClient, JediLspClient, uEditAppIntfs, uCommonFunctions; { TLspSynEditPlugin } constructor TLspSynEditPlugin.Create(AOwner: TCustomSynEdit); begin inherited Create(AOwner); FIncChanges := TJSONArray.Create; FIncChanges.Owned := False; FDiagnostics := TDiagnostics.Create; TJedi.OnInitialized.AddHandler(FOnLspInitialized); Instances.Add(Self); end; destructor TLspSynEditPlugin.Destroy; begin Instances.Remove(Self); TJedi.OnInitialized.RemoveHandler(FOnLspInitialized); FDiagnostics.Free; FIncChanges.Free; inherited; end; class destructor TLspSynEditPlugin.Destroy; begin Instances.Free; end; procedure TLspSynEditPlugin.FileClosed; begin var TempFileName := FFileId; FFileId := ''; if not TJedi.Ready or not (lspscOpenCloseNotify in TJedi.LspClient.ServerCapabilities) or (TempFileName = '') then Exit; var Params := TSmartPtr.Make(TJsonObject.Create)(); Params.AddPair('textDocument', LspTextDocumentIdentifier(TempFileName)); TJedi.LspClient.Notify('textDocument/didClose', Params.ToJson); end; procedure TLspSynEditPlugin.FileOpened(const FileId, LangId: string); begin FFileId := FileId; fVersion := 0; if not TJedi.Ready or (FileId = '') or (LangId <> 'python') then // support for didOpen is mandatory for the client // but I assume that is supported by the Server even if it does not say so // or not (lspscOpenCloseNotify in fLspClient.ServerCapabilities) Exit; var Params := TSmartPtr.Make(TJsonObject.Create)(); // var OldTrailingLineBreak := Editor.Lines.TrailingLineBreak; // Editor.Lines.TrailingLineBreak := True; // try Params.AddPair('textDocument', LspTextDocumentItem(FileId, LangId, Editor.Text, 0)); // finally // Editor.Lines.TrailingLineBreak := OldTrailingLineBreak; // end; TJedi.LspClient.Notify('textDocument/didOpen', Params.ToJson); end; procedure TLspSynEditPlugin.FileSaved; begin if not TJedi.Ready or (FFileId = '') or not (lspscSaveNotify in TJedi.LspClient.ServerCapabilities) then Exit; var Params := TSmartPtr.Make(TJsonObject.Create)(); Params.AddPair('textDocument', LspTextDocumentIdentifier(FFileId)); TJedi.LspClient.Notify('textDocument/didSave', Params.ToJson); end; procedure TLspSynEditPlugin.FileSavedAs(const FileId, LangId: string); begin if (FFileId <> '') then FileClosed; if (FileId <> '') and (LangId = 'python') then FileOpened(FileId, LangId); end; procedure TLspSynEditPlugin.FOnLspInitialized(Sender: TObject); begin if FFileId <> '' then FileOpened(FFileId, 'python'); end; class procedure TLspSynEditPlugin.HandleLspNotify(const Method: string; Params: TJsonValue); var DiagArray: TArray<TDiagnostic>; LFileId : string; begin if GI_PyIDEServices.IsClosing then Exit; if Method <> 'textDocument/publishDiagnostics' then Exit; Params.Owned := False; var Task := TTask.Create(procedure begin try var Uri: string; if not Params.TryGetValue('uri', Uri) then Exit; LFileId := FileIdFromUri(Uri); if LFileId = '' then Exit; var Diagnostics := Params.FindValue('diagnostics'); if not (Diagnostics is TJSONArray) then Exit; var Diag: TJsonValue; SetLength(DiagArray, TJsonArray(Diagnostics).Count); for var I := 0 to TJsonArray(Diagnostics).Count - 1 do begin Diag := TJsonArray(Diagnostics).Items[I]; DiagArray[I].Severity := TDiagnositicSeverity(Diag.GetValue<integer>('severity')); DiagArray[I].Msg := Diag.GetValue<string>('message'); DiagArray[I].Source := Diag.GetValue<string>('source'); RangeFromJson(Diag as TJsonObject, DiagArray[I].BlockBegin, DiagArray[I].BlockEnd); end; finally Params.Free; end; if GI_PyIDEServices.IsClosing then Exit; TThread.ForceQueue(nil, procedure begin var Plugin := FindPluginWithFileId(LFileId); if not Assigned(Plugin) then Exit; var List := PlugIn.FDiagnostics.LockList; try PlugIn.InvalidateErrorLines; // old errors List.Clear; List.AddRange(DiagArray); PlugIn.InvalidateErrorLines; // new errors finally PlugIn.FDiagnostics.UnLockList; end; end); end); Task.Start; end; class function TLspSynEditPlugin.FindPluginWithFileId( const AFileId: string): TLspSynEditPlugin; begin Result := nil; var List := Instances.LockList; try for var Plugin in List do if SameFileName(AFileId, Plugin.FFileId) then Exit(Plugin); finally Instances.UnlockList; end; end; procedure TLspSynEditPlugin.InvalidateErrorLines; begin { Should be called from the main thread } Assert(GetCurrentThreadId = MainThreadId); var List := FDiagnostics.LockList; try for var Diag in List do Editor.InvalidateLine(Diag.BlockBegin.Line); finally FDiagnostics.UnlockList; end; end; procedure TLspSynEditPlugin.LinesChanged; begin Inc(fVersion); if not TJedi.Ready or (FFileId = '') or not fTransmitChanges then Exit; var Params := TSmartPtr.Make(TJsonObject.Create)(); try Params.AddPair('textDocument', LspVersionedTextDocumentIdentifier(FFileId, FVersion)); if not(lspscIncrementalSync in TJedi.LspClient.ServerCapabilities) or // too many changes - faster to send all text (FIncChanges.Count > Editor.Lines.Count div 3) then begin FIncChanges.Clear; var Change := TJsonObject.Create; // var OldTrailingLineBreak := Editor.Lines.TrailingLineBreak; // Editor.Lines.TrailingLineBreak := True; // try Change.AddPair('text', TJsonString.Create(Editor.Text)); // finally // Editor.Lines.TrailingLineBreak := OldTrailingLineBreak; // end; FIncChanges.Add(Change); end; Params.AddPair('contentChanges', FIncChanges as TJsonValue); TJedi.LspClient.Notify('textDocument/didChange', Params.ToJson); finally FIncChanges.Clear; end; end; procedure TLspSynEditPlugin.LinesDeleted(FirstLine, Count: Integer); var Change: TJsonObject; BB, BE: TBufferCoord; begin if not TJedi.Ready or (FFileId = '') or not fTransmitChanges or not (lspscIncrementalSync in TJedi.LspClient.ServerCapabilities) then Exit; BB := BufferCoord(1, FirstLine + 1); BE := BufferCoord(1, FirstLine + Count + 1); Change := TJsonObject.Create; Change.AddPair('range', LspRange(BB, BE)); Change.AddPair('text', TJsonString.Create('')); fIncChanges.Add(Change); end; procedure TLspSynEditPlugin.LinesInserted(FirstLine, Count: Integer); var Change: TJsonObject; BB, BE: TBufferCoord; begin if not TJedi.Ready or (FFileId = '') or not fTransmitChanges or not (lspscIncrementalSync in TJedi.LspClient.ServerCapabilities) then Exit; BB := BufferCoord(1, FirstLine + 1); BE := BB; Change := TJsonObject.Create; Change.AddPair('range', LspRange(BB, BE)); Change.AddPair('text', TJsonString.Create(DupeString(Editor.Lines.LineBreak, Count))); fIncChanges.Add(Change); end; procedure TLspSynEditPlugin.LinesPutted(aIndex, aCount: Integer); var Change: TJsonObject; BB, BE: TBufferCoord; begin if not TJedi.Ready or (FFileId = '') or not fTransmitChanges or not (lspscIncrementalSync in TJedi.LspClient.ServerCapabilities) then Exit; for var I := 0 to aCount - 1 do begin BB := BufferCoord(1, aIndex + I + 1); BE := BufferCoord(1, aIndex + I + 2); Change := TJsonObject.Create; Change.AddPair('range', LspRange(BB, BE)); Change.AddPair('text', TJsonString.Create(Editor.Lines[aIndex + I] + Editor.Lines.LineBreak)); fIncChanges.Add(Change); end; end; function LspPosition(const BC: TBufferCoord): TJsonObject; overload; begin Result := TJsonObject.Create; Result.AddPair('line', TJSONNumber.Create(BC.Line - 1)); Result.AddPair('character', TJSONNumber.Create(BC.Char - 1)); end; function LspDocPosition(const FileName: string; const BC: TBufferCoord): TJsonObject; overload; begin Result := LspDocPosition(FileName, BC.Line - 1, BC.Char - 1); end; function LspRange(const BlockBegin, BlockEnd: TBufferCoord): TJsonObject; begin Result := TJsonObject.Create; Result.AddPair('start', LspPosition(BlockBegin)); Result.AddPair('end', LspPosition(BlockEnd)); end; procedure RangeFromJson(Json: TJsonObject; out BlockBegin, BlockEnd: TBufferCoord); begin BlockBegin := Default(TBufferCoord); BlockEnd := BlockBegin; if not Assigned(Json) then Exit; var Range := Json.FindValue('range'); if not (Range is TJSONObject) then Exit; if Range.TryGetValue('start.line', BlockBegin.Line) then Inc(BlockBegin.Line); if Range.TryGetValue('start.character', BlockBegin.Char) then Inc(BlockBegin.Char); if Range.TryGetValue('end.line', BlockEnd.Line) then Inc(BlockEnd.Line); if Range.TryGetValue('end.character', BlockEnd.Char) then Inc(BlockEnd.Char); end; class constructor TLspSynEditPlugin.Create; begin Instances := TThreadList<TLspSynEditPlugin>.Create; end; end.
namespace RemotingSample.Server; interface uses System.Reflection, System.Runtime.Remoting, System.Runtime.Remoting.Channels, System.Runtime.Remoting.Channels.HTTP, RemotingSample.Implementation; type ConsoleApp = class class var fChannel: HttpChannel; public class method Main; end; implementation class method ConsoleApp.Main; const DefaultPort = 8033; begin // Initializes the server to listen for HTTP requests on a specific port fChannel := new HttpChannel(DefaultPort); ChannelServices.RegisterChannel(fChannel, false); // Registers the TRemoteService service RemotingConfiguration.RegisterWellKnownServiceType( typeOf(RemoteService), 'RemoteService.soap', WellKnownObjectMode.Singleton); // Starts accepting requests Console.WriteLine('HTTP channel created. Listening on port '+DefaultPort.ToString); Console.ReadLine; end; end.
unit GC.LaserCutBoxes.Test.Box; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FPCUnit, TestUtils, TestRegistry, GC.LaserCutBoxes.Box; type { TBoxTest } TBoxTest= class(TTestCase) private FBox: TLaserCutBox; protected published procedure TestBoxCreate; end; implementation procedure TBoxTest.TestBoxCreate; begin try FBox := TLaserCutBox.Create; AssertEquals('Dimensions are Inside', True, FBox.DimensionsInside); AssertEquals('Units are mm', True, (FBox.MeasureUnits=muMillimetres)); AssertEquals('Width is 100.0', 100.0, FBox.Width); AssertEquals('Height is 100.0', 100.0, FBox.Height); AssertEquals('Deep is 100.0', 100.0, FBox.Deep); AssertEquals('Tab Width is 6.0', 6.0, FBox.TabWidth); AssertEquals('Tabs ar not Proportional', False, FBox.TabsProportional); AssertEquals('MaterialThickness is 3.0', 3.0, FBox.MaterialThickness); AssertEquals('Kerf is 0.5', 0.5, FBox.Kerf); AssertEquals('Joint Clearance is 0.1', 0.1, FBox.JointClearance); AssertEquals('Space Between Parts is 1.0', 1.0, FBox.SpaceBetweenParts); AssertEquals('There are no Dividers Length Wise', 0, FBox.DividersLength); AssertEquals('There are no Dividers Width Wise', 0, FBox.DividersWidth); finally FBox.Free; end; end; initialization RegisterTest(TBoxTest); end.
unit CncShellDlgs; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Grids, ValEdit, ComCtrls, Math; type TLineAlignement = (laUndefined, laOdd, laEven, laNone); type TMetadataDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Panel1: TPanel; Panel2: TPanel; MetaEditor: TValueListEditor; Splitter1: TSplitter; Panel3: TPanel; Image1: TImage; TrackBar1: TTrackBar; Label1: TLabel; procedure FormCreate(Sender: TObject); private FLineEnding : string; FLineAlignement : TLineAlignement; public function ScanFile(const FileName : TFileName) : boolean; virtual; function Execute(const FileName : TFileName) : boolean; procedure AddMetadata(const KeyName, Desc, Value, Mask: string; MaxLen : integer; CanEdit : boolean); end; var MetadataDlg: TMetadataDlg; implementation {$R *.dfm} function TMetadataDlg.ScanFile(const FileName : TFileName) : boolean; const BufferSize = 2048; LineDelim = [#10, #13]; var s : TFileStream; Buffer : PChar; BytesRead : integer; i : integer; begin result := false; Buffer := StrAlloc(BufferSize+1); s := TFileStream.Create(FileName, fmOpenRead); BytesRead := s.Read(Buffer[0], BufferSize); Buffer[BytesRead] := #0; s.Free; // Check for line ending FLineEnding := ''; i :=0; while (i<Min(BytesRead, 255)) and not (Buffer[i] in LineDelim) do inc(i); while (i<Min(BytesRead, 255)) and (Buffer[i] in LineDelim) do begin FLineEnding := FLineEnding+Buffer[i]; inc(i); end; if Length(FLineEnding)=0 then exit; // no line found.... // Check for line alignement FLineAlignement := laUndefined; StrDispose(Buffer); result := true; end; function TMetadataDlg.Execute(const FileName : TFileName) : boolean; begin result := false; OKBtn.Enabled := ScanFile(FileName); Case ShowModal of mrOK : result := true; mrCancel : result := false; end; end; procedure TMetadataDlg.FormCreate(Sender: TObject); begin AddMetadata('Machine', 'Machine', '', '', 18, true); AddMetadata('Customer', 'Client', '', '', 18, true); AddMetadata('Object', 'Objet', '', '', 18, true); AddMetadata('Drawing', 'Plan', '', '', 18, true); AddMetadata('Thumbnail', 'Aperçu', '', '', 18, false); end; procedure TMetadataDlg.AddMetadata(const KeyName, Desc, Value, Mask: string; MaxLen : integer; CanEdit : boolean); begin MetaEditor.InsertRow(KeyName, Value, true); with MetaEditor.ItemProps[KeyName] do begin KeyDesc := Desc; MaxLength := MaxLen; EditMask := Mask; ReadOnly := not CanEdit; end; end; end.
unit Security4D.Impl; interface uses System.SysUtils, Security4D; type TSecurity = class(TInterfacedObject, ISecurity) private { private declarations } protected { protected declarations } public { public declarations } end; TSecurityProvider = class abstract(TSecurity) private fSecurityContext: Pointer; protected function SecurityContext: ISecurityContext; public constructor Create(securityContext: ISecurityContext); end; TDefaultAuthenticator = class(TSecurity, IAuthenticator) private const CLASS_NOT_FOUND = 'Security Authenticator not defined.'; protected function GetAuthenticatedUser: IUser; procedure Authenticate(user: IUser); procedure Unauthenticate; public { public declarations } end; TDefaultAuthorizer = class(TSecurity, IAuthorizer) private const CLASS_NOT_FOUND = 'Security Authorizer not defined.'; protected function HasRole(const role: string): Boolean; function HasPermission(const resource, operation: string): Boolean; public { public declarations } end; TUser = class(TSecurity, IUser) private fId: string; fAttribute: TObject; fOwns: Boolean; protected function GetId: string; function GetAttribute: TObject; public constructor Create(const id: string; attribute: TObject; const owns: Boolean = True); destructor Destroy; override; end; TSecurityContext = class(TSecurity, ISecurityContext) private const NOT_LOGGED_IN = 'User not authenticated.'; private fAuthenticator: IAuthenticator; fAuthorizer: IAuthorizer; fOnAfterLoginSuccessful: TProc; fOnAfterLogoutSuccessful: TProc; protected function GetAuthenticator: IAuthenticator; function GetAuthorizer: IAuthorizer; function GetAuthenticatedUser: IUser; procedure RegisterAuthenticator(authenticator: IAuthenticator); procedure RegisterAuthorizer(authorizer: IAuthorizer); procedure OnAfterLoginSuccessful(event: TProc); procedure OnAfterLogoutSuccessful(event: TProc); procedure Login(user: IUser); procedure Logout; function IsLoggedIn: Boolean; procedure CheckLoggedIn; function HasRole(const role: string): Boolean; function HasPermission(const resource, operation: string): Boolean; public constructor Create; destructor Destroy; override; end; implementation { TDefaultAuthenticator } procedure TDefaultAuthenticator.Authenticate(user: IUser); begin raise EAuthenticatorException.Create(CLASS_NOT_FOUND); end; function TDefaultAuthenticator.GetAuthenticatedUser: IUser; begin raise EAuthenticatorException.Create(CLASS_NOT_FOUND); end; procedure TDefaultAuthenticator.Unauthenticate; begin raise EAuthenticatorException.Create(CLASS_NOT_FOUND); end; { TDefaultAuthorizer } function TDefaultAuthorizer.HasPermission(const resource, operation: string): Boolean; begin raise EAuthorizerException.Create(CLASS_NOT_FOUND); end; function TDefaultAuthorizer.HasRole(const role: string): Boolean; begin raise EAuthorizerException.Create(CLASS_NOT_FOUND); end; { TUser } constructor TUser.Create(const id: string; attribute: TObject; const owns: Boolean); begin inherited Create; fId := id; fAttribute := attribute; fOwns := owns; end; destructor TUser.Destroy; begin if fOwns and Assigned(fAttribute) then fAttribute.Free; inherited Destroy; end; function TUser.GetAttribute: TObject; begin Result := fAttribute; end; function TUser.GetId: string; begin Result := fId; end; { TSecurityContext } procedure TSecurityContext.CheckLoggedIn; begin if not IsLoggedIn then raise EAuthorizationException.Create(NOT_LOGGED_IN); end; constructor TSecurityContext.Create; begin inherited Create; fAuthenticator := nil; fAuthorizer := nil; fOnAfterLoginSuccessful := nil; fOnAfterLogoutSuccessful := nil; end; destructor TSecurityContext.Destroy; begin inherited Destroy; end; function TSecurityContext.GetAuthenticatedUser: IUser; begin Result := GetAuthenticator.AuthenticatedUser; end; function TSecurityContext.GetAuthenticator: IAuthenticator; begin if not Assigned(fAuthenticator) then fAuthenticator := TDefaultAuthenticator.Create; Result := fAuthenticator; end; function TSecurityContext.GetAuthorizer: IAuthorizer; begin if not Assigned(fAuthorizer) then fAuthorizer := TDefaultAuthorizer.Create; Result := fAuthorizer; end; function TSecurityContext.HasPermission(const resource, operation: string): Boolean; begin CheckLoggedIn; try Result := GetAuthorizer.HasPermission(resource, operation); except on E: Exception do raise EAuthorizationException.Create(E.Message); end; end; function TSecurityContext.HasRole(const role: string): Boolean; begin CheckLoggedIn; try Result := GetAuthorizer.HasRole(role); except on E: Exception do raise EAuthorizationException.Create(E.Message); end; end; function TSecurityContext.IsLoggedIn: Boolean; begin Result := Assigned(GetAuthenticatedUser()); end; procedure TSecurityContext.Login(user: IUser); begin try GetAuthenticator.Authenticate(user); except on E: Exception do raise EAuthorizationException.Create(E.Message); end; if Assigned(fOnAfterLoginSuccessful) then fOnAfterLoginSuccessful(); end; procedure TSecurityContext.Logout; begin try GetAuthenticator.Unauthenticate; except on E: Exception do raise EAuthorizationException.Create(E.Message); end; if Assigned(fOnAfterLogoutSuccessful) then fOnAfterLogoutSuccessful(); end; procedure TSecurityContext.OnAfterLoginSuccessful(event: TProc); begin fOnAfterLoginSuccessful := event; end; procedure TSecurityContext.OnAfterLogoutSuccessful(event: TProc); begin fOnAfterLogoutSuccessful := event; end; procedure TSecurityContext.RegisterAuthenticator(authenticator: IAuthenticator); begin fAuthenticator := authenticator; end; procedure TSecurityContext.RegisterAuthorizer(authorizer: IAuthorizer); begin fAuthorizer := authorizer; end; { TSecurityProvider } constructor TSecurityProvider.Create(securityContext: ISecurityContext); begin inherited Create; fSecurityContext := Pointer(securityContext); end; function TSecurityProvider.SecurityContext: ISecurityContext; begin Result := ISecurityContext(fSecurityContext); end; end.
unit uContaContabil; interface uses Contnrs, uRegistroEmpresaContabil , uRegistro; type TContaContabil = class(TRegistroEmpresaContabil) private fGrau: Integer; fID: Integer; fTipo: String; fCodigo: String; fDescricao: String; fCodigoReduzido: String; procedure setCodigo(const Value: String); procedure setDescricao(const Value: String); procedure setGrau(const Value: Integer); procedure setID(const Value: Integer); procedure setTipo(const Value: String); procedure SetCodigoReduzido(const Value: String); function RPad(S: string; Ch: Char; Len: Integer): string; public property ID : Integer read fID write setID; property CodigoReduzido : String read fCodigoReduzido write SetCodigoReduzido; property Codigo : String read fCodigo write setCodigo; property Descricao : String read fDescricao write setDescricao; property Grau : Integer read fGrau write setGrau; property Tipo : String read fTipo write setTipo; function Procurar() : TRegistro; constructor create(); end; implementation uses uContaContabilBD, uEmpresa; { TContaContabil } constructor TContaContabil.create; begin Empresa := TEmpresa.create; end; function TContaContabil.Procurar: TRegistro; var lContaContabilBD : TContaContabilBD; begin lContaContabilBD := TContaContabilBD.Create; result := lContaContabilBD.Procurar(self); lContaContabilBD.Free; lContaContabilBD := nil; end; procedure TContaContabil.setCodigo(const Value: String); begin fCodigo := Value; end; procedure TContaContabil.SetCodigoReduzido(const Value: String); begin fCodigoReduzido := RPad(Value, ' ', 12); end; procedure TContaContabil.setDescricao(const Value: String); begin fDescricao := Value; end; procedure TContaContabil.setGrau(const Value: Integer); begin fGrau := Value; end; procedure TContaContabil.setID(const Value: Integer); begin fID := Value; end; procedure TContaContabil.setTipo(const Value: String); begin fTipo := Value; end; //function TContaContabil.LPad(S: string; Ch: Char; Len: Integer): string; //var // RestoTamanho: Integer; //begin // Result := S; // RestoTamanho := Len - Length(s); // if RestoTamanho < 1 then Exit; // Result := S + StringOfChar(Ch, RestoTamanho); //end; function TContaContabil.RPad(S: string; Ch: Char; Len: Integer): string; var RestoTamanho: Integer; begin Result := S; RestoTamanho := Len - Length(s); if RestoTamanho < 1 then Exit; Result := StringOfChar(Ch, RestoTamanho) + S; end; //{exemplo de uso} //procedure TForm1.Button1Click(Sender: TObject); //begin Edit1.Text := RPad(Edit2.Text, '-', 30); //end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Dateutils; type TForm1 = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; Label1: TLabel; Button1: TButton; Label2: TLabel; Label3: TLabel; Button2: TButton; Label4: TLabel; Button3: TButton; Label5: TLabel; Button4: TButton; Label6: TLabel; Button5: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var date1, date2, date3, date4 : TDateTime; // TDateTime variables in System.unit begin //Obs. to be processed you need add SysUtil and Dateutils in USES.(start of day). date4 := Now; // Set to the current day and time date2 := Date; // Set to the start of the current day date1 := Yesterday; // Set to the start of yesterday date3 := Tomorrow; // Set to the start of tomorrow end; procedure TForm1.Button2Click(Sender: TObject); var month : Integer; begin for month := 1 to 12 do // Display the short and long month names begin ShowMessage(ShortMonthNames[month]); //SHORT ShowMessage(LongMonthNames[month]); //LONG end; end; procedure TForm1.Button3Click(Sender: TObject); var day : Integer; begin for day := 1 to 7 do // Display the short and long day names begin ShowMessage(ShortDayNames[day]); ShowMessage(LongDayNames[day]); end; end; procedure TForm1.Button4Click(Sender: TObject); var myDate : TDateTime; day, month, year : string; begin // Set up our TDateTime variable with a full date and time : 09/02/2000 at 05:06:07.008 (.008 milli-seconds) myDate := EncodeDateTime(2000, 2, 9, 5, 6, 7, 8); // Date only - numeric values with no leading zeroes (except year) d/m/y = 9/2/00 ShowMessage('d/m/y = '+ FormatDateTime('d/m/y', myDate)); // Date only - numeric values with leading zeroes - dd/mm/yy = 09/02/00 ShowMessage('dd/mm/yy = '+ FormatDateTime('dd/mm/yy', myDate)); // Use short names for the day, month, and add freeform text ('of') ddd d of mmm yyyy = Wed 9 of Feb 2000 ShowMessage('ddd d of mmm yyyy = '+ FormatDateTime('ddd d of mmm yyyy', myDate)); // Use long names for the day and month - dddd d of mmmm yyyy = Wednesday 9 of February 2000 ShowMessage('dddd d of mmmm yyyy = '+ FormatDateTime('dddd d of mmmm yyyy', myDate)); // Use the ShortDateFormat settings only - ddddd = 09/02/2000 ShowMessage('ddddd = '+ FormatDateTime('ddddd', myDate)); // Use the LongDateFormat settings only - dddddd = 09 February 2000 ShowMessage('dddddd = '+ FormatDateTime('dddddd', myDate)); ShowMessage(''); // Time only - numeric values with no leading zeroes - h:n:s.z = 5:6:7.008 ShowMessage('h:n:s.z = '+ FormatDateTime('h:n:s.z', myDate)); // Time only - numeric values with leading zeroes - hh:nn:ss.zzz = 05:06:07.008 ShowMessage('hh:nn:ss.zzz = '+ FormatDateTime('hh:nn:ss.zzz', myDate)); // Use the ShortTimeFormat settings only - t = 05:06 ShowMessage('t = '+FormatDateTime('t', myDate)); // Use the LongTimeFormat settings only - tt = 05:06:07 ShowMessage('tt = '+FormatDateTime('tt', myDate)); // Use the ShortDateFormat + LongTimeFormat settings - c = 09/02/2000 05:06:07 ShowMessage('c = '+FormatDateTime('c', myDate)); //Formatting control variables //DateSeparator - The character used to separate display date fields - value is '/' by default myDate := EndOfAMonth(2000, 2); // 29th Feb 2000 at 23:59:59.999 ShowMessage('Date = '+DateTimeToStr(myDate)); // Date = 29/02/2000 23:59:59 DateSeparator := '_'; // Override the / date separator ShowMessage('Date now = '+DateTimeToStr(myDate)); //Date now = 29_02_2000 23:59:59 //TimeSeparator - The character used to separate display time fields myDate := EndOfAMonth(2000, 2); // 29th Feb 2000 at 23:59:59.999 LongTimeFormat := 'hh:mm:ss.zzz'; // Show milli-seconds ShowMessage('Date = '+DateTimeToStr(myDate)); //Date = 29/02/2000 23:59:59.999 TimeSeparator := '_'; // Override the : time separator ShowMessage('Date now = '+DateTimeToStr(myDate)); //Date now = 29/02/2000 23_59_59.999 //ShortDateFormat - Compact version of the date to string format myDate := StrToDate('29/02/2000'); // Display using the default ShortDateFormat ShowMessage('29/02/2000 using default = '+DateToStr(myDate)); //29/02/2000 using default = 29/02/2000 // Change the display formatting ShortDateFormat := 'dddd dd mmmm yyyy'; ShowMessage('29/02/2000 using dddd dd mmmm yyyy = '+DateToStr(myDate)); //29/02/2000 using dddd dd mmmm yyyy = Tuesday 29 February 2000 { y = Year last 2 digits yy = Year last 2 digits yyyy = Year as 4 digits m = Month number no-leading 0 mm = Month number as 2 digits mmm = Month using ShortDayNames (Jan) mmmm = Month using LongDayNames (January) d = Day number no-leading 0 dd = Day number as 2 digits ddd = Day using ShortDayNames (Sun) dddd = Day using LongDayNames (Sunday)} //LongDateFormat - Long version of the date to string format myDate := StrToDate('29/02/2000'); // Display using the default LongDateFormat DateTimeToString(formattedDate, 'dddddd', myDate); ShowMessage('29/02/2000 using default = '+formattedDate); // Change the display formatting LongDateFormat := 'dddd dd of mmmm yyyy'; DateTimeToString(formattedDate, 'dddddd', myDate); // 29/02/2000 using default = 29 February 2000 ShowMessage('29/02/2000 using override = '+formattedDate); //29/02/2000 using override = Tuesday 29 of February 2000 { y = Year last 2 digits yy = Year last 2 digits yyyy = Year as 4 digits m = Month number no-leading 0 mm = Month number as 2 digits mmm = Month using ShortDayNames (Jan) mmmm = Month using LongDayNames (January) d = Day number no-leading 0 dd = Day number as 2 digits ddd = Day using ShortDayNames (Sun) dddd = Day using LongDayNames (Sunday)} //ShortTimeFormat - Short version of the time to string format myDate := StrToTime('15:06:23.456'); // Display using the default ShortTimeFormat DateTimeToString(formattedDate, 't', myDate); ShowMessage('15:06:23.456 using default = '+formattedDate); //15:06:23.456 using default = 15:06 // Change the display formatting ShortTimeFormat := 'hh nn ss'; DateTimeToString(formattedDate, 't', myDate); ShowMessage('15:06:23.456 using override = '+formattedDate); //15:06:23.456 using override = 15 06 23 { h = Hour with no leading 0's hh = Hour as 2 digits n = Minute with no leading 0's nn = Minute as 2 digits s = Seconds with no leading 0's ss = Seconds as 2 digits z = Milli-seconds with no leading 0's zzz = Milli-seconds as 3 digits} //LongTimeFormat - Long version of the time to string format myDate := StrToTime('15:06:23.456'); // Display using the default LongTimeFormat DateTimeToString(formattedDate, 'tt', myDate); ShowMessage('15:06:23.456 using default = '+formattedDate); //15:06:23.456 using default = 15:06:23 // Change the display formatting LongTimeFormat := 'hh nn ss (zzz)'; DateTimeToString(formattedDate, 'tt', myDate); ShowMessage('15:06:23.456 using override = '+formattedDate); //15:06:23.456 using override = 15 06 23 (456) //ShortDayNames - The ShortDayNames variable provides an array of short string names of the days of the week. myDate := EncodeDate(2002, 12, 31); day := ShortDayNames[DayOfWeek(myDate)]; //O delphi ja tem na Sysutil um array dos dias da semana com nome curto. ShowMessage('Christmas day 2002 is on a '+day); //Christmas day 2002 is on a Tue //ShortMonthNames - The ShortMonthNames variable provides an array of short string names of the months of the year. month := ShortMonthNames[12]; //o delphi ja tem na sysutil um array dos meses do ano com nome curto. ShowMessage('Month 12 = '+month); //Month 12 = Dec //LongDayNames - The LongDayNames variable provides an array of full string names of the days of the week. myDate := EncodeDate(2002, 12, 31); day := LongDayNames[DayOfWeek(myDate)]; //delphi ja tem na sysutils um array com nome dos dias completo. starting 1 = Sunday ShowMessage('Christmas day 2002 is on a '+day); //Christmas day 2002 is on a Tuesday //LongMonthNames - The LongMonthNames variable provides an array of full string names of the months of the year. month := LongMonthNames[12]; //o delphi ja tem na sysutil um array com nome dos meses completo. starting 1 = January ShowMessage('Month 12 = '+month); //Month 12 = December end; procedure TForm1.Button5Click(Sender: TObject); var myDate : TDateTime; begin //EXEMPLOS DE CALCULOS DATE AND TIMES. //EncodeDateTime - The EncodeDateTime function generates a TDateTime return value from the passed Year, Month, Day, Hour, Min, Sec and MSec (millisecond) values. {The permitted parameter values are : (If you exceed these values, an EConvertError is raised.) Year = 0..9999 Month = 1..12 Day = 1..31 (depending on month/year) Hour = 0..23 Min = 0..59 Sec = 0..59 MSec = 0..999} myDate := EncodeDateTime(2000, 02, 29, 12, 34, 56, 789); LongTimeFormat := 'hh:mm:ss.z'; // Ensure that MSecs are shown ShowMessage('Date set to '+DateToStr(myDate)); //Date set to 29/02/2000 ShowMessage('Time set to '+TimeToStr(myDate)); //Time set to 12:34:56.789 //EncodeDate The EncodeDate function generates a TDateTime return value from the passed Year, Month and Day values. {he permitted parameter values are : (If you exceed these values, an EConvertError is raised.) Year = 2000..9999 Month = 1..12 Day = 1..31 (depending on month/year)} // Set my date variable using the EncodeDate function myDate := EncodeDate(2000, 02, 29); LongTimeFormat := 'hh:mm:ss.zzz'; // Ensure that MSecs are shown ShowMessage('Date set to '+DateToStr(myDate)); //Date set to 29/02/2000 ShowMessage('Time set to '+TimeToStr(myDate)); //Time set to 00:00:00.000 // EncodeTime - The EncodeTime function generates a TDateTime return value from the passed Hour, Min, Sec and MSec (millisecond) values. {The permitted parameter values are : (If you exceed these values, an EConvertError is raised.) Hour = 0..23 Min = 0..59 Sec = 0..59 MSec = 0..999 } LongTimeFormat := 'hh:mm:ss.z'; // Ensure that MSecs are shown ShowMessage('Date set to '+DateToStr(myDate)); //Date set to 30/12/1899 ShowMessage('Time set to '+TimeToStr(myDate)); //Time set to 12:34:56.789 // DecodeDateTime - The DecodeDateTime procedure extracts year, month, day, hour, minute, second and milli-second values from a given // SourceDate TDateTime type value. It stores the values in the output variables : Year, Month, Day, Hour, Min, Sec and MSec. {var myDate : TDateTime; myYear, myMonth, myDay : Word; myHour, myMin, mySec, myMilli : Word; begin // Set up the myDate variable to have a December 2000 value myDate := StrToDateTime('29/12/2000 12:45:12.34'); // Now add a month to this value myDate := IncMonth(myDate); // And let us see what we get DecodeDateTime(myDate, myYear, myMonth, myDay, myHour, myMin, mySec, myMilli); ShowMessage('myDate now = '+DateToStr(myDate)); //myDate now = 29/01/2001 ShowMessage('myHour = '+IntToStr(myHour)); //myHour = 12 ShowMessage('myMin = '+IntToStr(myMin)); //myMin = 45 ShowMessage('mySec = '+IntToStr(mySec)); //mySec = 12 ShowMessage('myMilli = '+IntToStr(myMilli)); //myMilli = 34 ShowMessage('myDay = '+IntToStr(myDay)); //myDay = 29 ShowMessage('myMonth = '+IntToStr(myMonth)); //myMonth = 1 ShowMessage('myYear = '+IntToStr(myYear)); //myYear = 2001 end;} //DecodeDate The DecodeDate procedure extracts year, month and day values from a given SourceDate TDateTime type value. //It stores the values in the output variables : Year, Month and Day. { var myDate : TDateTime; myYear, myMonth, myDay : Word; begin // Set up the myDate variable to have a December 2000 value myDate := StrToDate('29/12/2000'); // Now add a month to this value myDate := IncMonth(myDate); // And let us see what we get DecodeDate(myDate, myYear, myMonth, myDay); ShowMessage('myDate now = '+DateToStr(myDate)); //myDate now = 29/01/2001 ShowMessage('myDay = '+IntToStr(myDay)); //myDay = 29 ShowMessage('myMonth = '+IntToStr(myMonth)); //myMonth = 1 ShowMessage('myYear = '+IntToStr(myYear)); //myYear = 2001 end;} //DecodeTime The DecodeTime procedure extracts hour, minute, second and milli-second values from a given SourceDateTime TDateTime type value. //It stores the values in the output variables : Hour, Min, Sec and MSec. {var myDate : TDateTime; myHour, myMin, mySec, myMilli : Word; begin // Set up the myDate variable to have a December 2000 value myDate := StrToDateTime('29/12/2000 12:45:12.34'); // Now add 5 minutes to this value myDate := IncMinute(myDate, 5); // And let us see what we get DecodeTime(myDate, myHour, myMin, mySec, myMilli); ShowMessage('Time now = '+TimeToStr(myDate)); // Time now = 12:50:12 ShowMessage('Hour = '+IntToStr(myHour)); //Hour = 12 ShowMessage('Minute = '+IntToStr(myMin)); //Minute = 50 ShowMessage('Second = '+IntToStr(mySec)); //Second = 12 ShowMessage('MilliSec = '+IntToStr(myMilli)); //MilliSec = 34 end;} //RecodeDate - The RecodeDate function allows the Year, Month and Day values of a TDateTime variable to be changed without affecting the time. // Set the date to 29/10/2002 at 12:34:56 myDate := EncodeDateTime(2002, 10, 29, 12, 34, 56, 0); ShowMessage('The starting date/time = '+DateTimeToStr(myDate)); // The starting date/time = 29/10/2002 12:34:56 // Now change the date portion without touching the time myDate := RecodeDate(myDate, 1957, 2, 18); ShowMessage('The new date/time = '+DateTimeToStr(myDate)); // The new date/time = 18/02/1957 12:34:56 //RecodeTime The RecodeTime function allows the Hour, Min, Sec and MSec (milli-second) values of a TDateTime variable to be changed without affecting the date. // Set the date to 29/10/2002 at 12:34:56 myDate := EncodeDateTime(2002, 10, 29, 12, 34, 56, 0); ShowMessage('The starting date/time = '+DateTimeToStr(myDate)); //The starting date/time = 29/10/2002 12:34:56 // Now change the time portion without touching the date myDate := RecodeTime(myDate, 7, 35, 22, 0); ShowMessage('The new date/time = '+DateTimeToStr(myDate)); // The new date/time = 29/10/2002 07:35:22 //ReplaceDate - The ReplaceDate function updates the date part of a TDateTime variable DateTimeVar with the date part of another TDateTime value NewDateValue without affecting the time. {var myDateTime, newDate : TDateTime; begin // Set the date to 29/10/2002 at 12:34:56 myDateTime := EncodeDateTime(2002, 10, 29, 12, 34, 56, 0); ShowMessage('The starting date/time = '+DateTimeToStr(myDateTime)); //The starting date/time = 29/10/2002 12:34:56 // Now change the date portion without touching the time newDate := EncodeDate(1957, 02, 18); ReplaceDate(myDateTime, newDate); ShowMessage('The new date/time = '+DateTimeToStr(myDateTime)); //The new date/time = 18/02/1957 12:34:56 end;} //ReplaceTime - The ReplaceTime function updates the time part of a TDateTime variable DateTimeVar with the time part of another TDateTime value NewTimeValue without affecting the date. { // Set the date to 29/10/2002 at 12:34:56 myDateTime := EncodeDateTime(2002, 10, 29, 12, 34, 56, 0); ShowMessage('The starting date/time = '+DateTimeToStr(myDateTime)); //The starting date/time = 29/10/2002 12:34:56 // Now change the time portion without touching the date newTime := EncodeTime(9, 45, 52, 0); ReplaceTime(myDateTime, newTime); ShowMessage('The new date/time = '+DateTimeToStr(myDateTime));} //The new date/time = 29/10/2002 09:45:52 myDate := EncodeDate(2002, 12, 31); //Seta uma data qualquer para exemplo. //DayOfTheMonth. The DayOfTheMonth function returns an index number for the day of the month. Depending on the year and month, the value is in the range 1..31 ShowMessage('The day of the month = '+IntToStr(DayOfTheMonth(myDate))); // retorno: The day of the month = 31 //DayOfTheYear Show the day of the year for a TDateTime variable - return 20/10/2002 day of the year = 302 ShowMessage('20/10/2002 day of year = '+ IntToStr(DayOfTheYear(myDate))); //Show the month of the year for a TDateTime variable - The month of the year = 10 ShowMessage('The month of the year = '+ IntToStr(MonthOfTheYear(myDate))); //DaysInAMonth Gives the number of days in a month, ex: // How many days in February 2000 ? ShowMessage('Days in February 2000 = '+IntToStr(DaysInAMonth(2000, 2))); //retorno: Days in February 2000 = 29 //DaysInAYear Function Gives the number of days in a year - // How many days in the leap year 2000? ShowMessage('Days in 2000 = '+ IntToStr(DaysInAYear(2000))); // return0: Days in 2000 = 366 //MinsPerDay - Constant Gives the number of minutes in a day - returno Number of minutes in a week = 10080 ShowMessage('Number of minutes in a week = '+IntToStr(MinsPerDay*7)); //SecsPerDay - Constant Gives the number of seconds in a day retorno Number of seconds in a week = 604800 ShowMessage('Number of seconds in a week = '+IntToStr(SecsPerDay*7)); // MonthDays - Gives the number of days in a month - Days in February 2000 = 29 ///A função IsLeapYear retorna true se um determinado valor do calendário for um ano bissexto. ///if IsLeapYear(2000) then ShowMessage ('2000 foi um ano bissexto') ShowMessage('Days in February 2000 = '+ IntToStr(MonthDays[IsLeapYear(2000)][2])); //DaySpan - Find the days difference between two date+time values. ///-The DaySpan function subtracts the FromDate from the ToDate, returning the fractional days difference. ///For example, a difference of 2 days and 6 hours would give a value of 2.25 { Example code : Find the days difference between two date+time values. var fromdate, toDate : TDateTime; begin // Set up our date variables fromDate := EncodeDateTime(2000, 01, 01, 0, 0, 0, 0); toDate := EncodeDateTime(2000, 01, 02, 12, 0, 0, 0); // Display these dates and the days between them ShowMessage('From date = '+DateTimeToStr(fromDate)); ShowMessage('To date = '+DateTimeToStr(toDate)); ShowMessage('Fractional days difference = '+ FloatToStr(DaySpan(toDate, fromDate))+' days'); end; RESULT: Show full unit code From date = 01/01/2000 To date = 02/01/2000 12:00:00 Fractional days difference = 1.5 days } //IncDay - The IncDay function returns a TDateTime value that is NumberOfDays greater than the passed StartDateTime value. //There is no DecDay function.Instead, use IncDay with a negative increment. // Set up our date just before the end of the year 2000 myDate := EncodeDate(2000, 12, 30); ShowMessage('myDate = '+DateToStr(myDate)); // myDate = 30/12/2000 // Add 10 days to this date myDate := IncDay(myDate, 10); ShowMessage('myDate + 10 days = '+DateToStr(myDate)); //myDate + 10 days = 09/01/2001 // Subtract 12 days from this date myDate := IncDay(myDate, -12); ShowMessage('myDate - 12 days = '+DateToStr(myDate)); //myDate - 12 days = 29/12/2000 //IncMinute - The IncMinute function returns a TDateTime value that is NumberOfMinutes greater than the passed StartDateTime value. //There is no DecMinute function. Instead, use IncMinute with a negative increment. // Set up our date just before the end of the year 2000 myDate := EncodeDateTime(2000, 12, 31, 23, 0, 0, 0); ShowMessage('myDate = '+DateTimeToStr(myDate)); //myDate = 31/12/2000 23:00:00 // Add 100 minutes to this date myDate := IncMinute(myDate, 100); ShowMessage('myDate + 100 minutes = '+DateTimeToStr(myDate)); //myDate + 100 minutes = 01/01/2001 00:40:00 // Subtract 40 minutes from this date myDate := IncMinute(myDate, -40); ShowMessage('myDate - 40 minutes = '+DateTimeToStr(myDate)); //myDate - 40 minutes = 01/01/2001 //IncMillisecond The IncMillisecond function returns a TDateTime value that is NumberOfMilliSeconds greater than the passed StartDateTime value. //There is no DecMillisecond function. Instead, use IncMillisecond with a negative increment. // Set up our date to the start of 2006 myDate := EncodeDateTime(2006, 1, 1, 0, 0, 0, 0); ShowMessage('myDate = '+DateTimeToStr(myDate)); //myDate = 01/01/2006 // Add 5000 milliseconds to this date myDate := IncMillisecond(myDate, 5000); ShowMessage('myDate + 5000 milliseconds = '+DateTimeToStr(myDate)); //myDate = 01/01/2006 00:00:05 // Subtract 2000 milliseconds from this date myDate := IncMillisecond(myDate, -2000); ShowMessage('myDate - 2000 milliseconds = '+DateTimeToStr(myDate)); //myDate = 01/01/2006 00:00:03 //IncMonth - The IncMonth function returns a TDateTime value that is NumberOfMonths greater than the passed StartDate value. //There is no DecMonth function. Instead, use IncMonth with a negative increment. myDate := StrToDate('31/01/2000'); // End of Jan in a leap year ShowMessage('myDate = '+DateToStr(myDate)); //myDate = 31/01/2000 // Increment by 1 (default) // 31st Jan 2000 ==> 31st Feb 2000 (illegal) ==> 29th Feb 2000 myDate := IncMonth(myDate); ShowMessage('myDate + 1 month = '+DateToStr(myDate)); //myDate + 1 month = 29/02/2000 // Increment by 12 months // 29th Feb 2000 ==> 29th Feb 2000 (illegal) ==> 28th Feb 2001 myDate := IncMonth(myDate, 12); // Increment by 12 months ShowMessage('myDate + 12 months = '+DateToStr(myDate)); //myDate + 12 months = 28/02/2001 //IncYear Increments a TDateTime variable by a number of years. There is no DecYear function. Instead, use IncYear with a negative increment. // Set up our date to a leap year special day myDate := EncodeDate(2000, 02, 29); ShowMessage('myDate = '+DateToStr(myDate)); // myDate = 29/02/2000 // Add 2 years to this date myDate := IncYear(myDate, 2); ShowMessage('myDate + 2 years = '+DateToStr(myDate)); //myDate + 2 years = 28/02/2002 // Subtract 2 years from this date myDate := IncYear(myDate, -2); ShowMessage('myDate - 2 years = '+DateToStr(myDate)); //myDate - 2 years = 28/02/2000 //EndOfAMonth set to the very end of a month myDate := EndOfAMonth(2000, 2); // Ensure that milli-seconds are shown LongTimeFormat := 'hh:mm:ss.zzz'; ShowMessage('End of February 2000 = '+DateTimeToStr(myDate)); //End of February 2000 = 29/02/2000 23:59:59.999 //EndOfADay set to the very end of a day myDate := EndOfADay(1999, 365); //function EndOfADay ( const Year, DayOfYear : Word ) : TDateTime; // Ensure that milli-seconds are shown LongTimeFormat := 'hh:mm:ss.zzz'; ShowMessage('End of 1999 using short syntax = '+DateTimeToStr(myDate)); myDate := EndOfADay(1999, 12, 31);//unction EndOfADay ( const Year, Month, Day : Word ) : TDateTime; // Ensure that milli-seconds are shown LongTimeFormat := 'hh:mm:ss.zzz'; ShowMessage('End of 1999 using long syntax = '+DateTimeToStr(myDate)); end; end.
unit WidgetChats; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CryptChat, MainCrypt, Dialogs, Forms, Unix, ExtCtrls; const // Сообщения всегда имеют эту тему CHAT_MAIN_SUBJECT = '{6D78D26F-347E-4D57-9E9C-03C82139CD38}'; CHAT_MAIN_ADD_CONTACT = '{138C7A7C-8F74-4DAF-838B-21E6842A031D}'; CHAT_INOUT_MESSAGE = '{DDDAAC7D-DF47-4588-B596-FF963B6B0328}'; type { TCryptChat } TCryptChat = class(TCustomCryptChat) private fLastCountMails: Integer; UpdateTimer: TTimer; protected procedure MainNewContact(MailIndex: integer); procedure MainReadMessage(MailIndex: integer); procedure OnTimerUpdate(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure GlobalUpdate; override; procedure Send(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); override; procedure ContactDblClick(Sender: TObject); override; public function GetFriendIndex(AMail: String): Integer; function ExistMessage(FriendIndex: Integer; ADate: TDateTime): Boolean; function GetNickFromMail(AMail: String): String; function LoadOpenKey(FriendIndex, MailIndex: Integer): Boolean; published property HostPop3; property HostSmtp; property Host; end; implementation { TCryptChat } function TCryptChat.GetFriendIndex(AMail: String): Integer; var i: Integer; begin Result:= -1; for i := 0 to GetCountFriend - 1 do if SameText(Friend[i].Email, AMail) then Result:= i; end; function TCryptChat.ExistMessage(FriendIndex: Integer; ADate: TDateTime): Boolean; var i: Integer; begin Result:= false; for i:= 0 to GetCountMessage(FriendIndex)-1 do if GetMessageEntry(i, FriendIndex).Date = ADate then begin Result:= True; break; end; end; function TCryptChat.GetNickFromMail(AMail: String): String; var ch: Char; begin Result:= ''; for ch in AMail do if ch = '@' then break else Result+= ch; end; function TCryptChat.LoadOpenKey(FriendIndex, MailIndex: Integer): Boolean; var Msg: TMessageEntry; begin Msg.ID_FRIEND:= FriendIndex; Msg.ID_USER:= GetUserInfo.ID_USER; msg.Date:= GetMailDate(MailIndex); Msg.IsMyMsg:= false; Msg.XID:= GetMaxXid(FriendIndex-1); SaveAttachToFile(MailIndex, 0, '/tmp/public.key'); Msg.OpenKey:= TextReadFile('/tmp/public.key'); Result:= AddMessage(Msg); end; procedure TCryptChat.MainNewContact(MailIndex: integer); const mrNone = 0; mrYes = mrNone + 6; var FriendIndex: Integer; FriendEntry: TFriendEntry; isLoadMessage: Boolean; begin // Если наше письмо, то выходим if SameText(GetUserInfo.Email, GetMailFrom(MailIndex)) then exit; // Узнаём индекс друга FriendIndex:= GetFriendIndex(GetMailFrom(MailIndex)); if FriendIndex = -1 then begin // Такого друга нет if MessageDlg('Вопрос', 'К Вам хочет добавиться в друзья: '+GetMailFrom(MailIndex)+', добавить?', mtConfirmation, [mbYes, mbNo], 0) = MrYes then begin FriendEntry.ID_USER:= GetUserInfo.ID_USER; FriendEntry.ID_FRIEND:= GetCountFriend + 1; if FriendEntry.ID_FRIEND = 0 then FriendEntry.ID_FRIEND:= 1; FriendEntry.Email:= GetMailFrom(MailIndex); FriendEntry.NickName:= GetNickFromMail(FriendEntry.Email); if AddFriend(FriendEntry) then ShowMessage('Ключ '+BoolToStr(LoadOpenKey(FriendEntry.ID_FRIEND, MailIndex), 'добавлен', 'не добавлен')); end; end else begin // Такой друг есть isLoadMessage:= ExistMessage(FriendIndex, GetMailDate(MailIndex)); if not isLoadMessage then ShowMessage('Ключ '+BoolToStr(LoadOpenKey(FriendIndex+1, MailIndex), 'добавлен', 'не добавлен')); end; end; procedure TCryptChat.GlobalUpdate; var i: integer; CMD_UUID: string; begin inherited GlobalUpdate; host := 'pop.yandex.ru'; if not ConnectMail then ShowMessage('No connect'); for i := 1 to GetMailCount do // Если сообщение наше if SameText(GetMailSubject(i), CHAT_MAIN_SUBJECT) then begin GetMail(i); // то получаем UUID комманды CMD_UUID := trim(GetMailCommand(i)); // выполняем соответствующие действия case CMD_UUID of CHAT_MAIN_ADD_CONTACT: MainNewContact(i); CHAT_INOUT_MESSAGE: MainReadMessage(i); end; end; end; procedure TCryptChat.MainReadMessage(MailIndex: integer); var FriendIndex: integer; AFiles: TFiles; Path: String; i: Integer; FromIndex: Integer; begin // Если наше письмо, то выходим if SameText(GetUserInfo.Email, GetMailFrom(MailIndex)) then exit; // Узнаём индекс друга FriendIndex:= GetFriendIndex(GetMailFrom(MailIndex)); if FriendIndex = -1 then exit; // Если сообщение не загружено, то загружаем if not ExistMessage(FriendIndex, GetMailDate(MailIndex)) then begin fpSystem('rm -fR /tmp/crypt'); MkDir('/tmp/crypt'); SetCurrentDir('/tmp/crypt/'); Path:= '/tmp/crypt/'+GetAttachName(MailIndex, 0); if SaveAttachToFile(MailIndex, 0, path) then begin AddMarkListBox(FriendIndex); ExtractBz2(Path, '/tmp/crypt/'); if ReadMail('/tmp/crypt/', FriendIndex, GetMailDate(MailIndex)) then begin // Открыть вкладку if not IsOpenPage(FriendIndex) then begin // Если вкладка не открыта, то открываем и подгружаем последние 10 ссобщений NewPage(FriendIndex); if GetCountMessage(FriendIndex)-1 < 10 then FromIndex:= 0 else FromIndex:= GetCountMessage(FriendIndex)-10; end else // Вкладка открыта, а это значит грузим лишь не достающие сообщения FromIndex:= GetCountMessage(FriendIndex)-1; // Кол-во загруженных сообщений for i:= FromIndex to GetCountMessage(FriendIndex) - 1 do begin with GetMessageEntry(i, FriendIndex) do if Message <> '' then case IsMyMsg of TRUE: Send(FriendIndex, Message, Date, nil, TRUE); FALSE: Recv(FriendIndex, Message, Date, nil, TRUE); end; end; ScrollDown(FriendIndex); DeleteCryptFiles('/tmp/crypt/'); end; end; SetCurrentDir(ExtractFilePath(ParamStr(0))); end; end; procedure TCryptChat.OnTimerUpdate(Sender: TObject); var ThisCount: Integer; begin if isUserLogin then begin ThisCount:= GetMailCount; if (ConnectMail) and (fLastCountMails <> ThisCount) then begin GlobalUpdate; fLastCountMails:= ThisCount; end; end; end; constructor TCryptChat.Create(AOwner: TComponent); begin inherited Create(AOwner); fLastCountMails:= 0; UpdateTimer:= TTimer.Create(self); UpdateTimer.Interval:= 3000; UpdateTimer.OnTimer:= @OnTimerUpdate; UpdateTimer.Enabled:= True; end; destructor TCryptChat.Destroy; begin UpdateTimer.Enabled:= False; UpdateTimer.Free; inherited Destroy; end; procedure TCryptChat.Send(AFriendID: integer; AText: string; ADate: TDateTime; AFiles: TFiles); var TarFile: TStringList; begin { TODO : Проверить отправку сообщения } fpSystem('rm -fR /tmp/crypt'); MkDir('/tmp/crypt'); SetCurrentDir('/tmp/crypt/'); if MakeMail('/tmp/crypt/', AText, String(AFiles), AFriendID) then begin // Закидываем в архив MakeBz2('BFKEY.enc MSG.enc Pub.enc', 'mail.tar.bz2'); TarFile:= TStringList.Create; TarFile.Add('mail.tar.bz2'); HostSmtp:= 'smtp.yandex.ru'; SendMail(HostSmtp, CHAT_MAIN_SUBJECT, Friend[AFriendID].Email, GetUserInfo.Email, CHAT_INOUT_MESSAGE, '', TarFile); TarFile.Free; //fpSystem('tar vczf mail.tar.gz *'); inherited Send(AFriendID, AText, ADate, AFiles); end; SetCurrentDir(ExtractFilePath(ParamStr(0))); //fpSystem('rm -fR /tmp/crypt'); end; procedure TCryptChat.ContactDblClick(Sender: TObject); var i: integer; Selected: Integer; // Friend FromIndex: Integer; begin if fListBox.ItemIndex = -1 then exit; for i := 0 to GetCountFriend - 1 do with Friend[i] do begin if fListBox.Items[fListBox.ItemIndex] = (NickName + '< ' + Email + ' >') then Selected:= i; end; inherited ContactDblClick(Sender); // Загрузка последних 10 сообщений if GetCountMessage(Selected)-1 < 10 then FromIndex:= 0 else FromIndex:= GetCountMessage(Selected)-10; for i:= FromIndex to GetCountMessage(Selected) - 1 do begin with GetMessageEntry(i, Selected) do if Message <> '' then case IsMyMsg of TRUE: Send(Selected, Message, Date, nil, TRUE); FALSE: Recv(Selected, Message, Date, nil, TRUE); end; end; end; end.
program CoolingDeviceInfo; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uSMBIOS { you can add units after this }; function ByteToBinStr(AValue:Byte):string; const Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1); var i: integer; begin Result:='00000000'; if (AValue<>0) then for i:=1 to 8 do if (AValue and Bits[i])<>0 then Result[i]:='1'; end; procedure GetCoolingDeviceInfo; Var SMBios: TSMBios; LCoolingDevice: TCoolingDeviceInformation; begin SMBios:=TSMBios.Create; try WriteLn('Cooling Device Information'); WriteLn('--------------------------'); if SMBios.HasCoolingDeviceInfo then for LCoolingDevice in SMBios.CoolingDeviceInformation do begin if LCoolingDevice.RAWCoolingDeviceInfo^.TemperatureProbeHandle<>$FFFF then WriteLn(Format('Temperature Probe Handle %.4x',[LCoolingDevice.RAWCoolingDeviceInfo^.TemperatureProbeHandle])); WriteLn(Format('Device Type and Status %s',[ByteToBinStr(LCoolingDevice.RAWCoolingDeviceInfo^.DeviceTypeandStatus)])); WriteLn(Format('Type %s',[LCoolingDevice.GetDeviceType])); WriteLn(Format('Status %s',[LCoolingDevice.GetStatus])); WriteLn(Format('Cooling Unit Group %d',[LCoolingDevice.RAWCoolingDeviceInfo^.CoolingUnitGroup])); WriteLn(Format('OEM Specific %.8x',[LCoolingDevice.RAWCoolingDeviceInfo^.OEMdefined])); if LCoolingDevice.RAWCoolingDeviceInfo^.NominalSpeed=$8000 then WriteLn(Format('Nominal Speed %s',['Unknown'])) else WriteLn(Format('Nominal Speed %d rpm',[LCoolingDevice.RAWCoolingDeviceInfo^.NominalSpeed])); if SMBios.SmbiosVersion>='2.7' then WriteLn(Format('Description %s',[LCoolingDevice.GetDescriptionStr])); WriteLn; end else Writeln('No Cooling Device Info was found'); finally SMBios.Free; end; end; begin try GetCoolingDeviceInfo; except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLAtmosphere <p> This unit contains classes that imitate an atmosphere around a planet.<p> <b>History : </b><font size=-1><ul> <li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records <li>19/03/11 - Yar - Added setters for Low and High atmosphere colors <li>04/11/10 - DaStr - Restored Delphi5 and Delphi6 compatibility <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) <li>03/04/07 - DaStr - Optimized TGLCustomAtmosphere.DoRender Fixed SetPlanetRadius and SetAtmosphereRadius <li>21/03/07 - DaStr - Cleaned up "uses" section (thanks Burkhard Carstens) (Bugtracker ID = 1684432) <li>01/03/07 - DaStr - Fixed TGLAtmosphereBlendingMode (old version did not generate RTTI) Added default values to all properties <li>15/02/07 - DaStr - Added TGLCustomAtmosphere.AxisAlignedDimensionsUnscaled <li>07/02/07 - DaStr - Initial version (donated to GLScene) Comments: 1) Eats a lot of CPU (reduces FPS from 1240 to 520 on my PC with cSlices=100) 2) Alpha in LowAtmColor, HighAtmColor is ignored. Previous version history: v1.0 06 February '2005 Creation (based on demo "Earth" by Eric Grange) v1.1 28 February '2005 Don't remmember what... v1.2 16 March '2005 Small improvements, including ability to load files using short (not full) paths v1.3 21 March '2005 Positioning bugfix!!! v1.4 3 October '2005 Camera parameter no longer needed "Enabled" is now a property LoadFromMemory added SaveToFile, SaveToMemory added Normal error message v1.5 4 November '2005 BlendingMode1,2 added TogleBlengindMode added LoadFromMemory bugfix v1.6 28 February '2006 Became a standard GLScene object, child of TglBaseSceneObject Range bug fixed, along with a bug, the caused Atmosphere to draw itseft incorrectly on some occasions Demo inhanced New Load/Save code v1.6.2 05 June '2006 Assign() added Alpha in LowAtmColor, HighAtmColor was removed from Loading/saving code v1.6.4 07 July '2006 All variables in the class converted into properties TStrangeCustomAtmosphere added v1.6.6 08 October '2006 Made compatible with the new persistance mechanism v1.7 22 October '2006 Notification() and SetSun() added v1.8 08 February '2007 TStrangeCustomAtmosphere.Assign fixed Blending mode Integer ---> Enumeration Donated to GLScene } unit GLAtmosphere; interface {$I GLScene.inc} uses // VCL SysUtils, Classes, // GLScene GLScene, GLObjects, GLCadencer, OpenGLTokens, GLVectorGeometry, GLContext, GLStrings, GLColor, GLRenderContextInfo, GLState, GLCrossPlatform, GLVectorTypes; type EGLAtmosphereException = class(Exception); {: With aabmOneMinusSrcAlpha atmosphere is transparent to other objects, but has problems, which are best seen when the Atmosphere radius is big. With bmOneMinusDstColor atmosphere doesn't have these problems, but offers limited transparency (when you look closely on the side). } TGLAtmosphereBlendingMode = (abmOneMinusDstColor, abmOneMinusSrcAlpha); {: This class imitates an atmosphere around a planet. } TGLCustomAtmosphere = class(TGLBaseSceneObject) private // Used in DoRenderl cosCache, sinCache: array of Single; pVertex, pColor: PVectorArray; FSlices: Integer; FBlendingMode: TGLAtmosphereBlendingMode; FPlanetRadius: Single; FAtmosphereRadius: Single; FOpacity: Single; FLowAtmColor: TGLColor; FHighAtmColor: TGLColor; FSun: TglBaseSceneObject; procedure SetSun(const Value: TglBaseSceneObject); procedure SetAtmosphereRadius(const Value: Single); procedure SetPlanetRadius(const Value: Single); procedure EnableGLBlendingMode(StateCache: TGLStateCache); function StoreAtmosphereRadius: Boolean; function StoreOpacity: Boolean; function StorePlanetRadius: Boolean; procedure SetSlices(const Value: Integer); procedure SetLowAtmColor(const AValue: TGLColor); procedure SetHighAtmColor(const AValue: TGLColor); function StoreLowAtmColor: Boolean; function StoreHighAtmColor: Boolean; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property Sun: TglBaseSceneObject read FSun write SetSun; property Slices: Integer read FSlices write SetSlices default 60; property Opacity: Single read FOpacity write FOpacity stored StoreOpacity; //: AtmosphereRadius > PlanetRadius!!! property AtmosphereRadius: Single read FAtmosphereRadius write SetAtmosphereRadius stored StoreAtmosphereRadius; property PlanetRadius: Single read FPlanetRadius write SetPlanetRadius stored StorePlanetRadius; //: Use value slightly lower than actual radius, for antialiasing effect. property LowAtmColor: TGLColor read FLowAtmColor write SetLowAtmColor stored StoreLowAtmColor; property HighAtmColor: TGLColor read FHighAtmColor write SetHighAtmColor stored StoreHighAtmColor; property BlendingMode: TGLAtmosphereBlendingMode read FBlendingMode write FBlendingMode default abmOneMinusSrcAlpha; procedure SetOptimalAtmosphere(const ARadius: Single); //absolute procedure SetOptimalAtmosphere2(const ARadius: Single); //relative procedure TogleBlendingMode; //changes between 2 blending modes //: Standard component stuff. procedure Assign(Source: TPersistent); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; //: Main rendering procedure. procedure DoRender(var rci: TRenderContextInfo; renderSelf, renderChildren: Boolean); override; //: Used to determine extents. function AxisAlignedDimensionsUnscaled : TVector; override; end; TGLAtmosphere = class(TGLCustomAtmosphere) published property Sun; property Slices; property Opacity; property AtmosphereRadius; property PlanetRadius; property LowAtmColor; property HighAtmColor; property BlendingMode; property Position; property ObjectsSorting; property ShowAxes; property Visible; property OnProgress; property Behaviours; property Effects; end; implementation const EPS = 0.0001; cIntDivTable: array [2..20] of Single = (1 / 2, 1 / 3, 1 / 4, 1 / 5, 1 / 6, 1 / 7, 1 / 8, 1 / 9, 1 / 10, 1 / 11, 1 / 12, 1 / 13, 1 / 14, 1 / 15, 1 / 16, 1 / 17, 1 / 18, 1 / 19, 1 / 20); procedure TGLCustomAtmosphere.SetOptimalAtmosphere(const ARadius: Single); begin FAtmosphereRadius := ARadius + 0.25; FPlanetRadius := ARadius - 0.07; end; procedure TGLCustomAtmosphere.SetOptimalAtmosphere2(const ARadius: Single); begin FAtmosphereRadius := ARadius + ARadius / 15; FPlanetRadius := ARadius - ARadius / 50; end; constructor TGLCustomAtmosphere.Create(AOwner: TComponent); begin inherited; FLowAtmColor := TGLColor.Create(Self); FHighAtmColor := TGLColor.Create(Self); FOpacity := 2.1; SetSlices(60); FAtmosphereRadius := 3.55; FPlanetRadius := 3.395; FLowAtmColor.Color := VectorMake(1, 1, 1, 1); FHighAtmColor.Color := VectorMake(0, 0, 1, 1); FBlendingMode := abmOneMinusSrcAlpha; end; destructor TGLCustomAtmosphere.Destroy; begin FLowAtmColor.Free; FHighAtmColor.Free; FreeMem(pVertex); FreeMem(pColor); inherited; end; procedure TGLCustomAtmosphere.DoRender(var rci: TRenderContextInfo; renderSelf, renderChildren: Boolean); var radius, invAtmosphereHeight: Single; sunPos, eyePos, lightingVector: TVector; diskNormal, diskRight, diskUp: TVector; function AtmosphereColor(const rayStart, rayEnd: TVector): TColorVector; var I, n: Integer; atmPoint, normal: TVector; altColor: TColorVector; alt, rayLength, contrib, decay, intensity, invN: Single; begin Result := clrTransparent; rayLength := VectorDistance(rayStart, rayEnd); n := Round(3 * rayLength * invAtmosphereHeight) + 2; if n > 10 then n := 10; invN := cIntDivTable[n];//1/n; contrib := rayLength * invN * Opacity; decay := 1 - contrib * 0.5; contrib := contrib * (1 / 1.1); for I := n - 1 downto 0 do begin VectorLerp(rayStart, rayEnd, I * invN, atmPoint); // diffuse lighting normal normal := VectorNormalize(atmPoint); // diffuse lighting intensity intensity := VectorDotProduct(normal, lightingVector) + 0.1; if PInteger(@intensity)^ > 0 then begin // sample on the lit side intensity := intensity * contrib; alt := (VectorLength(atmPoint) - FPlanetRadius) * invAtmosphereHeight; VectorLerp(LowAtmColor.Color, HighAtmColor.Color, alt, altColor); Result.V[0] := Result.V[0] * decay + altColor.V[0] * intensity; Result.V[1] := Result.V[1] * decay + altColor.V[1] * intensity; Result.V[2] := Result.V[2] * decay + altColor.V[2] * intensity; end else begin // sample on the dark sid Result.V[0] := Result.V[0] * decay; Result.V[1] := Result.V[1] * decay; Result.V[2] := Result.V[2] * decay; end; end; Result.V[3] := n * contrib * Opacity * 0.1; end; function ComputeColor(var rayDest: TVector; mayHitGround: Boolean): TColorVector; var ai1, ai2, pi1, pi2: TVector; rayVector: TVector; begin rayVector := VectorNormalize(VectorSubtract(rayDest, eyePos)); if RayCastSphereIntersect(eyePos, rayVector, NullHmgPoint, FAtmosphereRadius, ai1, ai2) > 1 then begin // atmosphere hit if mayHitGround and (RayCastSphereIntersect(eyePos, rayVector, NullHmgPoint, FPlanetRadius, pi1, pi2) > 0) then begin // hit ground Result := AtmosphereColor(ai1, pi1); end else begin // through atmosphere only Result := AtmosphereColor(ai1, ai2); end; rayDest := ai1; end else Result := clrTransparent; end; var I, J, k0, k1: Integer; begin if FSun <> nil then begin Assert(FAtmosphereRadius > FPlanetRadius); sunPos := VectorSubtract(FSun.AbsolutePosition, AbsolutePosition); eyepos := VectorSubtract(rci.CameraPosition, AbsolutePosition); diskNormal := VectorNegate(eyePos); NormalizeVector(diskNormal); diskRight := VectorCrossProduct(rci.CameraUp, diskNormal); NormalizeVector(diskRight); diskUp := VectorCrossProduct(diskNormal, diskRight); NormalizeVector(diskUp); invAtmosphereHeight := 1 / (FAtmosphereRadius - FPlanetRadius); lightingVector := VectorNormalize(sunPos); // sun at infinity rci.GLStates.DepthWriteMask := False; rci.GLStates.Disable(stLighting); rci.GLStates.Enable(stBlend); EnableGLBlendingMode(rci.GLStates); for I := 0 to 13 do begin if I < 5 then radius := FPlanetRadius * Sqrt(I * (1 / 5)) else radius := FPlanetRadius + (I - 5.1) * (FAtmosphereRadius - FPlanetRadius) * (1 / 6.9); radius := SphereVisibleRadius(VectorLength(eyePos), radius); k0 := (I and 1) * (FSlices + 1); k1 := (FSlices + 1) - k0; for J := 0 to FSlices do begin VectorCombine(diskRight, diskUp, cosCache[J] * radius, sinCache[J] * radius, pVertex[k0 + J]); if I < 13 then pColor[k0 + J] := ComputeColor(pVertex[k0 + J], I <= 7); if I = 0 then Break; end; if I > 1 then begin if I = 13 then begin // GL.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL.Begin_(GL_QUAD_STRIP); for J := FSlices downto 0 do begin GL.Color4fv(@pColor[k1 + J]); GL.Vertex3fv(@pVertex[k1 + J]); GL.Color4fv(@clrTransparent); GL.Vertex3fv(@pVertex[k0 + J]); end; GL.End_; end else begin // GL.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_COLOR); GL.Begin_(GL_QUAD_STRIP); for J := FSlices downto 0 do begin GL.Color4fv(@pColor[k1 + J]); GL.Vertex3fv(@pVertex[k1 + J]); GL.Color4fv(@pColor[k0 + J]); GL.Vertex3fv(@pVertex[k0 + J]); end; GL.End_; end; end else if I = 1 then begin //GL.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL.Begin_(GL_TRIANGLE_FAN); GL.Color4fv(@pColor[k1]); GL.Vertex3fv(@pVertex[k1]); for J := k0 + FSlices downto k0 do begin GL.Color4fv(@pColor[J]); GL.Vertex3fv(@pVertex[J]); end; GL.End_; end; end; end; inherited; end; procedure TGLCustomAtmosphere.TogleBlendingMode; begin if FBlendingMode = abmOneMinusSrcAlpha then FBlendingMode := abmOneMinusDstColor else FBlendingMode := abmOneMinusSrcAlpha; end; procedure TGLCustomAtmosphere.Assign(Source: TPersistent); begin inherited; if Source is TGLCustomAtmosphere then begin SetSlices(TGLCustomAtmosphere(Source).FSlices); FOpacity := TGLCustomAtmosphere(Source).FOpacity; FAtmosphereRadius := TGLCustomAtmosphere(Source).FAtmosphereRadius; FPlanetRadius := TGLCustomAtmosphere(Source).FPlanetRadius; FLowAtmColor.Color := TGLCustomAtmosphere(Source).FLowAtmColor.Color; FHighAtmColor.Color := TGLCustomAtmosphere(Source).FHighAtmColor.Color; FBlendingMode := TGLCustomAtmosphere(Source).FBlendingMode; SetSun(TGLCustomAtmosphere(Source).FSun); end; end; procedure TGLCustomAtmosphere.SetSun(const Value: TglBaseSceneObject); begin if FSun <> nil then FSun.RemoveFreeNotification(Self); FSun := Value; if FSun <> nil then FSun.FreeNotification(Self); end; function TGLCustomAtmosphere.AxisAlignedDimensionsUnscaled : TVector; begin Result.V[0] := FAtmosphereRadius; Result.V[1] := Result.V[0]; Result.V[2] := Result.V[0]; Result.V[3] := 0; end; procedure TGLCustomAtmosphere.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FSun) then FSun := nil; end; procedure TGLCustomAtmosphere.SetAtmosphereRadius( const Value: Single); begin FAtmosphereRadius := Value; if Value <= FPlanetRadius then FPlanetRadius := FAtmosphereRadius / 1.01; end; procedure TGLCustomAtmosphere.SetPlanetRadius(const Value: Single); begin FPlanetRadius := Value; if Value >= FAtmosphereRadius then FAtmosphereRadius := FPlanetRadius * 1.01; end; procedure TGLCustomAtmosphere.EnableGLBlendingMode(StateCache: TGLStateCache); begin case FBlendingMode of abmOneMinusDstColor: StateCache.SetBlendFunc(bfDstAlpha, bfOneMinusDstColor); abmOneMinusSrcAlpha: StateCache.SetBlendFunc(bfDstAlpha, bfOneMinusSrcAlpha); else Assert(False, glsErrorEx + glsUnknownType); end; StateCache.Enable(stAlphaTest); end; function TGLCustomAtmosphere.StoreAtmosphereRadius: Boolean; begin Result := Abs(FAtmosphereRadius - 3.55) > EPS; end; function TGLCustomAtmosphere.StoreOpacity: Boolean; begin Result := Abs(FOpacity - 2.1) > EPS; end; function TGLCustomAtmosphere.StorePlanetRadius: Boolean; begin Result := Abs(FPlanetRadius - 3.395) > EPS; end; procedure TGLCustomAtmosphere.SetSlices(const Value: Integer); begin if Value > 0 then begin FSlices := Value; SetLength(cosCache, FSlices + 1); SetLength(sinCache, FSlices + 1); PrepareSinCosCache(sinCache, cosCache, 0, 360); GetMem(pVertex, 2 * (FSlices + 1) * SizeOf(TVector)); GetMem(pColor, 2 * (FSlices + 1) * SizeOf(TVector)); end else raise EGLAtmosphereException.Create('Slices must be more than0!'); end; procedure TGLCustomAtmosphere.SetHighAtmColor(const AValue: TGLColor); begin FHighAtmColor.Assign(AValue); end; procedure TGLCustomAtmosphere.SetLowAtmColor(const AValue: TGLColor); begin FLowAtmColor.Assign(AValue); end; function TGLCustomAtmosphere.StoreHighAtmColor: Boolean; begin Result := not VectorEquals(FHighAtmColor.Color, VectorMake(0, 0, 1, 1)); end; function TGLCustomAtmosphere.StoreLowAtmColor: Boolean; begin Result := not VectorEquals(FLowAtmColor.Color, VectorMake(1, 1, 1, 1)); end; initialization RegisterClasses([TGLCustomAtmosphere, TGLAtmosphere]); end.
{ ID: a2peter1 PROG: transform LANG: PASCAL } {$B-,I-,Q-,R-,S-} const problem = 'transform'; MaxN = 10; var N,i,j : longint; start,target, t1,t2 : array[1..MaxN,1..MaxN] of char; procedure rotate; begin for i := 1 to N do for j := 1 to N do t2[i,j] := t1[N - j + 1,i]; t1 := t2; end;{rotate} procedure reflect; var i,j : longint; begin for i := 1 to N do for j := 1 to N do t2[i,j] := t1[i,N - j + 1]; t1 := t2; end;{reflect} function equal: boolean; begin equal := true; for i := 1 to N do for j := 1 to N do if t1[i,j] <> target[i,j] then exit(false); end;{equal} procedure sol(op: longint); begin writeln(op); close(output); end;{sol} begin assign(input,problem + '.in'); reset(input); assign(output,problem + '.out'); rewrite(output); readln(N); for i := 1 to N do readln(start[i]); for i := 1 to N do readln(target[i]); t1 := start; rotate; if equal then sol(1); rotate; if equal then sol(2); rotate; if equal then sol(3); t1 := start; reflect; if equal then sol(4); rotate; if equal then sol(5); rotate; if equal then sol(5); rotate; if equal then sol(5); t1 := start; if equal then sol(6); sol(7); end.{main}
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.ExtCtrls, Vcl.Menus, Vcl.Samples.Spin, sfLog, org.utilities, org.tcpip.tcp, org.tcpip.tcp.proxy, dm.tcpip.tcp.proxy; type TForm3 = class(TForm) Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Memo1: TMemo; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Edit2: TEdit; Label3: TLabel; Edit3: TEdit; btnStart: TButton; btnStop: TButton; MainMenu1: TMainMenu; N1: TMenuItem; Fatal1: TMenuItem; Error1: TMenuItem; Warning1: TMenuItem; Normal1: TMenuItem; Debug1: TMenuItem; GroupBox1: TGroupBox; Label4: TLabel; SpinEdit1: TSpinEdit; Label5: TLabel; SpinEdit2: TSpinEdit; procedure FormCreate(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure Normal1Click(Sender: TObject); procedure Debug1Click(Sender: TObject); procedure Warning1Click(Sender: TObject); procedure Error1Click(Sender: TObject); procedure Fatal1Click(Sender: TObject); procedure SpinEdit1Change(Sender: TObject); procedure SpinEdit2Change(Sender: TObject); private FLog: TsfLog; FLogLevel: TLogLevel; FMaxPreAcceptCount: Integer; FMultiIOBufferCount: Integer; FTCPProxy: TDMTCPProxy; procedure OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); procedure OnConnected(Sender: TObject; Context: TTCPIOContext); procedure WriteToScreen(const Value: string); protected procedure WndProc(var MsgRec: TMessage); override; public { Public declarations } procedure StartService; procedure StopService; end; var Form3: TForm3; const WM_WRITE_LOG_TO_SCREEN = WM_USER + 1; implementation {$R *.dfm} procedure TForm3.btnStartClick(Sender: TObject); begin StartService(); end; procedure TForm3.Debug1Click(Sender: TObject); begin FLogLevel := llDebug; FTCPProxy.LogLevel := llDebug; end; procedure TForm3.Error1Click(Sender: TObject); begin FLogLevel := llError; FTCPProxy.LogLevel := llError; end; procedure TForm3.Fatal1Click(Sender: TObject); begin FLogLevel := llFatal; FTCPProxy.LogLevel := llFatal; end; procedure TForm3.FormCreate(Sender: TObject); var CurDir: string; LogFile: string; begin CurDir := ExtractFilePath(ParamStr(0)); ForceDirectories(CurDir + 'Log\'); LogFile := CurDir + 'Log\Log_' + FormatDateTime('YYYYMMDD', Now()) + '.txt'; FLog := TsfLog.Create(LogFile); FLog.AutoLogFileName := True; FLog.LogFilePrefix := 'Log_'; FLogLevel := llNormal; FTCPProxy := TDMTCPProxy.Create(); FTCPProxy.HeadSize := Sizeof(TTCPSocketProtocolHead); end; procedure TForm3.Normal1Click(Sender: TObject); begin FLogLevel := llNormal; FTCPProxy.LogLevel := llNormal; end; procedure TForm3.OnConnected(Sender: TObject; Context: TTCPIOContext); var Msg: string; begin {$IfDef DEBUG} Msg := Format('[µ÷ÊÔ][%d][%d]<OnConnected> [%s:%d]', [ Context.Socket, GetCurrentThreadId(), Context.RemoteIP, Context.RemotePort]); OnLog(nil, llDebug, Msg); {$Endif} end; procedure TForm3.OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); begin if LogLevel <= FLogLevel then WriteToScreen(LogContent); FLog.WriteLog(LogContent); end; procedure TForm3.SpinEdit1Change(Sender: TObject); begin FMaxPreAcceptCount := SpinEdit1.Value; end; procedure TForm3.SpinEdit2Change(Sender: TObject); begin FMultiIOBufferCount := SpinEdit2.Value; end; procedure TForm3.StartService; var Msg: string; CurDir: string; begin CurDir := ExtractFilePath(ParamStr(0)); FMaxPreAcceptCount := SpinEdit1.Value; FMultiIOBufferCount := SpinEdit2.Value; // FTCPProxy.LocalIP := '0.0.0.0'; FTCPProxy.LocalPort := StrToInt(Edit3.Text); FTCPProxy.LogLevel := FLogLevel; FTCPProxy.MaxPreAcceptCount := FMaxPreAcceptCount; FTCPProxy.MultiIOBufferCount := FMultiIOBufferCount; FTCPProxy.TempDirectory := CurDir + 'Temp\'; ForceDirectories(FTCPProxy.TempDirectory); FTCPProxy.OnLog := OnLog; FTCPProxy.OnConnected := OnConnected; FTCPProxy.RegisterIOContextClass($00000000, TDMTCPProxyServerClientSocket); FTCPProxy.RegisterIOContextClass($20000000, TDMTCPProxyClientSocket); FTCPProxy.Start(); SpinEdit1.Enabled := False; SpinEdit2.Enabled := False; Edit3.Enabled := False; Msg := Format('»ù±¾ÅäÖÃ:'#13#10'MaxPreAcceptCount: %d'#13#10'MultiIOBufferCount: %d'#13#10'BufferSize: %d', [ FMaxPreAcceptCount, FMultiIOBufferCount, FTCPProxy.BufferSize]); Memo1.Lines.Add(Msg); end; procedure TForm3.StopService; begin end; procedure TForm3.Warning1Click(Sender: TObject); begin FLogLevel := llWarning; FTCPProxy.LogLevel := llWarning; end; procedure TForm3.WndProc(var MsgRec: TMessage); var Msg: string; begin if MsgRec.Msg = WM_WRITE_LOG_TO_SCREEN then begin Msg := FormatDateTime('YYYY-MM-DD hh:mm:ss.zzz',Now) + ':' + string(MsgRec.WParam); Memo1.Lines.Add(Msg); end else inherited; end; procedure TForm3.WriteToScreen(const Value: string); begin SendMessage(Application.MainForm.Handle, WM_WRITE_LOG_TO_SCREEN, WPARAM(Value), 0); end; end.
{******************************************} { TeeChart Pro - URL files retrieval } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeURL; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, {$ENDIF} Classes, Chart, TeEngine; type TChartWebSource = class(TComponent) private { Private declarations } FChart : TCustomChart; FURL : String; procedure SetChart(const Value: TCustomChart); protected { Protected declarations } procedure Notification( AComponent: TComponent; Operation: TOperation); override; public { Public declarations } Constructor Create(AOwner:TComponent); override; Procedure Execute; published { Published declarations } property Chart:TCustomChart read FChart write SetChart; property URL:String read FURL write FURL; end; { Series Source with FileName property } TTeeSeriesSourceFile=class(TTeeSeriesSource) private FFileName : String; procedure SetFileName(const Value: String); public Procedure Load; override; Procedure LoadFromFile(Const AFileName:String); Procedure LoadFromStream(AStream:TStream); virtual; Procedure LoadFromURL(Const AURL:String); property FileName:String read FFileName write SetFileName; end; { Read a Chart from a file (ie: Chart1,'http://www.steema.com/demo.tee' ) } Procedure LoadChartFromURL(Var AChart:TCustomChart; Const URL:String); Function DownloadURL(AURL:{$IFDEF CLR}string{$ELSE}PChar{$ENDIF}; ToStream:TStream): HResult; // Returns True when St parameter contains a web address (http or ftp) Function TeeIsURL(St:String):Boolean; { Returns a string with the error message from WinInet.dll. The Parameter ErrorCode is the result of the DownloadURL function. } function TeeURLErrorMessage(ErrorCode: Integer): string; { 5.01 } {$IFNDEF CLR} {$IFNDEF CLX} { The Windows Handle to WinInet.dll. 0=not opened yet. } var TeeWinInetDLL:THandle=0; // 5.01 {$ENDIF} {$ENDIF} implementation Uses {$IFDEF CLX} Types, {$IFNDEF LINUX} IdHTTP, {$ENDIF} {$ENDIF} {$IFDEF CLR} System.Text, System.Net, System.IO, {$ENDIF} TeCanvas, TeeProcs, SysUtils, TeeConst, TeeStore; Procedure LoadChartFromURL(Var AChart:TCustomChart; Const URL:String); var tmp : Integer; R : TRect; Stream : TMemoryStream; tmpURL : String; begin Stream:=TMemoryStream.Create; try tmpURL:=URL; tmp:=DownloadURL({$IFNDEF CLR}PChar{$ENDIF}(tmpURL),Stream); if tmp=0 then begin R:=AChart.BoundsRect; Stream.Position:=0; { 5.01 } LoadChartFromStream(TCustomChart(AChart),Stream); if csDesigning in AChart.ComponentState then AChart.BoundsRect:=R; end else Raise ChartException.CreateFmt(TeeMsg_CannotLoadChartFromURL, [tmp,#13+URL+#13+TeeURLErrorMessage(tmp)]); finally Stream.Free; end; end; {$IFNDEF CLX} Const INTERNET_OPEN_TYPE_PRECONFIG = 0; INTERNET_FLAG_RAW_DATA = $40000000; { receive the item as raw data } INTERNET_FLAG_NO_CACHE_WRITE = $04000000; { do not write this item to the cache } INTERNET_FLAG_DONT_CACHE = INTERNET_FLAG_NO_CACHE_WRITE; WININET_API_FLAG_SYNC = $00000004; { force sync operation } INTERNET_FLAG_RELOAD = $80000000; { retrieve the original item } INTERNET_FLAG_HYPERLINK = $00000400; { asking wininet to do hyperlinking semantic which works right for scripts } INTERNET_FLAG_PRAGMA_NOCACHE = $00000100; { asking wininet to add "pragma: no-cache" } type HINTERNET = Pointer; {$IFNDEF CLR} var _InternetOpenA:function(lpszAgent: PAnsiChar; dwAccessType: DWORD; lpszProxy, lpszProxyBypass: PAnsiChar; dwFlags: DWORD): HINTERNET; stdcall; _InternetOpenURLA:function(hInet: HINTERNET; lpszUrl: PAnsiChar; lpszHeaders: PAnsiChar; dwHeadersLength: DWORD; dwFlags: DWORD; dwContext: DWORD): HINTERNET; stdcall; _InternetReadFile:function(hFile: HINTERNET; lpBuffer: Pointer; dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall; _InternetCloseHandle:function(hInet: HINTERNET): BOOL; stdcall; {$ENDIF} {$IFNDEF CLR} procedure InitWinInet; begin if TeeWinInetDLL=0 then begin TeeWinInetDLL:=TeeLoadLibrary('wininet.dll'); if TeeWinInetDLL<>0 then begin @_InternetOpenA :=GetProcAddress(TeeWinInetDLL,'InternetOpenA'); @_InternetOpenURLA :=GetProcAddress(TeeWinInetDLL,'InternetOpenUrlA'); @_InternetReadFile :=GetProcAddress(TeeWinInetDLL,'InternetReadFile'); @_InternetCloseHandle:=GetProcAddress(TeeWinInetDLL,'InternetCloseHandle'); end; end; end; {$ENDIF} (* function InternetSetStatusCallback(hInet: HINTERNET; lpfnInternetCallback: PFNInternetStatusCallback): PFNInternetStatusCallback; stdcall; *) Function DownloadURL(AURL:{$IFDEF CLR}string{$ELSE}PChar{$ENDIF}; ToStream:TStream): HResult; Const MaxSize= 128*1024; var {$IFNDEF CLR} H1 : HINTERNET; H2 : HINTERNET; Buf : Pointer; tmp : Boolean; r : DWord; {$ELSE} tmpClient : WebClient; Buf : Array of Byte; {$ENDIF} begin {$IFDEF CLR} tmpClient:=WebClient.Create; Buf:=tmpClient.DownloadData(AURL); if Length(Buf)>0 then begin ToStream.Write(Buf,Length(Buf)); ToStream.Position:=0; result:=0; end else result:=-1; {$ELSE} {$IFDEF D5} result:=-1; {$ELSE} result:=$80000000; {$ENDIF} if TeeWinInetDLL=0 then InitWinInet; if TeeWinInetDLL<>0 then begin h1:=_InternetOpenA('Tee', INTERNET_OPEN_TYPE_PRECONFIG, nil,nil, WININET_API_FLAG_SYNC{ INTERNET_FLAG_DONT_CACHE 5.02 }); if h1<>nil then try h2:=_InternetOpenUrlA(h1, AURL, nil,$80000000, { INTERNET_FLAG_DONT_CACHE or 5.02 } INTERNET_FLAG_RELOAD or INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_HYPERLINK or INTERNET_FLAG_PRAGMA_NOCACHE , {INTERNET_FLAG_EXISTING_CONNECT} 0); if h2<>nil then try ToStream.Position:=0; Buf:=AllocMem(MaxSize); try Repeat r:=0; tmp:=_InternetReadFile(h2,Buf,MaxSize,r); if tmp then begin if r>0 then ToStream.WriteBuffer(Buf^,r) else begin ToStream.Position:=0; result:=0; break; end; end else result:=GetLastError; Until r=0; finally FreeMem(Buf,MaxSize); end; finally if not _InternetCloseHandle(h2) then result:=GetLastError; end else result:=GetLastError; finally if not _InternetCloseHandle(h1) then result:=GetLastError; end else result:=GetLastError; end else ShowMessageUser('Cannot load WinInet.dll to access TeeChart file: '+AURL); {$ENDIF} end; {$ELSE} Function DownloadURL(AURL:PChar; ToStream:TStream): HResult; begin {$IFDEF LINUX} result:=-1; {$ELSE} With TIdHttp.Create(nil) do try Get(string(AURL),ToStream); ToStream.Position:=0; result:=0; finally Free; end; {$ENDIF} end; {$ENDIF} function TeeURLErrorMessage(ErrorCode: Integer): string; {$IFNDEF CLX} var Len : Integer; Buffer : {$IFDEF CLR}StringBuilder{$ELSE}TeeString256{$ENDIF}; {$ENDIF} begin {$IFDEF CLX} result:=IntToStr(ErrorCode); {$ELSE} {$IFDEF CLR} Buffer:=StringBuilder.Create(256); Len:=0; {$ENDIF} {$IFNDEF CLR} Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_ARGUMENT_ARRAY, {$IFDEF CLR}IntPtr{$ELSE}Pointer{$ENDIF}(TeeWinInetDLL), ErrorCode, 0, Buffer, SizeOf(Buffer), nil); while (Len > 0) and ({$IFDEF CLR}AnsiChar{$ENDIF}(Buffer[Len - 1]) in [#0..#32, '.']) do Dec(Len); {$ENDIF} {$IFDEF CLR} result:=Buffer.ToString(0,Len); {$ELSE} SetString(result, Buffer, Len); {$ENDIF} {$ENDIF} end; // Returns True when "St" is suspicious to contain a web address... Function TeeIsURL(St:String):Boolean; begin St:=UpperCase(Trim(St)); result:=(Pos('HTTP://',St)>0) or (Pos('FTP://',St)>0); end; { TTeeSeriesSourceFile } Procedure TTeeSeriesSourceFile.Load; begin if Assigned(Series) and (FileName<>'') then if TeeIsURL(FileName) then LoadFromURL(FileName) else LoadFromFile(FileName); end; procedure TTeeSeriesSourceFile.SetFileName(const Value: String); begin if FFileName<>Value then begin Close; FFileName:=Value; end; end; procedure TTeeSeriesSourceFile.LoadFromFile(const AFileName: String); var tmp : TFileStream; begin tmp:=TFileStream.Create(AFileName,fmOpenRead); try LoadFromStream(tmp); finally tmp.Free; end; end; procedure TTeeSeriesSourceFile.LoadFromURL(const AURL: String); var Stream : TMemoryStream; tmpURL : String; tmp : Integer; begin Stream:=TMemoryStream.Create; try tmpURL:=AURL; tmp:=DownloadURL({$IFNDEF CLR}PChar{$ENDIF}(tmpURL),Stream); if tmp=0 then LoadFromStream(Stream) else Raise ChartException.CreateFmt(TeeMsg_CannotLoadSeriesDataFromURL, [tmp,AURL+' '+TeeURLErrorMessage(tmp)]); finally Stream.Free; end; end; procedure TTeeSeriesSourceFile.LoadFromStream(AStream: TStream); begin if not Assigned(Series) then Raise Exception.Create(TeeMsg_NoSeriesSelected); end; { TChartWebSource } Constructor TChartWebSource.Create(AOwner: TComponent); begin inherited {$IFDEF CLR}Create(AOwner){$ENDIF}; FURL:=TeeMsg_DefaultDemoTee; end; procedure TChartWebSource.Execute; begin if Assigned(FChart) and (FURL<>'') then LoadChartFromURL(FChart,FURL); end; procedure TChartWebSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and Assigned(FChart) and (AComponent=FChart) then Chart:=nil; end; procedure TChartWebSource.SetChart(const Value: TCustomChart); begin if FChart<>Value then begin {$IFDEF D5} if Assigned(FChart) then FChart.RemoveFreeNotification(Self); {$ENDIF} FChart:=Value; if Assigned(FChart) then FChart.FreeNotification(Self); end; end; {$IFNDEF CLR} {$IFNDEF CLX} initialization {$IFDEF C3} TeeWinInetDLL:=0; { <-- BCB3 crashes in Win95 if we do not do this... } {$ENDIF} finalization if TeeWinInetDLL<>0 then TeeFreeLibrary(TeeWinInetDLL); {$ENDIF} {$ENDIF} end.
unit Generator; interface uses Points; const LabSize=24; type PassMap = array [0..LabSize-1,0..LabSize-1] of integer; var cp : array [0..31] of PassMap; type DeltaArr = array [0..LabSize*2,0..LabSize*2] of float; procedure InitLab(var cp : PassMap; index : integer); procedure GenDeltas (const cp : PassMap; var D : DeltaArr; mode : integer); function IsLight(n : integer) : boolean; function Maxd (f : integer): integer; procedure OutLabs; implementation function Maxd (f : integer): integer; begin case f div 4 of 0 : result := 2; 7 : result := LabSize * 4 div 9; 6 : result := LabSize * 4 div 9; 5 : result := LabSize * 6 div 9; else result := LabSize; end; end; function CanBeEmpty (f,x,y : integer): boolean; var d : integer; begin d := Maxd(f); result := false; case f mod 4 of 0 : result := (x>= 1) and (x<=d -2) and (y>= 1) and (y<=d -2); 1 : result := (x>= 1) and (x<=d -2) and (y>=LabSize-d+1) and (y<=LabSize-2); 2 : result := (x>=LabSize-d+1) and (x<=LabSize-2) and (y>=LabSize-d+1) and (y<=LabSize-2); 3 : result := (x>=LabSize-d+1) and (x<=LabSize-2) and (y>= 1) and (y<=d -2); end; end; function CanBeEmptyR (f,x,y : integer): boolean; var i,j : integer; begin for i := x-1 to x+1 do for j := y-1 to y+1 do if CanBeEmpty(f,i,j) then begin Result := True; Exit; end; Result := False; end; function GetD(l : integer): integer; begin Result := Maxd(l); if Result>Maxd(l+1) then Result :=Maxd(l+1); Result := 1 + round((0.5 + abs(sin(l*l))*0.5) * (Result-3)); end; procedure InitLab(var cp : PassMap; index : integer); var i,j,k,m : integer; x,y : integer; lc : integer; c : integer; bad : boolean; cl,cl2 : array [0..7] of integer; const dx : array [0..7] of integer = (0,1,1,1,0,-1,-1,-1); dy : array [0..7] of integer = (1,1,0,-1,-1,-1,0,1); function Good(x,y: integer) : boolean; begin Result := (x>=0) and (x<LabSize) and (y>=0) and (y<LabSize); end; function Inner(x,y: integer) : boolean; begin Result := (x>=1) and (x<LabSize-1) and (y>=1) and (y<LabSize-1); end; function Busy(x,y: integer) : boolean; begin Result := not Good(x,y) or (cp[x,y]>0); end; procedure FillC(x,y: integer; cl : integer); var i,j: integer; begin if Good(x,y) and (cp[x,y]>0) and (cp[x,y]<>cl) then begin cp[x,y] := cl; for i := x-1 to x+1 do for j := y-1 to y+1 do FillC(i,j,cl); end; end; procedure FillH(x,y: integer; cl : integer); begin if Good(x,y) and (cp[x,y]=-1) then begin cp[x,y] := cl; FillH(x-1,y,cl); FillH(x,y-1,cl); FillH(x+1,y,cl); FillH(x,y+1,cl); end; end; function NearBubble (x,y : integer): boolean; var i,j : integer; begin for i := x-1 to x+1 do for j := y-1 to y+1 do if Good(i,j) and (cp[i,j]=-1) then begin Result := True; Exit; end; Result := False; end; procedure CreateBubble(x,y:integer;ir,sr:integer); var i,j : integer; begin for i := x-(sr) div 2 to x+(sr) div 2 do for j := y-(sr) div 2 to y+(sr) div 2 do if (sqr(i*2+1-x*2)+sqr(j*2+1-y*2)<=sqr(sr)) and (sqr(i*2+1-x*2)+sqr(j*2+1-y*2)> sqr(ir)) and Inner(i,j) and not NearBubble(i,j) and (cp[i,j]=0) then cp[i,j] := -2; for i := x-(sr) div 2 to x+(sr) div 2 do for j := y-(sr) div 2 to y+(sr) div 2 do if Inner(i,j) and (cp[i,j]=-2) then cp[i,j] := -1; end; begin for i := 0 to LabSize-1 do for j := 0 to LabSize-1 do if CanBeEmpty(index,i,j) then cp[i,j] := 0 else cp[i,j] := 1; lc := 1; if index>=4 then case index mod 4 of 0 : begin if index>4 then cp[0, GetD(index-1)] := -1; cp[GetD(index), 0] := -1; end; 1 : begin cp[GetD(index-1), LabSize-1] := -1; cp[0, LabSize-1-GetD(index)] := -1; end; 2 : begin cp[LabSize-1, LabSize-1-GetD(index-1)] := -1; cp[LabSize-1-GetD(index), LabSize-1] := -1; end; 3 : begin cp[LabSize-1-GetD(index-1), 0] := -1; if index<31 then cp[LabSize-1, GetD(index)] := -1; end; end; if index=16 then begin CreateBubble(LabSize-3,LabSize-3,0,6); CreateBubble(LabSize-3,LabSize-3,7,12); Assert(cp[LabSize-2,LabSize-2]<0); end; if index=20 then cp[1,1] := -1; if index in [10..14] then m := LabSize*LabSize div 128 else if index<8 then m := LabSize*LabSize div 32 else if index<10 then m := LabSize*LabSize div 96 else if index<28 then m := LabSize*LabSize div 128 else m := LabSize*LabSize div 32; for k := 0 to m-1 do begin x := random(LabSize); y := random(LabSize); CreateBubble(x,y,0,2+random(4)); if index in [8..9,15..31] then CreateBubble(x+(random(5)-1) div 2,y+(random(5)-1) div 2,3,9-random(4)); end; if index in [4..7,10..14] then m := 3200 else m := 170; for k := 0 to LabSize*LabSize*m div 100 -1 do begin x := Random(LabSize-2)+1; y := Random(LabSize-2)+1; if cp[x,y]=0 then begin for i := 0 to 7 do cl[i] := cp[x+dx[i],y+dy[i]]; bad := false; for i := 0 to 3 do begin if (cl[(i*2+1) and 7]>0) and ((cl[(i*2) and 7]<=0) and (cl[(i*2+2) and 7]<=0)) then bad := true; end; for i := 0 to 3 do if cl[i*2+1]<=0 then begin c := cl[(i*2+2) and 7]; if c>0 then cl[i*2+1] := c; c := cl[(i*2+0) and 7]; if c>0 then cl[i*2+1] := c; end; m := 0; for i := 0 to 7 do begin if (cl[i]>0) and (cl[(i+7)and 7]<=0) then begin cl2[m]:=cl[i]; inc(m); end; end; for i := 0 to m-1 do begin for j := i+1 to m-1 do if cl2[i]=cl2[j] then begin bad := true; break; end; end; if not bad then begin if index in [0..3,9,10..14] then for i := 0 to 3 do begin if not Busy(x+dx[i*2],y+dy[i*2]) then begin j := 0; if Busy(x+2*dx[i*2],y+2*dy[i*2]) then inc(j); if Busy(x+dx[(i*2+7) and 7], y+dy[(i*2+7) and 7]) then inc(j); if Busy(x+dx[(i*2+1) and 7], y+dy[(i*2+1) and 7]) then inc(j); if (j>=2) then bad := true; end; end; if not bad then begin if m=0 then begin inc(lc); cp[x,y] := lc; end else begin cp[x,y] := cl2[0]; for i := 0 to m-1 do if cl2[i]=1 then cp[x,y] := cl2[i]; for i := x-1 to x+1 do for j := y-1 to y+1 do fillc(i,j,cp[x,y]); end; end; end; end; end; for i := 0 to LabSize-1 do for j := 0 to LabSize-1 do begin if cp[i,j]<=0 then cp[i,j] := 0 else if CanBeEmpty(index,i,j) then cp[i,j] := 1 else if CanBeEmptyR(index,i,j) then cp[i,j] := 2 else cp[i,j] := 3; end; for i := 0 to LabSize-2 do for j := 0 to LabSize-2 do begin if (cp[i,j]<=0) and (cp[i+1,j]<=0) and (cp[i,j+1]<=0) and (cp[i+1,j+1]<=0) then begin cp[i,j] := -1; cp[i+1,j] := -1; cp[i,j+1] := -1; cp[i+1,j+1] := -1; end; end; if index>=4 then begin for i := 0 to LabSize-2 do for j := 0 to LabSize-2 do begin c := random($10000); FillH(i,j,-(c and $7FFF)-1); end; end; for i := 0 to LabSize-1 do for j := 0 to LabSize-1 do begin if (cp[i,j]<0) and (cp[i,j]>-100) then cp[i,j] := 0; end; { for k := 0 to LabSize*LabSize div 4-1 do begin x := random(LabSize*2-1)-LabSize+1; y := Random(LabSize*2-1)-LabSize+1; if (cp[x,y]<=0) and (cp[x,y]>=-1) then begin i := random(4); case i of 0 : if (x<LabSize-1) and (cp[x+1,y-1]>0) and (cp[x+1,y]>0) and (cp[x+1,y+1]>0) then cp[x+1,y] := 1; 1 : if (y<LabSize-1) and (cp[x-1,y+1]>0) and (cp[x,y+1]>0) and (cp[x+1,y+1]>0) then cp[x,y+1] := 2; 2 : if (x>1-LabSize) and (cp[x-1,y-1]>0) and (cp[x-1,y]>0) and (cp[x-1,y+1]>0) then cp[x-1,y] := 3; 3 : if (y>1-LabSize) and (cp[x-1,y-1]>0) and (cp[x,y-1]>0) and (cp[x+1,y-1]>0) then cp[x,y-1] := 4; end; end; end; } end; function IsLight(n : integer) : boolean; begin Result := n<>0; end; procedure GenDeltas (const cp : PassMap; var D : DeltaArr; mode : integer); var i,j,k : integer; nd : DeltaArr; f : boolean; d1,d2 : float; maxd,mind : float; LS : integer; procedure cd (x,y: integer); begin if d1>d[x,y] then d1 := d[x,y]; if d2<d[x,y] then d2 := d[x,y]; end; procedure eq (x1,y1,x2,y2: integer); begin if d[x1,y1]<>d[x2,y2] then begin if (abs(x1*2-LS+1)+abs(y1*2-LS+1)>abs(x2*2-LS+1)+abs(y2*2-LS+1)) then begin nd[x1,y1] := d[x2,y2] end else nd[x1,y1] := d[x2,y2]*0.5+d[x1,y1]*0.5; nd[x2,y2] := nd[x1,y1]; f := false; end; end; var Pr : array [0..LabSize,0..LabSize] of byte; v : single; c : integer; procedure Test(x,y,m : integer); procedure Go(cp1,cp2,cp3,cp4,cp5,cp6 : integer; nx,ny : integer); begin if (cp1<=0) and (cp2<=0) then Test(nx,ny,m) else if (cp1<=0) or (cp2<=0) then begin if ((cp3>0) and (cp4>0)) or ((cp5>0) and (cp6>0)) then Test(nx,ny,m); end; end; begin if pr[x,y]>=m then Exit; if (x<=0) or (y<=0) or (x>=LS) or (y>=LS) then exit; pr[x,y] := m; if m=1 then begin v := v + d[x,y]; c := c + 1; end else nd[x,y] := v; if x>1 then Go(cp[x-1,y-1], cp[x-1,y], cp[x-2,y-1], cp[x-2,y], cp[x,y-1], cp[x,y], x-1, y) else Go(cp[x-1,y-1], cp[x-1,y], 1, 1, cp[x,y-1], cp[x,y], x-1, y); if y>1 then Go(cp[x-1,y-1], cp[x,y-1], cp[x-1,y-2], cp[x,y-2], cp[x-1,y], cp[x,y], x, y-1) else Go(cp[x-1,y-1], cp[x,y-1], 1, 1, cp[x-1,y], cp[x,y], x, y-1); if x<LabSize-1 then Go(cp[x,y-1], cp[x,y], cp[x+1,y-1], cp[x+1,y], cp[x-1,y-1], cp[x-1,y], x+1, y) else Go(cp[x,y-1], cp[x,y], 1, 1, cp[x-1,y-1], cp[x-1,y], x+1, y); if y<LabSize-1 then Go(cp[x-1,y], cp[x,y], cp[x-1,y+1], cp[x,y+1], cp[x-1,y-1], cp[x,y-1], x, y+1) else Go(cp[x-1,y], cp[x,y], 1, 1, cp[x-1,y-1], cp[x,y-1], x, y+1); end; begin if Mode=3 then LS := LabSize*2 else LS := LabSize; maxd := 0; mind := 0; for i := 1 to LS-1 do for j := 1 to LS-1 do begin if ((i=1) and (j=1)) or (maxd<d[i,j]) then maxd := d[i,j]; if ((i=1) and (j=1)) or (mind>d[i,j]) then mind := d[i,j]; end; nd := d; for k := 0 to LS-1 do begin f := true; if mode=2 then begin FillChar(Pr, sizeof(Pr), 0); for i := 1 to LS-1 do for j := 1 to LS-1 do begin c := 0; v := 0; Test(i,j,1); if c>0 then begin v := v/c; Test(i,j,2); end; end; d := nd; end; for i := 1 to LS-1 do begin for j := 1 to LS-1 do begin d1 := maxd; d2 := mind; if (mode=3) or (cp[i-1,j-1]<=0) or (cp[i-1,j]<=0) then cd(i-1,j); if (mode=3) or (cp[i-1,j-1]<=0) or (cp[i,j-1]<=0) then cd(i,j-1); if (mode=3) or (cp[i ,j-1]<=0) or (cp[i ,j]<=0) then cd(i+1,j); if (mode=3) or (cp[i-1,j ]<=0) or (cp[i,j ]<=0) then cd(i,j+1); if d1<=d2 then begin if (d[i,j]>d1+1) or (d[i,j]<d2-1) then f := false; if d1<=d2-1.6 then nd[i,j] := d[i,j]*0.5 + (d1+d2)*0.25 else if d[i,j]>d1+0.8 then nd[i,j] := d[i,j]*0.5 + (d1+0.8)*0.5 else if d[i,j]<d2-0.8 then nd[i,j] := d[i,j]*0.5 + (d2-0.8)*0.5 else nd[i,j] := d[i,j]; end else nd[i,j] := d[i,j]; end; end; if mode=1 then begin for i := 1 to LS-1 do begin for j := 1 to LS-1 do begin if (cp[i-1,j-1]>0) or (cp[i,j-1]>0) or (cp[i-1,j]>0) or (cp[i,j]>0) then nd[i,j] := 0; end; end; end; d := nd; if f then break; end; if mode<>3 then for k := 0 to LS-1 do begin for i := 1 to LS-1 do for j := 1 to LS-1 do begin if (cp[i-1,j-1]>0) and (cp[i ,j-1]>0) and (cp[i-1,j ]>0) and (cp[i ,j ]>0) then begin nd[i,j] := d[i,j]*0.5 + d[i-1,j]*0.125 + d[i,j-1]*0.125 + d[i+1,j]*0.125 + d[i,j+1]*0.125; end; end; d := nd; end; end; procedure OutLab(var f : text; const cp : PassMap); var i,j:integer; begin for i := 0 to LabSize-1 do begin for j := 0 to LabSize-1 do begin if cp[i,j] <= -$20000 then write(f,'v') else if cp[i,j] <= -$10000 then write (f,'.') else if cp[i,j] <= 0 then write(f, ' ') else Write(f, 'M'); end; WriteLn(f); end; WriteLn(f); end; procedure OutLabs; var i : integer; f : text; begin Assign(f, 'lab.txt'); Rewrite(f); if IOResult=0 then begin for i := 4 to 31 do begin WriteLn(f, 'Level ', i-3); OutLab(f, cp[i]); end; Close(f); end; end; end.
unit GrievanceDuplicatesDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls; type TGrievanceDuplicatesDialog = class(TForm) YesButton: TBitBtn; NoButton: TBitBtn; GrievanceTable: TTable; DescriptionLabel: TLabel; DuplicateGrievanceList: TListBox; OKButton: TBitBtn; PromptLabel: TLabel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } AssessmentYear : String; GrievanceNumber : LongInt; AskForConfirmation : Boolean; end; var GrievanceDuplicatesDialog: TGrievanceDuplicatesDialog; implementation {$R *.DFM} uses PASUtils, WinUtils; {===============================================================} Procedure TGrievanceDuplicatesDialog.FormShow(Sender: TObject); var FirstTimeThrough, Done : Boolean; begin Caption := 'Parcels with grievance #' + IntToStr(GrievanceNumber) + '.'; DescriptionLabel.Caption := 'The following parcels all have grievance #' + IntToStr(GrievanceNumber) + '.'; try GrievanceTable.Open; except MessageDlg('Error opening grievance table.', mtError, [mbOK], 0); end; If AskForConfirmation then begin PromptLabel.Visible := True; YesButton.Visible := True; NoButton.Visible := True; end else begin OKButton.Visible := True; OKButton.Default := True; end; SetRangeOld(GrievanceTable, ['TaxRollYr', 'GrievanceNumber'], [AssessmentYear, IntToStr(GrievanceNumber)], [AssessmentYear, IntToStr(GrievanceNumber)]); Done := False; FirstTimeThrough := True; GrievanceTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else GrievanceTable.Next; If GrievanceTable.EOF then Done := True; If not Done then DuplicateGrievanceList.Items.Add(ConvertSwisSBLToDashDot(GrievanceTable.FieldByName('SwisSBLKey').Text)); until Done; end; {FormShow} {==============================================================} Procedure TGrievanceDuplicatesDialog.FormClose( Sender: TObject; var Action: TCloseAction); begin GrievanceTable.Close; Action := caFree; end; end.
unit u_DevAPI; {$MODE objfpc}{$H+} interface uses windows,Classes, SysUtils; type TTagType=(None,ultra_light,Mifare_DESFire,Mifare_One_S50,Mifare_ProX,Mifare_One_S70,Mifare_Pro); const DevAPI_DLL = 'DevAPI.dll'; WIFI_DLL='wifi.dll'; ISO14443A = 0; //获取硬件版本号 function HardwareVersion_Ex(pszData: Pbyte): Integer; stdcall; External DevAPI_DLL; //端口选择 0 RFID 1 外接串口 2 Barcode 3 GPS procedure SerialPortSwitch_Ex(ComID: Byte); stdcall; External DevAPI_DLL; //IO控制,对相应的功能模块上/下电 uPortID 端口 uValue 0 低电平 1 高电平 procedure SerialPortControl_Ex(uPortID, uValue: Byte); stdcall; External DevAPI_DLL; //设置波特率(针对RFID、条码) function SerialPortSetBaudRate_Ex(iBaudRate: Integer): LongBool; stdcall; External DevAPI_DLL; //功能模块切换(针对RFID、条码),必须在上电之后使用 //0 RFID 1 条码 function SerialPortFunctionSwitch_Ex(iModule: Integer): LongBool; stdcall; External DevAPI_DLL; //RFID模式切换(需要执行该命令之后,才可进行相应的卡操作,默认ISO14443A) //0 ISO14443A 1 ISO14443B 2 ISO15693 function RF_ModeSwitch(iMode: Integer): Integer; stdcall; External DevAPI_DLL; //震动器(毫秒) procedure StartShake(iTime: Integer); stdcall; External DevAPI_DLL; //获取背光等级 function GetBackLightLevel(): Integer; stdcall; External DevAPI_DLL; //设置背光等级 1-10 function SetBackLightLevel(iLevel: Integer): LongBool; stdcall; External DevAPI_DLL; //打开WIFI模块 function WLanOn():LongBool;stdcall; External WIFI_DLL; //关闭WIFI模块 function WLanOff():LongBool;stdcall; External WIFI_DLL; //1D条码====================================================================== //初始化 procedure Barcode1D_init(); stdcall; External DevAPI_DLL; //释放 procedure Barcode1D_free(); stdcall; External DevAPI_DLL; //扫描 (条码<=255 Byte) function Barcode1D_scan(pszData: PByte): Integer; stdcall; External DevAPI_DLL; //ISO 14443A================================================================== //初始化 function RF_ISO14443A_init(): LongBool; stdcall; External DevAPI_DLL; //释放 procedure RF_ISO14443A_free(); stdcall; External DevAPI_DLL; //呼叫天线内电子标签 0 未休眠电子标签 1 所有状态电子标签 返回ATQA信息 function RF_ISO14443A_request(iMode: Integer; pszATQA: PByte): Integer; stdcall; External DevAPI_DLL; //查询电子标签 0 未休眠电子标签 1 所有状态电子标签 返回ATQA信息2Byte+UID长度1Byte+UID(S50为4Byte) function RF_ISO14443A_request_Ex(iMode: Integer; pszData: PByte): Integer; stdcall; External DevAPI_DLL; //防冲突 返回标签UID function RF_ISO14443A_anticoll(pszUID: Pbyte): Integer; stdcall; External DevAPI_DLL; //选择电子标签指令(选择之后标签处于激活状态) function RF_ISO14443A_select(pszUID: Pbyte; iLenUID: Integer; pszSAK: Pbyte): Integer; stdcall; External DevAPI_DLL; //A卡休眠指令(电子标签接收到该指令后退出激活状态) function RF_ISO14443A_halt(): Integer; stdcall; External DevAPI_DLL; //认证卡密钥 function RF_ISO14443A_authentication(iMode, iBlock: Integer; pszKey: PByte; iLenKey: Integer): Integer; stdcall; External DevAPI_DLL; //读取标签内容 function RF_ISO14443A_read(iBlock: Integer; pszData: PByte): Integer; stdcall; External DevAPI_DLL; //写入标签内容 function RF_ISO14443A_write(iBlock: Integer; pszData: PByte; iLenData: Integer): Integer; stdcall; External DevAPI_DLL; //电子钱包初始化 function RF_ISO14443A_initval(iBlock, iValue: Integer): Integer; stdcall; External DevAPI_DLL; //读取电子钱包 function RF_ISO14443A_readval(iBlock: Integer; pszValue: Pbyte): Integer; stdcall; External DevAPI_DLL; //电子钱包 减 function RF_ISO14443A_decrement(iBlockValue, iBlockResult, iValue: Integer): Integer; stdcall; External DevAPI_DLL; //电子钱包 增 function RF_ISO14443A_increment(iBlockValue, iBlockResult, iValue: Integer): Integer; stdcall; External DevAPI_DLL; //回传函数,将EEPROM中内容传入卡的内部寄存器 function RF_ISO14443A_restore(iBlock: Integer): Integer; stdcall; External DevAPI_DLL; //传送,将寄存器内通传送到EEPROM function RF_ISO14443A_transfer(iBlock: Integer): Integer; stdcall; External DevAPI_DLL; //ul防冲突 UID 7Byte function RF_ISO14443A_ul_anticoll(pszUID: Pbyte): Integer; stdcall; External DevAPI_DLL; //ul 写入数据 0-3 不能写入数据 function RF_ISO14443A_ul_write(iBlock: Integer; pszData: Pbyte; iLenData: Integer): Integer; stdcall; External DevAPI_DLL; function Init_RF_ISO14443A_Mode(): Boolean; function Halt_RF_ISO14443A(): Boolean; procedure Free_RF_ISO14443A_Mode(); function getRFID(var TagType:TTagType;var UIDStr: string): Boolean; implementation function Init_RF_ISO14443A_Mode(): Boolean; begin Result := RF_ISO14443A_init(); if Result then begin Result := RF_ModeSwitch(ISO14443A) = 0; end; end; // halt 标签休眠 function Halt_RF_ISO14443A(): Boolean; begin Result := (RF_ISO14443A_halt() = 0); end; // 释放资源 procedure Free_RF_ISO14443A_Mode(); begin RF_ISO14443A_free(); end; //寻卡 成功返回true function ReadID(pszData: Pbyte): Boolean; begin //寻卡指令 Result := (RF_ISO14443A_request_Ex(1, pszData) = 0); end; // 读取指定块的所有数据 function ReadUL01Data(var UID:String):Boolean; Const DATALEN=16; var blk0:array[0..DATALEN] of Byte; j:integer; begin UID:=''; Result:=False; try Fillchar(blk0,DATALEN+1,0); //第一个字节是长度固定$10,然后是16Byte,UL卡的连续四块。 if RF_ISO14443A_read(0, blk0)<>0 then Exit; for j:=1 to 8 do UID:=UID+InttoHex(blk0[j],2); Result:=True; except ; end; end; function getRFID(var TagType:TTagType;var UIDStr: string): Boolean; var pszData: PByte; i: Integer; DLen, UIDLen: Byte; ATAQ: array[0..1] of Byte; begin Result := False; pszData := GetMem(255); try FillChar(pszData^, 255, 0); //电子标签 寻卡操作 look for cards if (not ReadID(pszData)) then exit; //寻卡成功 返回数组 0字节数据长度 1,2字节ATQA 3字节UID长度 4字节后为UID信息 DLen := pszData[0]; Move(pszData[1], ATAQ[0], 2); UIDLen := pszData[3]; UIDStr := ''; for i := 4 to (UIDLen + 4)-1 do UIDStr := UIDStr + InttoHex(pszData[i], 2); //卡类型 TagType := None; case ATAQ[0] of $44: begin if (ATAQ[1] = $00) then begin TagType := ultra_light; //读取 0 1 块全部数据 UIDStr:=''; if not ReadUL01Data(UIDStr) then exit; end; if (ATAQ[1] = $03) then TagType := Mifare_DESFire; end; $04: begin if (ATAQ[1] = $00) then TagType := Mifare_One_S50; if (ATAQ[1] = $03) then TagType := Mifare_ProX; end; $02: begin if (ATAQ[1] = $00) then TagType := Mifare_One_S70; end; $08: begin if (ATAQ[1] = $00) then TagType := Mifare_Pro; end; end; Result := (TagType <> None); finally FreeMem(pszData, 255); end; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.Editor.MultiView; interface uses DesignEditors, DesignMenus, FMX.MultiView, System.Classes, DesignIntf; type { TMultiViewEditor } TMultiViewEditor = class(TComponentEditor) private const EditorShowHide = 0; EditorMode = 1; private FMultiView: TMultiView; function ModeToString(const AMode: TMultiViewMode): string; function DefineCurrentMode: string; procedure DoSetMode(Sender: TObject); public constructor Create(AComponent: TComponent; ADesigner: IDesigner); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); override; procedure ExecuteVerb(Index: Integer); override; property MultiView: TMultiView read FMultiView; end; implementation uses FmxDsnConst, System.SysUtils, Vcl.Menus; { TMultiViewEditor } constructor TMultiViewEditor.Create(AComponent: TComponent; ADesigner: IDesigner); begin inherited; FMultiView := AComponent as TMultiView; end; function TMultiViewEditor.DefineCurrentMode: string; begin if MultiView.HasPresenter then Result := MultiView.Presenter.DisplayName else Result := ModeToString(MultiView.Mode); end; procedure TMultiViewEditor.DoSetMode(Sender: TObject); var MenuItem: TMenuItem; Mode: TMultiViewMode; begin if Sender is Vcl.Menus.TMenuItem then begin MenuItem := Sender as Vcl.Menus.TMenuItem; if MenuItem.Tag >= 0 then begin Mode := TMultiViewMode(MenuItem.Tag); MultiView.Mode := Mode; Designer.Modified; end; end; end; procedure TMultiViewEditor.ExecuteVerb(Index: Integer); begin inherited; if Index = EditorShowHide then begin if MultiView.IsShowed then MultiView.HideMaster else MultiView.ShowMaster; Designer.Modified; end; end; function TMultiViewEditor.GetVerb(Index: Integer): string; begin case Index of EditorMode: Result := Format(SMultiViewMode, [DefineCurrentMode]); EditorShowHide: if MultiView.IsShowed then Result := SMultiViewHide else Result := SMultiViewShow; else Result := string.Empty; end; end; function TMultiViewEditor.GetVerbCount: Integer; begin Result := 2; end; function TMultiViewEditor.ModeToString(const AMode: TMultiViewMode): string; begin case AMode of TMultiViewMode.PlatformBehaviour: Result := SMultiViewPlatformBehavior; TMultiViewMode.Panel: Result := SMultiViewPanel; TMultiViewMode.Popover: Result := SMultiViewlDropDown; TMultiViewMode.Drawer: Result := SMultiViewDrawer; TMultiViewMode.Custom: Result := SMultiViewCustom; TMultiViewMode.NavigationPane: Result := SMultiViewNavigationPane; end; end; procedure TMultiViewEditor.PrepareItem(Index: Integer; const AItem: IMenuItem); var Mode: TMultiViewMode; MenuItem: IMenuItem; Checked: Boolean; begin inherited PrepareItem(Index, AItem); case Index of EditorShowHide: AItem.Enabled := MultiView.HasPresenter and MultiView.Presenter.CanShowHideInDesignTime; EditorMode: for Mode := Low(TMultiViewMode) to High(TMultiViewMode) do begin Checked := MultiView.Mode = Mode; MenuItem := AItem.AddItem(ModeToString(Mode), 0, Checked, True, DoSetMode); MenuItem.GroupIndex := 1; MenuItem.RadioItem := True; MenuItem.Checked := Checked; MenuItem.Tag := NativeInt(Mode); MenuItem := nil; end; end; end; end.
unit empform; { This program demonstrates using TClientDataSet in a distributed data application. The data comes from a separate OLE Automation server, so before running this project you must compile and run EmpServ.dpr. } interface uses SysUtils, Forms, Dialogs, ExtCtrls, StdCtrls, Mask, Classes, DBClient, Db, Controls, DBCtrls, ComCtrls, MConnect; type TEmployeeForm = class(TForm) Label2: TLabel; UpdateButton: TButton; UndoButton: TButton; QueryButton: TButton; DBText1: TDBText; FirstName: TDBEdit; LastName: TDBEdit; PhoneExt: TDBEdit; HireDate: TDBEdit; Salary: TDBEdit; EmpData: TDataSource; DBNavigator1: TDBNavigator; Employees: TClientDataSet; RemoteServer1: TDCOMConnection; StatusBar1: TStatusBar; procedure QueryButtonClick(Sender: TObject); procedure UpdateButtonClick(Sender: TObject); procedure UndoButtonClick(Sender: TObject); procedure EmployeesReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); procedure EmpDataDataChange(Sender: TObject; Field: TField); end; var EmployeeForm: TEmployeeForm; implementation uses recerror; {$R *.dfm} procedure TEmployeeForm.QueryButtonClick(Sender: TObject); begin { Get data from the server. The number of records returned is dependent on the PacketRecords property of TClientDataSet. If PacketRecords is set to -1 then all records are returned. Otherwise, as the user scrolls through the data, additional records are returned in separate data packets. } Employees.Close; Employees.Open; end; procedure TEmployeeForm.UpdateButtonClick(Sender: TObject); begin { Apply any edits. The parameter indicates the number of errors which are allowed before the updating is aborted. A value of -1 indicates that all successful updates be applied regardless of the number of errors. } Employees.ApplyUpdates(-1); end; procedure TEmployeeForm.UndoButtonClick(Sender: TObject); begin { Here we demonstrate a new feature in TClientDataSet, the ability to undo changes in reverse order. The parameter indicates if the cursor should be repositioned to then record association with the change. } Employees.UndoLastChange(True); end; procedure TEmployeeForm.EmployeesReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin { This is the event handler which is called when there are errors during the update process. To demonstrate, you can create an error by running two copies of this application and modifying the same record in each one. Here we use the standard reconcile error dialog from the object repository. } Action := HandleReconcileError(DataSet, UpdateKind, E); end; procedure TEmployeeForm.EmpDataDataChange(Sender: TObject; Field: TField); begin { This code is used to update the status bar to show the number of records that have been retrieved an our relative position with the dataset. } with Employees do if Active then StatusBar1.Panels[1].Text := Format(' %d of %d', [RecNo, RecordCount]); end; end.
{ TGMInfoWindow demo program ES: programa de demostración de uso del componente TGMInfoWindow EN: demo program use of component TGMInfoWindow ========================================================================= History: ver 0.1: ES- primera versión EN- first version ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } unit UGMInfoWinFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GMMap, GMLinkedComponents, GMInfoWindow, GMClasses, GMMapVCL, Vcl.Buttons, Vcl.CheckLst, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin, Vcl.OleCtrls, SHDocVw, GMConstants; type TGMInfoWinFrm = class(TForm) StatusBar1: TStatusBar; Panel1: TPanel; Panel10: TPanel; mEvents: TMemo; Panel11: TPanel; wbWeb: TWebBrowser; Splitter1: TSplitter; GMMap1: TGMMap; bClearLog: TButton; pOptions: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; Panel12: TPanel; GroupBox1: TGroupBox; lLong: TLabel; lLat: TLabel; lTypMap: TLabel; lZoom: TLabel; eReqLng: TEdit; eReqLat: TEdit; cbTypMap: TComboBox; tbZoom: TTrackBar; GroupBox2: TGroupBox; Label7: TLabel; Label8: TLabel; cbZoomClick: TCheckBox; cbDraggable: TCheckBox; cbKeyboard: TCheckBox; cbNoClear: TCheckBox; eMaxZoom: TEdit; eMinZoom: TEdit; cbWheel: TCheckBox; GroupBox3: TGroupBox; pPages: TPageControl; tsGeneral: TTabSheet; Panel2: TPanel; Label16: TLabel; cbBGColor: TColorBox; tsMapType: TTabSheet; Panel3: TPanel; Label11: TLabel; Label12: TLabel; Label13: TLabel; cbShowMapType: TCheckBox; cbMapTypePos: TComboBox; cbMapTypeStyle: TComboBox; cbMapType: TCheckListBox; tsOverview: TTabSheet; Panel4: TPanel; cbShowOver: TCheckBox; cbOverOpened: TCheckBox; tsPan: TTabSheet; Panel5: TPanel; Label18: TLabel; cbShowPan: TCheckBox; cbPanPos: TComboBox; tsRotate: TTabSheet; Panel6: TPanel; Label17: TLabel; cbRoratePos: TComboBox; cbShowRotate: TCheckBox; tsScale: TTabSheet; Panel7: TPanel; Label19: TLabel; Label20: TLabel; cbShowScale: TCheckBox; cbScalePos: TComboBox; cbScaleStyle: TComboBox; tsStreetView: TTabSheet; Panel8: TPanel; Label21: TLabel; cbStreetViewPos: TComboBox; cbShowStreetView: TCheckBox; tsZoom: TTabSheet; Panel9: TPanel; Label9: TLabel; Label10: TLabel; cbZoomPos: TComboBox; cbZoomStyle: TComboBox; cbShowZoom: TCheckBox; bDoWeb: TButton; Panel13: TPanel; Panel14: TPanel; Panel15: TPanel; gbB1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; eLatASW: TEdit; eLngASW: TEdit; eLatANE: TEdit; eLngANE: TEdit; gbLatLng: TGroupBox; Label14: TLabel; Label15: TLabel; eLat: TEdit; eLng: TEdit; Label22: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; Label23: TLabel; Button4: TButton; Label24: TLabel; Button5: TButton; Button6: TButton; Label25: TLabel; Button7: TButton; Button8: TButton; GroupBox4: TGroupBox; Label26: TLabel; Label27: TLabel; eLatMethod: TEdit; eLngMethod: TEdit; Button9: TButton; Button12: TButton; Button16: TButton; Label29: TLabel; Label28: TLabel; tbZoomMet: TTrackBar; cbMapTypeMet: TComboBox; Button11: TButton; Button10: TButton; Button14: TButton; Button13: TButton; GroupBox5: TGroupBox; Label30: TLabel; Label31: TLabel; eXMet: TEdit; eYMet: TEdit; Button15: TButton; GroupBox6: TGroupBox; cbBoundsChanged: TCheckBox; cbCenterChanged: TCheckBox; cbDblClick: TCheckBox; cbClick: TCheckBox; cbMapTypeIdChanged: TCheckBox; cbDragStart: TCheckBox; cbDragEnd: TCheckBox; cbDrag: TCheckBox; cbZoomChanged: TCheckBox; cbRightClick: TCheckBox; cbMouseOver: TCheckBox; cbMouseOut: TCheckBox; cbMouseMove: TCheckBox; TabSheet5: TTabSheet; Panel16: TPanel; Label32: TLabel; lLatEvent: TLabel; lLngEvent: TLabel; Label34: TLabel; TabSheet6: TTabSheet; Panel17: TPanel; GroupBox7: TGroupBox; Label33: TLabel; Label35: TLabel; eInterval: TEdit; cbLanguages: TComboBox; cbCloseOtherBeforeOpen: TCheckBox; cbDisableAutoPan: TCheckBox; Label36: TLabel; Label37: TLabel; eInfoWinLat: TEdit; eInfoWinLng: TEdit; bAddInfoWin: TBitBtn; bDelInfoWin: TBitBtn; lbInfoWindows: TListBox; bUp: TButton; bDown: TButton; Label39: TLabel; lZIndex: TLabel; bNewMarker: TButton; bCenterInfoWin: TButton; Label40: TLabel; ePrecision: TSpinEdit; cbActive: TCheckBox; GMInfoWindow1: TGMInfoWindow; eMaxWidth: TEdit; Label41: TLabel; eWidth: TEdit; eHeight: TEdit; Label42: TLabel; Label43: TLabel; Label44: TLabel; Label38: TLabel; mHTMLContent: TMemo; bOpenClose: TButton; cbAutoOpen: TCheckBox; bSave: TButton; bPrint: TButton; bPreview: TButton; procedure bDoWebClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure GMMap1AfterPageLoaded(Sender: TObject; First: Boolean); procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure StatusBar1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure StatusBar1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Button9Click(Sender: TObject); procedure Button11Click(Sender: TObject); procedure Button13Click(Sender: TObject); procedure Button15Click(Sender: TObject); procedure Button16Click(Sender: TObject); procedure Button12Click(Sender: TObject); procedure Button10Click(Sender: TObject); procedure Button14Click(Sender: TObject); procedure GMMap1BoundsChanged(Sender: TObject; NewBounds: TLatLngBounds); procedure GMMap1CenterChanged(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1Click(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1DblClick(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1Drag(Sender: TObject); procedure GMMap1DragEnd(Sender: TObject); procedure GMMap1DragStart(Sender: TObject); procedure GMMap1MapTypeIdChanged(Sender: TObject; NewMapTypeId: TMapTypeId); procedure GMMap1MouseMove(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1MouseOut(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1MouseOver(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1RightClick(Sender: TObject; LatLng: TLatLng; X, Y: Double); procedure GMMap1ZoomChanged(Sender: TObject; NewZoom: Integer); procedure cbBoundsChangedClick(Sender: TObject); procedure cbCenterChangedClick(Sender: TObject); procedure cbClickClick(Sender: TObject); procedure cbDblClickClick(Sender: TObject); procedure cbDragClick(Sender: TObject); procedure cbDragEndClick(Sender: TObject); procedure cbDragStartClick(Sender: TObject); procedure cbMapTypeIdChangedClick(Sender: TObject); procedure cbMouseMoveClick(Sender: TObject); procedure cbMouseOutClick(Sender: TObject); procedure cbMouseOverClick(Sender: TObject); procedure cbRightClickClick(Sender: TObject); procedure cbZoomChangedClick(Sender: TObject); procedure bClearLogClick(Sender: TObject); procedure eIntervalChange(Sender: TObject); procedure cbLanguagesChange(Sender: TObject); procedure lbInfoWindowsClick(Sender: TObject); procedure bNewMarkerClick(Sender: TObject); procedure bUpClick(Sender: TObject); procedure bDownClick(Sender: TObject); procedure bAddInfoWinClick(Sender: TObject); procedure pOptionsChange(Sender: TObject); procedure bDelInfoWinClick(Sender: TObject); procedure bCenterInfoWinClick(Sender: TObject); procedure ePrecisionChange(Sender: TObject); procedure cbActiveClick(Sender: TObject); procedure GMInfoWindow1CloseOtherBeforeOpenChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); procedure GMInfoWindow1DisableAutoPanChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); procedure GMInfoWindow1HTMLContentChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); procedure GMInfoWindow1MaxWidthChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); procedure bOpenCloseClick(Sender: TObject); procedure GMInfoWindow1PositionChange(Sender: TObject; LatLng: TLatLng; Index: Integer; LinkedComponent: TLinkedComponent); procedure bPrintClick(Sender: TObject); procedure bPreviewClick(Sender: TObject); procedure bSaveClick(Sender: TObject); procedure GMInfoWindow1CloseClick(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); private procedure AddNewInfoWin; procedure DoMap; public constructor Create(aOwner: TComponent); override; end; var GMInfoWinFrm: TGMInfoWinFrm; implementation uses ShellAPI, Types, GMFunctionsVCL; function GetStatusBarPanelXY(StatusBar : TStatusBar; X, Y: Integer) : Integer; var i: Integer; R: TRect; begin Result := -1; // Buscamos panel a panel hasta encontrar en cual está XY with StatusBar do for i := 0 to Panels.Count - 1 do begin // Obtenemos las dimensiones del panel SendMessage(Handle, WM_USER + 10, i, Integer(@R)); if PtInRect(R, Point(x,y)) then begin Result := i; Break; end; end; end; {$R *.dfm} procedure TGMInfoWinFrm.bAddInfoWinClick(Sender: TObject); var InfoWin: TInfoWindow; begin if lbInfoWindows.ItemIndex = -1 then begin InfoWin := GMInfoWindow1.Add; lbInfoWindows.Items.Add(mHTMLContent.Lines.Text); end else InfoWin := GMInfoWindow1[lbInfoWindows.ItemIndex]; InfoWin.AutoOpen := cbAutoOpen.Checked; InfoWin.CloseOtherBeforeOpen := cbCloseOtherBeforeOpen.Checked; InfoWin.DisableAutoPan := cbDisableAutoPan.Checked; InfoWin.HTMLContent := mHTMLContent.Lines.Text; InfoWin.MaxWidth := StrToInt(eMaxWidth.Text); InfoWin.PixelOffset.Height := StrToInt(eHeight.Text); InfoWin.PixelOffset.Width := StrToInt(eWidth.Text); InfoWin.Position.Lat := StrToFloat(StringReplace(eInfoWinLat.Text, '.', ',', [rfReplaceAll])); InfoWin.Position.Lng := StrToFloat(StringReplace(eInfoWinLng.Text, '.', ',', [rfReplaceAll])); end; procedure TGMInfoWinFrm.bCenterInfoWinClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; GMInfoWindow1[lbInfoWindows.ItemIndex].CenterMapTo; end; procedure TGMInfoWinFrm.bClearLogClick(Sender: TObject); begin mEvents.Clear; end; procedure TGMInfoWinFrm.bDelInfoWinClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; GMInfoWindow1.Delete(lbInfoWindows.ItemIndex); lbInfoWindows.DeleteSelected; end; procedure TGMInfoWinFrm.bDoWebClick(Sender: TObject); begin DoMap; end; procedure TGMInfoWinFrm.bDownClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; if lbInfoWindows.ItemIndex = lbInfoWindows.Count - 1 then Exit; GMInfoWindow1.Move(lbInfoWindows.ItemIndex, lbInfoWindows.ItemIndex+1); lbInfoWindows.Items.Move(lbInfoWindows.ItemIndex, lbInfoWindows.ItemIndex+1); end; procedure TGMInfoWinFrm.bNewMarkerClick(Sender: TObject); begin AddNewInfoWin; end; procedure TGMInfoWinFrm.bOpenCloseClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; GMInfoWindow1[lbInfoWindows.ItemIndex].OpenClose; end; procedure TGMInfoWinFrm.bPreviewClick(Sender: TObject); begin GMMap1.PrintPreview; end; procedure TGMInfoWinFrm.bPrintClick(Sender: TObject); begin GMMap1.PrintWithDialog; end; procedure TGMInfoWinFrm.bSaveClick(Sender: TObject); begin GMMap1.SaveToJPGFile; end; procedure TGMInfoWinFrm.bUpClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; if lbInfoWindows.ItemIndex = 0 then Exit; GMInfoWindow1.Move(lbInfoWindows.ItemIndex, lbInfoWindows.ItemIndex-1); lbInfoWindows.Items.Move(lbInfoWindows.ItemIndex, lbInfoWindows.ItemIndex-1); end; procedure TGMInfoWinFrm.Button10Click(Sender: TObject); begin GMMap1.RequiredProp.MapType := TTransform.StrToMapTypeId(cbMapTypeMet.Text); end; procedure TGMInfoWinFrm.Button11Click(Sender: TObject); begin cbMapTypeMet.ItemIndex := cbMapTypeMet.Items.IndexOf(TTransform.MapTypeIdToStr(GMMap1.GetMapTypeId)); end; procedure TGMInfoWinFrm.Button12Click(Sender: TObject); begin GMMap1.SetCenter(StrToFloat(StringReplace(eLatMethod.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLngMethod.Text, '.', ',', [rfReplaceAll]))); end; procedure TGMInfoWinFrm.Button13Click(Sender: TObject); begin tbZoomMet.Position := GMMap1.GetZoom; end; procedure TGMInfoWinFrm.Button14Click(Sender: TObject); begin GMMap1.RequiredProp.Zoom := tbZoomMet.Position; end; procedure TGMInfoWinFrm.Button15Click(Sender: TObject); begin GMMap1.PanBy(StrToInt(eXMet.Text), StrToInt(eYMet.Text)); end; procedure TGMInfoWinFrm.Button16Click(Sender: TObject); begin GMMap1.PanTo(StrToFloat(StringReplace(eLatMethod.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLngMethod.Text, '.', ',', [rfReplaceAll]))); end; procedure TGMInfoWinFrm.Button1Click(Sender: TObject); var Bounds: TLatLngBounds; begin Bounds := TLatLngBounds.Create; try GMMap1.LatLngBoundsGetBounds(Bounds); eLatASW.Text := Bounds.SW.LatToStr(GMMap1.Precision); eLngASW.Text := Bounds.SW.LngToStr(GMMap1.Precision); eLatANE.Text := Bounds.NE.LatToStr(GMMap1.Precision); eLngANE.Text := Bounds.NE.LngToStr(GMMap1.Precision); finally FreeAndNil(Bounds); end; end; procedure TGMInfoWinFrm.Button2Click(Sender: TObject); begin GMMap1.LatLngBoundsSetBounds( StrToFloat(StringReplace(eLatASW.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLngASW.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLatANE.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLngANE.Text, '.', ',', [rfReplaceAll]))); end; procedure TGMInfoWinFrm.Button3Click(Sender: TObject); var LL: TLatLng; begin LL := TLatLng.Create(StrToFloat(StringReplace(eLat.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLng.Text, '.', ',', [rfReplaceAll]))); try ShowMessage(BoolToStr(GMMap1.MapLatLngBoundsContains(LL), True)); finally FreeAndNil(LL); end; end; procedure TGMInfoWinFrm.Button4Click(Sender: TObject); var Bounds: TLatLngBounds; begin Bounds := TLatLngBounds.Create; try GMMap1.LatLngBoundsExtend( StrToFloat(StringReplace(eLat.Text, '.', ',', [rfReplaceAll])), StrToFloat(StringReplace(eLng.Text, '.', ',', [rfReplaceAll])), Bounds); eLatASW.Text := Bounds.SW.LatToStr(GMMap1.Precision); eLngASW.Text := Bounds.SW.LngToStr(GMMap1.Precision); eLatANE.Text := Bounds.NE.LatToStr(GMMap1.Precision); eLngANE.Text := Bounds.NE.LngToStr(GMMap1.Precision); finally FreeAndNil(Bounds); end; end; procedure TGMInfoWinFrm.Button5Click(Sender: TObject); var LL: TLatLng; LLB: TLatLngBounds; begin LL := TLatLng.Create; LLB := TLatLngBounds.Create; try GMMap1.LatLngBoundsGetBounds(LLB); GMMap1.LatLngBoundsGetCenter(LLB, LL); eLat.Text := LL.LatToStr(GMMap1.Precision); eLng.Text := LL.LngToStr(GMMap1.Precision); finally FreeAndNil(LLB); FreeAndNil(LL); end; end; procedure TGMInfoWinFrm.Button6Click(Sender: TObject); var LL: TLatLng; begin LL := TLatLng.Create; try GMMap1.LatLngBoundsToSpan(LL); eLat.Text := LL.LatToStr(GMMap1.Precision); eLng.Text := LL.LngToStr(GMMap1.Precision); finally FreeAndNil(LL); end; end; procedure TGMInfoWinFrm.Button7Click(Sender: TObject); var LLB: TLatLngBounds; begin try GMMap1.LatLngBoundsGetBounds(LLB); ShowMessage(LLB.ToStr(GMMap1.Precision)); finally FreeAndNil(LLB); end; end; procedure TGMInfoWinFrm.Button8Click(Sender: TObject); var LLB: TLatLngBounds; begin try GMMap1.LatLngBoundsGetBounds(LLB); ShowMessage(LLB.ToUrlValue(GMMap1.Precision)); finally FreeAndNil(LLB); end; end; procedure TGMInfoWinFrm.Button9Click(Sender: TObject); var LL: TLatLng; begin LL := TLatLng.Create; try GMMap1.GetCenter(LL); eLatMethod.Text := LL.LatToStr(GMMap1.Precision); eLngMethod.Text := LL.LngToStr(GMMap1.Precision); finally FreeAndNil(LL); end; end; procedure TGMInfoWinFrm.cbActiveClick(Sender: TObject); begin GMMap1.Active := cbActive.Checked; end; procedure TGMInfoWinFrm.cbBoundsChangedClick(Sender: TObject); begin GMMap1.OnBoundsChanged := nil; if cbBoundsChanged.Checked then GMMap1.OnBoundsChanged := GMMap1BoundsChanged; end; procedure TGMInfoWinFrm.cbCenterChangedClick(Sender: TObject); begin GMMap1.OnCenterChanged := nil; if cbCenterChanged.Checked then GMMap1.OnCenterChanged := GMMap1CenterChanged; end; procedure TGMInfoWinFrm.cbClickClick(Sender: TObject); begin GMMap1.OnClick := nil; if cbClick.Checked then GMMap1.OnClick := GMMap1Click; end; procedure TGMInfoWinFrm.cbDblClickClick(Sender: TObject); begin GMMap1.OnDblClick := nil; if cbDblClick.Checked then GMMap1.OnDblClick := GMMap1DblClick; end; procedure TGMInfoWinFrm.cbDragClick(Sender: TObject); begin GMMap1.OnDrag := nil; if cbDrag.Checked then GMMap1.OnDrag := GMMap1Drag; end; procedure TGMInfoWinFrm.cbDragEndClick(Sender: TObject); begin GMMap1.OnDragEnd := nil; if cbDragEnd.Checked then GMMap1.OnDragEnd := GMMap1DragEnd; end; procedure TGMInfoWinFrm.cbDragStartClick(Sender: TObject); begin GMMap1.OnDragStart := nil; if cbDragStart.Checked then GMMap1.OnDragStart := GMMap1DragStart; end; procedure TGMInfoWinFrm.cbLanguagesChange(Sender: TObject); begin case cbLanguages.ItemIndex of 0: GMMap1.Language := Espanol; 1: GMMap1.Language := English; end; end; procedure TGMInfoWinFrm.cbMapTypeIdChangedClick(Sender: TObject); begin GMMap1.OnMapTypeIdChanged := nil; if cbMapTypeIdChanged.Checked then GMMap1.OnMapTypeIdChanged := GMMap1MapTypeIdChanged; end; procedure TGMInfoWinFrm.cbMouseMoveClick(Sender: TObject); begin GMMap1.OnMouseMove := nil; if cbMouseMove.Checked then GMMap1.OnMouseMove := GMMap1MouseMove; end; procedure TGMInfoWinFrm.cbMouseOutClick(Sender: TObject); begin GMMap1.OnMouseOut := nil; if cbMouseOut.Checked then GMMap1.OnMouseOut := GMMap1MouseOut; end; procedure TGMInfoWinFrm.cbMouseOverClick(Sender: TObject); begin GMMap1.OnMouseOver := nil; if cbMouseOver.Checked then GMMap1.OnMouseOver := GMMap1MouseOver; end; procedure TGMInfoWinFrm.cbRightClickClick(Sender: TObject); begin GMMap1.OnRightClick := nil; if cbRightClick.Checked then GMMap1.OnRightClick := GMMap1RightClick; end; procedure TGMInfoWinFrm.cbZoomChangedClick(Sender: TObject); begin GMMap1.OnZoomChanged := nil; if cbZoomChanged.Checked then GMMap1.OnZoomChanged := GMMap1ZoomChanged; end; constructor TGMInfoWinFrm.Create(aOwner: TComponent); var i: Integer; begin inherited; for i := 0 to GMInfoWindow1.VisualObjects.Count - 1 do lbInfoWindows.Items.Add(GMInfoWindow1[i].HTMLContent); case GMMap1.Language of Espanol: cbLanguages.ItemIndex := 0; English: cbLanguages.ItemIndex := 1; end; eInterval.Text := IntToStr(GMMap1.IntervalEvents); bDoWeb.Enabled := False; pPages.ActivePageIndex := 0; pOptions.ActivePageIndex := 0; ePrecision.Value := GMMap1.Precision; cbMapType.CheckAll(cbChecked); mEvents.Clear; cbActive.Checked := GMMap1.Active; end; procedure TGMInfoWinFrm.DoMap; begin // required properties GMMap1.RequiredProp.Center.Lat := StrToFloat(StringReplace(eReqLat.Text, '.', ',', [rfReplaceAll])); GMMap1.RequiredProp.Center.Lng := StrToFloat(StringReplace(eReqLng.Text, '.', ',', [rfReplaceAll])); GMMap1.RequiredProp.MapType := TTransform.StrToMapTypeId(cbTypMap.Text); GMMap1.RequiredProp.Zoom := tbZoom.Position; // non visual properties with GMMap1.NonVisualProp do begin MaxZoom := StrToInt(eMaxZoom.Text); MinZoom := StrToInt(eMinZoom.Text); Options := []; if cbZoomClick.Checked then Options := Options + [DisableDoubleClickZoom]; if cbDraggable.Checked then Options := Options + [Draggable]; if cbKeyboard.Checked then Options := Options + [KeyboardShortcuts]; if cbNoClear.Checked then Options := Options + [NoClear]; if cbWheel.Checked then Options := Options + [ScrollWheel]; end; // visual properties with GMMap1.VisualProp do begin BGColor := cbBGColor.Selected; MapTypeCtrl.Show := cbShowMapType.Checked; MapTypeCtrl.Position := TTransform.StrToPosition(cbMapTypePos.Text); MapTypeCtrl.Style := TTransform.StrToMapTypeControlStyle(cbMapTypeStyle.Text); MapTypeCtrl.MapTypeIds := []; if cbMapType.Checked[0] then MapTypeCtrl.MapTypeIds := MapTypeCtrl.MapTypeIds + [mtHYBRID]; if cbMapType.Checked[1] then MapTypeCtrl.MapTypeIds := MapTypeCtrl.MapTypeIds + [mtROADMAP]; if cbMapType.Checked[2] then MapTypeCtrl.MapTypeIds := MapTypeCtrl.MapTypeIds + [mtSATELLITE]; if cbMapType.Checked[3] then MapTypeCtrl.MapTypeIds := MapTypeCtrl.MapTypeIds + [mtTERRAIN]; OverviewMapCtrl.Show := cbShowOver.Checked; OverviewMapCtrl.Opened := cbOverOpened.Checked; PanCtrl.Show := cbShowPan.Checked; PanCtrl.Position := TTransform.StrToPosition(cbPanPos.Text); RotateCtrl.Show := cbShowRotate.Checked; RotateCtrl.Position := TTransform.StrToPosition(cbRoratePos.Text); ScaleCtrl.Show := cbShowScale.Checked; ScaleCtrl.Position := TTransform.StrToPosition(cbScalePos.Text); ScaleCtrl.Style := TTransform.StrToScaleControlStyle(cbScaleStyle.Text); StreetViewCtrl.Show := cbShowStreetView.Checked; StreetViewCtrl.Position := TTransform.StrToPosition(cbStreetViewPos.Text); ZoomCtrl.Show := cbShowZoom.Checked; ZoomCtrl.Position := TTransform.StrToPosition(cbZoomPos.Text); ZoomCtrl.Style := TTransform.StrToZoomControlStyle(cbZoomStyle.Text); end; // do map GMMap1.DoMap; end; procedure TGMInfoWinFrm.AddNewInfoWin; begin cbAutoOpen.Checked := True; cbCloseOtherBeforeOpen.Checked := False; cbDisableAutoPan.Checked := False; eMaxWidth.Text := '0'; eHeight.Text := '0'; eWidth.Text := '0'; eInfoWinLat.Text := '0'; eInfoWinLng.Text := '0'; mHTMLContent.Lines.Text := 'New InfoWindow'; lZIndex.Caption := ''; lbInfoWindows.ItemIndex := -1; end; procedure TGMInfoWinFrm.eIntervalChange(Sender: TObject); var Temp: Integer; begin if TryStrToInt(eInterval.Text, Temp) then GMMap1.IntervalEvents := Temp; end; procedure TGMInfoWinFrm.GMInfoWindow1CloseClick(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnCloseClick fired - Content: %s'; begin mEvents.Lines.Add(Format(Str, [TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMInfoWindow1CloseOtherBeforeOpenChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnCloseOtherBeforeOpenChange fired - Content: %s'; begin mEvents.Lines.Add(Format(Str, [TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMInfoWindow1DisableAutoPanChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnDisableAutoPanChange fired - Content: %s'; begin mEvents.Lines.Add(Format(Str, [TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMInfoWindow1HTMLContentChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnHTMLContentChange fired - Content: %s'; begin mEvents.Lines.Add(Format(Str, [TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMInfoWindow1MaxWidthChange(Sender: TObject; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnMaxWidthChange fired - Content: %s'; begin mEvents.Lines.Add(Format(Str, [TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMInfoWindow1PositionChange(Sender: TObject; LatLng: TLatLng; Index: Integer; LinkedComponent: TLinkedComponent); const Str = 'OnPositionChange fired - Lat: %s, Lng: %s - Content: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision), TInfoWindow(LinkedComponent).HTMLContent])); end; procedure TGMInfoWinFrm.GMMap1AfterPageLoaded(Sender: TObject; First: Boolean); begin bDoWeb.Enabled := True; if First then begin mEvents.Lines.Add('AfterPageLoaded fired - first page loaded'); DoMap; end else mEvents.Lines.Add('AfterPageLoaded fired - all tiles loaded'); end; procedure TGMInfoWinFrm.GMMap1BoundsChanged(Sender: TObject; NewBounds: TLatLngBounds); const Str = 'OnBoundChanged fired - SW.Lat: %s, SW.Lng: %s, NE.Lat: %s, NE.Lng: %s'; begin mEvents.Lines.Add(Format(Str, [ NewBounds.SW.LatToStr(GMMap1.Precision), NewBounds.SW.LngToStr(GMMap1.Precision), NewBounds.NE.LatToStr(GMMap1.Precision), NewBounds.NE.LngToStr(GMMap1.Precision) ])) end; procedure TGMInfoWinFrm.GMMap1CenterChanged(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnCenterChanged fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1Click(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnClick fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1DblClick(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnDblClick fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1Drag(Sender: TObject); begin mEvents.Lines.Add('OnDrag fired'); end; procedure TGMInfoWinFrm.GMMap1DragEnd(Sender: TObject); begin mEvents.Lines.Add('OnDragEnd fired'); end; procedure TGMInfoWinFrm.GMMap1DragStart(Sender: TObject); begin mEvents.Lines.Add('OnDragStart fired'); end; procedure TGMInfoWinFrm.GMMap1MapTypeIdChanged(Sender: TObject; NewMapTypeId: TMapTypeId); const Str = 'OnMapeTypeIdChanged fired - New MapTypeId: %s'; var Strg: string; begin Strg := TTransform.MapTypeIdToStr(NewMapTypeId); mEvents.Lines.Add(Format(Str, [Strg])); cbMapTypeMet.ItemIndex := cbMapTypeMet.Items.IndexOf(Strg); cbTypMap.ItemIndex := cbTypMap.Items.IndexOf(Strg); end; procedure TGMInfoWinFrm.GMMap1MouseMove(Sender: TObject; LatLng: TLatLng; X, Y: Double); begin lLatEvent.Caption := LatLng.LatToStr(GMMap1.Precision); lLngEvent.Caption := LatLng.LngToStr(GMMap1.Precision); end; procedure TGMInfoWinFrm.GMMap1MouseOut(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnMouseOut fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1MouseOver(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnMouseOver fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1RightClick(Sender: TObject; LatLng: TLatLng; X, Y: Double); const Str = 'OnRightClick fired - Lat: %s, Lng: %s'; begin mEvents.Lines.Add(Format(Str, [LatLng.LatToStr(GMMap1.Precision), LatLng.LngToStr(GMMap1.Precision)])); end; procedure TGMInfoWinFrm.GMMap1ZoomChanged(Sender: TObject; NewZoom: Integer); const Str = 'OnZoomChanged fired - New zoom: %d'; begin mEvents.Lines.Add(Format(Str, [NewZoom])); tbZoom.Position := NewZoom; tbZoomMet.Position := NewZoom; end; procedure TGMInfoWinFrm.lbInfoWindowsClick(Sender: TObject); begin if lbInfoWindows.ItemIndex = -1 then Exit; cbDisableAutoPan.Checked := GMInfoWindow1[lbInfoWindows.ItemIndex].DisableAutoPan; cbAutoOpen.Checked := GMInfoWindow1[lbInfoWindows.ItemIndex].AutoOpen; cbCloseOtherBeforeOpen.Checked := GMInfoWindow1[lbInfoWindows.ItemIndex].CloseOtherBeforeOpen; eMaxWidth.Text := IntToStr(GMInfoWindow1[lbInfoWindows.ItemIndex].MaxWidth); eHeight.Text := IntToStr(GMInfoWindow1[lbInfoWindows.ItemIndex].PixelOffset.Height); eWidth.Text := IntToStr(GMInfoWindow1[lbInfoWindows.ItemIndex].PixelOffset.Width); eInfoWinLng.Text := GMInfoWindow1[lbInfoWindows.ItemIndex].Position.LngToStr(GMMap1.Precision); eInfoWinLat.Text := GMInfoWindow1[lbInfoWindows.ItemIndex].Position.LatToStr(GMMap1.Precision); mHTMLContent.Lines.Text := GMInfoWindow1[lbInfoWindows.ItemIndex].HTMLContent; lZIndex.Caption := IntToStr(GMInfoWindow1[lbInfoWindows.ItemIndex].Index); end; procedure TGMInfoWinFrm.pOptionsChange(Sender: TObject); begin if pOptions.ActivePageIndex = 5 then AddNewInfoWin; end; procedure TGMInfoWinFrm.ePrecisionChange(Sender: TObject); begin GMMap1.Precision := ePrecision.Value; end; procedure TGMInfoWinFrm.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); begin StatusBar.Canvas.Font.Color := clBlue; Statusbar.Canvas.TextRect(Rect, Rect.Left, Rect.Top, Panel.Text); end; procedure TGMInfoWinFrm.StatusBar1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if GetStatusBarPanelXY(StatusBar1, X, Y) = 1 then StatusBar1.Cursor := crHandPoint else StatusBar1.Cursor := crDefault; end; procedure TGMInfoWinFrm.StatusBar1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (GetStatusBarPanelXY(StatusBar1, X, Y) = 1) and (Button = mbLeft) then ShellExecute(Handle, 'open', 'http://www.cadetill.com', nil, nil, SW_SHOW); end; end.
namespace RemObjects.Elements.System; {.$DEFINE DEBUG_UTF8} type { UTF8: 00000000-0000007F 1 7 0xxxxxxx 00000080-000007FF 2 11 110xxxxx 10xxxxxx 00000800-0000FFFF 3 16 1110xxxx 10xxxxxx 10xxxxxx 00010000-001FFFFF 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 00200000-03FFFFFF 5 26 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 04000000-7FFFFFFF 6 31 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx } TextConvert = static public class private {$IFDEF DEBUG_UTF8} class method DebugLog(InputString: String; CurPos: Integer; Len: Integer; Decoded : Char); begin var s := 'pos = '+CurPos.ToString+'; '+Len+'ch input: '+InputString.Substring(CurPos,Len)+' ; output = '+Decoded; //writeLn(s); end; {$ENDIF} class method MalformedError; begin {$IFDEF DEBUG_UTF8} writeln('malformed string is detected'); {$ELSE} raise new Exception('malformed string is detected'); {$ENDIF} end; class method BadUTF8Error; begin {$IFDEF DEBUG_UTF8} writeLn('bad UTF8 string is detected'); {$ELSE} raise new Exception('bad UTF8 string is detected'); {$ENDIF} end; class method BadStringError; begin {$IFDEF DEBUG_UTF8} writeLn('bad string is detected'); {$ELSE} raise new Exception('bad string is detected'); {$ENDIF} end; class method BadArray; begin {$IFDEF DEBUG_UTF8} writeLn('bad array length is detected'); {$ELSE} raise new Exception('bad array length is detected'); {$ENDIF} end; protected public class method StringToUTF8(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin if Value = nil then new ArgumentNullException('Value is nil'); if Value = '' then exit new array of Byte(0); var len := Value.Length; var arr:= new array of Byte(len*4 + iif(aGenerateBOM,3,0)); var pos := 0; var pos1 := 0; // write BOM if aGenerateBOM then begin arr[0] := $EF; arr[1] := $BB; arr[2] := $BF; pos1 := 3; end; while pos < len do begin var code := UInt32(Value[pos]); case code of 0..$7F: begin // 0xxxxxxx arr[pos1] := byte(code); inc(pos1); end; $80..$7FF: begin // 110xxxxx 10xxxxxx arr[pos1] := $C0 or (code shr 6); arr[pos1+1] := $80 or (code and $3F); inc(pos1,2); end; $800..$FFFF: begin //1110xxxx 10xxxxxx 10xxxxxx if (($D800 <= code) and (code <= $DBFF)) then begin if pos+1>=len then MalformedError; var code1 := UInt32(Value[pos+1]); if not (($DC00 <= code1) and (code1 <= $DFFF)) then MalformedError; //$10000..$1FFFFF, 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx code := $10000 + (code and $03FF) shl 10 + code1 and $03FF; arr[pos1] := $F0 or (code shr 18); arr[pos1+1] := $80 or ((code shr 12) and $3F); arr[pos1+2] := $80 or ((code shr 6) and $3F); arr[pos1+3] := $80 or (code and $3F); inc(pos1,4); inc(pos); end else begin arr[pos1] := $E0 or (code shr 12); arr[pos1+1] := $80 or ((code shr 6) and $3F); arr[pos1+2] := $80 or (code and $3F); inc(pos1,3); end; end; else BadStringError; end; inc(pos); end; var r := new array of Byte(pos1); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@r[0], @arr[0], pos1); exit r; end; class method StringToUTF16(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin exit StringToUTF16LE(Value, aGenerateBOM); end; class method StringToUTF16BE(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin if Value = nil then new ArgumentNullException('Value is nil'); if Value = '' then exit new array of Byte(0); var len := Value.Length; var arr := new array of Byte(len*2 + iif(aGenerateBOM, 2, 0)); var pos: Integer := 0; if aGenerateBOM then begin arr[0] := $FE; arr[1] := $FF; inc(pos,2); end; for i: Integer := 0 to len-1 do begin var ch := UInt16(Value[i]); arr[pos] := ch shr 8; arr[pos+1] := ch and $FF; inc(pos,2); end; exit arr; end; class method StringToUTF16LE(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin if Value = nil then new ArgumentNullException('Value is nil'); if Value = '' then exit new array of Byte(0); var len := Value.Length; var arr := new array of Byte(len*2 + iif(aGenerateBOM, 2, 0)); var pos: Integer := 0; if aGenerateBOM then begin arr[0] := $FE; arr[1] := $FF; inc(pos,2); end; for i: Integer := 0 to len-1 do begin var ch := UInt16(Value[i]); arr[pos] := ch and $FF; arr[pos+1] := ch shr 8; inc(pos,2); end; exit arr; end; class method StringToUTF32(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin exit StringToUTF32LE(Value,aGenerateBOM); end; class method StringToUTF32BE(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin if Value = nil then new ArgumentNullException('Value is nil'); if Value = '' then exit new array of Byte(0); var len := Value.Length; var arr := new array of Byte(len*4+iif(aGenerateBOM, 4, 0)); var pos: Integer := 0; var pos1:Integer := 0; if aGenerateBOM then begin arr[0]:= $00; arr[1]:= $00; arr[2]:= $FE; arr[3]:= $FF; inc(pos1,4); end; while pos < len do begin var code := UInt32(Value[pos]); if (($D800 <= code) and (code <= $DBFF)) then begin if pos+1>=len then MalformedError; var code1 := UInt32(Value[pos+1]); if not (($DC00 <= code1) and (code1 <= $DFFF)) then MalformedError; code := $10000 + (code and $03FF) shl 10 + code1 and $03FF; inc(pos); end; arr[pos1] := (code shr 24) and $FF; arr[pos1+1] := (code shr 16) and $FF; arr[pos1+2] := (code shr 8) and $FF; arr[pos1+3] := code and $FF; inc(pos1,4); inc(pos); end; var r := new array of Byte(pos1); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@r[0], @arr[0], pos1); exit r; end; class method StringToUTF32LE(Value: String; aGenerateBOM: Boolean := False): array of Byte; begin if Value = nil then new ArgumentNullException('Value is nil'); if Value = '' then exit new array of Byte(0); var len := Value.Length; var arr := new array of Byte(len*4+iif(aGenerateBOM, 4, 0)); var pos: Integer := 0; var pos1:Integer := 0; if aGenerateBOM then begin arr[0]:= $FF; arr[1]:= $FE; arr[2]:= $00; arr[3]:= $00; inc(pos1,4); end; while pos < len do begin var code := UInt32(Value[pos]); if (($D800 <= code) and (code <= $DBFF)) then begin if pos+1>=len then MalformedError; var code1 := UInt32(Value[pos+1]); if not (($DC00 <= code1) and (code1 <= $DFFF)) then MalformedError; code := $10000 + (code and $03FF) shl 10 + code1 and $03FF; inc(pos); end; arr[pos1] := code and $FF; arr[pos1+1] := (code shr 8) and $FF; arr[pos1+2] := (code shr 16) and $FF; arr[pos1+3] := (code shr 24) and $FF; inc(pos1,4); inc(pos); end; var r := new array of Byte(pos1); {$IFDEF WINDOWS}ExternalCalls.{$ELSEIF POSIX}rtl.{$ELSE}{$ERROR}{$ENDIF}memcpy(@r[0], @arr[0], pos1); exit r; end; class method UTF8ToString(Value: array of Byte): String; begin if Value = nil then new ArgumentNullException('Value is nil'); var len := length(Value); if len = 0 then exit ''; var str:= new StringBuilder(len); var pos:Integer := 0; // skip BOM if len>2 then begin if (Value[0] = $EF) and (Value[1] = $BB) and (Value[2] = $BF) then pos := 3; end; while pos < len do begin var ch := Value[pos]; {$REGION 4 bytes char} if ch and $F0 = $F0 then begin // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if pos+4 > len then BadUTF8Error; var code := ((((( UInt32(ch and $7) shl 6 + (UInt32(Value[pos+1]) and $3F)) shl 6)+ (UInt32(Value[pos+2]) and $3F)) shl 6)+ (UInt32(Value[pos+3]) and $3F)); if (code < $10000) or (code>$1FFFFF) then MalformedError; {$IFDEF DEBUG_UTF8} DebugLog(Value,pos,4,Char(code)); {$ENDIF} var code1 := code - $10000; str.Append(Char($D800 or (code1 shr 10))); str.Append(Char($DC00 or (code1 and $3FF))); inc(pos,4); end {$ENDREGION} {$REGION 3 bytes char} else if (ch and $E0) = $E0 then begin //1110xxxx 10xxxxxx 10xxxxxx if pos+3 > len then BadUTF8Error; var code := (( UInt32(ch and $F) shl 6 + (UInt32(Value[pos+1]) and $3F)) shl 6)+ (UInt32(Value[pos+2]) and $3F); if (code < $800) or (code > $FFFF) then MalformedError; {$IFDEF DEBUG_UTF8} DebugLog(Value,pos,3,Char(code)); {$ENDIF} str.Append(Char(code)); inc(pos,3); end {$ENDREGION} {$REGION 2 bytes char} else if (ch and $C0) = $C0 then begin // 110xxxxx 10xxxxxx if pos+2 > len then BadUTF8Error; var code := UInt32(ch and $1F) shl 6 + (UInt32(Value[pos+1]) and $3F); if (code < $80) or (code >$7FF) then MalformedError; {$IFDEF DEBUG_UTF8} DebugLog(Value,pos,2,Char(code)); {$ENDIF} str.Append(Char(code)); inc(pos,2); end {$ENDREGION} {$REGION 1 byte char} else if (ch or $7f) = $7f then begin // 0xxxxxxx var code := ch; if (code < $0) or (code > $7F) then MalformedError; {$IFDEF DEBUG_UTF8} DebugLog(Value,pos,1,Char(code)); {$ENDIF} str.Append(Char(code)); inc(pos,1); end {$ENDREGION} else begin BadUTF8Error; inc(pos); end; end; exit str.ToString; end; class method UTF16ToString(Value: array of Byte): String; begin exit UTF16LEToString(Value); end; class method UTF16BEToString(Value: array of Byte): String; begin if Value = nil then new ArgumentNullException('Value is nil'); var len := length(Value); if len = 0 then exit ''; var len2 := len/2; if len - len2*2 = 1 then BadArray; var str := new StringBuilder(len2); var start :=0; if len>1 then begin if (Value[0] = $FE) and (Value[1] = $FF) then inc(start,2); end; for i: Integer :=start to len2 - 1 do str.Append(Char(Value[i*2] shl 8 + Value[i*2+1])); exit str.ToString; end; class method UTF16LEToString(Value: array of Byte): String; begin if Value = nil then new ArgumentNullException('Value is nil'); var len := length(Value); if len = 0 then exit ''; var len2 := len/2; if len - len2*2 = 1 then BadArray; var str := new StringBuilder(len2); var start :=0; if len>1 then begin if (Value[0] = $FF) and (Value[1] = $FE) then inc(start,2); end; for i: Integer := start to len2 - 1 do str.Append(Char(Value[i*2] + Value[i*2+1] shl 8)); exit str.ToString; end; class method UTF32ToString(Value: array of Byte): String; begin exit UTF32LEToString(Value); end; class method UTF32BEToString(Value: array of Byte): String; begin if Value = nil then new ArgumentNullException('Value is nil'); var len := length(Value); if len - (len /4)*4 > 0 then BadArray; var str:= new StringBuilder; var idx := 0; // ignore BOM if len>3 then begin if (Value[0]=$00) and (Value[1]=$00) and (Value[2]=$FE) and (Value[3]=$FF) then inc(idx,4) ; end; while idx < len do begin var code:UInt32 := Value[idx] shl 24 + Value[idx+1] shl 16 + Value[idx+2] shl 8 + Value[idx+3] ; if code < $10000 then begin //$0000-$FFFF str.Append(Char(code)); end else if (code <=$10FFFF) then begin //00010000-001FFFFF var code1 := code - $10000; str.Append(Char($DC00 or (code1 and $3FF))); str.Append(Char($D800 or (code1 shr 10))); end else begin MalformedError; end; inc(idx, 4); end; exit str.ToString; end; class method UTF32LEToString(Value: array of Byte): String; begin if Value = nil then new ArgumentNullException('Value is nil'); var len := length(Value); if len - (len /4)*4 > 0 then BadArray; var str:= new StringBuilder; var idx := 0; // ignore BOM if len>3 then begin if (Value[0]=$FF) and (Value[1]=$FE) and (Value[2]=$00) and (Value[3]=$00) then inc(idx,4) ; end; while idx < len do begin var code:UInt32 := Value[idx] + Value[idx+1] shl 8 + Value[idx+2] shl 16 + Value[idx+3] shl 24; if code < $10000 then begin //$0000-$FFFF str.Append(Char(code)); end else if (code <=$10FFFF) then begin //00010000-001FFFFF var code1 := code - $10000; str.Append(Char($D800 or (code1 shr 10))); str.Append(Char($DC00 or (code1 and $3FF))); end else begin MalformedError; end; inc(idx, 4); end; exit str.ToString; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ToolWin, SMSummInfo; type TfrmMain = class(TForm) OpenDialog: TOpenDialog; tbMain: TToolBar; btnOpen: TToolButton; ImageList: TImageList; btnSeparator1: TToolButton; btnClose: TToolButton; btnAbout: TToolButton; btnSeparator2: TToolButton; lvSummary: TListView; SMSummaryInformation: TSMSummaryInformation; procedure btnOpenClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.DFM} procedure TfrmMain.btnOpenClick(Sender: TObject); begin if OpenDialog.Execute then begin SMSummaryInformation.LoadFromFile(OpenDialog.FileName); lvSummary.Items.Clear; with lvSummary.Items.Add do begin Caption := 'FileName'; SubItems.Add(OpenDialog.FileName) end; with lvSummary.Items.Add do begin Caption := 'Title'; SubItems.Add(SMSummaryInformation.Title) end; with lvSummary.Items.Add do begin Caption := 'Subject'; SubItems.Add(SMSummaryInformation.Subject) end; with lvSummary.Items.Add do begin Caption := 'Author'; SubItems.Add(SMSummaryInformation.Author) end; with lvSummary.Items.Add do begin Caption := 'Keywords'; SubItems.Add(SMSummaryInformation.Keywords) end; with lvSummary.Items.Add do begin Caption := 'Comments'; SubItems.Add(SMSummaryInformation.Comments) end; with lvSummary.Items.Add do begin Caption := 'Template'; SubItems.Add(SMSummaryInformation.Template) end; with lvSummary.Items.Add do begin Caption := 'LastAuthor'; SubItems.Add(SMSummaryInformation.LastAuthor) end; with lvSummary.Items.Add do begin Caption := 'Created'; SubItems.Add(DateToStr(SMSummaryInformation.Created)) end; with lvSummary.Items.Add do begin Caption := 'LastSaved'; SubItems.Add(DateToStr(SMSummaryInformation.LastSaved)) end; with lvSummary.Items.Add do begin Caption := 'LastPrinted'; SubItems.Add(DateToStr(SMSummaryInformation.LastPrinted)) end; with lvSummary.Items.Add do begin Caption := 'RevNumber'; SubItems.Add(SMSummaryInformation.RevNumber) end; with lvSummary.Items.Add do begin Caption := 'EditTime (min)'; SubItems.Add(IntToStr(SMSummaryInformation.EditTime)) end; with lvSummary.Items.Add do begin Caption := 'PageCount'; SubItems.Add(IntToStr(SMSummaryInformation.PageCount)) end; with lvSummary.Items.Add do begin Caption := 'CharCount'; SubItems.Add(IntToStr(SMSummaryInformation.CharCount)) end; with lvSummary.Items.Add do begin Caption := 'WordCount'; SubItems.Add(IntToStr(SMSummaryInformation.WordCount)) end; end; end; procedure TfrmMain.btnCloseClick(Sender: TObject); begin Close end; procedure TfrmMain.btnAboutClick(Sender: TObject); begin Application.MessageBox('TSMSummaryInformation component, written by Scalabium Software'#13#10 + ''#13#10 + 'Allow to read summary information for any compound file/stream/storage'#13#10 + 'Direct and native document processing allow to extract an info very-very fast'#13#10 + ''#13#10 + 'For additional tech information or support ask Mike Shkolnik:' + #13#10 + 'http://www.scalabium.com, e-mail: mshkolnik@scalabium.com' + #13#10, 'About SMComponent library', MB_OK); end; end.
unit Test_data_stream; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TfrmTestDataStream = class(TForm) btnStartStop: TBitBtn; btnExit: TBitBtn; edDelimeter: TEdit; Label1: TLabel; edSeriesCount: TEdit; Label2: TLabel; Timer1: TTimer; edInterval: TEdit; Label3: TLabel; Label4: TLabel; procedure btnExitClick(Sender: TObject); procedure btnStartStopClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private series_count : integer; public { Public declarations } end; var frmTestDataStream: TfrmTestDataStream; implementation uses Main; {$R *.dfm} procedure TfrmTestDataStream.btnExitClick(Sender: TObject); begin Timer1.Enabled := False; Free; end; procedure TfrmTestDataStream.btnStartStopClick(Sender: TObject); begin if Timer1.Enabled then begin Timer1.Enabled := False; btnStartStop.Caption := 'Start'; end else begin try Timer1.Interval := StrToInt(edInterval.Text); finally edInterval.SetFocus; end; try series_count := StrToInt(edSeriesCount.Text); finally edSeriesCount.SetFocus; end; frmMain.PrepareRecv; btnStartStop.Caption := 'Stop'; Timer1.Enabled := True; end; end; procedure TfrmTestDataStream.Timer1Timer(Sender: TObject); var str: ShortString; i: integer; buf: array[0..128] of char; begin str := ''; for i := 0 to series_count - 1 do begin str := str + format('%d', [Random(100)]); if i<>series_count - 1 then str := str + edDelimeter.Text; end; str := str + #13#10; Move(str[1],buf, Length(str)); frmMain.Data_packetPacket(Self, @buf[0], Length(str)); end; procedure TfrmTestDataStream.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
// ------------------------------------------------------------------------------- // Descrição: Escreva um programa pascal que determine a área do circulo dado // pela formula: Area = MeuPi * Raio * Raio onde MeuPi é uma constante // com valor 3.14159 // ------------------------------------------------------------------------------- // Autor : Fernando Gomes // Data : 22/08/2021 // ------------------------------------------------------------------------------- Program Area_Circulo ; const MeuPi = 3.14159; var raio, Area: real; Begin write('Digite o raio do cículo: '); readln(raio); Area := MeuPi * raio * raio; write('A Área do cículo é ',Area:6:2); End.
unit uGetHandlesThread; interface uses Classes, Windows, SysUtils, PSApi, Math, SyncObjs, ShellApi, Graphics, TLHelp32, Dialogs; function ConvertPhysicalNameToVirtualPathName(const PhysicalName: string): string; function GetHDDDevicesWithDOSPath: TStringList; function GetFileFolderTypeNumber: Byte; type TGetHandlesThread = class(TThread) private FVol: Char; { Private declarations } protected procedure Execute; override; public isJobDone: Boolean; mEvent: TEvent; constructor Create(const Vol: Char; const DoCleanup: Boolean = False); destructor Destroy; override; end; const SystemHandleInformation = $10; FileNameInformation = 9; FileAccessInformation = 8; ObjectNameInformation = 1; DefaulBUFFERSIZE = $100000; STATUS_SUCCESS = $00000000; STATUS_TIMEOUT = $00000102; var hTest: THandle; FnCPU, FhCPU: SmallInt; FprocessID: DWORD; FhProcess: THandle; type TStrObj = class Value: string; end; implementation uses MainForm; function GetFileNameHandleThr(Data: Pointer): DWORD; stdcall; var dwReturn: DWORD; FileNameInfo: FILE_NAME_INFORMATION; ObjectNameInfo: OBJECT_NAME_INFORMATION; IoStatusBlock: IO_STATUS_BLOCK; pThreadParam: TGetFileNameThreadParam; begin ZeroMemory(@FileNameInfo, SizeOf(FILE_NAME_INFORMATION)); try pThreadParam := PGetFileNameThreadParam(Data)^; Result := STATUS_SUCCESS; except Result := STATUS_TIMEOUT; end; if Result = STATUS_SUCCESS then try Result := NtQueryInformationFile(pThreadParam.hFile, @IoStatusBlock, @FileNameInfo, MAX_PATH * 2, FileNameInformation); except Result := STATUS_TIMEOUT; end; if Result = STATUS_SUCCESS then begin try Result := NtQueryObject(pThreadParam.hFile, ObjectNameInformation, @ObjectNameInfo, MAX_PATH * 2, @dwReturn); except Result := STATUS_TIMEOUT; end; if Result = STATUS_SUCCESS then begin pThreadParam.Result := Result; {$IFDEF WIN32} Move(ObjectNameInfo.Name[0], pThreadParam.FileName[0], Min(ObjectNameInfo.Length, MAX_PATH) * SizeOf(WideChar)); {$ENDIF} {$IFDEF WIN64} Move(ObjectNameInfo.Name[(ObjectNameInfo.MaximumLength - ObjectNameInfo.Length) * SizeOf(WideChar)], pThreadParam.FileName[0], Min(ObjectNameInfo.Length, MAX_PATH) * SizeOf(WideChar)); {$ENDIF} end else begin pThreadParam.Result := STATUS_SUCCESS; Result := STATUS_SUCCESS; Move(FileNameInfo.FileName[0], pThreadParam.FileName[0], Min(IoStatusBlock.Information, MAX_PATH) * SizeOf(WideChar)); end; end; if Result = STATUS_SUCCESS then try PGetFileNameThreadParam(Data)^ := pThreadParam; Result := STATUS_SUCCESS; except Result := STATUS_TIMEOUT; end; ExitThread(Result); end; type aTHandle = array of THandle; aString = array of string; aDWORD = array of DWORD; function GetFileNameHandle(hFiles: aTHandle): aString; var i: Integer; lpExitCode: DWORD; pThreadParams: array of TGetFileNameThreadParam; hThreads: array of THandle; begin SetLength(hThreads, FnCPU); SetLength(pThreadParams, FnCPU); SetLength(Result, FnCPU); for i := 0 to FnCPU - 1 do begin Result[i] := ''; ZeroMemory(@pThreadParams[i], SizeOf(TGetFileNameThreadParam)); pThreadParams[i].hFile := hFiles[i]; try hThreads[i] := CreateThread(nil, 0, @GetFileNameHandleThr, @pThreadParams[i], 0, PDWORD(nil)^); except hThreads[i] := 0; end; end; for i := 0 to FnCPU - 1 do if hThreads[i] <> 0 then try SetThreadPriority(hThreads[i], THREAD_PRIORITY_HIGHEST); case WaitForSingleObject(hThreads[i], 100) of WAIT_OBJECT_0: begin GetExitCodeThread(hThreads[i], lpExitCode); if lpExitCode = STATUS_SUCCESS then Result[i] := pThreadParams[i].FileName; end; WAIT_TIMEOUT: TerminateThread(hThreads[i], 0); end; finally CloseHandle(hThreads[i]); end; end; function GetHDDDevicesWithDOSPath: TStringList; var i: integer; Root: string; Device: string; Buffer: string; strObj: TStrObj; begin SetLength(Buffer, 1000); Result := TStringList.Create; Result.CaseSensitive := False; Result.Sorted := False; Result.Duplicates := dupIgnore; Result.BeginUpdate; for i := Ord('a') to Ord('z') do begin Root := Char(i - 32) + ':'; if (QueryDosDevice(PChar(Root), PChar(Buffer), 1000) <> 0) then begin Device := PChar(Buffer); strObj := TStrObj.Create; strObj.Value := Root; Result.AddObject(Device, strObj); end; end; Result.EndUpdate; end; function ConvertPhysicalNameToVirtualPathName(const PhysicalName: string): string; var i, Index: Integer; Device: string; begin i := Length(PhysicalName); while i > 1 do begin if PhysicalName[i] = '\' then begin Device := Copy(PhysicalName, 1, i - 1); Index := DevPathNameMap.IndexOf(Device); if Index > -1 then begin Result := TStrObj(DevPathNameMap.Objects[Index]).Value + Copy(PhysicalName, i, Length(PhysicalName) - i + 1); Exit; end; end; Dec(i); end; Result := PhysicalName; end; {function GetParentProcessId(ProcessID: DWORD): DWORD; var Snapshot: THandle; Entry: TProcessEntry32; B: Boolean; begin Result := 0; // 0 means not found Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); if Snapshot <> 0 then begin FillChar(Entry, SizeOf(Entry), 0); Entry.dwSize := SizeOf(Entry); B := Process32First(Snapshot, Entry); while B do begin if Entry.th32ProcessID = ProcessID then begin Result := Entry.th32ParentProcessID; Break; end; B := Process32Next(Snapshot, Entry); end; CloseHandle(Snapshot); end; end;} function GetEXEVersionProductName(const FileName: string): string; type PLandCodepage = ^TLandCodepage; TLandCodepage = record wLanguage, wCodePage: word; end; var dummy, len: cardinal; buf, pntr: pointer; lang: string; begin try len := GetFileVersionInfoSize(PChar(FileName), dummy); except len := 0; end; if len = 0 then Exit; GetMem(buf, len); try try if not GetFileVersionInfo(PChar(FileName), 0, len, buf) then Exit; if not VerQueryValue(buf, '\VarFileInfo\Translation\', pntr, len) then Exit; lang := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage, PLandCodepage(pntr)^.wCodePage]); if VerQueryValue(buf, PChar('\StringFileInfo\' + lang + '\ProductName'), pntr, len) { and (@len <> nil)} then result := string(PChar(pntr)); except end; finally FreeMem(buf); end; end; function SetDebugPrivilege: Boolean; var TokenHandle: THandle; TokenPrivileges: TTokenPrivileges; isOpened: Boolean; begin Result := false; try isOpened := OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle); except; isOpened := False; end; if isOpened then begin if LookupPrivilegeValue(nil, PChar('SeDebugPrivilege'), TokenPrivileges.Privileges[0].Luid) then begin TokenPrivileges.PrivilegeCount := 1; TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; try Result := AdjustTokenPrivileges(TokenHandle, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, PDWord(nil)^); except Result := False; end; end; end; end; procedure EnumerateOpenDevicesOnVolume(const v: Char); var Root, Device, Buffer: string; FileNames: aString; hProcesses: aTHandle; hFiles, hOrgFiles: aTHandle; ProcessIDs, aAccess: aDWORD; ResultLength, aBufferSize: DWORD; aIndex, ld, ldc, le, nAddPos, pCPU: Integer; pHandleInfo: PSYSTEM_HANDLE_INFORMATION; hInfoHandles: NT_STATUS; lpszProcess: PWideChar; idDuplicated: Boolean; hIcon: THandle; nIconId: DWORD; iconFound: Boolean; bIsFolder: Boolean; procedure AddToFound; var j: Integer; begin for j := 0 to FhCPU do if Length(FileNames[j]) > ld then if CompareMem(@Filenames[j][1], @Device[1], ldc) then begin FileNames[j] := UpperCase(v) + ':' + Copy(FileNames[j], ld + 1, Length(FileNames[j]) - ld + 1); if DirectoryExists(FileNames[j]) then bIsFolder := True else if FileExists(FileNames[j]) then bIsFolder := False else Continue; nAddPos := 0; while nAddPos <= High(OpenHandlesInfo) do begin if OpenHandlesInfo[nAddPos].ProcessID = ProcessIDs[j] then Break; Inc(nAddPos); end; lpszProcess := AllocMem(MAX_PATH); if nAddPos > High(OpenHandlesInfo) then begin iconFound := False; SetLength(OpenHandlesInfo, Length(OpenHandlesInfo) + 1); try if GetProcessImageFileName(hProcesses[j], lpszProcess, 2 * MAX_PATH) <> 0 then begin OpenHandlesInfo[High(OpenHandlesInfo)].Process := ExtractFileName(lpszProcess); le := Length(ExtractFileExt(OpenHandlesInfo[High(OpenHandlesInfo)].Process)); OpenHandlesInfo[High(OpenHandlesInfo)].Process := Copy(OpenHandlesInfo[High(OpenHandlesInfo)].Process, 1, Length(OpenHandlesInfo[High(OpenHandlesInfo)].Process) - le); OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath := ConvertPhysicalNameToVirtualPathName(string(lpszProcess)); OpenHandlesInfo[High(OpenHandlesInfo)].ProcessID := ProcessIDs[j]; OpenHandlesInfo[High(OpenHandlesInfo)].ProductName := GetEXEVersionProductName(OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath); if OpenHandlesInfo[High(OpenHandlesInfo)].ProductName = '' then OpenHandlesInfo[High(OpenHandlesInfo)].ProductName := OpenHandlesInfo[High(OpenHandlesInfo)].Process; OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon := TIcon.Create; iconFound := False; case SystemIconSize of -2147483647..18: begin if PrivateExtractIcons(PWideChar(OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath), 0, 16, 16, @hIcon, @nIconId, 1, LR_LOADFROMFILE) <> 0 then begin OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon.Handle := hIcon; iconFound := True; end; end; 19..22: begin if PrivateExtractIcons(PWideChar(OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath), 0, 20, 20, @hIcon, @nIconId, 1, LR_LOADFROMFILE) <> 0 then begin OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon.Handle := hIcon; iconFound := True; end; end; 23..2147483647: begin if PrivateExtractIcons(PWideChar(OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath), 0, 24, 24, @hIcon, @nIconId, 1, LR_LOADFROMFILE) <> 0 then begin OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon.Handle := hIcon; iconFound := True; end; end; end; if not iconFound then begin OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon.Free; OpenHandlesInfo[High(OpenHandlesInfo)].ProcessIcon := nil; end; end else begin OpenHandlesInfo[High(OpenHandlesInfo)].Process := 'System'; OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath := ''; OpenHandlesInfo[High(OpenHandlesInfo)].ProductName := 'System'; end; except OpenHandlesInfo[High(OpenHandlesInfo)].Process := 'System'; OpenHandlesInfo[High(OpenHandlesInfo)].ProcessFullPath := ''; OpenHandlesInfo[High(OpenHandlesInfo)].ProductName := 'System'; end; SetLength(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData, 0); end; SetLength(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData, Length(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData) + 1); OpenHandlesInfo[High(OpenHandlesInfo)].FilesData[High(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData)].FileName := FileNames[j]; OpenHandlesInfo[High(OpenHandlesInfo)].FilesData[High(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData)].FileHandle := hOrgFiles[j]; OpenHandlesInfo[High(OpenHandlesInfo)].FilesData[High(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData)].AccessType := aAccess[j]; OpenHandlesInfo[High(OpenHandlesInfo)].FilesData[High(OpenHandlesInfo[High(OpenHandlesInfo)].FilesData)].isFolder := bIsFolder; OpenHandlesInfo[High(OpenHandlesInfo)].Delete := False; FreeMem(lpszProcess); end; end; var j: Integer; CurProcessID: DWORD; hCurProcess: THandle; //dt: Cardinal; begin //dt := Gettickcount; SetLength(OpenHandlesInfo, 0); SetDebugPrivilege; SetLength(Buffer, 1000); Root := v + ':'; if (QueryDosDevice(PChar(Root), PChar(Buffer), 1000) <> 0) then Device := PChar(Buffer) else Exit; ld := Length(Device); ldc := 2 * ld; AbufferSize := DefaulBUFFERSIZE; pHandleInfo := AllocMem(AbufferSize); try hInfoHandles := NTQuerySystemInformation(DWORD(SystemHandleInformation), pHandleInfo, AbufferSize, @ResultLength); except hInfoHandles := STATUS_TIMEOUT; end; if hInfoHandles = STATUS_SUCCESS then begin if (FprocessID <> 0) and (FhProcess <> 0) then begin for aIndex := 0 to pHandleInfo^.uCount - 1 do if pHandleInfo.Handles[aIndex].ObjectType = nObjectType then //Files and folders if pHandleInfo.Handles[aIndex].uIdProcess = FprocessID then begin try DuplicateHandle(FhProcess, pHandleInfo.Handles[aIndex].Handle, 0, nil, 0, False, DUPLICATE_CLOSE_SOURCE); except end; end; try TerminateProcess(FhProcess, 0); except end; FreeMem(pHandleInfo); Exit; end; //Aligned parts pCPU := 0; SetLength(FileNames, FnCPU); SetLength(hFiles, FnCPU); SetLength(hOrgFiles, FnCPU); SetLength(hProcesses, FnCPU); SetLength(ProcessIDs, FnCPU); SetLength(aAccess, FnCPU); CurProcessID := GetCurrentProcessID; hCurProcess := GetCurrentProcess(); for aIndex := 0 to pHandleInfo^.uCount - 1 do if pHandleInfo.Handles[aIndex].ObjectType = nObjectType then //Files and folders if pHandleInfo.Handles[aIndex].uIdProcess <> CurProcessID then begin ProcessIDs[pCPU] := pHandleInfo.Handles[aIndex].uIdProcess; hOrgFiles[pCPU] := pHandleInfo.Handles[aIndex].Handle; aAccess[pCPU] := pHandleInfo.Handles[aIndex].GrantedAccess; try hProcesses[pCPU] := OpenProcess(PROCESS_DUP_HANDLE or PROCESS_QUERY_INFORMATION, FALSE, pHandleInfo.Handles[aIndex].uIdProcess); except hProcesses[pCPU] := 0; end; if hProcesses[pCPU] <> 0 then begin hFiles[pCPU] := 0; LastError := 0; try idDuplicated := DuplicateHandle(hProcesses[pCPU], pHandleInfo.Handles[aIndex].Handle, hCurProcess, @hFiles[pCPU], 0, False, DUPLICATE_SAME_ACCESS); LastError := GetLastError; except idDuplicated := False; end; if idDuplicated then begin if pCPU = FhCPU then begin FileNames := GetFileNameHandle(hFiles); for j := 0 to FhCPU do begin AddToFound; CloseHandle(hProcesses[j]); CloseHandle(hFiles[j]); end; pCPU := 0; end else Inc(pCPU); end else CloseHandle(hProcesses[pCPU]); end; end; if pCPU > 0 then begin //Unaligned part FnCPU := pCPU; Dec(pCPU); FhCPU := pCPU; SetLength(FileNames, FnCPU); SetLength(hFiles, FnCPU); SetLength(hOrgFiles, FnCPU); SetLength(hProcesses, FnCPU); SetLength(ProcessIDs, FnCPU); SetLength(aAccess, FnCPU); FileNames := GetFileNameHandle(hFiles); for j := 0 to FhCPU do begin AddToFound; CloseHandle(hProcesses[j]); CloseHandle(hFiles[j]); end; end; end; FreeMem(pHandleInfo); //dt := Gettickcount - dt; //messagebox(0, pchar(inttostr(dt)), '', mb_ok); end; function GetFileFolderTypeNumber: Byte; var hGetType: THandle; pHandleInfo: PSYSTEM_HANDLE_INFORMATION; resInfoHandles: NT_STATUS; CurProcessID, ResultLength, aBufferSize: DWORD; aIndex: Integer; begin Result := 0; try hGetType := CreateFile(PChar('Nul'), GENERIC_READ, 0, nil, CREATE_NEW, 0, 0); except hGetType := INVALID_HANDLE_VALUE; end; if hGetType <> INVALID_HANDLE_VALUE then try AbufferSize := DefaulBUFFERSIZE; pHandleInfo := AllocMem(AbufferSize); try resInfoHandles := NTQuerySystemInformation(DWORD(SystemHandleInformation), pHandleInfo, AbufferSize, @ResultLength); except resInfoHandles := STATUS_TIMEOUT; end; if resInfoHandles = STATUS_SUCCESS then begin CurProcessID := GetCurrentProcessID; for aIndex := 0 to pHandleInfo^.uCount - 1 do begin if pHandleInfo.Handles[aIndex].uIdProcess = CurProcessID then if pHandleInfo.Handles[aIndex].Handle = hGetType then begin Result := pHandleInfo.Handles[aIndex].ObjectType; Break; end; end; end; FreeMem(pHandleInfo); finally CloseHandle(hGetType); end; if Result = 0 then case TOSVersion.Major of 5: if TOSVersion.Minor = 0 then Result := 26 //2000 else Result := 28; //XP 6: case TOSVersion.Minor of 0: Result := 25; //Vista 1: Result := 28; //7 2: Result := 31; //8 3: Result := 30; //8.1 end; 10: Result := 35; //10 end; end; constructor TGetHandlesThread.Create(const Vol: Char; const DoCleanup: Boolean = False); begin if not DoCleanup then begin FprocessID := 0; FhProcess := 0; end; inherited Create(False); FnCPU := NumberOfProcessors; FhCPU := NumberOfProcessors - 1; mEvent := TEvent.Create(nil, True, False, ''); FVol := Vol; isJobDone := False; Priority := tpHighest; end; { TGetHandlesThread.Create } destructor TGetHandlesThread.Destroy; begin mEvent.Free; mEvent := nil; end; procedure TGetHandlesThread.Execute; begin try EnumerateOpenDevicesOnVolume(FVol); finally isJobDone := True; end; end; { TGetHandlesThread.Execute } end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC PostgreSQL API } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.PGCli; interface uses FireDAC.Stan.Intf; {----------------------------------------------------------------------------} { POSTGRES_EXT.H } {----------------------------------------------------------------------------} type Oid = Cardinal; POid = ^Oid; const InvalidOid = 0; // error fields PG_DIAG_SEVERITY = Ord('S'); PG_DIAG_SQLSTATE = Ord('C'); PG_DIAG_MESSAGE_PRIMARY = Ord('M'); PG_DIAG_MESSAGE_DETAIL = Ord('D'); PG_DIAG_MESSAGE_HINT = Ord('H'); PG_DIAG_STATEMENT_POSITION = Ord('P'); PG_DIAG_INTERNAL_POSITION = Ord('p'); PG_DIAG_INTERNAL_QUERY = Ord('q'); PG_DIAG_CONTEXT = Ord('W'); PG_DIAG_SCHEMA_NAME = Ord('s'); PG_DIAG_TABLE_NAME = Ord('t'); PG_DIAG_COLUMN_NAME = Ord('c'); PG_DIAG_DATATYPE_NAME = Ord('d'); PG_DIAG_CONSTRAINT_NAME = Ord('n'); PG_DIAG_SOURCE_FILE = Ord('F'); PG_DIAG_SOURCE_LINE = Ord('L'); PG_DIAG_SOURCE_FUNCTION = Ord('R'); {----------------------------------------------------------------------------} { LIBPQ-FE.H } {----------------------------------------------------------------------------} // Option flags for PQcopyResult PG_COPYRES_ATTRS = $01; PG_COPYRES_TUPLES = $02; // Implies PG_COPYRES_ATTRS PG_COPYRES_EVENTS = $04; PG_COPYRES_NOTICEHOOKS = $08; // ConnStatusType CONNECTION_OK = 0; CONNECTION_BAD = 1; // Non-blocking mode only below here CONNECTION_STARTED = 2; // Waiting for connection to be made. CONNECTION_MADE = 3; // Connection OK; waiting to send. CONNECTION_AWAITING_RESPONSE = 4; // Waiting for a response from the postmaster CONNECTION_AUTH_OK = 5; // Received authentication; waiting for backend startup. CONNECTION_SETENV = 6; // Negotiating environment. CONNECTION_SSL_STARTUP = 7; // Negotiating SSL. CONNECTION_NEEDED = 8; // Internal state: connect() needed // PostgresPollingStatusType PGRES_POLLING_FAILED = 0; PGRES_POLLING_READING = 1; // These two indicate that one may PGRES_POLLING_WRITING = 2; // use select before polling again. PGRES_POLLING_OK = 3; PGRES_POLLING_ACTIVE = 4; // unused; keep for awhile for backwards compatibility // ExecStatusType PGRES_EMPTY_QUERY = 0; // empty query string was executed PGRES_COMMAND_OK = 1; // a query command that doesn't return // anything was executed properly by the // backend PGRES_TUPLES_OK = 2; // a query command that returns tuples was // executed properly by the backend, PGresult // contains the result tuples PGRES_COPY_OUT = 3; // Copy Out data transfer in progress PGRES_COPY_IN = 4; // Copy In data transfer in progress PGRES_BAD_RESPONSE = 5; // an unexpected response was recv'd from the backend PGRES_NONFATAL_ERROR = 6; // notice or warning message PGRES_FATAL_ERROR = 7; // query failed PGRES_COPY_BOTH = 8; // Copy In/Out data transfer in progress PGRES_SINGLE_TUPLE = 9; // single tuple from larger resultset // PGTransactionStatusType PQTRANS_IDLE = 0; // connection idle PQTRANS_ACTIVE = 1; // command in progress PQTRANS_INTRANS = 2; // idle, within transaction block PQTRANS_INERROR = 3; // idle, within failed transaction PQTRANS_UNKNOWN = 4; // cannot determine status // PGVerbosity PQERRORS_TERSE = 0; // single-line error messages PQERRORS_DEFAULT = 1; // recommended style PQERRORS_VERBOSE = 2; // all the facts, ma'am // PGPing PQPING_OK = 0; // server is accepting connections PQPING_REJECT = 1; // server is alive but rejecting connections PQPING_NO_RESPONSE = 2; // could not establish connection PQPING_NO_ATTEMPT = 3; // connection not attempted (bad params) type PGConn = Pointer; PPGConn = Pointer; // Internal pqlib structure pgresAttValue = record len: Integer; value: PFDAnsiString; end; pgresAttValueEDB = record len: Integer; value: PFDAnsiString; refcurRes: Pointer; end; PPGresAttValue = ^pgresAttValue; PPPGresAttValue = ^PPGresAttValue; // Internal pqlib structure pg_result = record ntups: Integer; numAttributes: Integer; attDescs: Pointer; tuples: PPPGresAttValue; // each PGresTuple is an array of PGresAttValue's // .......... end; PGresult = pg_result; PPGresult = ^PGresult; PGcancel = Pointer; PPGcancel = Pointer; PPGnotify = ^PGnotify; PGnotify = record relname: PFDAnsiString; // notification condition name be_pid: Integer; // process ID of notifying server process extra: PFDAnsiString; // notification parameter // Fields below here are private to libpq; apps should not use 'em next: PPGnotify; // list link end; // Function types for notice-handling callbacks TPQnoticeReceiver = procedure(arg: Pointer; res: PPGresult); cdecl; TPQnoticeProcessor = procedure(arg: Pointer; msg: PFDAnsiString); cdecl; pqbool = Byte; // Print options for PQprint() PQprintOpt = record header: pqbool; // print output field headings and row count align: pqbool; // fill align the fields standard: pqbool; // old brain dead format html3: pqbool; // output html tables expanded: pqbool; // expand tables pager: pqbool; // use pager for output if needed fieldSep: PFDAnsiString; // field separator tableOpt: PFDAnsiString; // insert to HTML <table ...> caption: PFDAnsiString; // HTML <caption> fieldName: PPByte; // null terminated array of replacement field names end; PPQprintOpt = ^PQprintOpt; // Structure for the conninfo parameter definitions returned by PQconndefaults // or PQconninfoParse. PQConninfoOptions = record keyword: PFDAnsiString; // The keyword of the option envvar: PFDAnsiString; // Fallback environment variable name compiled: PFDAnsiString; // Fallback compiled in default value val: PFDAnsiString; // Option's current value, or NULL lbl: PFDAnsiString; // Label for field in connect dialog dispchar: PFDAnsiString; // Character to display for this field in a // connect dialog. Values are: "" Display // entered value as is "*" Password field - // hide value "D" Debug option - don't show // by default dispsize: integer; // Field size in characters for dialog end; PPQconninfoOption = ^PQConninfoOptions; // PQArgBlock -- structure for PQfn() arguments PQArgBlock = record len: Integer; isint: Integer; case Integer of 0: (ptr: PInteger); // can't use void (dec compiler barfs) 1: (_integer: Integer); end; // PGresAttDesc -- Data about a single attribute (column) of a query result PGresAttDesc = record name: PFDAnsiString; // column name tableid: Oid; // source table, if known columnid: Integer; // source column, if known format: Integer; // format code for value (text/binary) typid: Oid; // type id typlen: Integer; // type size atttypmod: Integer; // type-specific modifier info end; {----------------------------------------------------------------------------} { Other } {----------------------------------------------------------------------------} const // Base PostgreSQL datatypes SQL_BOOL = 16; SQL_BYTEA = 17; SQL_CHAR = 18; // Internal SQL_NAME = 19; // Internal SQL_INT8 = 20; SQL_INT2 = 21; SQL_INT2VECTOR = 22; // Internal SQL_INT4 = 23; SQL_REGPROC = 24; SQL_TEXT = 25; SQL_OID = 26; // Internal SQL_TID = 27; SQL_XID = 28; SQL_CID = 29; // Internal SQL_OIDVECTOR = 30; // Internal SQL_JSON = 114; SQL_XML = 142; SQL_NODE_TREE = 194; SQL_SMGR = 210; SQL_POINT = 600; SQL_LSEG = 601; SQL_PATH = 602; SQL_BOX = 603; SQL_POLYGON = 604; SQL_LINE = 628; SQL_CIDR = 650; // Internal SQL_FLOAT4 = 700; SQL_FLOAT8 = 701; SQL_ABSTIME = 702; SQL_RELTIME = 703; SQL_TINTERVAL = 704; SQL_UNKNOWN = 705; // Internal SQL_CIRCLE = 718; SQL_MACADDR8 = 774; // Internal SQL_CASH = 790; SQL_MACADDR = 829; // Internal SQL_INET = 869; // Internal SQL_ACLITEM = 1033; SQL_BPCHAR = 1042; SQL_VARCHAR = 1043; SQL_DATE = 1082; SQL_TIME = 1083; SQL_TIMESTAMP = 1114; SQL_TIMESTAMPTZ = 1184; SQL_INTERVAL = 1186; SQL_TIMETZ = 1266; SQL_BIT = 1560; SQL_VARBIT = 1562; SQL_NUMERIC = 1700; SQL_REFCURSOR = 1790; SQL_REGPROCEDURE = 2202; SQL_REGOPER = 2203; SQL_REGOPERATOR = 2204; SQL_REGCLASS = 2205; SQL_REGTYPE = 2206; SQL_RECORD = 2249; SQL_CSTRING = 2275; SQL_ANY = 2276; SQL_VOID = 2278; // Internal SQL_UUID = 2950; SQL_JSONB = 3802; // Attribute numbers for the system-defined attributes // Source: src\include\access\htup.h SelfItemPointerAttributeNumber = -1; ObjectIdAttributeNumber = -2; MinTransactionIdAttributeNumber = -3; MinCommandIdAttributeNumber = -4; MaxTransactionIdAttributeNumber = -5; MaxCommandIdAttributeNumber = -6; TableOidAttributeNumber = -7; // A range's flags byte contains these bits // Source: src\include\utils\rangetypes.h RANGE_EMPTY = $01; // range is empty RANGE_LB_INC = $02; // lower bound is inclusive RANGE_UB_INC = $04; // upper bound is inclusive RANGE_LB_INF = $08; // lower bound is -infinity RANGE_UB_INF = $10; // upper bound is +infinity RANGE_LB_NULL = $20; // lower bound is null (NOT USED) RANGE_UB_NULL = $40; // upper bound is null (NOT USED) RANGE_CONTAIN_EMPTY = $80; // marks a GiST internal-page entry whose // subtree contains some empty ranges // other POSTGRES_EPOCH_JDATE = 2451545; NAMEMAXLEN = 64; VARHDRSZ = 4; ARRHDRSZ = 20; JSONB_VER = 1; NULL_LEN = -1; SEEK_SET = 0; {$EXTERNALSYM SEEK_SET} SEEK_CUR = 1; {$EXTERNALSYM SEEK_CUR} SEEK_END = 2; {$EXTERNALSYM SEEK_END} INV_WRITE = $00020000; INV_READ = $00040000; type Tid = array[0..5] of Byte; PTid = ^Tid; {----------------------------------------------------------------------------} { LIBPQ-FE.H } {----------------------------------------------------------------------------} {$IFDEF FireDAC_PGSQL_STATIC} {$L crypt.obj} // {$L dirent.obj} // {$L dirmod.obj} {$L encnames.obj} {$L fe-auth.obj} {$L fe-connect.obj} {$L fe-exec.obj} {$L fe-lobj.obj} {$L fe-misc.obj} {$L fe-print.obj} {$L fe-protocol2.obj} {$L fe-protocol3.obj} {$L fe-secure.obj} {$L getaddrinfo.obj} {$L inet_aton.obj} {$L ip.obj} {$L md5.obj} {$L noblock.obj} {$L open.obj} {$L pgsleep.obj} {$L pgstrcasecmp.obj} {$L pqexpbuffer.obj} {$L pqsignal.obj} {$L pthread-win32.obj} {$L snprintf.obj} {$L strlcpy.obj} {$L thread.obj} {$L wchar.obj} {$L win32.obj} {$L win32error.obj} // Database Connection Control Functions function PQconnectdb(ConnInfo: PFDAnsiString): PPGconn; cdecl; external; // function PQsetdbLogin(Host, Port, Options, Tty, Db, User, Passwd: PFDAnsiString): PPGconn; cdecl; external; function PQconndefaults: PPQconninfoOption; cdecl; external; procedure PQfinish(conn: PPGconn); cdecl; external; procedure PQreset(conn: PPGconn); cdecl; external; // Connection Status Functions function PQdb(conn: PPGconn): PFDAnsiString; cdecl; external; function PQuser(conn: PPGconn): PFDAnsiString; cdecl; external; function PQpass(conn: PPGconn): PFDAnsiString; cdecl; external; function PQhost(conn: PPGconn): PFDAnsiString; cdecl; external; function PQport(conn: PPGconn): PFDAnsiString; cdecl; external; function PQtty(conn: PPGconn): PFDAnsiString; cdecl; external; function PQoptions(conn: PPGconn): PFDAnsiString; cdecl; external; function PQstatus(conn: PPGconn): Integer; cdecl; external; function PQparameterStatus(conn: PGconn; ParamName: PFDAnsiString): PFDAnsiString; cdecl; external; function PQtransactionStatus(conn: PGconn): Integer; cdecl; external; function PQserverVersion(conn: PPGconn): Integer; cdecl; external; function PQprotocolVersion(conn: PPGconn): Integer; cdecl; external; function PQsetClientEncoding(conn: PPGconn; encoding: PFDAnsiString): Integer; cdecl; external; function PQclientEncoding(conn: PPGconn): Integer; cdecl; external; function pg_encoding_to_char(encoding_id: Integer): PFDAnsiString; cdecl; external; function PQerrorMessage(conn: PPGconn): PByte; cdecl; external; function PQbackendPID(conn: PPGconn): Integer; cdecl; external; // SSL *_PQgetssl(const PGconn *conn); // Command Execution Functions function PQexec(conn: PPGconn; command: PByte): PPGresult; cdecl; external; function PQexecParams(conn: PPGconn; command: PByte; nParams: integer; paramTypes: PInteger; ParamValues: Pointer; paramLengths: PInteger; paramFormats: Integer; resultFormat: Integer): PPGresult; cdecl; external; function PQprepare(conn: PPGconn; stmtName: PFDAnsiString; query: PByte; nParams: Integer; ParamTypes: POid): PPGresult; cdecl; external; function PQexecPrepared(conn: PPGconn; stmtName: PFDAnsiString; nParams: Integer; paramValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; external; function PQdescribePrepared(conn: PPGconn; stmtName: PFDAnsiString): PPGresult; cdecl; external; function PQdescribePortal(conn: PPGconn; portalName: PFDAnsiString): PPGresult; cdecl; external; function PQresultStatus(res: PPGresult): Integer; cdecl; external; function PQresultErrorMessage(res: PPGresult): PByte; cdecl; external; function PQresultErrorField(res: PPGResult; fieldcode: integer): PByte; cdecl; external; procedure PQclear(res: PPGresult); cdecl; external; function PQmakeEmptyPGresult(conn: PPGconn; status: Integer): PPGresult; cdecl; external; function PQntuples(res: PPGresult): Integer; cdecl; external; function PQnfields(res: PPGresult): Integer; cdecl; external; function PQfname(res: PPGresult; field_num: Integer): PByte; cdecl; external; function PQfnumber(res: PPGresult; field_name: PByte): Integer; cdecl; external; function PQftable(res: PPGresult; column_number: Integer): Oid; cdecl; external; function PQftablecol(res: PPGresult; column_number: Integer): Integer; cdecl; external; function PQfformat(res: PPGresult; column_number: Integer): Integer; cdecl; external; function PQftype(res: PPGresult; field_num: Integer): Oid; cdecl; external; function PQfmod(res: PPGresult; field_num: Integer): Integer; cdecl; external; function PQfsize(res: PPGresult; field_num: Integer): Integer; cdecl; external; function PQbinaryTuples(res: PPGresult): Integer; cdecl; external; function PQgetvalue(res: PPGresult; row_number, column_number: Integer): PByte; cdecl; external; function PQgetisnull(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; external; function PQgetlength(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; external; function PQnparams(res: PPGresult): Integer; cdecl; external; function PQparamtype(res: PPGresult; param_number: Integer): Oid; cdecl; external; function PQcmdStatus(res: PPGresult): PFDAnsiString; cdecl; external; function PQoidValue(res: PPGresult): Oid; cdecl; external; function PQoidStatus(res: PPGresult): PFDAnsiString; cdecl; external; function PQcmdTuples(res: PPGresult): PFDAnsiString; cdecl; external; // Notice Processing function PQsetNoticeReceiver(conn: PPGconn; proc: TPQnoticeReceiver; arg: Pointer): TPQnoticeReceiver; cdecl; external; function PQsetNoticeProcessor(conn: PPGconn; proc: TPQnoticeProcessor; arg: Pointer): TPQnoticeProcessor; cdecl; external; // Cancelling Queries in Progress function PQgetCancel(conn: PPGconn): PPGcancel; cdecl; external; procedure PQfreeCancel(cancel: PPGcancel); cdecl; external; function PQcancel(cancel: PPGcancel; errbuf: PFDAnsiString; errbufsize: Integer): Integer; cdecl; external; // Large Objects support function lo_creat(conn: PPGconn; mode: Integer): Oid; cdecl; external; function lo_open(conn: PPGconn; objoid: Oid; mode: Integer): Integer; cdecl; external; function lo_write(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; external; function lo_read(conn: PPGconn; fd: Integer; buf: Pointer; len: Integer): Integer; cdecl; external; function lo_lseek(conn: PPGconn; fd: Integer; offset: Integer; whence: Integer): Integer; cdecl; external; function lo_tell(conn: PPGconn; fd: Integer): Integer; cdecl; external; function lo_close(conn: PPGconn; fd: Integer): Integer; cdecl; external; function lo_unlink(conn: PPGconn; objoid: Oid): Integer; cdecl; external; function PQgetResult(conn: PPGconn): PPGresult; cdecl; external; // Functions Associated with the COPY Command function PQputCopyData(conn: PPGconn; buffer: Pointer; nbytes: Integer): Integer; cdecl; external; function PQputCopyEnd(conn: PPGconn; errormsg: Pointer): Integer; cdecl; external; // Async notifications // Check after: prepare, execute, describe, isbusy, getresult, putcopydata function PQnotifies(conn: PPGconn): PPGnotify; cdecl; external; procedure PQfreemem(ptr: Pointer); cdecl; external; function PQconsumeInput(conn: PPGconn): Integer; cdecl; external; function PQsocket(conn: PPGconn): Integer; cdecl; external; function PQencryptPassword(passwd, user: PFDAnsiString): PFDAnsiString; cdecl; external; function PQencryptPasswordConn(conn: PPGconn; passwd, user, algorithm: PFDAnsiString): PFDAnsiString; cdecl; external; {$ENDIF} type // Database Connection Control Functions TPQconnectdb = function(ConnInfo: PFDAnsiString): PPGconn; cdecl; // TPQsetdbLogin = function(Host, Port, Options, Tty, Db, User, Passwd: PFDAnsiString): PPGconn; cdecl; TPQconndefaults = function: PPQconninfoOption; cdecl; TPQfinish = procedure(conn: PPGconn); cdecl; TPQreset = procedure(conn: PPGconn); cdecl; // Connection Status Functions TPQdb = function(conn: PPGconn): PFDAnsiString; cdecl; TPQuser = function(conn: PPGconn): PFDAnsiString; cdecl; TPQpass = function(conn: PPGconn): PFDAnsiString; cdecl; TPQhost = function(conn: PPGconn): PFDAnsiString; cdecl; TPQport = function(conn: PPGconn): PFDAnsiString; cdecl; TPQtty = function(conn: PPGconn): PFDAnsiString; cdecl; TPQoptions = function(conn: PPGconn): PFDAnsiString; cdecl; TPQstatus = function(conn: PPGconn): Integer; cdecl; TPQparameterStatus = function(conn: PGconn; ParamName: PFDAnsiString): PFDAnsiString; cdecl; TPQtransactionStatus = function(conn: PGconn): Integer; cdecl; TPQserverVersion = function(conn: PPGconn): Integer; cdecl; TPQprotocolVersion = function(conn: PPGconn): Integer; cdecl; TPQsetClientEncoding = function(conn: PPGconn; encoding: PFDAnsiString): Integer; cdecl; TPQclientEncoding = function(conn: PPGconn): Integer; cdecl; Tpg_encoding_to_char = function(encoding_id: Integer): PFDAnsiString; cdecl; TPQerrorMessage = function(conn: PPGconn): PByte; cdecl; TPQbackendPID = function(conn: PPGconn): Integer; cdecl; // SSL *PQgetssl(const PGconn *conn); // Command Execution Functions TPQexec = function(conn: PPGconn; command: PByte): PPGresult; cdecl; TPQexecParams = function(conn: PPGconn; command: PByte; nParams: integer; paramTypes: PInteger; ParamValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; TPQprepare = function(conn: PPGconn; stmtName: PFDAnsiString; query: PByte; nParams: Integer; ParamTypes: POid): PPGresult; cdecl; TPQexecPrepared = function(conn: PPGconn; stmtName: PFDAnsiString; nParams: Integer; paramValues: Pointer; paramLengths: PInteger; paramFormats: PInteger; resultFormat: Integer): PPGresult; cdecl; TPQdescribePrepared = function(conn: PPGconn; stmtName: PFDAnsiString): PPGresult; cdecl; TPQdescribePortal = function(conn: PPGconn; portalName: PFDAnsiString): PPGresult; cdecl; TPQresultStatus = function(res: PPGresult): Integer; cdecl; TPQresultErrorMessage = function(res: PPGresult): PByte; cdecl; TPQresultErrorField = function(res: PPGResult; fieldcode: integer): PByte; cdecl; TPQclear = procedure(res: PPGresult); cdecl; TPQmakeEmptyPGresult = function(conn: PPGconn; status: Integer): PPGresult; cdecl; TPQntuples = function(res: PPGresult): Integer; cdecl; TPQnfields = function(res: PPGresult): Integer; cdecl; TPQfname = function(res: PPGresult; field_num: Integer): PByte; cdecl; TPQfnumber = function(res: PPGresult; field_name: PByte): Integer; cdecl; TPQftable = function(res: PPGresult; column_number: Integer): Oid; cdecl; TPQftablecol = function(res: PPGresult; column_number: Integer): Integer; cdecl; TPQfformat = function(res: PPGresult; column_number: Integer): Integer; cdecl; TPQftype = function(res: PPGresult; field_num: Integer): Oid; cdecl; TPQfmod = function(res: PPGresult; field_num: Integer): Integer; cdecl; TPQfsize = function(res: PPGresult; field_num: Integer): Integer; cdecl; TPQbinaryTuples = function(res: PPGresult): Integer; cdecl; TPQgetvalue = function(res: PPGresult; row_number, column_number: Integer): PByte; cdecl; TPQgetisnull = function(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; TPQgetlength = function(res: PPGresult; tup_num, field_num: Integer): Integer; cdecl; TPQnparams = function(res: PPGresult): Integer; cdecl; TPQparamtype = function(res: PPGresult; param_number: Integer): Oid; cdecl; TPQcmdStatus = function(res: PPGresult): PFDAnsiString; cdecl; TPQoidValue = function(res: PPGresult): Oid; cdecl; TPQoidStatus = function(res: PPGresult): PFDAnsiString; cdecl; TPQcmdTuples = function(res: PPGresult): PFDAnsiString; cdecl; // Notice Processing TPQsetNoticeReceiver = function(conn: PPGconn; proc: TPQnoticeReceiver; arg: Pointer): TPQnoticeReceiver; cdecl; TPQsetNoticeProcessor = function(conn: PPGconn; proc: TPQnoticeProcessor; arg: Pointer): TPQnoticeProcessor; cdecl; // Cancelling Queries in Progress TPQgetCancel = function(conn: PPGconn): PPGcancel; cdecl; TPQfreeCancel = procedure(cancel: PPGcancel); cdecl; TPQcancel = function(cancel: PPGcancel; errbuf: PFDAnsiString; errbufsize: Integer): Integer; cdecl; // Large Objects support Tlo_creat = function(conn: PPGconn; mode: Integer): Oid; cdecl; Tlo_open = function(conn: PPGconn; objoid: Oid; mode: Integer): Integer; cdecl; Tlo_write = function(conn: PPGconn; fd: Integer; buf: Pointer; len: TFDsize_t): Integer; cdecl; Tlo_read = function(conn: PPGconn; fd: Integer; buf: Pointer; len: TFDsize_t): Integer; cdecl; Tlo_lseek = function(conn: PPGconn; fd: Integer; offset: Integer; whence: Integer): Integer; cdecl; Tlo_tell = function(conn: PPGconn; fd: Integer): Integer; cdecl; Tlo_close = function(conn: PPGconn; fd: Integer): Integer; cdecl; Tlo_unlink = function(conn: PPGconn; objoid: Oid): Integer; cdecl; Tlo_truncate = function(conn: PPGconn; fd: Integer; len: TFDsize_t): Integer; cdecl; TPQgetResult = function(conn: PPGconn): PPGresult; cdecl; // Functions Associated with the COPY Command TPQputCopyData = function(conn: PPGconn; buffer: Pointer; nbytes: Integer): Integer; cdecl; TPQputCopyEnd = function(conn: PPGconn; errormsg: Pointer): Integer; cdecl; // Async notifications // Check after: prepare, execute, describe, isbusy, getresult, putcopydata TPQnotifies = function(conn: PPGconn): PPGnotify; cdecl; TPQfreemem = procedure(ptr: Pointer); cdecl; TPQconsumeInput = function(conn: PPGconn): Integer; cdecl; TPQsocket = function(conn: PPGconn): Integer; cdecl; // EnterpriseDB: Bulk insert/update related functions TQsendBulkStart = function(conn: PPGconn; stmtName: PFDAnsiString; nCols: Cardinal; paramFormats: PInteger): Integer; cdecl; TPQsendBulk = function(conn: PPGconn; nRows: Cardinal; paramValues: PPointer; paramLengths: PInteger): Integer; cdecl; TPQsendBulkFinish = function(conn: PPGconn): Integer; TPQBulkStart = function(conn: PPGconn; stmtName: PFDAnsiString; nCols: Cardinal; paramFormats: PInteger): PPGResult; cdecl; TPQexecBulk = function(conn: PPGconn; nRows: Cardinal; paramValues: PPointer; paramLengths: PInteger): PPGResult; cdecl; TPQBulkFinish = function(conn: PPGconn): PPGResult; cdecl; TPQexecBulkPrepared = function(conn: PPGconn; stmtName: PFDAnsiString; nCols, nRows: Cardinal; paramValues: PPointer; paramLengths: PInteger; paramFormats: PInteger): PPGresult; cdecl; TPQencryptPassword = function(passwd, user: PFDAnsiString): PFDAnsiString; cdecl; TPQencryptPasswordConn = function (conn: PPGconn; passwd, user, algorithm: PFDAnsiString): PFDAnsiString; cdecl; // Functions mentioned below are not used in FireDAC PostgreSQL driver // Asynchronous Command Processing // PQsendQuery // PQsendQueryParams // PQsendPrepare // PQsendQueryPrepared // PQsendDescribePrepared // PQsendDescribePortal // PQgetResult // PQconsumeInput // PQisBusy // PQsetnonblocking // PQisnonblocking // PQflush // The Fast-Path Interface // PQfn implementation {$IFDEF FireDAC_PGSQL_STATIC} {$IFDEF MSWINDOWS} uses Winapi.Windows, Winapi.WinSock, System.ShlObj, System.Win.Crtl; {$ENDIF} {$ENDIF} end.
eEn un entrenamiento de fútbol hay 20 jugadores que forman 4 equipos (cada jugador conoce el equipo al cual pertenece llamando a la función DarEquipo()). Cuando un equipo está listo (han llegado los 5 jugadores que lo componen), debe enfrentarse a otro equipo que también esté listo (los dos primeros equipos en juntarse juegan en la cancha 1, y los otros dos equipos juegan en la cancha 2). Una vez que el equipo conoce la cancha en la que juega,sus jugadores se dirigen a ella. Cuando los 10 jugadores del partido llegaron a la cancha comienza el partido, juegan durante 50 minutos, y al terminar todos los jugadores del partido se retiran (no es necesario que se esperen para salir). PROGRAM 8 BEGIN Monitor Equipo[p=1 to 4] BEGIN int cantidadJugares=1 cond cola; // es como un recurso compartido // que utilizan todos los procesos // pero solo lo modifica el ultimo //y es el valor que le va a dar a todos los otros proceos int cancha; procedure llegue(var int canchaAsignada) BEGIN cantidadJugares ++; if(cantidadJugares == 5) THEN // AsignarEquipos.obtenerCancha(cancha); signalAll(cola); END ELSE wait(cola); canchaAsignada= cancha; END; END; Monitor AsignarEquipos BEGIN int cantidadJugadores= 0; procedure obtenerCancha(var int cancha) BEGIN cantidadJugadores ++: if(cantidadJugadores <=10) cancha = 1; ELSE cancha = 2; END END; Monitor Partido [p= 1 to 2] BEGIN int cantidadJugadores= 0; cond cola; procedure jugarPartido() BEGIN cantidadJugadores++; if(cantidadJugadores < 10) THEN wait(cola); END ELSE BEGIN delay("50m"); signalAll(cola); END END END; Process jugador [j=1 to 20] BEGIN //obtengo el equipo del jugador int equipo = DarEquipo(); int cancha; Equipo[equipo].llegue(cancha); Partido[cancha].jugarPartido(); END; END;
unit uPublic; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,uEngine2DModel,uEngine2DSprite; const SWITCH_INTERVAL = 2000; Type TBaseLogic = class protected FLogicName : String; [weak]FEngineModel : TEngine2DModel; FIndexList : TStringList; FTotalCount : Integer; FCurIndex : Integer; FNextTimer : TTimer; function GetTotalCount:Integer; procedure SetMouseCursor(value : TCursor); procedure OnNextTimer(Sender :TObject);virtual; public Constructor Create; Destructor Destroy;override; procedure Init;virtual;abstract; procedure MouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);virtual; procedure MouseMoveHandler(Sender: TObject; Shift: TShiftState; X, Y: Single);virtual; procedure MouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);virtual; procedure MouseEnterHandler(Sender : TObject); virtual; procedure MouseLeaveHandler(Sender : TObject); virtual; procedure NextSight;virtual; property LogicName : String read FLogicName write FLogicName; property EngineModel : TEngine2DModel read FEngineModel write FEngineModel; property IndexList : TStringList read FIndexList write FIndexList; property TotalCount : Integer read GetTotalCount; property CurIndex : Integer read FCurIndex write FCurIndex; property MouseCursor : TCursor write SetMouseCursor; //设置鼠标样式 end; TLogicWithStar = class(TBaseLogic) protected FStarCount : Integer; // 星星数量 FFullStarName : String; FHalfStarName : String; FEmptyStarName : String; function UpdateASingleStarStatus(AStarIndex : Integer): TEngine2DSprite; procedure PlayStarAnimationWhenDone(ATotalCount : Integer); procedure UpdateStarStatus;virtual;abstract; end; TLogicClass = class of TBaseLogic; TLogicRecord = record LogicClass : TLogicClass; LogicInstance : TBaseLogic; AliasName : String; end; var G_LogicManager : array of TLogicRecord; G_CurrentLogic : TBaseLogic; //当前使用的逻辑单元 procedure RegisterLogicUnit(const ALogicClass:TLogicClass;const AAliasName:String); procedure UnRegisterLogicUnit; function GetLogicUnitByAliasName(AAliasName:String):TBaseLogic; implementation uses AniMain,uEngine,uEngine2DExtend,Math; procedure RegisterLogicUnit(const ALogicClass:TLogicClass;const AAliasName:String); begin SetLength(G_LogicManager,Length(G_LogicManager)+1); G_LogicManager[High(G_LogicManager)].LogicClass := ALogicClass; G_LogicManager[High(G_LogicManager)].LogicInstance := nil; G_LogicManager[High(G_LogicManager)].AliasName := AAliasName; end; procedure UnRegisterLogicUnit; var i: Integer; begin for i := 0 to High(G_LogicManager) do begin if G_LogicManager[i].LogicInstance <> nil then G_LogicManager[i].LogicInstance.DisposeOf; end; SetLength(G_LogicManager,0); G_LogicManager := nil; end; function GetLogicUnitByAliasName(AAliasName:String):TBaseLogic; var i: Integer; LPos : Integer; LLogic : TBaseLogic; begin result := nil; if Length(G_LogicManager)= 0 then exit; try for i := 0 to Length(G_LogicManager)-1 do begin if G_LogicManager[i].AliasName.Equals(AAliasName) then begin LPos := i; break; end; end; LLogic := G_LogicManager[LPos].LogicInstance; if LLogic = nil then begin LLogic := G_LogicManager[LPos].LogicClass.Create; LLogic.LogicName := AAliasName; G_LogicManager[LPos].LogicInstance := LLogic; end; except on e : Exception do Showmessage('Error @GetLogicUnitByAliasName: '+e.Message); end; result := LLogic; end; { TBaseLogic } constructor TBaseLogic.Create; begin FIndexList := TStringList.Create; FCurIndex := 0; if Not Assigned(FNextTimer) then begin FNextTimer := TTimer.Create(nil); FNextTimer.Interval := SWITCH_INTERVAL; FNextTimer.OnTimer := OnNextTimer; FNextTimer.Enabled := false; end; end; destructor TBaseLogic.Destroy; begin FIndexList.DisposeOf; if Assigned(FNextTimer) then FNextTimer.DisposeOf; inherited; end; function TBaseLogic.GetTotalCount: Integer; begin result := FIndexList.Count; end; procedure TBaseLogic.MouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin //todo end; procedure TBaseLogic.MouseEnterHandler(Sender: TObject); begin //todo Self.MouseCursor := crHandPoint; end; procedure TBaseLogic.MouseLeaveHandler(Sender: TObject); begin //todo Self.MouseCursor := crDefault; end; procedure TBaseLogic.MouseMoveHandler(Sender: TObject; Shift: TShiftState; X, Y: Single); begin //todo end; procedure TBaseLogic.MouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin //todo end; procedure TBaseLogic.NextSight; begin Form1.FormResize(nil); end; procedure TBaseLogic.OnNextTimer(Sender: TObject); begin //todo end; procedure TBaseLogic.SetMouseCursor(value: TCursor); begin G_Engine.Cursor := value; end; { TLogicWithStar } procedure TLogicWithStar.PlayStarAnimationWhenDone(ATotalCount : Integer); var LSprite : TEngine2DSprite; LPoint : TPointF; begin inc(FStarCount); if (FStarCount div 2) > ATotalCount then begin FStarCount := ATotalCount * 2; exit; end; LSprite := UpdateASingleStarStatus(Math.Ceil(FStarCount/2.0)); if LSprite <> nil then begin LPoint.X := LSprite.Position.InitWidth/2; LPoint.Y := LSprite.Position.InitHeight/2; LSprite.CreateRotateAnimation(0,360,false,300,LPoint); end; end; function TLogicWithStar.UpdateASingleStarStatus(AStarIndex: Integer): TEngine2DSprite; var LSpriteName,LImageName :String; LSprite : TEngine2DSprite; LImage : TEngine2DImage; LModeV,LDivV : Integer; begin LSpriteName := 'StarSprite'+AStarIndex.ToString(); LSprite := FEngineModel.StarSpriteList.Has(LSpriteName); if LSprite <> nil then begin LImageName := 'StarImage'+AStarIndex.ToString(); LImage := TEngine2DImage(LSprite.Children.Has(LImageName)); LDivV := (FStarCount div 2); if AStarIndex <= LDivV then LImage.ImageConfig.SetNormalImg(FFullStarName) else begin LModeV := FStarCount mod 2; if AStarIndex = LDivV+1 then begin if LModeV = 1 then LImage.ImageConfig.SetNormalImg(FHalfStarName) else if LModeV = 0 then LImage.ImageConfig.SetNormalImg(FEmptyStarName); end else begin LImage.ImageConfig.SetNormalImg(FEmptyStarName); end; end; end; result := LSprite; end; Initialization Finalization UnRegisterLogicUnit; end.
{$i deltics.interfacedobjects.inc} unit Deltics.InterfacedObjects.Interfaces.IInterfacedObjectList; interface type IInterfacedObjectList = interface ['{C7761F1C-2DFB-4FBA-8EED-46556675E8D1}'] function get_Capacity: Integer; function get_Count: Integer; function get_Item(const aIndex: Integer): IUnknown; function get_Object(const aIndex: Integer): TObject; procedure set_Capacity(const aValue: Integer); function Add(const aInterface: IInterface): Integer; overload; function Add(const aObject: TObject): Integer; overload; procedure Clear; function Contains(const aItem: IInterface): Boolean; overload; function Contains(const aItem: IInterface; var aIndex: Integer): Boolean; overload; function Contains(const aItem: TObject): Boolean; overload; function Contains(const aItem: TObject; var aIndex: Integer): Boolean; overload; procedure Delete(const aIndex: Integer); function IndexOf(const aItem: IInterface): Integer; overload; function IndexOf(const aItem: TObject): Integer; overload; function Insert(const aIndex: Integer; const aInterface: IInterface): Integer; overload; function Insert(const aIndex: Integer; const aObject: TObject): Integer; overload; function Remove(const aItem: IInterface): Boolean; overload; function Remove(const aItem: TObject): Boolean; overload; property Capacity: Integer read get_Capacity write set_Capacity; property Count: Integer read get_Count; property Items[const aIndex: Integer]: IUnknown read get_Item; default; property Objects[const aIndex: Integer]: TObject read get_Object; end; implementation end.
unit fNewQSO; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ComCtrls, fCommonLocal, uRigControl, uCfgStorage, uCWKeying, LCLType; const C_EMPTY_FREQ = '0.00000'; type TRadio = (trRadio1, trRadio2); type { TfrmNewQSO } TfrmNewQSO = class(TfrmCommonLocal) edtCall: TEdit; edtExch1: TEdit; edtExch2: TEdit; edtExch3: TEdit; Label1: TLabel; lblCWSpeed: TLabel; lblExch1: TLabel; lblExch2: TLabel; lblExch3: TLabel; Panel3: TPanel; pnlCallsign: TPanel; pnlExch1: TPanel; pnlExch2: TPanel; pnlExch3: TPanel; sbNewQSO: TStatusBar; tmrRadio: TTimer; procedure edtCallChange(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure tmrRadioTimer(Sender: TObject); private radio : TRigControl; procedure CheckDXCCInfo; procedure ClearAll; procedure InicializeRig; procedure InitializeCW; //procedure SetMode(mode : String;bandwidth :Integer); //function GetActualMode : String; //function GetModeNumber(mode : String) : Cardinal; public RadioOperated : TRadio; CWint : TCWKeying; end; var frmNewQSO: TfrmNewQSO; implementation {$R *.lfm} uses dDXCC, dUtils; { TfrmNewQSO } procedure TfrmNewQSO.FormShow(Sender: TObject); begin inherited; InitializeCW; InicializeRig; edtCall.SetFocus end; procedure TfrmNewQSO.tmrRadioTimer(Sender: TObject); var b : String; f : Double; m : String; begin if Assigned(radio) then begin f := radio.GetFreqMHz; m := radio.GetModeOnly end else f := 0; sbNewQSO.Panels[sbNewQSO.Panels.Count-2].Text := FormatFloat(C_EMPTY_FREQ+';;',f); sbNewQSO.Panels[sbNewQSO.Panels.Count-1].Text := m end; procedure TfrmNewQSO.ClearAll; begin sbNewQSO.Panels[0].Text := ''; edtCall.Clear; edtExch1.Clear; edtExch2.Clear; edtExch3.Clear end; procedure TfrmNewQSO.edtCallChange(Sender: TObject); begin if (Length(edtCall.Text) > 2) then CheckDXCCInfo end; procedure TfrmNewQSO.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin if Assigned(CWint) then begin CWint.Close; FreeAndNil(CWint) end; if Assigned(radio) then FreeAndNil(radio) end; procedure TfrmNewQSO.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var speed : Word; begin if (key = 33) then //pgup begin speed := CWint.GetSpeed+2; CWint.SetSpeed(speed); lblCWSpeed.Caption := IntToStr(speed)+' WPM' end; if (key = 34) then //pgdwn begin speed := CWint.GetSpeed-2; CWint.SetSpeed(speed); lblCWSpeed.Caption := IntToStr(speed)+' WPM' end end; procedure TfrmNewQSO.CheckDXCCInfo; var pfx, cont, country, WAZ, offset, ITU, lat, long : String; begin //function TdmDXCC.id_country(call: string;date : TDateTime; var pfx, cont, country, WAZ, // offset, ITU, lat, long: string) : Word; dmDXCC.id_country(edtCall.Text, now, pfx, cont, country, WAZ, offset, ITU, lat, long); sbNewQSO.Panels[0].Text := country end; procedure TfrmNewQSO.InicializeRig; var n : String = ''; id : Integer = 0; Resume : Boolean = False; begin if Assigned(radio) then begin //Writeln('huu0'); FreeAndNil(radio); end; //Writeln('huu1'); Application.ProcessMessages; Sleep(500); //Writeln('huu2'); tmrRadio.Enabled := False; if RadioOperated = trRadio1 then n := '1' else n := '2'; radio := TRigControl.Create; //if dmData.DebugLevel>0 then radio.DebugMode := True; //Writeln('huu3'); if not TryStrToInt(iniLocal.ReadString('TRX'+n,'model',''),id) then radio.RigId := 1 else radio.RigId := id; //Writeln('huu4'); radio.RigCtldPath := iniLocal.ReadString('TRX','RigCtldPath','/usr/bin/rigctld'); radio.RigCtldArgs := dmUtils.GetRadioRigCtldCommandLine(StrToInt(n)); radio.RunRigCtld := iniLocal.ReadBool('TRX'+n,'RunRigCtld',False); radio.RigDevice := iniLocal.ReadString('TRX'+n,'device',''); radio.RigCtldPort := StrToInt(iniLocal.ReadString('TRX'+n,'RigCtldPort','4532')); radio.RigCtldHost := iniLocal.ReadString('TRX'+n,'host','localhost'); radio.RigPoll := StrToInt(iniLocal.ReadString('TRX'+n,'poll','500')); radio.RigSendCWR := iniLocal.ReadBool('TRX'+n,'CWR',False); tmrRadio.Interval := radio.RigPoll; tmrRadio.Enabled := True; if not radio.Connected then begin //Writeln('huu5'); FreeAndNil(radio) end end; procedure TfrmNewQSO.InitializeCW; var Section : String; begin if Assigned(CWint) then FreeAndNil(CWint); if RadioOperated = trRadio1 then Section := 'CW1' else Section := 'CW2'; dmUtils.DebugMsg('CW init'); CWint := TCWKeying.Create; CWint.DebugMode := True; if iniLocal.ReadInteger(Section,'Type',0) > 0 then begin if iniLocal.ReadInteger(Section,'Type',0) = 1 then begin CWint.KeyType := ktWinKeyer; CWint.Port := iniLocal.ReadString(Section,'wk_port',''); CWint.Device := iniLocal.ReadString(Section,'wk_port',''); CWint.Open; CWint.SetSpeed(iniLocal.ReadInteger(Section,'wk_speed',30)); lblCWSpeed.Caption := IntToStr(iniLocal.ReadInteger(Section,'wk_speed',30)) + ' WPM' end else begin CWint.KeyType := ktCWdaemon; CWint.Port := iniLocal.ReadString(Section,'cw_port',''); CWint.Device := iniLocal.ReadString(Section,'cw_address',''); CWint.Open; CWint.SetSpeed(iniLocal.ReadInteger(Section,'cw_speed',30)); lblCWSpeed.Caption := IntToStr(iniLocal.ReadInteger(Section,'cw_speed',30)) + ' WPM' end end end; end.
{ Sergey Bodrov, 2012-2016 Data exchange via file. Suitable for device files (/dev/* under Unix or special files in Windows). Conventional data files can be used too. Properties: Filename - Path (optionally) and name of file. FilePos - Current position in file, bytes from beginning (for conventional files). QueryInterval - Interval for checking changes in file, milliseconds. MinDataBytes - Minimum number of bytes in buffer for triggering OnDataAppear event. KeepOpen - Keep the file open between read and write operations: True - file stay opened False - file will be opened before every read/write operation and closed after. WriteMode - File write mode: fwmRewrite - every write apply to beginning of file fwmAppend - data written from last operation position or appended to the end of file Methods: Open() - Opens file with given name, "file:" prefix can be used. } { TODO : Add thread-safe file reader } unit DataPortFile; interface uses SysUtils, Classes, DataPort {$IFDEF UNIX} , BaseUnix {$ENDIF} {$ifndef FPC} , Windows {$endif}; type TFileWriteMode = (fwmRewrite, fwmAppend); { TDataPortFile } TDataPortFile = class(TDataPort) private sReadData: AnsiString; lock: TMultiReadExclusiveWriteSynchronizer; FFileHandle: THandle; FFileName: string; FFilePos: Cardinal; FQueryInterval: Cardinal; FMinDataBytes: Cardinal; FKeepOpen: boolean; FWriteMode: TFileWriteMode; procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string); procedure OnErrorHandler(Sender: TObject; const AMsg: string); procedure ReadToSelf(); protected procedure SetActive(Val: boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; { Opens file with given name, "file:" prefix can be used } procedure Open(const AInitStr: string = ''); override; procedure Close(); override; function Push(const AData: AnsiString): boolean; override; function Pull(size: Integer = MaxInt): AnsiString; override; function Peek(size: Integer = MaxInt): AnsiString; override; function PeekSize(): Cardinal; override; function ioctl_cmd(const ACmd: string): string; published property Active; { Path (optionally) and name of file } property FileName: string read FFileName write FFileName; { Current position in file, bytes from beginning (for conventional files) } property FilePos: Cardinal read FFilePos write FFilePos; { Interval for checking changes in file, milliseconds } property QueryInterval: Cardinal read FQueryInterval write FQueryInterval; { Minimum number of bytes in buffer for triggering OnDataAppear event } property MinDataBytes: Cardinal read FMinDataBytes write FMinDataBytes; { Keep the file open between read and write operations: True - file stay opened False - file will be opened before every read/write operation and closed after. } property KeepOpen: boolean read FKeepOpen write FKeepOpen; { WriteMode - File write mode: fwmRewrite - every write apply to beginning of file fwmAppend - data written from last operation position or appended to the end of file } property WriteMode: TFileWriteMode read FWriteMode write FWriteMode; property OnDataAppear; property OnError; property OnOpen; property OnClose; end; procedure Register; implementation {$ifndef FPC} const feInvalidHandle = INVALID_HANDLE_VALUE; fsFromBeginning = 0; fsFromEnd = 2; procedure FileTruncate(AFileHandle: Cardinal; ASize: Cardinal); begin FileSeek(AFileHandle, ASize, fsFromBeginning); SetEndOfFile(AFileHandle); end; {$endif} procedure Register; begin RegisterComponents('DataPort', [TDataPortFile]); end; { TDataPortFile } constructor TDataPortFile.Create(AOwner: TComponent); begin inherited Create(AOwner); self.lock := TMultiReadExclusiveWriteSynchronizer.Create(); sReadData := ''; FFilePos := 0; FQueryInterval := 100; FMinDataBytes := 1; FFileHandle := feInvalidHandle; FKeepOpen := False; FWriteMode := fwmAppend; FActive := False; end; procedure TDataPortFile.Open(const AInitStr: string = ''); var n: Integer; begin // Set filename from init string if AInitStr <> '' then begin n := Pos(':', AInitStr); if n > 0 then begin Self.FFileName := Copy(AInitStr, n + 1, MaxInt); end else Self.FFileName := AInitStr; end; if FFileName = '' then Exit; if not FileExists(FFileName) then begin // file not exists - test file create and write try FFileHandle := FileCreate(FFileName); except FFileHandle := feInvalidHandle; end; if FFileHandle = feInvalidHandle then Exit; {$ifdef CHECK_FILE_WRITE} // try to write first char of filename into file try FileWrite(FFileHandle, FFileName[1], 1); FileTruncate(FFileHandle, 0); if not FKeepOpen then begin FileClose(FFileHandle); FFileHandle := feInvalidHandle; end; except FileClose(FFileHandle); FFileHandle := feInvalidHandle; Exit; end; {$endif} end else begin if KeepOpen then begin try FFileHandle := FileOpen(FFileName, fmOpenReadWrite); except FFileHandle := feInvalidHandle; end; if FFileHandle = feInvalidHandle then Exit; if WriteMode = fwmAppend then FileSeek(FFileHandle, 0, fsFromEnd); end; end; inherited Open(AInitStr); end; procedure TDataPortFile.Close(); begin if KeepOpen or (FFileHandle <> feInvalidHandle) then begin FileClose(FFileHandle); FFileHandle := feInvalidHandle; end; inherited Close(); end; destructor TDataPortFile.Destroy(); begin FreeAndNil(self.lock); inherited Destroy(); end; procedure TDataPortFile.OnIncomingMsgHandler(Sender: TObject; const AMsg: string); begin if AMsg <> '' then begin if lock.BeginWrite then begin sReadData := sReadData + AMsg; lock.EndWrite; if Cardinal(Length(sReadData)) >= FMinDataBytes then begin if Assigned(FOnDataAppear) then FOnDataAppear(self); end; end; end; end; procedure TDataPortFile.OnErrorHandler(Sender: TObject; const AMsg: string); begin if Assigned(Self.FOnError) then Self.FOnError(Self, AMsg); end; procedure TDataPortFile.ReadToSelf(); var buf: array [0..1023] of byte; s: string; res: Integer; begin if not KeepOpen then begin // open file if FFileName = '' then Exit; try FFileHandle := FileOpen(FFileName, fmOpenReadWrite or fmShareDenyNone); if WriteMode = fwmAppend then FileSeek(FFileHandle, FilePos, fsFromBeginning); except on E: Exception do begin if Assigned(FOnError) then FOnError(Self, E.Message); Exit; end; end; end; // read data to buf try res := FileRead(FFileHandle, buf, SizeOf(buf)); except on E: Exception do begin if Assigned(FOnError) then FOnError(Self, E.Message); Exit; end; end; // if write-mode Rewrite then truncate readed data if WriteMode = fwmRewrite then FileTruncate(FFileHandle, 0) else if (WriteMode = fwmAppend) and (res > 0) then FilePos := FilePos + Cardinal(res); // read data from buf to result {$ifdef FPC} SetString(s, @buf, res); {$else} SetString(s, PChar(@buf), res); {$endif} sReadData := sReadData + s; if not KeepOpen then begin // close file FileClose(FFileHandle); FFileHandle := feInvalidHandle; end; end; function TDataPortFile.Peek(size: Integer = MaxInt): AnsiString; begin lock.BeginRead(); try ReadToSelf(); Result := Copy(sReadData, 1, size); finally lock.EndRead(); end; end; function TDataPortFile.PeekSize(): Cardinal; begin lock.BeginRead(); try ReadToSelf(); Result := Cardinal(Length(sReadData)); finally lock.EndRead(); end; end; function TDataPortFile.ioctl_cmd(const ACmd: string): string; {$IFDEF UNIX} var iArg, iRes: Integer; {$ENDIF} begin { * Per POSIX guidelines, this module reserves the LP and lp prefixes * These are the lp_table[minor].flags flags... #define LP_EXIST 0x0001 #define LP_SELEC 0x0002 #define LP_BUSY 0x0004 #define LP_BUSY_BIT_POS 2 #define LP_OFFL 0x0008 #define LP_NOPA 0x0010 #define LP_ERR 0x0020 #define LP_ABORT 0x0040 #define LP_CAREFUL 0x0080 /* obsoleted -arca */ #define LP_ABORTOPEN 0x0100 * bit defines for 8255 status port * base + 1 * accessed with LP_S(minor), which gets the byte... #define LP_PBUSY 0x80 /* inverted input, active high */ #define LP_PACK 0x40 /* unchanged input, active low */ #define LP_POUTPA 0x20 /* unchanged input, active high */ #define LP_PSELECD 0x10 /* unchanged input, active high */ #define LP_PERRORP 0x08 /* unchanged input, active low */ #define LPGETSTATUS 0x060b /* return LP_S(minor) */ #define LPRESET 0x060c /* reset printer */ } Result := ''; if not KeepOpen then begin // open file if FFileName = '' then Exit; try FFileHandle := FileOpen(FFileName, fmOpenReadWrite or fmShareDenyNone); except on E: Exception do begin if Assigned(FOnError) then FOnError(Self, E.Message); Exit; end; end; end; if ACmd = 'LPGETSTATUS' then begin {$IFDEF UNIX} iRes := FpIOCtl(FFileHandle, $060b, @iArg); Result := IntToHex(iArg, 4) + ' '; if (iArg and $80) > 0 then Result := Result + 'busy '; // busy input if (iArg and $40) = 0 then Result := Result + 'ack '; // acknowleged input if (iArg and $20) > 0 then Result := Result + 'outpa '; // out-of-paper if (iArg and $10) > 0 then Result := Result + 'selectd '; // selected input if (iArg and $08) = 0 then Result := Result + 'errorp '; // error input {$ENDIF} end else if ACmd = 'LPRESET' then begin {$IFDEF UNIX} iRes := FpIOCtl(FFileHandle, $060c, @iArg); {$ENDIF} end; if not KeepOpen then begin // close file FileClose(FFileHandle); FFileHandle := feInvalidHandle; end; end; function TDataPortFile.Pull(size: Integer = MaxInt): AnsiString; begin Result := ''; if lock.BeginWrite() then begin try ReadToSelf(); Result := Copy(sReadData, 1, size); Delete(sReadData, 1, size); //sReadData:=''; finally lock.EndWrite(); end; end; end; function TDataPortFile.Push(const AData: AnsiString): boolean; var sErrMsg: string; begin Result := False; if Length(AData) = 0 then Exit; if lock.BeginWrite() then begin sErrMsg := ''; try if KeepOpen then begin try if Length(AData) > 0 then FileWrite(FFileHandle, PAnsiChar(AData)^, Length(AData)); Result := True; except on E: Exception do begin sErrMsg := E.Message; end; end; end else begin if FFileName = '' then Exit; try //FFileHandle:=FileOpen(FFileName, fmOpenReadWrite or fmShareCompat); FFileHandle := FileOpen(FFileName, fmOpenReadWrite or fmShareDenyWrite); if WriteMode = fwmAppend then FileSeek(FFileHandle, 0, fsFromEnd); if Length(AData) > 0 then FileWrite(FFileHandle, PAnsiChar(AData)^, Length(AData)); FileClose(FFileHandle); Result := True; except on E: Exception do begin sErrMsg := E.Message; end; end; FFileHandle := feInvalidHandle; end; finally lock.EndWrite(); end; if Assigned(FOnError) and (sErrMsg <> '') then FOnError(Self, sErrMsg); end; end; procedure TDataPortFile.SetActive(Val: boolean); begin inherited SetActive(Val); //if FActive then Open(); //else if Assigned(self.IpClient) then FreeAndNil(self.IpClient); end; end.
{***********************************************} { } { XML Data Binding } { } { Generated on: 2011-01-29 ¿ÀÈÄ 2:59:31 } { Generated from: C:\test1.xml } { Settings stored in: C:\test1.xdb } { } {***********************************************} unit weather; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLCurrentType = interface; IXMLWeatherType = interface; IXMLLocalType = interface; { IXMLCurrentType } IXMLCurrentType = interface(IXMLNode) ['{C28C46F7-67B5-4114-B56C-F5E389FFFE98}'] { Property Accessors } function Get_Xmlns: UnicodeString; function Get_Weather: IXMLWeatherType; procedure Set_Xmlns(Value: UnicodeString); { Methods & Properties } property Xmlns: UnicodeString read Get_Xmlns write Set_Xmlns; property Weather: IXMLWeatherType read Get_Weather; end; { IXMLWeatherType } IXMLWeatherType = interface(IXMLNodeCollection) ['{7227AC4D-0275-4105-9C3A-E7F40E79A20D}'] { Property Accessors } function Get_Year: Integer; function Get_Month: Integer; function Get_Day: Integer; function Get_Hour: Integer; function Get_Local(Index: Integer): IXMLLocalType; procedure Set_Year(Value: Integer); procedure Set_Month(Value: Integer); procedure Set_Day(Value: Integer); procedure Set_Hour(Value: Integer); { Methods & Properties } function Add: IXMLLocalType; function Insert(const Index: Integer): IXMLLocalType; property Year: Integer read Get_Year write Set_Year; property Month: Integer read Get_Month write Set_Month; property Day: Integer read Get_Day write Set_Day; property Hour: Integer read Get_Hour write Set_Hour; property Local[Index: Integer]: IXMLLocalType read Get_Local; default; end; { IXMLLocalType } IXMLLocalType = interface(IXMLNode) ['{42726FCA-9A53-489C-9A62-B1435E68D243}'] { Property Accessors } function Get_Stn_id: Integer; function Get_Icon: Integer; function Get_Desc: UnicodeString; function Get_Ta: UnicodeString; function Get_Rn_hr1: UnicodeString; function Get_Sd_day: UnicodeString; procedure Set_Stn_id(Value: Integer); procedure Set_Icon(Value: Integer); procedure Set_Desc(Value: UnicodeString); procedure Set_Ta(Value: UnicodeString); procedure Set_Rn_hr1(Value: UnicodeString); procedure Set_Sd_day(Value: UnicodeString); { Methods & Properties } property Stn_id: Integer read Get_Stn_id write Set_Stn_id; property Icon: Integer read Get_Icon write Set_Icon; property Desc: UnicodeString read Get_Desc write Set_Desc; property Ta: UnicodeString read Get_Ta write Set_Ta; property Rn_hr1: UnicodeString read Get_Rn_hr1 write Set_Rn_hr1; property Sd_day: UnicodeString read Get_Sd_day write Set_Sd_day; end; { Forward Decls } TXMLCurrentType = class; TXMLWeatherType = class; TXMLLocalType = class; { TXMLCurrentType } TXMLCurrentType = class(TXMLNode, IXMLCurrentType) protected { IXMLCurrentType } function Get_Xmlns: UnicodeString; function Get_Weather: IXMLWeatherType; procedure Set_Xmlns(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLWeatherType } TXMLWeatherType = class(TXMLNodeCollection, IXMLWeatherType) protected { IXMLWeatherType } function Get_Year: Integer; function Get_Month: Integer; function Get_Day: Integer; function Get_Hour: Integer; function Get_Local(Index: Integer): IXMLLocalType; procedure Set_Year(Value: Integer); procedure Set_Month(Value: Integer); procedure Set_Day(Value: Integer); procedure Set_Hour(Value: Integer); function Add: IXMLLocalType; function Insert(const Index: Integer): IXMLLocalType; public procedure AfterConstruction; override; end; { TXMLLocalType } TXMLLocalType = class(TXMLNode, IXMLLocalType) protected { IXMLLocalType } function Get_Stn_id: Integer; function Get_Icon: Integer; function Get_Desc: UnicodeString; function Get_Ta: UnicodeString; function Get_Rn_hr1: UnicodeString; function Get_Sd_day: UnicodeString; procedure Set_Stn_id(Value: Integer); procedure Set_Icon(Value: Integer); procedure Set_Desc(Value: UnicodeString); procedure Set_Ta(Value: UnicodeString); procedure Set_Rn_hr1(Value: UnicodeString); procedure Set_Sd_day(Value: UnicodeString); end; { Global Functions } function Getcurrent(Doc: IXMLDocument): IXMLCurrentType; function Loadcurrent(const FileName: string): IXMLCurrentType; function Newcurrent: IXMLCurrentType; const TargetNamespace = 'current'; implementation { Global Functions } function Getcurrent(Doc: IXMLDocument): IXMLCurrentType; begin Result := Doc.GetDocBinding('current', TXMLCurrentType, TargetNamespace) as IXMLCurrentType; end; function Loadcurrent(const FileName: string): IXMLCurrentType; begin Result := LoadXMLDocument(FileName).GetDocBinding('current', TXMLCurrentType, TargetNamespace) as IXMLCurrentType; end; function Newcurrent: IXMLCurrentType; begin Result := NewXMLDocument.GetDocBinding('current', TXMLCurrentType, TargetNamespace) as IXMLCurrentType; end; { TXMLCurrentType } procedure TXMLCurrentType.AfterConstruction; begin RegisterChildNode('weather', TXMLWeatherType); inherited; end; function TXMLCurrentType.Get_Xmlns: UnicodeString; begin Result := AttributeNodes['xmlns'].Text; end; procedure TXMLCurrentType.Set_Xmlns(Value: UnicodeString); begin SetAttribute('xmlns', Value); end; function TXMLCurrentType.Get_Weather: IXMLWeatherType; begin Result := ChildNodes['weather'] as IXMLWeatherType; end; { TXMLWeatherType } procedure TXMLWeatherType.AfterConstruction; begin RegisterChildNode('local', TXMLLocalType); ItemTag := 'local'; ItemInterface := IXMLLocalType; inherited; end; function TXMLWeatherType.Get_Year: Integer; begin Result := AttributeNodes['year'].NodeValue; end; procedure TXMLWeatherType.Set_Year(Value: Integer); begin SetAttribute('year', Value); end; function TXMLWeatherType.Get_Month: Integer; begin Result := AttributeNodes['month'].NodeValue; end; procedure TXMLWeatherType.Set_Month(Value: Integer); begin SetAttribute('month', Value); end; function TXMLWeatherType.Get_Day: Integer; begin Result := AttributeNodes['day'].NodeValue; end; procedure TXMLWeatherType.Set_Day(Value: Integer); begin SetAttribute('day', Value); end; function TXMLWeatherType.Get_Hour: Integer; begin Result := AttributeNodes['hour'].NodeValue; end; procedure TXMLWeatherType.Set_Hour(Value: Integer); begin SetAttribute('hour', Value); end; function TXMLWeatherType.Get_Local(Index: Integer): IXMLLocalType; begin Result := List[Index] as IXMLLocalType; end; function TXMLWeatherType.Add: IXMLLocalType; begin Result := AddItem(-1) as IXMLLocalType; end; function TXMLWeatherType.Insert(const Index: Integer): IXMLLocalType; begin Result := AddItem(Index) as IXMLLocalType; end; { TXMLLocalType } function TXMLLocalType.Get_Stn_id: Integer; begin Result := AttributeNodes['stn_id'].NodeValue; end; procedure TXMLLocalType.Set_Stn_id(Value: Integer); begin SetAttribute('stn_id', Value); end; function TXMLLocalType.Get_Icon: Integer; begin Result := AttributeNodes['icon'].NodeValue; end; procedure TXMLLocalType.Set_Icon(Value: Integer); begin SetAttribute('icon', Value); end; function TXMLLocalType.Get_Desc: UnicodeString; begin Result := AttributeNodes['desc'].Text; end; procedure TXMLLocalType.Set_Desc(Value: UnicodeString); begin SetAttribute('desc', Value); end; function TXMLLocalType.Get_Ta: UnicodeString; begin Result := AttributeNodes['ta'].Text; end; procedure TXMLLocalType.Set_Ta(Value: UnicodeString); begin SetAttribute('ta', Value); end; function TXMLLocalType.Get_Rn_hr1: UnicodeString; begin Result := AttributeNodes['rn_hr1'].Text; end; procedure TXMLLocalType.Set_Rn_hr1(Value: UnicodeString); begin SetAttribute('rn_hr1', Value); end; function TXMLLocalType.Get_Sd_day: UnicodeString; begin Result := AttributeNodes['sd_day'].Text; end; procedure TXMLLocalType.Set_Sd_day(Value: UnicodeString); begin SetAttribute('sd_day', Value); 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 September '1999 Problem 31 O(N3) Floyd Method } program SemiConnectedGraph; const MaxN = 100; var N : Integer; G : array [1 .. MaxN, 1 .. MaxN] of Integer; I, J, K : Integer; F : Text; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); for I := 1 to N do begin for J := 1 to N do begin Read(F, G[I, J]); if (G[I, J] = 0) and (I <> J) then G[I, J] := 10000; end; Readln(F); end; Close(F); end; procedure NonSemiCon; begin Writeln('Graph is not SemiConnected.'); Halt; end; procedure SemiCon; begin for K := 1 to N do for I := 1 to N do for J := 1 to N do if G[I, J] > G[I, K] + G[K, J] then G[I, J] := G[I, K] + G[K, J]; for I := 1 to N do for J := 1 to N do if G[I, J] + G[J, I] = 20000 then NonSemiCon; Writeln('Graph is SemiConnected.'); end; begin ReadInput; SemiCon; end.
unit fChat; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, uIRCRichEdit, Contnrs; const WM_ADDTEXT = WM_USER + 100; type TIRCParams = class public TimeStamp: TDateTime; RawCommand: string; Nickname: string; Host: string; Target: string; Text: string; IsMe: Boolean; Text2: string; Sign: string; Nickname2: string; end; TChatFrame = class(TFrame) procedure FrameResize(Sender: TObject); private FChatEdit: TIRCRichEdit; FTreeNode: TTreeNode; FNicknames: TStrings; FTopic: string; FTheme: TStrings; FMarkerLine: Integer; FMarkerDropped: Boolean; FIRCLines: TObjectList; procedure CheckAndDropMarker; procedure AddIRCLineToMemo(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); procedure CreateChatEdit; procedure SetTreeNode(const Value: TTreeNode); procedure ChatEditURLClick(Sender: TObject; const URL: string); procedure ChatEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetTopic(const Value: string); procedure WmAddText(var Message: TMessage); message WM_ADDTEXT; function GetMarkerCharCount: Integer; procedure DeleteMarker; procedure SetMarkerDropped(const Value: Boolean); procedure AddTextToMemo(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); procedure AddIRCLine(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); overload; procedure SetMarkerLine(const Value: Integer); public procedure RecreateMarkerLine; procedure DropMarker; property MarkerLine: Integer read FMarkerLine write SetMarkerLine; procedure AddText(const AText: string); procedure AddStrings(const AStrings: TStrings); procedure AddIRCLine(const ARawCmd, ANickname, AHost, ATarget, AText: string; const AIsMe: Boolean; const AText2: string = ''; const ASign: string = ''; const ANickname2: string = ''; const AMultiThreaded: Boolean = True); overload; property TreeNode: TTreeNode read FTreeNode write SetTreeNode; constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Nicknames: TStrings read FNicknames; property Topic: string read FTopic write SetTopic; property ChatEdit: TIRCRichEdit read FChatEdit; property MarkerDropped: Boolean read FMarkerDropped write SetMarkerDropped; procedure ReloadTheme; end; implementation uses ShellAPI, fMain, Clipbrd, IniFiles, StrUtils, Math; {$R *.dfm} { TChatFrame } const MarkerDelim = #1; ScrollBackLength = 300; procedure TChatFrame.AddIRCLine(const ARawCmd, ANickname, AHost, ATarget, AText: string; const AIsMe: Boolean; const AText2: string = ''; const ASign: string = ''; const ANickname2: string = ''; const AMultiThreaded: Boolean = True); var IRCParams: TIRCParams; begin IRCParams := TIRCParams.Create; IRCParams.RawCommand := ARawCmd; IRCParams.Nickname := ANickname; IRCParams.Host := AHost; IRCParams.Target := ATarget; IRCParams.Text := AText; IRCParams.IsMe := AIsMe; IRCParams.Text2 := AText2; IRCParams.Sign := ASign; IRCParams.Nickname2 := ANickname2; AddIRCLine(IRCParams, AMultiThreaded); end; procedure TChatFrame.CheckAndDropMarker; begin if ((MainForm.ActiveChatFrame <> Self) or (MainForm.WindowState = wsMinimized) or not MainForm.Active) then begin if not FMarkerDropped then begin DropMarker; PostMessage(MainForm.Handle, WM_PAINTCHANNELS, 0, 0); FMarkerLine := FIRCLines.Count - 1; FMarkerDropped := True; end; end else FMarkerDropped := False; end; procedure TChatFrame.AddIRCLine(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); begin AIRCParams.TimeStamp := Now; AddIRCLineToMemo(AIRCParams, AMultiThreaded); end; procedure TChatFrame.AddStrings(const AStrings: TStrings); var I: Integer; begin for I := 0 to AStrings.Count - 1 do AddText(AStrings[I]); end; procedure TChatFrame.AddText(const AText: string); begin AddIRCLine('TEXT', '', '', '', AText, False); end; procedure TChatFrame.AddIRCLineToMemo(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); begin if AMultiThreaded then begin PostMessage(Handle, WM_ADDTEXT, Integer(AIRCParams), Integer(AMultiThreaded)); end else begin AddTextToMemo(AIRCParams, AMultiThreaded); end; end; procedure TChatFrame.WmAddText(var Message: TMessage); begin AddTextToMemo(TIRCParams(Message.WParam), Boolean(Message.LParam)); end; procedure TChatFrame.AddTextToMemo(const AIRCParams: TIRCParams; const AMultiThreaded: Boolean = True); var FormatStr, Ident: string; begin MainForm.Perform(WM_SETREDRAW, 0, 0); ChatEdit.Lines.BeginUpdate; try // if AMultiThreaded then // FIRCLines.Add(AIRCParams); if (SameText(AIRCParams.RawCommand, 'RAWIN') or SameText(AIRCParams.RawCommand, 'RAWOUT')) and not MainForm.RawAction.Checked then Exit; //only drop a marker if someone talks if (SameText(AIRCParams.RawCommand, 'PRIVMSG') or SameText(AIRCParams.RawCommand, 'CHANMSG') or SameText(AIRCParams.RawCommand, 'ACTION')) and AMultiThreaded then CheckAndDropMarker; FormatStr := ''; if AIRCParams.IsMe then begin Ident := Format('MY%s', [AIRCParams.RawCommand]); FormatStr := FTheme.Values[Ident]; end; if FormatStr = '' then FormatStr := FTheme.Values[AIRCParams.RawCommand]; if FormatStr = '' then FormatStr := Format('%s %s %s %s %s', [AIRCParams.RawCommand, AIRCParams.Nickname, AIRCParams.Host, AIRCParams.Target, AIRCParams.Text]) else begin FormatStr := StringReplace(FormatStr, '$indent', IndentDelim, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$nick2', AIRCParams.Nickname2, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$nick', AIRCParams.Nickname, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$sign', AIRCParams.Sign, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$host', AIRCParams.Host, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$target', AIRCParams.Target, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$text2', AIRCParams.Text2, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$text', AIRCParams.Text, [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$time', FormatDateTime(FTheme.Values['TIME'], AIRCParams.TimeStamp), [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$prompt', FTheme.Values['PROMPT'], [rfReplaceAll, rfIgnoreCase]); FormatStr := StringReplace(FormatStr, '$br', #13#10, [rfReplaceAll, rfIgnoreCase]); end; while FChatEdit.Lines.Count >= ScrollBackLength do FChatEdit.Lines.Delete(0); FChatEdit.AddIRCText(FormatStr); finally MainForm.Perform(WM_SETREDRAW, 1, 0); MainForm.RedrawWindow(MainForm.Handle, True); ChatEdit.Lines.EndUpdate; end; end; constructor TChatFrame.Create(AOwner: TComponent); begin inherited; FIRCLines := TObjectList.Create; FNicknames := TStringList.Create; FMarkerLine := -1; CreateChatEdit; FTheme := TStringList.Create; ReloadTheme; end; procedure TChatFrame.CreateChatEdit; begin FChatEdit := TIRCRichEdit.Create(Self); FChatEdit.Parent := Self; FChatEdit.BorderStyle := bsNone; FChatEdit.Align := alClient; FChatEdit.HideSelection := False; FChatEdit.ParentColor := True; FChatEdit.ReadOnly := True; FChatEdit.ScrollBars := ssVertical; FChatEdit.OnURLClick := ChatEditURLClick; FChatEdit.OnMouseUp := ChatEditMouseUp; HideCaret(FChatEdit.Handle); end; procedure TChatFrame.ChatEditURLClick(Sender :TObject; const URL: string); begin ShellExecute(Handle, 'open', PChar(URL), nil, nil, SW_SHOWNORMAL); end; procedure TChatFrame.ChatEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FChatEdit.CopyToClipboard; FChatEdit.SelLength := 0; MainForm.InputFrame.InputEdit.SetFocus; end; destructor TChatFrame.Destroy; begin FIRCLines.Free; FTheme.Free; FNicknames.Free; if not (csDestroying in ComponentState) then TTreeView(FTreeNode.TreeView).Items.Delete(FTreeNode); inherited; end; procedure TChatFrame.DropMarker; begin if FMarkerLine >= 0 then DeleteMarker; ChatEdit.AddIRCText(MarkerDelim + DupeString('-', GetMarkerCharCount) + MarkerDelim); end; procedure TChatFrame.DeleteMarker; var I: Integer; Line: string; begin for I := 0 to ChatEdit.Lines.Count - 1 do begin if Length(ChatEdit.Lines[I]) > 0 then begin Line := ChatEdit.Lines[I]; if Line[1] = MarkerDelim then begin ChatEdit.Lines.Delete(I); if Line[Length(Line)] <> MarkerDelim then begin while Pos(MarkerDelim, ChatEdit.Lines[I]) = 0 do begin ChatEdit.Lines.Delete(I); end; ChatEdit.Lines.Delete(I); end; Break; end; end; end; end; function TChatFrame.GetMarkerCharCount: Integer; var MarkerWidth: Integer; begin Result := 1; MarkerWidth := MainForm.Canvas.TextWidth(DupeString('-', Result)) + GetSystemMetrics(SM_CXVSCROLL); while MarkerWidth < Width do begin Inc(Result); MarkerWidth := MainForm.Canvas.TextWidth(DupeString('-', Result)) + GetSystemMetrics(SM_CXVSCROLL); end; Dec(Result, 3); end; procedure TChatFrame.ReloadTheme; var I, Count, StartIndex: Integer; IRCParams: TIRCParams; begin FTheme.LoadFromFile(ExtractFilePath(Application.ExeName) + MainForm.CurrentTheme + '.theme'); // if FIRCLines.Count = 0 then // Exit; ChatEdit.Lines.BeginUpdate; try ChatEdit.Clear; ChatEdit.SelectAll; ChatEdit.SelAttributes.Color := ChatEdit.Font.Color; ChatEdit.SelLength := 0; I := FIRCLines.Count - 1; Count := 0; while (Count < ScrollBackLength) and (I > 0) do begin IRCParams := TIRCParams(FIRCLines[I]); if (not SameText(IRCParams.RawCommand, 'RAWIN') and not SameText(IRCParams.RawCommand, 'RAWOUT')) or MainForm.RawAction.Checked then Inc(Count); Dec(I); end; StartIndex := I; if I < 0 then Exit; for I := StartIndex to FIRCLines.Count - 1 do begin if I = FMarkerLine then DropMarker; AddIRCLineToMemo(TIRCParams(FIRCLines[I]), False); end; finally ChatEdit.Lines.EndUpdate; end; end; procedure TChatFrame.RecreateMarkerLine; var I: Integer; Line: string; begin if FMarkerLine >= 0 then begin for I := 0 to ChatEdit.Lines.Count - 1 do begin if Length(ChatEdit.Lines[I]) > 0 then begin Line := ChatEdit.Lines[I]; if Line[1] = MarkerDelim then begin MainForm.Perform(WM_SETREDRAW, 0, 0); ChatEdit.Lines.BeginUpdate; try ChatEdit.Lines.Delete(I); if Line[Length(Line)] <> MarkerDelim then begin while Pos(MarkerDelim, ChatEdit.Lines[I]) = 0 do begin ChatEdit.Lines.Delete(I); end; ChatEdit.Lines.Delete(I); end; ChatEdit.Lines.Insert(I, MarkerDelim + DupeString('-', GetMarkerCharCount) + MarkerDelim); ChatEdit.SelStart := 0; ChatEdit.SelStart := Length(ChatEdit.Text); Break; finally MainForm.Perform(WM_SETREDRAW, 1, 0); MainForm.RedrawWindow(MainForm.Handle, True); ChatEdit.Lines.EndUpdate; end; end; end; end; end; end; procedure TChatFrame.FrameResize(Sender: TObject); begin RecreateMarkerLine; end; procedure TChatFrame.SetMarkerDropped(const Value: Boolean); begin FMarkerDropped := Value; end; procedure TChatFrame.SetMarkerLine(const Value: Integer); begin FMarkerLine := Value; end; procedure TChatFrame.SetTopic(const Value: string); begin FTopic := Value; end; procedure TChatFrame.SetTreeNode(const Value: TTreeNode); begin FTreeNode := Value; end; end.
{*******************************************************} { } { Delphi Runtime Library } { SOAP Support } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Soap.SOAPConst; interface uses System.TypInfo, Xml.XMLSchema; const SHTTPPrefix = 'http://'; { Do not localize } SContentId = 'Content-ID'; { Do not localize } SContentLocation = 'Content-Location'; { Do not localize } SContentLength = 'Content-Length'; { Do not localize } SContentType = 'Content-Type'; { Do not localize } SWSDLMIMENamespace = 'http://schemas.xmlsoap.org/wsdl/mime/';{ Do not localize } SBorlandMimeBoundary = 'MIME_boundaryB0R9532143182121'; SSoapXMLHeader = '<?xml version="1.0" encoding=''UTF-8''?>'; { Do not localize } SUTF8 = 'UTF-8'; { Do not localize } ContentTypeTemplate = 'Content-Type: %s'; { Do not localize } ContentTypeWithActionFmt = 'Content-Type: %s;action="%s"'; { Do not localize } ContentTypeWithActionNoLabelFmt = '%s;action="%s"'; { Do not localize } ContentTypeApplicationBinary = 'application/binary'; { Do not localize } SBinaryEncoding = 'binary'; { Do not localize } S8BitEncoding = '8bit'; { Do not localize } ContentTypeTextPlain = 'text/plain'; { Do not localize } SCharacterEncodingFormat = 'Content-transfer-encoding: %s'; { Do not localize } SCharacterEncoding = 'Content-transfer-encoding'; { Do not localize } SBoundary = 'boundary='; { Do not localize } SMultiPartRelated = 'multipart/related'; { Do not localize } SMultiPartRelatedNoSlash = 'multipartRelated'; { Do not localize } ContentHeaderMime = SMultiPartRelated + '; boundary=%s'; { Do not localize } SStart = '; start="<%s>"'; { Do not localize } SBorlandSoapStart = 'http://www.borland.com/rootpart.xml'; { Do not localize } SAttachmentIdPrefix = 'cid:'; { Do not localize } MimeVersion = 'MIME-Version: 1.0'; sTextHtml = 'text/html'; { Do not localize } sTextHtmlUTF8 = 'text/html; charset="utf-8"'; { Do not localize } sTextXML = 'text/xml'; { Do not localize } ContentTypeUTF8 = 'text/xml; charset="utf-8"'; { Do not localize } ContentTypeNoUTF8 = 'text/xml'; { Do not localize } ContentType12UTF8 = 'application/soap+xml; charset="utf-8"'; { Do not localize } ContentType12NoUTF8 = 'application/soap+xml'; { Do not localize } SSoapNamespace = 'http://schemas.xmlsoap.org/soap/envelope/'; { do not localize } SSoap12Namespace = 'http://www.w3.org/2003/05/soap-envelope'; { do not localize } SOAPEnvelopeNamespaces: array[Boolean] of string = (SSoapNamespace, SSoap12Namespace); SXMLNS = 'xmlns'; { do not localize } SSoapEncodingAttr = 'encodingStyle'; { do not localize } SSoap11EncodingS5 = 'http://schemas.xmlsoap.org/soap/encoding/'; { do not localize } SSoap12EncodingNamespace = 'http://www.w3.org/2003/05/soap-encoding'; { do not localize } SOAPEncodingNamespaces: array[Boolean] of string = (SSoap11EncodingS5, SSoap12EncodingNamespace); SSOAP12RPCNamespace = 'http://www.w3.org/2003/05/soap-rpc'; { do not localize } SSoapEncodingArray = 'Array'; { do not localize } SSoapEncodingArrayType = 'arrayType'; { do not localize } SSoap12EncodingArrayType = 'itemType'; { do not localize } SSoapEncodingArrayTypes: array[Boolean] of string = (SSoapEncodingArrayType, SSoap12EncodingArrayType); SSoap12EncodingArraySize = 'arraySize'; { do not localize } SSoapHTTPTransport = 'http://schemas.xmlsoap.org/soap/http'; { do not localize } SSoapBodyUseEncoded = 'encoded'; { do not localize } SSoapBodyUseLiteral = 'literal'; { do not localize } SSoapEnvelope = 'Envelope'; { do not localize } SSoapHeader = 'Header'; { do not localize } SSoapBody = 'Body'; { do not localize } SSoapResponseSuff = 'Response'; { do not localize } SRequired = 'required'; { do not localize } SSoapActor = 'actor'; { do not localize } STrue = 'true'; { do not localize } SSoapServerFaultCode = 'Server'; { do not localize } SSoapServerFaultString = 'Server Error'; { do not localize } SSoapFault = 'Fault'; { do not localize } SSoapFaultCode = 'faultcode'; { do not localize } SSoapFaultString = 'faultstring'; { do not localize } SSoapFaultActor = 'faultactor'; { do not localize } SSoapFaultDetails = 'detail'; { do not localize } SFaultCodeMustUnderstand = 'MustUnderstand'; { do not localize } SSOAP12FaultCode = 'Code'; SSOAP12FaultSubCode = 'Subcode'; SSOAP12FaultReason = 'Reason'; SSOAP12FaultReasonLang = 'lang'; SSOAP12FaultNode = 'Node'; SSOAP12FaultRole = 'Role'; SSOAP12FaultDetail = 'Detail'; SSOAP12FaultText = 'Text'; SHTTPSoapAction = 'SOAPAction'; { do not localize } SHeaderMustUnderstand = 'mustUnderstand'; { do not localize } SHeaderActor = 'actor'; { do not localize } SActorNext= 'http://schemas.xmlsoap.org/soap/actor/next';{ do not localize } SSoapType = 'type'; { do not localize } SSoapResponse = 'Response'; { do not localize } SDefaultReturnName = 'return'; { do not localize } SDefaultResultName = 'result'; { do not localize } SXMLID = 'id'; { do not localize } SXMLHREF = 'href'; { do not localize } SSOAP12XMLHREF = 'ref'; { do not localize } SSOAPXMLHREFs: array[Boolean] of string = (SXMLHREF, SSOAP12XMLHREF); SSoapNULL = 'NULL'; { do not localize } SSoapNIL = 'nil'; { do not localize } SSoapNillable = 'nillable'; { do not localize } SOptional = 'optional'; { do not localize } SElemForm = 'form'; { do not localize } SUnqualified = 'unqualified'; { do not localize } SHREFPre = '#'; { do not localize } SSOAP12HREFPre = ''; { do not localize } SSOAPHREFPres: array[Boolean] of WideString = (SHREFPre, SSOAP12HREFPre); SArrayIDPre = 'Array-'; { do not localize } SDefVariantElemName = 'V'; { do not localize } SDefaultBaseURI = 'thismessage:/'; { do not localize } SDelphiTypeNamespace = 'http://www.borland.com/namespaces/Delphi/Types'; { do not localize } SBorlandTypeNamespace= 'http://www.borland.com/namespaces/Types'; { do not localize } SOperationNameSpecifier = '%operationName%'; { Do not localize } SDefaultReturnParamNames= 'Result;Return'; { Do not localize } sReturnParamDelimiters = ';,/:'; { Do not localize } KindNameArray: array[tkUnknown..tkDynArray] of string = ('Unknown', 'Integer', 'Char', 'Enumeration', 'Float', { do not localize } 'String', 'Set', 'Class', 'Method', 'WChar', 'LString', 'WString', { do not localize } 'Variant', 'Array', 'Record', 'Interface', 'Int64', 'DynArray'); { do not localize } SSoapNameSpacePre = 'SOAP-ENV'; { do not localize } SXMLSchemaNameSpacePre = 'xsd'; { do not localize } SXMLSchemaInstNameSpace99Pre = 'xsi'; { do not localize } SSoapEncodingPre = 'SOAP-ENC'; { do not localize } {$IFDEF D6_STYLE_COLORS} sDefaultColor = '#006699'; sIntfColor = '#006699'; sTblHdrColor = '#CCCC99'; sTblColor1 = '#FFFFCC'; sTblColor0 = '#CCCC99'; sBkgndColor = '#CCCC99'; sTipColor = '#666666'; sWSDLColor = '#666699'; sOFFColor = '#A0A0A0'; sNavBarColor = '#006699'; sNavBkColor = '#cccccc'; {$ELSE} sDefaultColor = '#333333'; sIntfColor = '#660000'; sTblHdrColor = '#CCCC99'; sTblColor1 = '#f5f5dc'; sTblColor0 = '#d9d4aa'; sBkgndColor = '#d9d4aa'; sTipColor = '#666666'; sWSDLColor = '#990000'; sOFFColor = '#A0A0A0'; sNavBarColor = '#660000'; sNavBkColor = '#f5f5dc'; {$ENDIF} HTMLStylBeg = '<style type="text/css"><!--' + sLineBreak; HTMLStylEnd = '--></style>' + sLineBreak; BodyStyle1 = 'body {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; }' + sLineBreak; BodyStyle2 = 'body {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; margin-left: 0px; margin-top: 0px; margin-right: 0px; }' + sLineBreak; OtherStyles = 'h1 {color: '+sDefaultColor+'; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h2 {color: '+sDefaultColor+'; font-size: 14pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h3 {color: '+sDefaultColor+'; font-size: 12pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.h1Style {color: '+sDefaultColor+'; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.TblRow {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; }' + sLineBreak + '.TblRow1 {color: '+sDefaultColor+'; background-color: '+sTblColor1+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblRow0 {color: '+sDefaultColor+'; background-color: '+sTblColor0+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblHdr {color: '+sTblHdrColor+ '; background-color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; text-align: center;}' + sLineBreak + '.IntfName {color: '+sIntfColor + '; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; }' + sLineBreak + '.MethName {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; text-decoration: none; }' + sLineBreak + '.ParmName {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; text-decoration: none; }' + sLineBreak + '.Namespace {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-style: italic; }' + sLineBreak + '.WSDL {color: '+sWSDLColor+ '; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; }' + sLineBreak + '.MainBkgnd {background-color : '+sBkgndColor+'; }' + sLineBreak + '.Info {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; }' + sLineBreak + '.NavBar {color: '+sNavBarColor+'; background-color: '+sNavBkColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold;text-decoration: none; }'+ sLineBreak + '.Off {color: '+sOFFColor+'; }' + sLineBreak + '.Tip {color: '+sTipColor+'; font-family : Verdana, Arial, Helvetica, sans-serif; font-weight : normal; font-size : 9pt; }' + sLineBreak; HTMLStyles = HTMLStylBeg + BodyStyle1 + OtherStyles + HTMLStylEnd; HTMLNoMargin= HTMLStylBeg + BodyStyle2 + OtherStyles + HTMLStylEnd; TableStyle = 'border=1 cellspacing=1 cellpadding=2 '; resourcestring HTMLContentLanguage = ''; // '<meta http-equiv="Content-Language" content="ja"><meta http-equiv="Content-Type" content="text/html; charset=shift_jis">'; const HTMLHead = '<html><head>'; HTMLServiceInspection = '<META name="serviceInspection" content="inspection.wsil">'; {resourcestring - these are getting truncated as resources currently resulting in bad HTML pages!!} HTMLTopPlain = HTMLHead + '</head><body>'; HTMLTop = HTMLHead + HTMLStyles + '</head>' + '<body>'; HTMLTopNoMargin = HTMLHead + HTMLNoMargin+'</head>' + '<body>'; HTMLTopTitleNoMargin = HTMLHead + '<title>%s</title>'+HTMLNoMargin+'</head><body>'; HTMLTopNoStyles = HTMLHead + '</head><body>'; HTMLTopTitle = HTMLHead + '<title>%s</title>'+HTMLStyles+'</head><body>'; HTMLTopTitleNoMarginWSIL = HTMLHead + HTMLServiceInspection + '<title>%s</title>'+HTMLNoMargin+'</head><body>'; const HTMLEnd = '</body></html>'; InfoTitle1 = '<table class="MainBkgnd" border=0 cellpadding=0 cellspacing=0 width="100%">' + '<tr><td>&nbsp;</td></tr>'; InfoTitle2 = '<tr><td class="h1Style" align="center">%s - %s</td></tr>' + '</table>'; TblCls: array[Boolean] of string = ('TblRow0', 'TblRow1'); sTblRow = 'TblRow'; sTblHdrCls = 'TblHdr'; sQueryStringIntf = 'intf'; { Do not localize } sQueryStringTypes= 'types'; { Do not localize } sNBSP = '&nbsp;'; { Do not localize } var XMLSchemaNameSpace: string = SXMLSchemaURI_2001; { Default namespace we publish under } XMLSchemaInstNameSpace: string = SXMLSchemaInstURI; resourcestring SUnsupportedEncodingSyle = 'Unsupported SOAP encodingStyle %s'; SInvalidSoapRequest = 'Invalid SOAP request'; SInvalidSoapResponse = 'Invalid SOAP response'; SMultiBodyNotSupported = 'Multiple body elements not supported'; SUnsupportedCC = 'Unsupported calling convention: %s'; SUnsupportedCCIntfMeth = 'Remote Method Call: unsupported calling convention %s for method %s on interface %s'; SInvClassNotRegistered = 'No invokable class registered that implements interface %s of (soap action/path) %s'; SInvInterfaceNotReg = 'No interface registered for soap action ''%s'''; SInvInterfaceNotRegURL = 'No interface registered for URL ''%s'''; SRemTypeNotRegistered = 'Remotable Type %s not registered'; STypeMismatchInParam = 'Type mismatch in parameter %s'; SNoSuchMethod = 'No method named ''%s'' is supported by interface ''%s'''; SInterfaceNotReg = 'Interface not registered, UUID = %s'; SInterfaceNoRTTI = 'Interface has no RTTI, UUID = %s'; SNoWSDL = 'No WSDL document associated with WSDLView'; SWSDLError = 'Invalid WSDL document ''%s'' - Please verify the location and content!'#13#10'Error: %s'; SEmptyWSDL = 'Empty document'; sNoWSDLURL = 'No WSDL or URL property was set in the THTTPRIO component. You must set the WSDL or URL property before invoking the Web Service'; sCantGetURL= 'Unable to retrieve the URL endpoint for Service/Port ''%s''/''%s'' from WSDL ''%s'''; SDataTypeNotSupported = 'Datatype of TypeKind: %s not supported as argument for remote invocation'; SUnknownSOAPAction = 'Unknown SOAPAction %s'; SScalarFromTRemotableS = 'Classes that represent scalar types must descend from TRemotableXS, %s does not'; SNoSerializeGraphs = 'Must enable multiref output for objects when serializing a graph of objects - (%s)'; SUnsuportedClassType = 'Conversion from class %s to SOAP is not supported - SOAP classes must derive from TRemotable'; SUnexpectedDataType = 'Internal error: data type kind %s cannot be converted to and from text'; SInvalidContentType = 'Received content of invalid Content-Type setting: %s - SOAP expects "text/xml"'; SArrayTooManyElem = 'Array Node: %s has too many elements'; SWrongDocElem = 'DocumentElement %s:%s expected, %s:%s found'; STooManyParameters = 'Too many parameters in method %s'; SArrayExpected = 'Array type expected. Node %s'; SNoInterfaceGUID = 'Class %s does not implement interface GUID %s'; SNoArrayElemRTTI = 'Element of Array type %s has no RTTI'; SInvalidResponse = 'Invalid SOAP Response'; SInvalidArraySpec = 'Invalid SOAP array specification'; SCannotFindNodeID = 'Cannot find node referenced by ID %s'; SNoNativeNULL = 'Option not set to allow Native type to be set to NULL'; SFaultCodeOnlyAllowed = 'Only one FaultCode element allowed'; SFaultStringOnlyAllowed = 'Only one FaultString element allowed'; SMissingFaultValue = 'Missing FaultString or FaultCode element'; SNoInterfacesInClass = 'Invokable Class %s implements no interfaces'; SCantReturnInterface = 'Pascal code generated by WSDL import cannot be modified to return an interface. GUID %s'; SVariantCastNotSupported = 'Type cannot be cast as Variant'; SVarDateNotSupported = 'varDate type not supported'; SVarDispatchNotSupported = 'varDispatch type not supported'; SVarErrorNotSupported = 'varError type not supported'; SVarVariantNotSupported = 'varVariant type not supported'; SHeaderError = 'Error Processing Header (%s)%s'; SMissingSoapReturn = 'SOAP Response Packet: element matching function return not found, received "%s"'; SInvalidPointer = 'Invalid Pointer'; SNoMessageConverter = 'No Native to Message converter set'; SNoMsgProcessingNode = 'No Message processing node set'; SHeaderAttributeError = 'Soap header %s with attribute ''mustUnderstand'' set to true was not handled'; {IntfInfo} SNoRTTI = 'Interface %s has no RTTI'; SNoRTTIParam = 'Parameter %s on Method %s of Interface %s has no RTTI'; {XSBuiltIns} SInvalidDateString = 'Invalid date string: %s'; SInvalidTimeString = 'Invalid time string: %s'; SInvalidHour = 'Invalid hour: %d'; SInvalidMinute = 'Invalid minute: %d'; SInvalidSecond = 'Invalid second: %d'; SInvalidFractionSecond = 'Invalid second: %f'; SInvalidMillisecond = 'Invalid millisecond: %d'; SInvalidFractionalSecond = 'Invalid fractional second: %f'; SInvalidHourOffset = 'Invalid hour offset: %d'; SInvalidDay = 'Invalid day: %d'; SInvalidMonth = 'Invalid month: %d'; SInvalidDuration = 'Invalid duration string: %s'; SMilSecRangeViolation = 'Millisecond Values must be between 000 - 999'; SInvalidYearConversion = 'Year portion of date too large for conversion'; SInvalidTimeOffset = 'Hour Offset portion of time invalid'; SInvalidDecimalString = 'Invalid decimal string: ''''%s'''''; SEmptyDecimalString = 'Cannot convert empty string to TBcd value'; SNoSciNotation = 'Cannot convert scientific notation to TBcd value'; SNoNAN = 'Cannot convert NAN to TBcd value'; SInvalidBcd = 'Invalid Bcd Precision (%d) or Scale (%d)'; SBcdStringTooBig = 'Cannot convert to TBcd: string has more than 64 digits: %s'; SInvalidHexValue = '%s is not a valid hex string'; SInvalidHTTPRequest = 'Invalid HTTP Request: Length is 0'; SInvalidHTTPResponse = 'Invalid HTTP Response: Length is 0'; {WebServExp} SInvalidBooleanParameter = 'ByteBool, WordBool and LongBool cannot be exposed by WebServices. Please use ''Boolean'''; {WSDLIntf} SWideStringOutOfBounds = 'WideString index out of bounds'; {WSDLPub} IWSDLPublishDoc = 'Lists all the PortTypes published by this Service'; sPortNameHeader = 'PortName'; sAddressHeader = 'address'; sAdminButtonCation = 'Administrator'; sAddButtonCaption = 'Add'; sDeleteButtonCaption = 'Remove'; SNoServiceForURL = 'No service available for URL %s'; SNoInterfaceForURL = 'No interface is registered to handle URL %s'; SNoClassRegisteredForURL = 'No Class is regisgtered to implement interface %s'; SEmptyURL = 'No URL was specified for ''GET'''; SInvalidURL = 'Invalid url ''%s'' - only supports ''http'' and ''https'' schemes'; SNoClassRegistered = 'No class registered for invokable interface %s'; SNoDispatcher = 'No Dispatcher set'; SMethNoRTTI = 'Method has no RTTI'; SUnsupportedVariant = 'Unsuppported variant type %d'; SNoVarDispatch = 'varDispatch type not supported'; SNoErrorDispatch = 'varError type not supported'; SUnknownInterface = '(Unknown)'; SInvalidTimeZone = 'Invalid or Unknown Time Zone'; sUnknownError = 'Unknown Error'; sErrorColon = 'Error: '; sServiceInfo = '%s - PortTypes:'; sInterfaceInfo= '<a href="%s">%s</a>&nbsp;&gt;&nbsp;<span class="Off">%s</span>'; sWSILInfo = 'WSIL:'; sWSILLink = '&nbsp;&nbsp;<span class="Tip">Link to WS-Inspection document of Services <a href="%s">here</a></span>'; sRegTypes = 'Registered Types'; sWebServiceListing = 'WebService Listing'; sWebServiceListingAdmin = 'WebService Listing Administrator'; sPortType = 'Port Type'; sNameSpaceURI = 'Namespace URI'; sDocumentation = 'Documentation'; sWSDL = 'WSDL'; sPortName = 'PortName'; sInterfaceNotFound = HTMLHead + '</head><body>' + '<h1>Error Encountered</h1><P>Interface %s not found</P>' +HTMLEnd; sForbiddenAccess = HTMLHead + '</head><body>' + '<h1>Forbidden (403)</h1><P>Access Forbidden</P>' +HTMLEnd; sWSDLPortsforPortType = 'WSDL Ports for PortType'; sWSDLFor = ''; sServiceInfoPage = 'Service Info Page'; {SOAPAttach} SEmptyStream = 'TAggregateStream Error: no internal streams'; SMethodNotSupported = 'method not supported'; SInvalidMethod = 'Method not permitted in TSoapDataList'; SNoContentLength = 'Content-Length header not found'; SInvalidContentLength = 'Insufficient data for Content-Length'; SMimeReadError = 'Error reading from Mime Request Stream'; {$IFDEF MSWINDOWS} STempFileAccessError = 'No access to temporary file'; {$ENDIF} {$IFDEF POSIX} STempFileAccessError = 'No access to temporary file: check TMPDIR setting'; {$ENDIF} {SoapConn} SSOAPServerIIDFmt = '%s - %s'; SNoURL = 'No URL property set - please specify the URL of the Service you wish to connect to'; SSOAPInterfaceNotRegistered = 'Interface (%s) is not registered - please include the unit that registers this interface to your project'; SSOAPInterfaceNotRemotable = 'Interface (%s) canno be remoted - please verify the interface declaration - specially the methods calling convention!'; SCantLoadLocation = 'Unable to load WSDL File/Location: %s. Error [%s]'; implementation end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.DSDef; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysDSConnectionDefParams // Generated for: FireDAC DS driver TFDDSProtocol = (prTcp_ip); TFDDSCommunicationIPVersion = (cipNone, cipIP_IPv4, cipIP_IPv6); TFDDSAuthenticationScheme = (dsaNone, dsaBasic); /// <summary> TFDPhysDSConnectionDefParams class implements FireDAC DS driver specific connection definition class. </summary> TFDPhysDSConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetDBXAdvanced: String; procedure SetDBXAdvanced(const AValue: String); function GetProtocol: TFDDSProtocol; procedure SetProtocol(const AValue: TFDDSProtocol); function GetIPImplementationID: String; procedure SetIPImplementationID(const AValue: String); function GetCommunicationIPVersion: TFDDSCommunicationIPVersion; procedure SetCommunicationIPVersion(const AValue: TFDDSCommunicationIPVersion); function GetServer: String; procedure SetServer(const AValue: String); function GetPort: Integer; procedure SetPort(const AValue: Integer); function GetBufferKBSize: Integer; procedure SetBufferKBSize(const AValue: Integer); function GetFilters: String; procedure SetFilters(const AValue: String); function GetLoginTimeout: Integer; procedure SetLoginTimeout(const AValue: Integer); function GetCommunicationTimeout: Integer; procedure SetCommunicationTimeout(const AValue: Integer); function GetURLPath: String; procedure SetURLPath(const AValue: String); function GetDatasnapContext: String; procedure SetDatasnapContext(const AValue: String); function GetDSProxyHost: String; procedure SetDSProxyHost(const AValue: String); function GetDSProxyPort: Integer; procedure SetDSProxyPort(const AValue: Integer); function GetDSProxyUsername: String; procedure SetDSProxyUsername(const AValue: String); function GetDSProxyPassword: String; procedure SetDSProxyPassword(const AValue: String); function GetDSAuthenticationScheme: TFDDSAuthenticationScheme; procedure SetDSAuthenticationScheme(const AValue: TFDDSAuthenticationScheme); published property DriverID: String read GetDriverID write SetDriverID stored False; property DBXAdvanced: String read GetDBXAdvanced write SetDBXAdvanced stored False; property Protocol: TFDDSProtocol read GetProtocol write SetProtocol stored False default prTCP_IP; property IPImplementationID: String read GetIPImplementationID write SetIPImplementationID stored False; property CommunicationIPVersion: TFDDSCommunicationIPVersion read GetCommunicationIPVersion write SetCommunicationIPVersion stored False; property Server: String read GetServer write SetServer stored False; property Port: Integer read GetPort write SetPort stored False default 8080; property BufferKBSize: Integer read GetBufferKBSize write SetBufferKBSize stored False default 32; property Filters: String read GetFilters write SetFilters stored False; property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False default 10000; property CommunicationTimeout: Integer read GetCommunicationTimeout write SetCommunicationTimeout stored False; property URLPath: String read GetURLPath write SetURLPath stored False; property DatasnapContext: String read GetDatasnapContext write SetDatasnapContext stored False; property DSProxyHost: String read GetDSProxyHost write SetDSProxyHost stored False; property DSProxyPort: Integer read GetDSProxyPort write SetDSProxyPort stored False default 8888; property DSProxyUsername: String read GetDSProxyUsername write SetDSProxyUsername stored False; property DSProxyPassword: String read GetDSProxyPassword write SetDSProxyPassword stored False; property DSAuthenticationScheme: TFDDSAuthenticationScheme read GetDSAuthenticationScheme write SetDSAuthenticationScheme stored False; end; implementation uses Data.DBXCommon, FireDAC.Stan.Consts; // TFDPhysDSConnectionDefParams // Generated for: FireDAC DS driver {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDBXAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_TDBX_DBXAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDBXAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_TDBX_DBXAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetProtocol: TFDDSProtocol; var s: String; begin s := FDef.AsString[S_FD_ConnParam_DS_Protocol]; if CompareText(s, 'tcp/ip') = 0 then Result := prTcp_ip else Result := prTCP_IP; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetProtocol(const AValue: TFDDSProtocol); const C_Protocol: array[TFDDSProtocol] of String = ('tcp/ip'); begin FDef.AsString[S_FD_ConnParam_DS_Protocol] := C_Protocol[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetIPImplementationID: String; begin Result := FDef.AsString[TDBXPropertyNames.IPImplementationID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetIPImplementationID(const AValue: String); begin FDef.AsString[TDBXPropertyNames.IPImplementationID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetCommunicationIPVersion: TFDDSCommunicationIPVersion; var s: String; begin s := FDef.AsString[TDBXPropertyNames.CommunicationIPVersion]; if CompareText(s, '') = 0 then Result := cipNone else if CompareText(s, 'IP_IPv4') = 0 then Result := cipIP_IPv4 else if CompareText(s, 'IP_IPv6') = 0 then Result := cipIP_IPv6 else Result := cipNone; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetCommunicationIPVersion(const AValue: TFDDSCommunicationIPVersion); const C_CommunicationIPVersion: array[TFDDSCommunicationIPVersion] of String = ('', 'IP_IPv4', 'IP_IPv6'); begin FDef.AsString[TDBXPropertyNames.CommunicationIPVersion] := C_CommunicationIPVersion[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetServer: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_Server]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetServer(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_Server] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetPort: Integer; begin if not FDef.HasValue(S_FD_ConnParam_Common_Port) then Result := 8080 else Result := FDef.AsInteger[S_FD_ConnParam_Common_Port]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetPort(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetBufferKBSize: Integer; begin if not FDef.HasValue(TDBXPropertyNames.BufferKBSize) then Result := 32 else Result := FDef.AsInteger[TDBXPropertyNames.BufferKBSize]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetBufferKBSize(const AValue: Integer); begin FDef.AsInteger[TDBXPropertyNames.BufferKBSize] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetFilters: String; begin Result := FDef.AsString[TDBXPropertyNames.Filters]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetFilters(const AValue: String); begin FDef.AsString[TDBXPropertyNames.Filters] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetLoginTimeout: Integer; begin if not FDef.HasValue(S_FD_ConnParam_Common_LoginTimeout) then Result := 10000 else Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetLoginTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetCommunicationTimeout: Integer; begin Result := FDef.AsInteger[TDBXPropertyNames.CommunicationTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetCommunicationTimeout(const AValue: Integer); begin FDef.AsInteger[TDBXPropertyNames.CommunicationTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetURLPath: String; begin Result := FDef.AsString[TDBXPropertyNames.URLPath]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetURLPath(const AValue: String); begin FDef.AsString[TDBXPropertyNames.URLPath] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDatasnapContext: String; begin Result := FDef.AsString[TDBXPropertyNames.DatasnapContext]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDatasnapContext(const AValue: String); begin FDef.AsString[TDBXPropertyNames.DatasnapContext] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDSProxyHost: String; begin Result := FDef.AsString[TDBXPropertyNames.DSProxyHost]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDSProxyHost(const AValue: String); begin FDef.AsString[TDBXPropertyNames.DSProxyHost] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDSProxyPort: Integer; begin if not FDef.HasValue(TDBXPropertyNames.DSProxyPort) then Result := 8888 else Result := FDef.AsInteger[TDBXPropertyNames.DSProxyPort]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDSProxyPort(const AValue: Integer); begin FDef.AsInteger[TDBXPropertyNames.DSProxyPort] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDSProxyUsername: String; begin Result := FDef.AsString[TDBXPropertyNames.DSProxyUsername]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDSProxyUsername(const AValue: String); begin FDef.AsString[TDBXPropertyNames.DSProxyUsername] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDSProxyPassword: String; begin Result := FDef.AsString[TDBXPropertyNames.DSProxyPassword]; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDSProxyPassword(const AValue: String); begin FDef.AsString[TDBXPropertyNames.DSProxyPassword] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysDSConnectionDefParams.GetDSAuthenticationScheme: TFDDSAuthenticationScheme; var s: String; begin s := FDef.AsString[TDBXPropertyNames.DSAuthenticationScheme]; if CompareText(s, '') = 0 then Result := dsaNone else if CompareText(s, 'basic') = 0 then Result := dsaBasic else Result := dsaNone; end; {-------------------------------------------------------------------------------} procedure TFDPhysDSConnectionDefParams.SetDSAuthenticationScheme(const AValue: TFDDSAuthenticationScheme); const C_DSAuthenticationScheme: array[TFDDSAuthenticationScheme] of String = ('', 'basic'); begin FDef.AsString[TDBXPropertyNames.DSAuthenticationScheme] := C_DSAuthenticationScheme[AValue]; end; end.
unit MainDM; interface uses SysUtils, Classes, DB, ADODB,dialogs; type TMainDataModule = class(TDataModule) ADOConnection1: TADOConnection; qryProjects: TADOQuery; qryDrills: TADOQuery; qryDrill_type: TADOQuery; qryEarthType: TADOQuery; qryStratum: TADOQuery; qryDPT: TADOQuery; qryBorer: TADOQuery; qrySPT: TADOQuery; qryStratum_desc: TADOQuery; qryPublic: TADOQuery; qryDPTCoef: TADOQuery; qrySection: TADOQuery; qrySectionDrill: TADOQuery; qryCPT: TADOQuery; qryEarthSample: TADOQuery; qryCrossBoard: TADOQuery; qrySectionTotal: TADOQuery; qryFAcount: TADOQuery; qryLegend: TADOQuery; procedure DataModuleDestroy(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } function DropTableFromDB(aTableName : string):String; function Connect_Database(serverName,PortNo,UserName,Password:string):string; end; var MainDataModule: TMainDataModule; implementation uses public_unit; {$R *.dfm} { TMainDataModule } function TMainDataModule.Connect_Database(serverName,PortNo, UserName, Password: string):string; var strConn : string; begin // strConn := 'Provider=SQLOLEDB.1;Persist Security Info=False;'; // strConn := strConn + 'User ID=' + UserName + ';'; // strConn := strConn + 'PassWord=' + PassWord + ';'; // strConn := strConn + 'Initial Catalog=GeoSoft;' ; // strConn := strConn + 'Network Address=' + serverName+ ','+ PortNo+';'; // strConn := strConn + 'Network Library=dbmssocn'; strConn:='Provider=SQLOLEDB.1;'; strConn:=strConn+'Data Source='; strConn:=strConn+ServerName; strConn:=strConn+';'; strConn:=strConn+'Initial Catalog=GeoSoft;'; strConn:=strConn+'User ID='; strConn:=strConn+UserName; strConn:=strConn+';'; strConn:=strConn+'PASSWORD='; strConn:=strConn+Password; strConn:=strConn+';'; ADOConnection1.ConnectionString := strConn; try ADOConnection1.Connected := true; result := ''; except on e:exception do begin if pos('ConnectionOpen',e.Message)<>0 then result := '数据库连接错误,请确定数据库存在并已经启动,端口号是否正确。' else if pos('Login failed',e.Message)<>0 then result := '登录失败,请检查用户名和密码!' else result := e.Message ; end; end; end; procedure TMainDataModule.DataModuleDestroy(Sender: TObject); begin ADOConnection1.Close; end; procedure TMainDataModule.DataModuleCreate(Sender: TObject); var strRootPath: string; begin strRootPath:= ExtractFilePath(ParamStr(0)); g_AppInfo.PathOfReports:= strRootPath + 'report\'; g_AppInfo.PathOfChartFile:= strRootPath + 'chart\'; g_AppInfo.CadExeName := strRootPath + 'ProjectCAD\MiniCAD.exe'; g_AppInfo.CadExeNameEn:= strRootPath + 'ProjectCAD\MiniCAD_EN.exe'; g_AppInfo.PathOfIniFile := strRootPath + 'Server.ini'; //在钻孔类型数据表中,单桥静力触探孔的编号是6,双桥静力触探孔的编号是7, //所以若此表有变动,要更新程序. g_ZKLXBianHao.ShuangQiao := '7'; g_ZKLXBianHao.DanQiao :='6'; g_ZKLXBianHao.XiaoZuanKong:='3'; g_ProjectInfo := TProjectInfo.Create; end; function TMainDataModule.DropTableFromDB(aTableName: string): String; var strSQL: string; begin strSQL:= 'DROP TABLE ' + aTableName; with qryPublic do begin close; sql.Clear; sql.Add(strSQL); try ExecSQL; except on e:exception do begin result := e.Message ; end; end; close; end; end; end.
{ test var parameters & new/dispose } program test; type ptr = ^integer; var p : ptr; i : integer; procedure init(var pointer : ptr); begin new(pointer); end; procedure setValue(var value : integer; var pointer : ptr); begin i := 12345; pointer^ := value; end; procedure free(var pointer : ptr); begin dispose(pointer); end; begin init(p); setValue(i, p); writeln('i = ', i); writeln('p^ = ', p^); free(p); if p = nil then writeln('ok') else writeln('FAILED!'); end.
{$INCLUDE ..\cDefines.inc} unit cWindows; { } { Windows functions v3.07 } { } { This unit is copyright © 2000-2004 by David J Butler } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cWindows.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { Description: } { MS Windows specific functions. } { } { Revision history: } { 2000/10/01 1.01 Initial version created from cUtils. } { 2001/12/12 2.02 Added AWindowHandle. } { 2002/03/15 2.03 Added GetWinOSType. } { 2002/06/26 3.04 Refactored for Fundamentals 3. } { 2002/09/22 3.05 Moved Registry functions to unit cRegistry. } { 2003/01/04 3.06 Added Reboot function. } { 2003/10/01 3.07 Updated GetWindowsVersion function. } { } interface uses { Delphi } Windows, Messages, SysUtils, Classes, { Fundamentals } cUtils; { } { Windows Version } { } type TWindowsVersion = ( // 16-bit Windows Win16_31, // 32-bit Windows Win32_95, Win32_95R2, Win32_98, Win32_98SE, Win32_ME, Win32_Future, // Windows NT 3 WinNT_31, WinNT_35, WinNT_351, // Windows NT 4 WinNT_40, // Windows NT 5 WinNT5_2000, WinNT5_XP, WinNT5_2003, WinNT5_Future, // Windows NT 6+ WinNT_Future, // Windows Post-NT Win_Future); TWindowsVersions = Set of TWindowsVersion; function GetWindowsVersion: TWindowsVersion; function IsWinPlatform95: Boolean; function IsWinPlatformNT: Boolean; function GetWindowsProductID: String; { } { Windows Paths } { } function GetWindowsTemporaryPath: String; function GetWindowsPath: String; function GetWindowsSystemPath: String; function GetProgramFilesPath: String; function GetCommonFilesPath: String; function GetApplicationPath: String; { } { Identification } { } function GetUserName: String; function GetLocalComputerName: String; { } { Application Version Info } { } type TVersionInfo = (viFileVersion, viFileDescription, viLegalCopyright, viComments, viCompanyName, viInternalName, viLegalTrademarks, viOriginalFilename, viProductName, viProductVersion); function GetAppVersionInfo(const VersionInfo: TVersionInfo): String; { } { Windows Processes } { } function WinExecute(const ExeName, Params: String; const ShowWin: Word = SW_SHOWNORMAL; const Wait: Boolean = True): Boolean; { } { Exit Windows } { } {$IFNDEF FREEPASCAL} type TExitWindowsType = (exitLogOff, exitPowerOff, exitReboot, exitShutDown); function ExitWindows(const ExitType: TExitWindowsType; const Force: Boolean = False): Boolean; function LogOff(const Force: Boolean = False): Boolean; function PowerOff(const Force: Boolean = False): Boolean; function Reboot(const Force: Boolean = False): Boolean; function ShutDown(const Force: Boolean = False): Boolean; {$ENDIF} { } { Windows Fibers } { These functions are redeclared because Delphi 7's Windows.pas declare } { them incorrectly. } { } {$IFDEF FREEPASCAL} type TFNFiberStartRoutine = TFarProc; {$ENDIF} function ConvertThreadToFiber(lpParameter: Pointer): Pointer; stdcall; function CreateFiber(dwStackSize: DWORD; lpStartAddress: TFNFiberStartRoutine; lpParameter: Pointer): Pointer; stdcall; { } { Windows Shell } { } procedure ShellLaunch(const S: String); { } { Miscelleaneous Windows API } { } function GetEnvironmentStrings: StringArray; function ContentTypeFromExtention(const Extention: String): String; function FileClassFromExtention(const Extention: String): String; function GetFileClass(const FileName: String): String; function GetFileAssociation(const FileName: String): String; function IsApplicationAutoRun(const Name: String): Boolean; procedure SetApplicationAutoRun(const Name: String; const AutoRun: Boolean); {$IFNDEF FREEPASCAL} function GetWinPortNames: StringArray; {$ENDIF} function GetKeyPressed(const VKeyCode: Integer): Boolean; function GetHardDiskSerialNumber(const DriveLetter: Char): String; { } { WinInet API } { } type TIEProxy = (iepHTTP, iepHTTPS, iepFTP, iepGOPHER, iepSOCKS); {$IFNDEF FREEPASCAL} function GetIEProxy(const Protocol: TIEProxy): String; {$ENDIF} { } { Window Handle } { Base class for allocation of a new Window handle that can process its own } { messages. } { } type TWindowHandleMessageEvent = function (const Msg: Cardinal; const wParam, lParam: Integer; var Handled: Boolean): Integer of object; TWindowHandle = class; TWindowHandleEvent = procedure (const Sender: TWindowHandle) of object; TWindowHandleErrorEvent = procedure (const Sender: TWindowHandle; const E: Exception) of object; TWindowHandle = class(TComponent) protected FWindowHandle : HWND; FTerminated : Boolean; FOnMessage : TWindowHandleMessageEvent; FOnException : TWindowHandleErrorEvent; FOnBeforeMessage : TWindowHandleEvent; FOnAfterMessage : TWindowHandleEvent; procedure RaiseError(const Msg: String); function AllocateWindowHandle: HWND; virtual; function MessageProc(const Msg: Cardinal; const wParam, lParam: Integer): Integer; function HandleWM(const Msg: Cardinal; const wParam, lParam: Integer): Integer; virtual; public destructor Destroy; override; procedure DestroyWindowHandle; virtual; property WindowHandle: HWND read FWindowHandle; function GetWindowHandle: HWND; function ProcessMessage: Boolean; procedure ProcessMessages; function HandleMessage: Boolean; procedure MessageLoop; property OnMessage: TWindowHandleMessageEvent read FOnMessage write FOnMessage; property OnException: TWindowHandleErrorEvent read FOnException write FOnException; property OnBeforeMessage: TWindowHandleEvent read FOnBeforeMessage write FOnBeforeMessage; property OnAfterMessage: TWindowHandleEvent read FOnAfterMessage write FOnAfterMessage; property Terminated: Boolean read FTerminated; procedure Terminate; virtual; end; EWindowHandle = class(Exception); { TfndWindowHandle } { Published Window Handle component. } TfndWindowHandle = class(TWindowHandle) published property OnMessage; property OnException; end; { } { TTimerHandle } { } type TTimerHandle = class; TTimerEvent = procedure (const Sender: TTimerHandle) of object; TTimerHandle = class(TWindowHandle) protected FTimerInterval : Integer; FTimerActive : Boolean; FOnTimer : TTimerEvent; function HandleWM(const Msg: Cardinal; const wParam, lParam: Integer): Integer; override; function DoSetTimer: Boolean; procedure TriggerTimer; virtual; procedure SetTimerActive(const TimerActive: Boolean); virtual; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; procedure DestroyWindowHandle; override; property TimerInterval: Integer read FTimerInterval write FTimerInterval default 1000; property TimerActive: Boolean read FTimerActive write SetTimerActive default False; property OnTimer: TTimerEvent read FOnTimer write FOnTimer; end; { TfndTimerHandle } { Published Timer Handle component. } TfndTimerHandle = class(TTimerHandle) published property OnMessage; property OnException; property TimerInterval; property TimerActive; property OnTimer; end; {$IFNDEF DELPHI6_UP} { } { RaiseLastOSError } { } procedure RaiseLastOSError; {$ENDIF} implementation uses { Delphi } {$IFNDEF FREEPASCAL} WinSpool, WinInet, {$ENDIF} ShellApi, { Fundamentals } cStrings, cRegistry; {$IFNDEF DELPHI6_UP} { } { RaiseLastOSError } { } procedure RaiseLastOSError; begin {$IFDEF FREEPASCAL} raise Exception.Create('OS Error'); {$ELSE} RaiseLastWin32Error; {$ENDIF} end; {$ENDIF} { } { Windows Version Info } { } {$IFDEF FREEPASCAL} var Win32Platform : Integer; Win32MajorVersion : Integer; Win32MinorVersion : Integer; Win32CSDVersion : String; procedure InitPlatformId; var OSVersionInfo : TOSVersionInfo; begin OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo); if GetVersionEx(OSVersionInfo) then with OSVersionInfo do begin Win32Platform := dwPlatformId; Win32MajorVersion := dwMajorVersion; Win32MinorVersion := dwMinorVersion; Win32CSDVersion := szCSDVersion; end; end; {$ENDIF} function GetWindowsVersion: TWindowsVersion; begin Case Win32Platform of VER_PLATFORM_WIN32s : Result := Win16_31; VER_PLATFORM_WIN32_WINDOWS : if Win32MajorVersion <= 4 then Case Win32MinorVersion of 0..9 : if Trim(Win32CSDVersion, csWhiteSpace) = 'B' then Result := Win32_95R2 else Result := Win32_95; 10..89 : if Trim(Win32CSDVersion, csWhiteSpace) = 'A' then Result := Win32_98SE else Result := Win32_98; 90..99 : Result := Win32_ME; else Result := Win32_Future; end else Result := Win32_Future; VER_PLATFORM_WIN32_NT : Case Win32MajorVersion of 3 : Case Win32MinorVersion of 1, 10..19 : Result := WinNT_31; 5, 50 : Result := WinNT_35; 51..99 : Result := WinNT_351; else Result := WinNT_31; end; 4 : Result := WinNT_40; 5 : Case Win32MinorVersion of 0 : Result := WinNT5_2000; 1 : Result := WinNT5_XP; 2 : Result := WinNT5_2003; else Result := WinNT5_Future; end; else Result := WinNT_Future; end; else Result := Win_Future; end; end; function IsWinPlatform95: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_WINDOWS; end; function IsWinPlatformNT: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT; end; function GetWindowsProductID: String; begin Result := GetRegistryString(HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion', 'ProductId'); end; { } { Windows Paths } { } function GetWindowsTemporaryPath: String; const MaxTempPathLen = MAX_PATH + 1; var I : LongWord; begin SetLength(Result, MaxTempPathLen); I := GetTempPath(MaxTempPathLen, PChar(Result)); if I > 0 then SetLength(Result, I) else Result := ''; end; function GetWindowsPath: String; const MaxWinPathLen = MAX_PATH + 1; var I : LongWord; begin SetLength(Result, MaxWinPathLen); I := GetWindowsDirectory(PChar(Result), MaxWinPathLen); if I > 0 then SetLength(Result, I) else Result := ''; end; function GetWindowsSystemPath: String; const MaxWinSysPathLen = MAX_PATH + 1; var I : LongWord; begin SetLength(Result, MaxWinSysPathLen); I := GetSystemDirectory(PChar(Result), MaxWinSysPathLen); if I > 0 then SetLength(Result, I) else Result := ''; end; const CurrentVersionRegistryKey = 'SOFTWARE\Microsoft\Windows\CurrentVersion'; function GetProgramFilesPath: String; begin Result := GetRegistryString(HKEY_LOCAL_MACHINE, CurrentVersionRegistryKey, 'ProgramFilesDir'); end; function GetCommonFilesPath: String; begin Result := GetRegistryString(HKEY_LOCAL_MACHINE, CurrentVersionRegistryKey, 'CommonFilesDir'); end; function GetApplicationPath: String; begin Result := ExtractFilePath(ParamStr(0)); StrEnsureSuffix(Result, '\'); end; { } { Identification } { } function GetUserName: String; const MAX_USERNAME_LENGTH = 256; var L : LongWord; begin L := MAX_USERNAME_LENGTH + 2; SetLength(Result, L); if Windows.GetUserName(PChar(Result), L) and (L > 0) then SetLength(Result, StrLen(PChar(Result))) else Result := ''; end; function GetLocalComputerName: String; var L : LongWord; begin L := MAX_COMPUTERNAME_LENGTH + 2; SetLength(Result, L); if Windows.GetComputerName(PChar(Result), L) and (L > 0) then SetLength(Result, StrLen(PChar(Result))) else Result := ''; end; { } { Application Version Info } { } var VersionInfoBuf : Pointer = nil; VerTransStr : String; // Returns True if VersionInfo is available function LoadAppVersionInfo: Boolean; type TTransBuffer = Array [1..4] of SmallInt; PTransBuffer = ^TTransBuffer; var InfoSize : Integer; Size, H : LongWord; EXEName : String; Trans : PTransBuffer; begin Result := Assigned(VersionInfoBuf); if Result then exit; EXEName := ParamStr(0); InfoSize := GetFileVersionInfoSize(PChar(EXEName), H); if InfoSize = 0 then exit; GetMem(VersionInfoBuf, InfoSize); if not GetFileVersionInfo(PChar(EXEName), H, InfoSize, VersionInfoBuf) then begin FreeMem(VersionInfoBuf); VersionInfoBuf := nil; exit; end; VerQueryValue(VersionInfoBuf, PChar('\VarFileInfo\Translation'), Pointer(Trans), Size); VerTransStr := IntToHex(Trans^ [1], 4) + IntToHex(Trans^ [2], 4); Result := True; end; const VersionInfoStr: Array [TVersionInfo] of String = ('FileVersion', 'FileDescription', 'LegalCopyright', 'Comments', 'CompanyName', 'InternalName', 'LegalTrademarks', 'OriginalFilename', 'ProductName', 'ProductVersion'); function GetAppVersionInfo(const VersionInfo: TVersionInfo): String; var S : String; Size : LongWord; Value : PChar; begin Result := ''; if not LoadAppVersionInfo then exit; S := 'StringFileInfo\' + VerTransStr + '\' + VersionInfoStr[VersionInfo]; if VerQueryvalue(VersionInfoBuf, PChar(S), Pointer(Value), Size) then Result := Value; end; { } { Windows Processes } { } function WinExecute(const ExeName, Params: String; const ShowWin: Word; const Wait: Boolean): Boolean; var StartUpInfo : TStartupInfo; ProcessInfo : TProcessInformation; Cmd : String; begin if Params = '' then Cmd := ExeName else Cmd := ExeName + ' ' + Params; FillChar(StartUpInfo, SizeOf(StartUpInfo), #0); StartUpInfo.cb := SizeOf(StartUpInfo); StartUpInfo.dwFlags := STARTF_USESHOWWINDOW; // STARTF_USESTDHANDLES StartUpInfo.wShowWindow := ShowWin; Result := CreateProcess( nil, PChar(Cmd), nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, PChar(ExtractFilePath(ExeName)), StartUpInfo, ProcessInfo); if Wait then WaitForSingleObject(ProcessInfo.hProcess, INFINITE); end; { } { Exit Windows } { } {$IFNDEF FREEPASCAL} function ExitWindows(const ExitType: TExitWindowsType; const Force: Boolean): Boolean; const SE_SHUTDOWN_NAME = 'SeShutDownPrivilege'; ExitTypeFlags : Array[TExitWindowsType] of Cardinal = (EWX_LOGOFF, EWX_POWEROFF, EWX_REBOOT, EWX_SHUTDOWN); var hToken : Cardinal; tkp : TTokenPrivileges; retval : Cardinal; uFlags : Cardinal; begin if IsWinPlatformNT then if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin LookupPrivilegeValue(nil, SE_SHUTDOWN_NAME, tkp.Privileges[0].Luid); tkp.PrivilegeCount := 1; tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, tkp, 0, tkp, retval); end; uFlags := ExitTypeFlags[ExitType]; if Force then uFlags := uFlags or EWX_FORCE; Result := Windows.ExitWindowsEx(uFlags, 0); end; function LogOff(const Force: Boolean = False): Boolean; begin Result := ExitWindows(exitLogOff, Force); end; function PowerOff(const Force: Boolean = False): Boolean; begin Result := ExitWindows(exitPowerOff, Force); end; function Reboot(const Force: Boolean): Boolean; begin Result := ExitWindows(exitReboot, Force); end; function ShutDown(const Force: Boolean = False): Boolean; begin Result := ExitWindows(exitShutDown, Force); end; {$ENDIF} { } { Windows Fibers } { } function ConvertThreadToFiber; external kernel32 name 'ConvertThreadToFiber'; function CreateFiber(dwStackSize: DWORD; lpStartAddress: TFNFiberStartRoutine; lpParameter: Pointer): Pointer; external kernel32 name 'CreateFiber'; { } { Windows Shell } { } procedure ShellLaunch(const S: String); begin ShellExecute(0, 'open', PChar(S), '', '', SW_SHOWNORMAL); end; { } { Miscelleaneous Windows API } { } function GetEnvironmentStrings: StringArray; var P, Q : PChar; I : Integer; S : String; begin P := PChar(Windows.GetEnvironmentStrings); try if P^ <> #0 then Repeat Q := P; I := 0; While Q^ <> #0 do begin Inc(Q); Inc(I); end; SetLength(S, I); if I > 0 then Move(P^, Pointer(S)^, I); Append(Result, S); P := Q; Inc(P); Until P^ = #0; finally FreeEnvironmentStrings(P); end; end; function ContentTypeFromExtention(const Extention: String): String; begin Result := GetRegistryString(HKEY_CLASSES_ROOT, Extention, 'Content Type'); end; function FileClassFromExtention(const Extention: String): String; begin Result := GetRegistryString(HKEY_CLASSES_ROOT, Extention, ''); end; function GetFileClass(const FileName: String): String; begin Result := FileClassFromExtention(ExtractFileExt(FileName)); end; function GetFileAssociation(const FileName: String): String; var S : String; begin S := FileClassFromExtention(ExtractFileExt(FileName)); if S = '' then Result := '' else Result := GetRegistryString(HKEY_CLASSES_ROOT, S + '\Shell\Open\Command', ''); end; const AutoRunRegistryKey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; function IsApplicationAutoRun(const Name: String): Boolean; var S : String; begin S := ParamStr(0); Result := (S <> '') and (Name <> '') and StrEqualNoCase(GetRegistryString(HKEY_LOCAL_MACHINE, AutoRunRegistryKey, Name), S); end; procedure SetApplicationAutoRun(const Name: String; const AutoRun: Boolean); begin if Name = '' then exit; if AutoRun then SetRegistryString(HKEY_LOCAL_MACHINE, AutoRunRegistryKey, Name, ParamStr(0)) else DeleteRegistryValue(HKEY_LOCAL_MACHINE, AutoRunRegistryKey, Name); end; {$IFNDEF FREEPASCAL} function GetWinPortNames: StringArray; var BytesNeeded, N, I : LongWord; Buf : Pointer; InfoPtr : PPortInfo1; TempStr : String; begin Result := nil; if EnumPorts(nil, 1, nil, 0, BytesNeeded, N) then exit; if GetLastError <> ERROR_INSUFFICIENT_BUFFER then RaiseLastOSError; GetMem(Buf, BytesNeeded); try if not EnumPorts(nil, 1, Buf, BytesNeeded, BytesNeeded, N) then RaiseLastOSError; For I := 0 to N - 1 do begin InfoPtr := PPortInfo1(LongWord(Buf) + I * SizeOf(TPortInfo1)); TempStr := InfoPtr^.pName; Append(Result, TempStr); end; finally FreeMem(Buf); end; end; {$ENDIF} function GetKeyPressed(const VKeyCode: Integer): Boolean; begin Result := GetKeyState(VKeyCode) and $80 <> 0; end; { } { WinInet API } { } const IEProtoPrefix : Array[TIEProxy] of String = ('http=', 'https=', 'ftp=', 'gopher=', 'socks='); {$IFNDEF FREEPASCAL} function GetIEProxy(const Protocol: TIEProxy): String; var ProxyInfo : PInternetProxyInfo; Len : LongWord; Proxies : StringArray; I : Integer; begin Proxies := nil; Result := ''; Len := 4096; GetMem(ProxyInfo, Len); try if InternetQueryOption(nil, INTERNET_OPTION_PROXY, ProxyInfo, Len) then if ProxyInfo^.dwAccessType = INTERNET_OPEN_TYPE_PROXY then begin Result := ProxyInfo^.lpszProxy; if PosChar('=', Result) = 0 then // same proxy for all protocols exit; // Find proxy for Protocol Proxies := StrSplitChar(Result, ' '); For I := 0 to Length(Proxies) - 1 do if StrMatchLeft(Proxies[I], IEProtoPrefix[Protocol], False) then begin Result := StrAfterChar(Proxies[I], '='); exit; end; // No proxy for Protocol Result := ''; end; finally FreeMem(ProxyInfo); end; end; {$ENDIF} function GetHardDiskSerialNumber(const DriveLetter: Char): String; var N, F, S : DWORD; begin S := 0; GetVolumeInformation(PChar(DriveLetter + ':\'), nil, MAX_PATH + 1, @S, N, F, nil, 0); Result := LongWordToHex(S, 8); end; { } { TWindowHandle } { } function WindowHandleMessageProc(const WindowHandle: HWND; const Msg: Cardinal; const wParam, lParam: Integer): Integer; stdcall; var V : TObject; begin V := TObject(GetWindowLong(WindowHandle, 0)); // Get user data if V is TWindowHandle then Result := TWindowHandle(V).MessageProc(Msg, wParam, lParam) else Result := DefWindowProc(WindowHandle, Msg, wParam, lParam); // Default handler end; var WindowClass: TWndClass = ( style : 0; lpfnWndProc : @WindowHandleMessageProc; cbClsExtra : 0; cbWndExtra : SizeOf(Pointer); // Size of extra user data hInstance : 0; hIcon : 0; hCursor : 0; hbrBackground : 0; lpszMenuName : nil; lpszClassName : 'FundamentalsWindowClass'); Destructor TWindowHandle.Destroy; begin DestroyWindowHandle; inherited Destroy; end; procedure TWindowHandle.RaiseError(const Msg: String); begin raise EWindowHandle.Create(Msg); end; function TWindowHandle.AllocateWindowHandle: HWND; var C : TWndClass; begin WindowClass.hInstance := HInstance; // Register class if not GetClassInfo(HInstance, WindowClass.lpszClassName, C) then if Windows.RegisterClass(WindowClass) = 0 then RaiseError('Window class registration failed: Windows error #' + IntToStr(GetLastError)); // Allocate handle Result := CreateWindowEx(WS_EX_TOOLWINDOW, WindowClass.lpszClassName, '', { Window name } WS_POPUP, { Window Style } 0, 0, { X, Y } 0, 0, { Width, Height } 0, { hWndParent } 0, { hMenu } HInstance, { hInstance } nil); { CreateParam } if Result = 0 then RaiseError('Window handle allocation failed: Windows error #' + IntToStr(GetLastError)); // Set user data SetWindowLong(Result, 0, Integer(self)); end; function TWindowHandle.HandleWM(const Msg: Cardinal; const wParam, lParam: Integer): Integer; var Handled : Boolean; begin Result := 0; Handled := False; if Assigned(FOnMessage) then Result := FOnMessage(Msg, wParam, lParam, Handled); if not Handled then Result := DefWindowProc(FWindowHandle, Msg, wParam, lParam); // Default handler end; function TWindowHandle.MessageProc(const Msg: Cardinal; const wParam, lParam: Integer): Integer; var R : Boolean; begin if Assigned(FOnBeforeMessage) then FOnBeforeMessage(self); R := Assigned(FOnAfterMessage); try try Result := HandleWM(Msg, wParam, lParam); except on E : Exception do begin if Assigned(FOnException) then FOnException(self, E); Result := 0; end; end; finally if R then if Assigned(FOnAfterMessage) then FOnAfterMessage(self); end; end; function TWindowHandle.GetWindowHandle: HWND; begin Result := FWindowHandle; if Result = 0 then begin FWindowHandle := AllocateWindowHandle; Result := FWindowHandle; end; end; procedure TWindowHandle.DestroyWindowHandle; begin if FWindowHandle = 0 then exit; // Clear user data SetWindowLong(FWindowHandle, 0, 0); DestroyWindow(FWindowHandle); FWindowHandle := 0; end; function TWindowHandle.ProcessMessage: Boolean; var Msg : Windows.TMsg; begin if FTerminated then begin Result := False; exit; end; Result := PeekMessage(Msg, 0, 0, 0, PM_REMOVE); if Result then if Msg.Message = WM_QUIT then FTerminated := True else if FTerminated then Result := False else begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; procedure TWindowHandle.ProcessMessages; begin While ProcessMessage do ; end; function TWindowHandle.HandleMessage: Boolean; var Msg : Windows.TMsg; begin if FTerminated then begin Result := False; exit; end; Result := GetMessage(Msg, 0, 0, 0); if not Result then FTerminated := True else if FTerminated then Result := False else begin TranslateMessage(Msg); DispatchMessage(Msg) end; end; procedure TWindowHandle.MessageLoop; begin While HandleMessage do ; end; procedure TWindowHandle.Terminate; begin FTerminated := True; end; { } { TTimerHandle } { } Constructor TTimerHandle.Create(AOwner: TComponent); begin inherited Create(AOwner); FTimerInterval := 1000; end; procedure TTimerHandle.DestroyWindowHandle; begin if not (csDesigning in ComponentState) and (FWindowHandle <> 0) and FTimerActive then KillTimer(FWindowHandle, 1); inherited DestroyWindowHandle; end; function TTimerHandle.DoSetTimer: Boolean; begin if FTimerInterval <= 0 then Result := False else Result := SetTimer (GetWindowHandle, 1, FTimerInterval, nil) = 0; end; procedure TTimerHandle.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) and FTimerActive then DoSetTimer; end; procedure TTimerHandle.TriggerTimer; begin if Assigned(FOnTimer) then FOnTimer(self); end; procedure TTimerHandle.SetTimerActive(const TimerActive: Boolean); begin if FTimerActive = TimerActive then exit; if [csDesigning, csLoading] * ComponentState = [] then if TimerActive then begin if not DoSetTimer then exit; end else KillTimer(FWindowHandle, 1); FTimerActive := TimerActive; end; function TTimerHandle.HandleWM(const Msg: Cardinal; const wParam, lParam: Integer): Integer; begin if Msg = WM_TIMER then try Result := 0; TriggerTimer; except on E: Exception do begin Result := 0; if Assigned(FOnException) then FOnException(self, E); exit; end; end else Result := inherited HandleWM(Msg, wParam, lParam); end; initialization finalization if Assigned(VersionInfoBuf) then FreeMem(VersionInfoBuf); end.
unit Macro; interface uses Classes, Types, SysUtils; type TMacro = class private FName: string; FParameters: TStringList; FContent: string; FAddAsExternal: Boolean; public constructor Create(const AName: string); destructor Destroy(); override; property Name: string read FName; property Parameters: TStringList read FParameters; property Content: string read FContent write FContent; property AddAsExternal: Boolean read FAddAsExternal write FAddAsExternal; end; implementation { TMacro } constructor TMacro.Create(const AName: string); begin inherited Create(); FName := AName; FParameters := TStringList.Create(); end; destructor TMacro.Destroy; begin FParameters.Free; inherited; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC VCL About dialog } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.VCLUI.About; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls; type { ------------------------------------------------------------------------- } { TfrmFDGUIxFormsAbout } { ------------------------------------------------------------------------- } TfrmFDGUIxFormsAbout = class(TForm) lblVersion: TLabel; lblCopyright: TLabel; lblInternetLink: TLabel; Image1: TImage; procedure lblInternetLinkClick(Sender: TObject); procedure Image1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public procedure Setup(AModHInst: THandle; const ACaption: String); class procedure Execute(AModHInst: THandle = 0; const ACaption: String = ''); end; var frmFDGUIxFormsAbout: TfrmFDGUIxFormsAbout; implementation uses FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.ResStrs; {$R *.dfm} { ------------------------------------------------------------------------- } { TfrmFDGUIxFormsAbout } { ------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsAbout.Setup(AModHInst: THandle; const ACaption: String); var {$IFDEF MSWINDOWS} sMod, sVersion, {$ENDIF} sProduct, sVersionName, sCopyright, sInfo: String; begin {$IFDEF MSWINDOWS} if AModHInst = 0 then AModHInst := HInstance; sMod := GetModuleName(AModHInst); FDGetVersionInfo(sMod, sProduct, sVersion, sVersionName, sCopyright, sInfo); {$ENDIF} {$IFDEF POSIX} sProduct := ''; {$ENDIF} if sProduct = '' then begin sProduct := C_FD_Product + ' ' + ExtractFileName(ParamStr(0)); sVersionName := C_FD_Version; sCopyright := C_FD_Copyright; sInfo := S_FD_Prod_Link; end; if ACaption = '' then Caption := Format(S_FD_ProductAbout, [sProduct]) else Caption := ACaption; lblVersion.Caption := sVersionName; lblCopyright.Caption := sCopyright; lblInternetLink.Caption := sInfo; end; { ------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsAbout.Image1Click(Sender: TObject); begin ModalResult := mrCancel; end; { ------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsAbout.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then ModalResult := mrCancel; end; { ------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsAbout.lblInternetLinkClick(Sender: TObject); begin if TLabel(Sender).Caption <> '' then FDShell(TLabel(Sender).Caption, S_FD_LComp_Design); end; { ------------------------------------------------------------------------- } class procedure TfrmFDGUIxFormsAbout.Execute(AModHInst: THandle = 0; const ACaption: String = ''); var oFrm: TfrmFDGUIxFormsAbout; begin oFrm := TfrmFDGUIxFormsAbout.Create(nil); oFrm.Position := poMainFormCenter; oFrm.Setup(AModHInst, ACaption); try oFrm.ShowModal; finally FDFree(oFrm); end; end; end.
unit Entity; interface uses SysUtils; type TEntity = class(TObject) protected FId: string; public property Id: string read FId write FId; procedure Add; virtual; abstract; procedure Save; virtual; abstract; procedure Edit; virtual; abstract; procedure Cancel; virtual; abstract; constructor Create; destructor Destroy; override; end; var ent: TEntity; implementation constructor TEntity.Create; begin if ent <> nil then Exit else ent := self; end; destructor TEntity.Destroy; begin if ent = self then ent := nil; inherited; end; end.
unit Vigilante.Conexao.JSON.Arquivo.Impl; interface uses System.Classes, System.JSON, Vigilante.Conexao.JSON; type TConexaoArquivoJSON = class(TInterfacedObject, IConexaoJSON) public FArquivo: TStringList; FNomeArquivo: string; public constructor Create(const AURL: string); destructor Destroy; override; function PegarBuild: TJSONObject; function PegarCompilacao: TJSONObject; function PegarPipeline: TJSONObject; end; implementation { TConexaoArquivoJSON } uses System.IOUtils, System.SysUtils; const COMPILACAO_SIMULADO = 'simulado\compilacao.json'; BUILD_SIMULADO = 'simulado\%s'; constructor TConexaoArquivoJSON.Create(const AURL: string); begin FArquivo := TStringList.Create; FNomeArquivo := AURL.Replace('/api/json',''); end; destructor TConexaoArquivoJSON.Destroy; begin FArquivo.Free; end; function TConexaoArquivoJSON.PegarBuild: TJSONObject; var _arquivo:string; begin Result := nil; _arquivo := Format(BUILD_SIMULADO,[FNomeArquivo]); if not TFile.Exists(_arquivo) then Exit; FArquivo.LoadFromFile(_arquivo); Result := TJSONObject.ParseJSONValue(FArquivo.Text) as TJSONObject; end; function TConexaoArquivoJSON.PegarCompilacao: TJSONObject; begin Result := nil; if not TFile.Exists(COMPILACAO_SIMULADO) then Exit; FArquivo.LoadFromFile(COMPILACAO_SIMULADO); Result := TJSONObject.ParseJSONValue(FArquivo.Text) as TJSONObject; end; function TConexaoArquivoJSON.PegarPipeline: TJSONObject; begin Result := nil; end; end.
unit ncMyImage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxCore, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, dxCoreGraphics, Menus, StdCtrls, cxButtons, ImgList, cxLabel, ExtCtrls; type TcxMyAlphaBitmap = class (TcxAlphaBitmap) function IsColorTransparent(const AColor: TRGBQuad): Boolean; procedure MyTransform; end; TMyImage = class(TcxControl) private procedure SetImageIndex(const Value: Integer); procedure SetImageList(const Value: TcxImageList); procedure SetMouseDownDrawMode(const Value: TcxImageDrawMode); procedure SetMouseOffDrawMode(const Value: TcxImageDrawMode); procedure SetMouseOverDrawMode(const Value: TcxImageDrawMode); procedure SetColorize(const Value: Boolean); protected FColorize: Boolean; FHot: Boolean; FMouseDown: Boolean; FMouseOverDrawMode: TcxImageDrawMode; FMouseOffDrawMode: TcxImageDrawMode; FMouseDownDrawMode: TcxImageDrawMode; FImageList : TcxImageList; FImageIndex : Integer; procedure MouseEnter(AControl: TControl); override; procedure MouseLeave(AControl: TControl); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; public constructor Create(ASelf: TComponent); override; published property Align; property ParentColor; property OnClick; property Enabled; property Visible; property MouseOverDrawMode: TcxImageDrawMode read FMouseOverDrawMode write SetMouseOverDrawMode; property MouseOffDrawMode: TcxImageDrawMode read FMouseOffDrawMode write SetMouseOffDrawMode; property MouseDownDrawMode: TcxImageDrawMode read FMouseDownDrawMode write SetMouseDownDrawMode; property ImageList: TcxImageList read FImageList write SetImageList; property ImageIndex: Integer read FImageIndex write SetImageIndex; property Colorize: Boolean read FColorize write SetColorize; end; procedure Register; implementation var DrawBitmap, ImageBitmap, MaskBitmap: TcxAlphaBitmap; cxNullPoint: TPoint; cxNullSize: TSize; procedure cxBitmapInit(var ABitmap: TcxAlphaBitmap; AWidth, AHeight: Integer); begin if ABitmap = nil then ABitmap := TcxAlphaBitmap.CreateSize(AWidth, AHeight, True) else ABitmap.RefreshImage(AWidth, AHeight); end; function GetDrawBitmap(AWidth, AHeight: Integer): TcxAlphaBitmap; begin cxBitmapInit(DrawBitmap, AWidth, AHeight); Result := DrawBitmap; end; function cxRectWidth(const R: TRect): Integer; begin Result := R.Right - R.Left; end; function cxRectHeight(const R: TRect): Integer; begin Result := R.Bottom - R.Top; end; function cxSizeIsEqual(const S1, S2: TSize): Boolean; begin Result := (S1.cx = S2.cx) and (S1.cy = S2.cy); end; procedure myDrawImage(ADC: THandle; AGlyphRect, ABackgroundRect: TRect; AGlyph: TBitmap; AImages: TCustomImageList; AImageIndex: Integer; ADrawMode: TcxImageDrawMode; ASmoothImage: Boolean = False; ABrush: THandle = 0; ATransparentColor: TColor = clNone; AUseLeftBottomPixelAsTransparent: Boolean = True); procedure DrawBackGround(ABitmap: TcxAlphaBitmap); begin if ABrush = 0 then cxBitBlt(ABitmap.Canvas.Handle, ADC, ABitmap.ClientRect, ABackgroundRect.TopLeft, SRCCOPY) else FillRect(ABitmap.Canvas.Handle, ABitmap.ClientRect, ABrush); end; procedure DrawImage(ABitmap: TcxAlphaBitmap; ADrawMode: TcxImageDrawMode); const AImageShadowSize = 2; var AImageBitmap, AMaskBitmap: TcxAlphaBitmap; AConstantAlpha: Byte; AIsAlphaUsed: Boolean; begin OffsetRect(AGlyphRect, -ABackgroundRect.Left, -ABackgroundRect.Top); if not Assigned(CustomDrawImageProc) or not CustomDrawImageProc(ABitmap.Canvas, AImages, AImageIndex, AGlyph, AGlyphRect, ADrawMode) then begin cxPrepareBitmapForDrawing(AGlyph, AImages, AImageIndex, AUseLeftBottomPixelAsTransparent, ATransparentColor, AImageBitmap, AMaskBitmap, AIsAlphaUsed); AConstantAlpha := $FF; TcxMyAlphaBitmap(aImageBitmap).MyTransform; AImageBitmap.AlphaBlend(ABitmap, AGlyphRect, ASmoothImage, AConstantAlpha); end; end; var ADrawBitmap: TcxAlphaBitmap; AImageSize: TSize; begin if not (IsGlyphAssigned(AGlyph) or IsImageAssigned(AImages, AImageIndex)) then Exit; AImageSize := dxGetImageSize(AGlyph, AImages, AImageIndex); if cxSizeIsEqual(AImageSize, cxNullSize) then Exit; AGlyphRect := cxGetImageRect(AGlyphRect, AImageSize, ifmNormal); ADrawBitmap := GetDrawBitmap(cxRectWidth(ABackgroundRect), cxRectHeight(ABackgroundRect)); DrawBackGround(ADrawBitmap); DrawImage(ADrawBitmap, ADrawMode); cxDrawBitmap(ADC, ADrawBitmap, ABackgroundRect, cxNullPoint); end; constructor TMyImage.Create(ASelf: TComponent); begin inherited; FocusOnClick := False; FMouseDownDrawMode := idmGrayScale; FMouseOverDrawMode := idmNormal; FMouseOffDrawMode := idmFaded; FMouseDown := False; FHot := False; FImageIndex := -1; FImageList := nil; end; procedure TMyImage.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; FMouseDown := True; Invalidate; Update; end; procedure TMyImage.MouseEnter(AControl: TControl); begin inherited; FHot := True; Invalidate; Update; end; procedure TMyImage.MouseLeave(AControl: TControl); begin inherited; FMouseDown := False; FHot := False; Invalidate; Update; end; procedure TMyImage.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; FMouseDown := False; Invalidate; Update; end; procedure TMyImage.Paint; var R: TRect; begin inherited; if FImageList=nil then Exit; if (FImageIndex<0) or (FImageIndex>(FImageList.Count-1)) then Exit; R.Left := Left; R.Top := Top; R.Bottom := Left+Width-1; R.Right := Top+Height-1; R := GetBounds; if not Enabled then cxDrawImage(Canvas, R, nil, FImageList, FImageIndex, ifmNormal, idmFaded) else if FHot then begin if FMouseDown then cxDrawImage(Canvas, R, nil, FImageList, FImageIndex, ifmNormal, FMouseDownDrawMode) else if FColorize then MyDrawImage(Canvas.Handle, R, R, nil, FImageList, FImageIndex, idmNormal) else cxDrawImage(Canvas, R, nil, FImageList, FImageIndex, ifmNormal, FMouseOverDrawMode); end else cxDrawImage(Canvas, R, nil, FImageList, FImageIndex, ifmNormal, FMouseOffDrawMode); end; procedure TMyImage.SetColorize(const Value: Boolean); begin FColorize := Value; Invalidate; Update; end; procedure TMyImage.SetImageIndex(const Value: Integer); begin FImageIndex := Value; Invalidate; Update; end; procedure TMyImage.SetImageList(const Value: TcxImageList); begin FImageList := Value; Invalidate; Update; end; procedure TMyImage.SetMouseDownDrawMode(const Value: TcxImageDrawMode); begin FMouseDownDrawMode := Value; Invalidate; Update; end; procedure TMyImage.SetMouseOffDrawMode(const Value: TcxImageDrawMode); begin FMouseOffDrawMode := Value; Invalidate; Update; end; procedure TMyImage.SetMouseOverDrawMode(const Value: TcxImageDrawMode); begin FMouseOverDrawMode := Value; Invalidate; Update; end; procedure Register; begin RegisterComponents('NexCafe', [TMyImage]); end; { TcxMyAlphaBitmap } function cxColorEssence(const AColor: TRGBQuad): DWORD; {$IFDEF DELPHI9} inline; {$ENDIF} begin Result := DWORD(AColor) and $00FFFFFF; end; function TcxMyAlphaBitmap.IsColorTransparent(const AColor: TRGBQuad): Boolean; function IsTransparentPixel(AColor: DWORD): Boolean; begin Result := TransparentPixels.IndexOf(Pointer(AColor)) <> -1; end; begin Result := cxColorIsEqual(AColor, TransparentBkColor) or IsTransparentPixel(cxColorEssence(AColor)); end; procedure TcxMyAlphaBitmap.MyTransform; var AColors: TRGBColors; I, J: Integer; procedure MakeBlue(var AColor: TRGBQuad); begin if not IsColorTransparent(AColor) then begin AColor.rgbRed := GetRValue(clBlue); AColor.rgbGreen := GetGValue(clBlue); AColor.rgbBlue := GetBValue(clBlue); end; end; begin GetBitmapColors(AColors); for I := 0 to Width - 1 do for J := 0 to Height - 1 do MakeBlue(AColors[J * Width + I]); SetBitmapColors(AColors); Changed(Self); end; end.
unit DropTarget; // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite // Module: DropTarget // Description: Implements the drop target base classes which allows your // application to accept data dropped on it from other // applications. // Version: 4.0 // Date: 18-MAY-2001 // Target: Win32, Delphi 5-6 // Authors: Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright Đ 1997-2001 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- // General changes: // - Some component glyphs has changed. // - New components: // * TDropMetaFileTarget // * TDropImageTarget // * TDropSuperTarget // * Replaced all use of KeysToShiftState with KeysToShiftStatePlus for // correct mapping of Alt key. // TCustomDropTarget changes: // - New protected method SetDataObject. // Provides write access to DataObject property for use in descendant classes. // - New protected methods: GetPreferredDropEffect and SetPerformedDropEffect. // - New protected method DoUnregister handles unregistration of all or // individual targets. // - Unregister method has been overloaded to handle multiple drop targets // (Delphi 4 and later only). // - All private methods has been made protected. // - New public methods: FindTarget and FindNearestTarget. // For use with multiple drop targets. // - New published property MultiTarget enables multiple drop targets. // - New public property Targets for support of multiple drop targets. // - Visibility of Target property has changed from public to published and // has been made writable. // - PasteFromClipboard method now handles all formats via DoGetData. // - Now "handles" situations where the target window handle is recreated. // - Implemented TCustomDropTarget.Assign to assign from TClipboard and any object // which implements IDataObject. // - Added support for optimized moves and delete-on-paste with new // OptimizedMove property. // - Fixed inconsistency between GetValidDropEffect and standard IDropTarget // behaviour. // - The HasValidFormats method has been made public and now accepts an // IDataObject as a parameter. // - The OnGetDropEffect Effect parameter is now initialized to the drop // source's allowed drop effect mask prior to entry. // - Added published AutoScroll property and OnScroll evenīt and public // NoScrollZone property. // Auto scroling can now be completely customized via the OnDragEnter, // OnDragOver OnGetDropEffect and OnScroll events and the above properties. // - Added support for IDropTargetHelper interface. // - Added support for IAsyncOperation interface. // - New OnStartAsyncTransfer and OnEndAsyncTransfer events. // // TDropDummy changes: // - Bug in HasValidFormats fixed. Spotted by David Polberger. // Return value changed from True to False. // // ----------------------------------------------------------------------------- interface uses DragDrop, Windows, ActiveX, Classes, Controls, CommCtrl, ExtCtrls, Forms; {$include DragDrop.inc} //////////////////////////////////////////////////////////////////////////////// // // TControlList // //////////////////////////////////////////////////////////////////////////////// // List of TWinControl objects. // Used for the TCustomDropTarget.Targets property. //////////////////////////////////////////////////////////////////////////////// type TControlList = class(TObject) private FList: TList; function GetControl(AIndex: integer): TWinControl; function GetCount: integer; protected function Add(AControl: TWinControl): integer; procedure Insert(Index: Integer; AControl: TWinControl); procedure Remove(AControl: TWinControl); procedure Delete(AIndex: integer); public constructor Create; destructor Destroy; override; function IndexOf(AControl: TWinControl): integer; property Count: integer read GetCount; property Controls[AIndex: integer]: TWinControl read GetControl; default; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDropTarget // //////////////////////////////////////////////////////////////////////////////// // Top level abstract base class for all drop target classes. // Implements the IDropTarget and IDataObject interfaces. // Do not derive from TCustomDropTarget! Instead derive from TCustomDropTarget. // TCustomDropTarget will be replaced by/renamed to TCustomDropTarget in a future // version. //////////////////////////////////////////////////////////////////////////////// type TScrolDirection = (sdUp, sdDown, sdLeft, sdRight); TScrolDirections = set of TScrolDirection; TDropTargetScrollEvent = procedure(Sender: TObject; Point: TPoint; var Scroll: TScrolDirections; var Interval: integer) of object; TScrollBars = set of TScrollBarKind; TDropTargetEvent = procedure(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Longint) of object; TCustomDropTarget = class(TDragDropComponent, IDropTarget) private FDataObject : IDataObject; FDragTypes : TDragTypes; FGetDataOnEnter : boolean; FOnEnter : TDropTargetEvent; FOnDragOver : TDropTargetEvent; FOnLeave : TNotifyEvent; FOnDrop : TDropTargetEvent; FOnGetDropEffect : TDropTargetEvent; FOnScroll : TDropTargetScrollEvent; FTargets : TControlList; FMultiTarget : boolean; FOptimizedMove : boolean; FTarget : TWinControl; FImages : TImageList; FDragImageHandle : HImageList; FShowImage : boolean; FImageHotSpot : TPoint; FDropTargetHelper : IDropTargetHelper; // FLastPoint points to where DragImage was last painted (used internally) FLastPoint : TPoint; // Auto scrolling enables scrolling of target window during drags and // paints any drag image 'cleanly'. FScrollBars : TScrollBars; FScrollTimer : TTimer; FAutoScroll : boolean; FNoScrollZone : TRect; FIsAsync : boolean; FOnEndAsyncTransfer : TNotifyEvent; FOnStartAsyncTransfer: TNotifyEvent; FAllowAsync : boolean; protected // IDropTarget implementation function DragEnter(const DataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT; stdcall; function DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT; stdcall; function DragLeave: HRESULT; stdcall; function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT; stdcall; procedure DoEnter(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); virtual; procedure DoDragOver(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); virtual; procedure DoDrop(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); virtual; procedure DoLeave; virtual; procedure DoOnPaste(var Effect: Integer); virtual; procedure DoScroll(Point: TPoint; var Scroll: TScrolDirections; var Interval: integer); virtual; function GetData(Effect: longInt): boolean; virtual; function DoGetData: boolean; virtual; abstract; procedure ClearData; virtual; abstract; function GetValidDropEffect(ShiftState: TShiftState; pt: TPoint; dwEffect: LongInt): LongInt; virtual; // V4: Improved function GetPreferredDropEffect: LongInt; virtual; // V4: New function SetPerformedDropEffect(Effect: LongInt): boolean; virtual; // V4: New function SetPasteSucceded(Effect: LongInt): boolean; virtual; // V4: New procedure DoUnregister(ATarget: TWinControl); // V4: New procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetTarget: TWinControl; procedure SetTarget(const Value: TWinControl); procedure DoAutoScroll(Sender: TObject); // V4: Renamed from DoTargetScroll. procedure SetShowImage(Show: boolean); procedure SetDataObject(Value: IDataObject); // V4: New procedure DoEndAsyncTransfer(Sender: TObject); property DropTargetHelper: IDropTargetHelper read FDropTargetHelper; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Register(ATarget: TWinControl); {$ifdef VER12_PLUS} procedure Unregister(ATarget: TWinControl = nil); // V4: New {$else} procedure Unregister; {$endif} function FindTarget(p: TPoint): TWinControl; virtual; // V4: New function FindNearestTarget(p: TPoint): TWinControl; // V4: New procedure Assign(Source: TPersistent); override; // V4: New function HasValidFormats(ADataObject: IDataObject): boolean; virtual; abstract; // V4: Improved function PasteFromClipboard: longint; virtual; // V4: Improved property DataObject: IDataObject read FDataObject; property Targets: TControlList read FTargets; // V4: New property NoScrollZone: TRect read FNoScrollZone write FNoScrollZone; // V4: New property AsyncTransfer: boolean read FIsAsync; published property Dragtypes: TDragTypes read FDragTypes write FDragTypes; property GetDataOnEnter: Boolean read FGetDataOnEnter write FGetDataOnEnter; // Events... property OnEnter: TDropTargetEvent read FOnEnter write FOnEnter; property OnDragOver: TDropTargetEvent read FOnDragOver write FOnDragOver; property OnLeave: TNotifyEvent read FOnLeave write FOnLeave; property OnDrop: TDropTargetEvent read FOnDrop write FOnDrop; property OnGetDropEffect: TDropTargetEvent read FOnGetDropEffect write FOnGetDropEffect; // V4: Improved property OnScroll: TDropTargetScrollEvent read FOnScroll write FOnScroll; // V4: New property OnStartAsyncTransfer: TNotifyEvent read FOnStartAsyncTransfer write FOnStartAsyncTransfer; property OnEndAsyncTransfer: TNotifyEvent read FOnEndAsyncTransfer write FOnEndAsyncTransfer; // Drag Images... property ShowImage: boolean read FShowImage write SetShowImage; // Target property Target: TWinControl read GetTarget write SetTarget; // V4: Improved property MultiTarget: boolean read FMultiTarget write FMultiTarget default False; // V4: New // Auto scroll property AutoScroll: boolean read FAutoScroll write FAutoScroll default True; // V4: New // Misc property OptimizedMove: boolean read FOptimizedMove write FOptimizedMove default False; // V4: New // Async transfer... property AllowAsyncTransfer: boolean read FAllowAsync write FAllowAsync; end; //////////////////////////////////////////////////////////////////////////////// // // TDropTarget // //////////////////////////////////////////////////////////////////////////////// // Deprecated base class for all drop target components. // Replaced by the TCustomDropTarget class. //////////////////////////////////////////////////////////////////////////////// TDropTarget = class(TCustomDropTarget) end; //////////////////////////////////////////////////////////////////////////////// // // TDropDummy // //////////////////////////////////////////////////////////////////////////////// // The sole purpose of this component is to enable drag images to be displayed // over the registered TWinControl(s). The component does not accept any drops. //////////////////////////////////////////////////////////////////////////////// TDropDummy = class(TCustomDropTarget) protected procedure ClearData; override; function DoGetData: boolean; override; public function HasValidFormats(ADataObject: IDataObject): boolean; override; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDropMultiTarget // //////////////////////////////////////////////////////////////////////////////// // Drop target base class which can accept multiple formats. //////////////////////////////////////////////////////////////////////////////// TAcceptFormatEvent = procedure(Sender: TObject; const DataFormat: TCustomDataFormat; var Accept: boolean) of object; TCustomDropMultiTarget = class(TCustomDropTarget) private FOnAcceptFormat: TAcceptFormatEvent; protected procedure ClearData; override; function DoGetData: boolean; override; procedure DoAcceptFormat(const DataFormat: TCustomDataFormat; var Accept: boolean); virtual; property OnAcceptFormat: TAcceptFormatEvent read FOnAcceptFormat write FOnAcceptFormat; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HasValidFormats(ADataObject: IDataObject): boolean; override; property DataFormats; end; //////////////////////////////////////////////////////////////////////////////// // // TDropEmptyTarget // //////////////////////////////////////////////////////////////////////////////// // Do-nothing target for use with TDataFormatAdapter and such //////////////////////////////////////////////////////////////////////////////// TDropEmptyTarget = class(TCustomDropMultiTarget); //////////////////////////////////////////////////////////////////////////////// // // Misc. // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; (******************************************************************************* ** ** IMPLEMENTATION ** *******************************************************************************) implementation uses DragDropFormats, ComObj, SysUtils, Graphics, Messages, ShlObj, ClipBrd, ComCtrls; resourcestring sAsyncBusy = 'Can''t clear data while async data transfer is in progress'; // sRegisterFailed = 'Failed to register %s as a drop target'; // sUnregisterActiveTarget = 'Can''t unregister target while drag operation is in progress'; //////////////////////////////////////////////////////////////////////////////// // // Component registration // //////////////////////////////////////////////////////////////////////////////// procedure Register; begin RegisterComponents(DragDropComponentPalettePage, [TDropEmptyTarget, TDropDummy]); end; //////////////////////////////////////////////////////////////////////////////// // // Misc. // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // TControlList // //////////////////////////////////////////////////////////////////////////////// constructor TControlList.Create; begin inherited Create; FList := TList.Create; end; destructor TControlList.Destroy; begin FList.Free; inherited Destroy; end; function TControlList.Add(AControl: TWinControl): integer; begin Result := FList.Add(AControl); end; procedure TControlList.Insert(Index: Integer; AControl: TWinControl); begin FList.Insert(Index, AControl); end; procedure TControlList.Delete(AIndex: integer); begin FList.Delete(AIndex); end; function TControlList.IndexOf(AControl: TWinControl): integer; begin Result := FList.IndexOf(AControl); end; function TControlList.GetControl(AIndex: integer): TWinControl; begin Result := TWinControl(FList[AIndex]); end; function TControlList.GetCount: integer; begin Result := FList.Count; end; procedure TControlList.Remove(AControl: TWinControl); begin FList.Remove(AControl); end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDropTarget // //////////////////////////////////////////////////////////////////////////////// constructor TCustomDropTarget.Create(AOwner: TComponent); var bm : TBitmap; begin inherited Create(AOwner); FScrollTimer := TTimer.Create(Self); FScrollTimer.Enabled := False; FScrollTimer.OnTimer := DoAutoScroll; // Note: Normally we would call _AddRef or coLockObjectExternal(Self) here to // make sure that the component wasn't deleted prematurely (e.g. after a call // to RegisterDragDrop), but since our ancestor class TInterfacedComponent // disables reference counting, we do not need to do so. FGetDataOnEnter := False; FTargets := TControlList.Create; FImages := TImageList.Create(Self); // Create a blank image for FImages which we will use to hide any cursor // 'embedded' in a drag image. // This avoids the possibility of two cursors showing. bm := TBitmap.Create; try bm.Height := 32; bm.Width := 32; bm.Canvas.Brush.Color := clWindow; bm.Canvas.FillRect(bm.Canvas.ClipRect); FImages.AddMasked(bm, clWindow); finally bm.Free; end; FDataObject := nil; ShowImage := True; FMultiTarget := False; FOptimizedMove := False; FAutoScroll := True; end; destructor TCustomDropTarget.Destroy; begin FDataObject := nil; FDropTargetHelper := nil; Unregister; FImages.Free; FScrollTimer.Free; FTargets.Free; inherited Destroy; end; // TDummyWinControl is declared just to expose the protected property - Font - // which is used to calculate the 'scroll margin' for the target window. type TDummyWinControl = Class(TWinControl); function TCustomDropTarget.DragEnter(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HRESULT; var ShiftState : TShiftState; TargetStyles : longint; begin ClearData; FDataObject := dataObj; Result := S_OK; // Find the target control. FTarget := FindTarget(pt); (* ** If no target control has been registered we disable all features which ** depends on the existence of a drop target (e.g. drag images and auto ** scroll). Presently, this situation can only arise if the drop target is ** being used as a drop handler (TDrophandler component). ** Note also that if no target control exists, the mouse coordinates are ** relative to the screen, not the control as is normally the case. *) if (FTarget = nil) then begin ShowImage := False; AutoScroll := False; end else begin pt := FTarget.ScreenToClient(pt); FLastPoint := pt; end; (* ** Refuse the drag if we can't handle any of the data formats offered by ** the drop source. We must return S_OK here in order for the drop to continue ** to generate DragOver events for this drop target (needed for drag images). *) if HasValidFormats(FDataObject) then begin FScrollBars := []; if (AutoScroll) then begin // Determine if the target control has scroll bars (and which). TargetStyles := GetWindowLong(FTarget.Handle, GWL_STYLE); if (TargetStyles and WS_HSCROLL <> 0) then include(FScrollBars, sbHorizontal); if (TargetStyles and WS_VSCROLL <> 0) then include(FScrollBars, sbVertical); // The Windows UI guidelines recommends that the scroll margin be based on // the width/height of the scroll bars: // From "The Windows Interface Guidelines for Software Design", page 82: // "Use twice the width of a vertical scroll bar or height of a // horizontal scroll bar to determine the width of the hot zone." // Previous versions of these components used the height of the current // target control font as the scroll margin. Yet another approach would be // to use the DragDropScrollInset constant. if (FScrollBars <> []) then begin FNoScrollZone := FTarget.ClientRect; if (sbVertical in FScrollBars) then InflateRect(FNoScrollZone, 0, -GetSystemMetrics(SM_CYHSCROLL)); // InflateRect(FNoScrollZone, 0, -abs(TDummyWinControl(FTarget).Font.Height)); if (sbHorizontal in FScrollBars) then InflateRect(FNoScrollZone, -GetSystemMetrics(SM_CXHSCROLL), 0); // InflateRect(FNoScrollZone, -abs(TDummyWinControl(FTarget).Font.Height), 0); end; end; // It's generally more efficient to get data only if and when a drop occurs // rather than on entering a potential target window. // However - sometimes there is a good reason to get it here. if FGetDataOnEnter then if (not GetData(dwEffect)) then begin FDataObject := nil; dwEffect := DROPEFFECT_NONE; Result := DV_E_CLIPFORMAT; exit; end; ShiftState := KeysToShiftStatePlus(grfKeyState); // Create a default drop effect based on the shift state and allowed // drop effects (or an OnGetDropEffect event if implemented). dwEffect := GetValidDropEffect(ShiftState, Pt, dwEffect); // Generate an OnEnter event DoEnter(ShiftState, pt, dwEffect); // If IDropTarget.DragEnter returns with dwEffect set to DROPEFFECT_NONE it // means that the drop has been rejected and IDropTarget.DragOver should // not be called (according to MSDN). Unfortunately IDropTarget.DragOver is // called regardless of the value of dwEffect. We work around this problem // (bug?) by setting FDataObject to nil and thus internally rejecting the // drop in TCustomDropTarget.DragOver. if (dwEffect = DROPEFFECT_NONE) then FDataObject := nil; end else begin FDataObject := nil; dwEffect := DROPEFFECT_NONE; end; // Display drag image. // Note: This was previously done prior to caling GetValidDropEffect and // DoEnter. The SDK documentation states that IDropTargetHelper.DragEnter // should be called last in IDropTarget.DragEnter (presumably after dwEffect // has been modified), but Microsoft's own demo application calls it as the // very first thing (same for all other IDropTargetHelper methods). if ShowImage then begin // Attempt to create Drag Drop helper object. // At present this is only supported on Windows 2000. If the object can't be // created, we fall back to the old image list based method (which only // works on Win9x). CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER, IDropTargetHelper, FDropTargetHelper); if (FDropTargetHelper <> nil) then begin // If the call to DragEnter fails (which it will do if the drop source // doesn't support IDropSourceHelper or hasn't specified a drag image), // we release the drop target helper and fall back to imagelist based // drag images. if (DropTargetHelper.DragEnter(FTarget.Handle, DataObj, pt, dwEffect) <> S_OK) then FDropTargetHelper := nil; end; if (FDropTargetHelper = nil) then begin FDragImageHandle := ImageList_GetDragImage(nil, @FImageHotSpot); if (FDragImageHandle <> 0) then begin // Currently we will just replace any 'embedded' cursor with our // blank (transparent) image otherwise we sometimes get 2 cursors ... ImageList_SetDragCursorImage(FImages.Handle, 0, FImageHotSpot.x, FImageHotSpot.y); with ClientPtToWindowPt(FTarget.Handle, pt) do ImageList_DragEnter(FTarget.handle, x, y); end; end; end else FDragImageHandle := 0; end; procedure TCustomDropTarget.DoEnter(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); begin if Assigned(FOnEnter) then FOnEnter(Self, ShiftState, Point, Effect); end; function TCustomDropTarget.DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; var ShiftState: TShiftState; IsScrolling: boolean; begin // Refuse drop if we dermined in DragEnter that a drop weren't possible, // but still handle drag images provided we have a valid target. if (FTarget = nil) then begin dwEffect := DROPEFFECT_NONE; Result := E_UNEXPECTED; exit; end; pt := FTarget.ScreenToClient(pt); if (FDataObject <> nil) then begin ShiftState := KeysToShiftStatePlus(grfKeyState); // Create a default drop effect based on the shift state and allowed // drop effects (or an OnGetDropEffect event if implemented). dwEffect := GetValidDropEffect(ShiftState, pt, dwEffect); // Generate an OnDragOver event DoDragOver(ShiftState, pt, dwEffect); // Note: Auto scroll is detected by the GetValidDropEffect method, but can // also be started by the user via the OnDragOver or OnGetDropEffect events. // Auto scroll is initiated by specifying the DROPEFFECT_SCROLL value as // part of the drop effect. // Start the auto scroll timer if auto scroll were requested. Do *not* rely // on any other mechanisms to detect auto scroll since the user can only // specify auto scroll with the DROPEFFECT_SCROLL value. IsScrolling := (dwEffect and DROPEFFECT_SCROLL <> 0); if (IsScrolling) and (not FScrollTimer.Enabled) then begin FScrollTimer.Interval := DragDropScrollDelay; // hardcoded to 100 in previous versions. FScrollTimer.Enabled := True; end; Result := S_OK; end else begin // Even though this isn't an error condition per se, we must return // an error code (e.g. E_UNEXPECTED) in order for the cursor to change // to DROPEFFECT_NONE. IsScrolling := False; Result := DV_E_CLIPFORMAT; end; // Move drag image if (DropTargetHelper <> nil) then begin OleCheck(DropTargetHelper.DragOver(pt, dwEffect)); end else if (FDragImageHandle <> 0) then begin if (not IsScrolling) and ((FLastPoint.x <> pt.x) or (FLastPoint.y <> pt.y)) then with ClientPtToWindowPt(FTarget.Handle, pt) do ImageList_DragMove(x, y); end; FLastPoint := pt; end; procedure TCustomDropTarget.DoDragOver(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); begin if Assigned(FOnDragOver) then FOnDragOver(Self, ShiftState, Point, Effect); end; function TCustomDropTarget.DragLeave: HResult; begin ClearData; FScrollTimer.Enabled := False; FDataObject := nil; if (DropTargetHelper <> nil) then begin DropTargetHelper.DragLeave; end else if (FDragImageHandle <> 0) then ImageList_DragLeave(FTarget.Handle); // Generate an OnLeave event. // Protect resources against exceptions in event handler. try DoLeave; finally FTarget := nil; FDropTargetHelper := nil; end; Result := S_OK; end; procedure TCustomDropTarget.DoLeave; begin if Assigned(FOnLeave) then FOnLeave(Self); end; function TCustomDropTarget.Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; var ShiftState: TShiftState; ClientPt: TPoint; begin FScrollTimer.Enabled := False; // Protect resources against exceptions in OnDrop event handler. try // Refuse drop if we have lost the data object somehow. // This can happen if the drop is rejected in one of the other IDropTarget // methods (e.g. DragOver). if (FDataObject = nil) then begin dwEffect := DROPEFFECT_NONE; Result := E_UNEXPECTED; end else begin ShiftState := KeysToShiftStatePlus(grfKeyState); // Create a default drop effect based on the shift state and allowed // drop effects (or an OnGetDropEffect event if implemented). if (FTarget <> nil) then ClientPt := FTarget.ScreenToClient(pt) else ClientPt := pt; dwEffect := GetValidDropEffect(ShiftState, ClientPt, dwEffect); // Get data from source and generate an OnDrop event unless we failed to // get data. if (FGetDataOnEnter) or (GetData(dwEffect)) then DoDrop(ShiftState, ClientPt, dwEffect) else dwEffect := DROPEFFECT_NONE; Result := S_OK; end; if (DropTargetHelper <> nil) then begin DropTargetHelper.Drop(DataObj, pt, dwEffect); end else if (FDragImageHandle <> 0) and (FTarget <> nil) then ImageList_DragLeave(FTarget.Handle); finally // clean up! ClearData; FDataObject := nil; FDropTargetHelper := nil; FTarget := nil; end; end; procedure TCustomDropTarget.DoDrop(ShiftState: TShiftState; Point: TPoint; var Effect: Longint); begin if Assigned(FOnDrop) then FOnDrop(Self, ShiftState, Point, Effect); (* Optimized move (from MSDN): Scenario: A file is moved from the file system to a namespace extension using an optimized move. In a conventional move operation, the target makes a copy of the data and the source deletes the original. This procedure can be inefficient because it requires two copies of the data. With large objects such as databases, a conventional move operation might not even be practical. With an optimized move, the target uses its understanding of how the data is stored to handle the entire move operation. There is never a second copy of the data, and there is no need for the source to delete the original data. Shell data is well suited to optimized moves because the target can handle the entire operation using the shell API. A typical example is moving files. Once the target has the path of a file to be moved, it can use SHFileOperation to move it. There is no need for the source to delete the original file. Note The shell normally uses an optimized move to move files. To handle shell data transfer properly, your application must be capable of detecting and handling an optimized move. Optimized moves are handled in the following way: 1) The source calls DoDragDrop with the dwEffect parameter set to DROPEFFECT_MOVE to indicate that the source objects can be moved. 2) The target receives the DROPEFFECT_MOVE value through one of its IDropTarget methods, indicating that a move is allowed. 3) The target either copies the object (unoptimized move) or moves the object (optimized move). 4) The target then tells the source whether it needs to delete the original data. An optimized move is the default operation, with the data deleted by the target. To inform the source that an optimized move was performed: - The target sets the pdwEffect value it received through its IDropTarget::Drop method to some value other than DROPEFFECT_MOVE. It is typically set to either DROPEFFECT_NONE or DROPEFFECT_COPY. The value will be returned to the source by DoDragDrop. - The target also calls the data object's IDataObject::SetData method and passes it a CFSTR_PERFORMEDDROPEFFECT format identifier set to DROPEFFECT_NONE. This method call is necessary because some drop targets might not set the pdwEffect parameter of DoDragDrop properly. The CFSTR_PERFORMEDDROPEFFECT format is the reliable way to indicate that an optimized move has taken place. If the target did an unoptimized move, the data must be deleted by the source. To inform the source that an unoptimized move was performed: - The target sets the pdwEffect value it received through its IDropTarget::Drop method to DROPEFFECT_MOVE. The value will be returned to the source by DoDragDrop. - The target also calls the data object's IDataObject::SetData method and passes it a CFSTR_PERFORMEDDROPEFFECT format identifier set to DROPEFFECT_MOVE. This method call is necessary because some drop targets might not set the pdwEffect parameter of DoDragDrop properly. The CFSTR_PERFORMEDDROPEFFECT format is the reliable way to indicate that an unoptimized move has taken place. 5) The source inspects the two values that can be returned by the target. If both are set to DROPEFFECT_MOVE, it completes the unoptimized move by deleting the original data. Otherwise, the target did an optimized move and the original data has been deleted. *) // TODO : Why isn't this code in the Drop method? // Report performed drop effect back to data originator. if (Effect <> DROPEFFECT_NONE) then begin // If the transfer was an optimized move operation (target deletes data), // we convert the move operation to a copy operation to prevent that the // source deletes the data. if (FOptimizedMove) and (Effect = DROPEFFECT_MOVE) then Effect := DROPEFFECT_COPY; SetPerformedDropEffect(Effect); end; end; type TDropTargetTransferThread = class(TThread) private FCustomDropTarget: TCustomDropTarget; FDataObject: IDataObject; FEffect: Longint; FMarshalStream: pointer; protected procedure Execute; override; property MarshalStream: pointer read FMarshalStream write FMarshalStream; public constructor Create(ACustomDropTarget: TCustomDropTarget; const ADataObject: IDataObject; AEffect: Longint); property CustomDropTarget: TCustomDropTarget read FCustomDropTarget; property DataObject: IDataObject read FDataObject; property Effect: Longint read FEffect; end; constructor TDropTargetTransferThread.Create(ACustomDropTarget: TCustomDropTarget; const ADataObject: IDataObject; AEffect: longInt); begin inherited Create(True); FreeOnTerminate := True; FCustomDropTarget := ACustomDropTarget; OnTerminate := FCustomDropTarget.DoEndAsyncTransfer; FEffect := AEffect; OleCheck(CoMarshalInterThreadInterfaceInStream(IDataObject, ADataObject, IStream(FMarshalStream))); end; procedure TDropTargetTransferThread.Execute; var Res: HResult; begin CoInitialize(nil); try try OleCheck(CoGetInterfaceAndReleaseStream(IStream(MarshalStream), IDataObject, FDataObject)); MarshalStream := nil; CustomDropTarget.FDataObject := DataObject; CustomDropTarget.DoGetData; Res := S_OK; except Res := E_UNEXPECTED; end; (FDataObject as IAsyncOperation).EndOperation(Res, nil, Effect); finally FDataObject := nil; CoUninitialize; end; end; procedure TCustomDropTarget.DoEndAsyncTransfer(Sender: TObject); begin // Reset async transfer flag once transfer completes and... FIsAsync := False; // ...Fire event. if Assigned(FOnEndAsyncTransfer) then FOnEndAsyncTransfer(Self); end; function TCustomDropTarget.GetData(Effect: longInt): boolean; var DoAsync: LongBool; AsyncOperation: IAsyncOperation; // h: HResult; begin ClearData; // Determine if drop source supports and has enabled asynchronous data // transfer. (* h := DataObject.QueryInterface(IAsyncOperation, AsyncOperation); h := DataObject.QueryInterface(IDropSource, AsyncOperation); OutputDebugString(PChar(SysErrorMessage(h))); *) if not(AllowAsyncTransfer and Succeeded(DataObject.QueryInterface(IAsyncOperation, AsyncOperation)) and Succeeded(AsyncOperation.GetAsyncMode(DoAsync))) then DoAsync := False; // Start an async data transfer... if (DoAsync) then begin // Fire event. if Assigned(FOnStartAsyncTransfer) then FOnStartAsyncTransfer(Self); FIsAsync := True; // Notify drop source that an async data transfer is starting. AsyncOperation.StartOperation(nil); // Create the data transfer thread and launch it. with TDropTargetTransferThread.Create(Self, DataObject, Effect) do Resume; Result := True; end else Result := DoGetData; end; procedure TCustomDropTarget.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent is TWinControl) then begin if (csDesigning in ComponentState) and (AComponent = FTarget) then FTarget := nil; if (FTargets.IndexOf(TWinControl(AComponent)) <> -1) then DoUnregister(TWinControl(AComponent)); end; end; type TWinControlProxy = class(TWinControl) protected procedure DestroyWnd; override; procedure CreateWnd; override; end; procedure TWinControlProxy.CreateWnd; begin inherited CreateWnd; OleCheck(RegisterDragDrop(Parent.Handle, TCustomDropTarget(Owner))); Visible := False; end; procedure TWinControlProxy.DestroyWnd; begin if (Parent.HandleAllocated) then RevokeDragDrop(Parent.Handle); // Control must be visible in order to guarantee that CreateWnd is called when // parent control recreates window handle. Visible := True; inherited DestroyWnd; end; procedure TCustomDropTarget.Register(ATarget: TWinControl); function Contains(Parent, Child: TWinControl): boolean; var i: integer; begin if (Child.Parent <> Parent) then begin Result := False; for i := 0 to Parent.ControlCount-1 do if (Parent.Controls[i] is TWinControl) and Contains(TWinControl(Parent.Controls[i]), Child) then begin Result := True; break; end; end else Result := True; end; var i: integer; Inserted: boolean; begin // Don't register if the target is already registered. // TODO -cImprovement : Maybe we should unregister and reregister the target if it has already been registered (in case the handle has changed)... if (FTargets.IndexOf(ATarget) <> -1) then exit; // Unregister previous target unless MultiTarget is enabled (for backwards // compatibility). if (not FMultiTarget) and not(csLoading in ComponentState) then Unregister; if (ATarget = nil) then exit; // Insert the target in Z order, Topmost last. // Note: The target is added to the target list even though the drop target // registration may fail below. This is done because we would like // the target to be unregistered (RevokeDragDrop) even if we failed to // register it. Inserted := False; for i := FTargets.Count-1 downto 0 do if Contains(FTargets[i], ATarget) then begin FTargets.Insert(i+1, ATarget); Inserted := True; break; end; if (not Inserted) then begin FTargets.Add(ATarget); // ATarget.FreeNotification(Self); end; // If the target is a TRichEdit control, we disable the rich edit control's // built-in drag/drop support. if (ATarget is TCustomRichEdit) then RevokeDragDrop(ATarget.Handle); // Create a child control to monitor the target window handle. // The child control will perform the drop target registration for us. with TWinControlProxy.Create(Self) do Parent := ATarget; end; {$ifdef VER12_PLUS} procedure TCustomDropTarget.Unregister(ATarget: TWinControl); begin // Unregister a single targets (or all targets if ATarget is nil). DoUnregister(ATarget); end; {$else} procedure TCustomDropTarget.Unregister; begin // Unregister all targets (for backward compatibility). DoUnregister(nil); end; {$endif} procedure TCustomDropTarget.DoUnregister(ATarget: TWinControl); var i : integer; begin if (ATarget = nil) then begin for i := FTargets.Count-1 downto 0 do DoUnregister(FTargets[i]); exit; end; i := FTargets.IndexOf(ATarget); if (i = -1) then exit; if (ATarget = FTarget) then FTarget := nil; // raise Exception.Create(sUnregisterActiveTarget); FTargets.Delete(i); (* Handled by proxy if (ATarget.HandleAllocated) then // Ignore failed unregistrations - nothing to do about it anyway RevokeDragDrop(ATarget.Handle); *) // Delete target proxy. // The target proxy willl unregister the drop target for us when it is // destroyed. for i := ATarget.ControlCount-1 downto 0 do if (ATarget.Controls[i] is TWinControlProxy) and (TWinControlProxy(ATarget.Controls[i]).Owner = Self) then with TWinControlProxy(ATarget.Controls[i]) do begin Parent := nil; Free; break; end; end; function TCustomDropTarget.FindTarget(p: TPoint): TWinControl; (* var i: integer; r: TRect; Parent: TWinControl; *) begin Result := FindVCLWindow(p); while (Result <> nil) and (Targets.IndexOf(Result) = -1) do begin Result := Result.Parent; end; (* // Search list in Z order. Top to bottom. for i := Targets.Count-1 downto 0 do begin Result := Targets[i]; // If the control or any of its parent aren't visible, we can't drop on it. Parent := Result; while (Parent <> nil) do begin if (not Parent.Showing) then break; Parent := Parent.Parent; end; if (Parent <> nil) then continue; GetWindowRect(Result.Handle, r); if PtInRect(r, p) then exit; end; Result := nil; *) end; function TCustomDropTarget.FindNearestTarget(p: TPoint): TWinControl; var i : integer; r : TRect; pc : TPoint; Control : TWinControl; Dist , BestDist : integer; function Distance(r: TRect; p: TPoint): integer; var dx , dy : integer; begin if (p.x < r.Left) then dx := r.Left - p.x else if (p.x > r.Right) then dx := r.Right - p.x else dx := 0; if (p.y < r.Top) then dy := r.Top - p.y else if (p.y > r.Bottom) then dy := r.Bottom - p.y else dy := 0; Result := dx*dx + dy*dy; end; begin Result := nil; BestDist := high(integer); for i := 0 to Targets.Count-1 do begin Control := Targets[i]; r := Control.ClientRect; inc(r.Right); inc(r.Bottom); pc := Control.ScreenToClient(p); if (PtInRect(r, p)) then begin Result := Control; exit; end; Dist := Distance(r, pc); if (Dist < BestDist) then begin Result := Control; BestDist := Dist; end; end; end; function TCustomDropTarget.GetTarget: TWinControl; begin Result := FTarget; if (Result = nil) and not(csDesigning in ComponentState) then begin if (FTargets.Count > 0) then Result := TWinControl(FTargets[0]) else Result := nil; end; end; procedure TCustomDropTarget.SetTarget(const Value: TWinControl); begin if (FTarget = Value) then exit; if (csDesigning in ComponentState) then FTarget := Value else begin // If MultiTarget isn't enabled, Register will automatically unregister do // no need to do it here. if (FMultiTarget) and not(csLoading in ComponentState) then Unregister; Register(Value); end; end; procedure TCustomDropTarget.SetDataObject(Value: IDataObject); begin FDataObject := Value; end; procedure TCustomDropTarget.SetShowImage(Show: boolean); begin FShowImage := Show; if (DropTargetHelper <> nil) then DropTargetHelper.Show(Show) else if (FDataObject <> nil) then ImageList_DragShowNolock(FShowImage); end; function TCustomDropTarget.GetValidDropEffect(ShiftState: TShiftState; pt: TPoint; dwEffect: LongInt): LongInt; begin // dwEffect 'in' parameter = set of drop effects allowed by drop source. // Now filter out the effects disallowed by target... Result := dwEffect AND DragTypesToDropEffect(FDragTypes); Result := ShiftStateToDropEffect(ShiftState, Result, True); // Add Scroll effect if necessary... if (FAutoScroll) and (FScrollBars <> []) then begin // If the cursor is inside the no-scroll zone, clear the drag scroll flag, // otherwise set it. if (PtInRect(FNoScrollZone, pt)) then Result := Result AND NOT integer(DROPEFFECT_SCROLL) else Result := Result OR integer(DROPEFFECT_SCROLL); end; // 'Default' behaviour can be overriden by assigning OnGetDropEffect. if Assigned(FOnGetDropEffect) then FOnGetDropEffect(Self, ShiftState, pt, Result); end; function TCustomDropTarget.GetPreferredDropEffect: LongInt; begin with TPreferredDropEffectClipboardFormat.Create do try if GetData(DataObject) then Result := Value else Result := DROPEFFECT_NONE; finally Free; end; end; function TCustomDropTarget.SetPasteSucceded(Effect: LongInt): boolean; var Medium: TStgMedium; begin with TPasteSuccededClipboardFormat.Create do try Value := Effect; Result := SetData(DataObject, FormatEtc, Medium); finally Free; end; end; function TCustomDropTarget.SetPerformedDropEffect(Effect: longInt): boolean; var Medium: TStgMedium; begin with TPerformedDropEffectClipboardFormat.Create do try Value := Effect; Result := SetData(DataObject, FormatEtc, Medium); finally Free; end; end; (* The basic procedure for a delete-on-paste operation is as follows (from MSDN): 1) The source marks the screen display of the selected data. 2) The source creates a data object. It indicates a cut operation by adding the CFSTR_PREFERREDDROPEFFECT format with a data value of DROPEFFECT_MOVE. 3) The source places the data object on the Clipboard using OleSetClipboard. 4) The target retrieves the data object from the Clipboard using OleGetClipboard. 5) The target extracts the CFSTR_PREFERREDDROPEFFECT data. If it is set to only DROPEFFECT_MOVE, the target can either do an optimized move or simply copy the data. 6) If the target does not do an optimized move, it calls the IDataObject::SetData method with the CFSTR_PERFORMEDDROPEFFECT format set to DROPEFFECT_MOVE. 7) When the paste is complete, the target calls the IDataObject::SetData method with the CFSTR_PASTESUCCEEDED format set to DROPEFFECT_MOVE. 8) When the source's IDataObject::SetData method is called with the CFSTR_PASTESUCCEEDED format set to DROPEFFECT_MOVE, it must check to see if it also received the CFSTR_PERFORMEDDROPEFFECT format set to DROPEFFECT_MOVE. If both formats are sent by the target, the source will have to delete the data. If only the CFSTR_PASTESUCCEEDED format is received, the source can simply remove the data from its display. If the transfer fails, the source updates the display to its original appearance. *) function TCustomDropTarget.PasteFromClipboard: longint; var Effect: longInt; begin // Get an IDataObject interface to the clipboard. // Temporarily pretend that the IDataObject has been dropped on the target. OleCheck(OleGetClipboard(FDataObject)); try Effect := GetPreferredDropEffect; // Get data from the IDataObject. if (GetData(Effect)) then Result := Effect else Result := DROPEFFECT_NONE; DoOnPaste(Result); finally // Clean up FDataObject := nil; end; end; procedure TCustomDropTarget.DoOnPaste(var Effect: longint); begin // Generate an OnDrop event DoDrop([], Point(0,0), Effect); // Report performed drop effect back to data originator. if (Effect <> DROPEFFECT_NONE) then // Delete on paste: // We now set the CF_PASTESUCCEDED format to indicate to the source // that we are using the "delete on paste" protocol and that the // paste has completed. SetPasteSucceded(Effect); end; procedure TCustomDropTarget.Assign(Source: TPersistent); begin if (Source is TClipboard) then PasteFromClipboard else if (Source.GetInterface(IDataObject, FDataObject)) then begin try // Get data from the IDataObject if (not GetData(DROPEFFECT_COPY)) then inherited Assign(Source); finally // Clean up FDataObject := nil; end; end else inherited Assign(Source); end; procedure TCustomDropTarget.DoAutoScroll(Sender: TObject); var Scroll: TScrolDirections; Interval: integer; begin // Disable timer until we are ready to auto-repeat the scroll. // If no scroll is performed, the scroll stops here. FScrollTimer.Enabled := False;; Interval := DragDropScrollInterval; Scroll := []; // Only scroll if the pointer is outside the non-scroll area if (not PtInRect(FNoScrollZone, FLastPoint)) then begin with FLastPoint do begin // Determine which way to scroll. if (Y < FNoScrollZone.Top) then include(Scroll, sdUp) else if (Y > FNoScrollZone.Bottom) then include(Scroll, sdDown); if (X < FNoScrollZone.Left) then include(Scroll, sdLeft) else if (X > FNoScrollZone.Right) then include(Scroll, sdRight); end; end; DoScroll(FLastPoint, Scroll, Interval); // Note: Once the OnScroll event has been fired and the user has had a // chance of overriding the auto scroll logic, we should *only* use to Scroll // variable to determine if and how to scroll. Do not use FScrollBars past // this point. // Only scroll if the pointer is outside the non-scroll area if (Scroll <> []) then begin // Remove drag image before scrolling if (FDragImageHandle <> 0) then ImageList_DragLeave(FTarget.Handle); try if (sdUp in Scroll) then FTarget.Perform(WM_VSCROLL,SB_LINEUP, 0) else if (sdDown in Scroll) then FTarget.Perform(WM_VSCROLL,SB_LINEDOWN, 0); if (sdLeft in Scroll) then FTarget.Perform(WM_HSCROLL,SB_LINEUP, 0) else if (sdRight in Scroll) then FTarget.Perform(WM_HSCROLL,SB_LINEDOWN, 0); finally // Restore drag image if (FDragImageHandle <> 0) then with ClientPtToWindowPt(FTarget.Handle, FLastPoint) do ImageList_DragEnter(FTarget.Handle, x, y); end; // Reset scroll timer interval once timer has fired once. FScrollTimer.Interval := Interval; FScrollTimer.Enabled := True; end; end; procedure TCustomDropTarget.DoScroll(Point: TPoint; var Scroll: TScrolDirections; var Interval: integer); begin if Assigned(FOnScroll) then FOnScroll(Self, FLastPoint, Scroll, Interval); end; //////////////////////////////////////////////////////////////////////////////// // // TDropDummy // //////////////////////////////////////////////////////////////////////////////// function TDropDummy.HasValidFormats(ADataObject: IDataObject): boolean; begin Result := False; end; procedure TDropDummy.ClearData; begin // Abstract method override - doesn't do anything as you can see. end; function TDropDummy.DoGetData: boolean; begin Result := False; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDropMultiTarget // //////////////////////////////////////////////////////////////////////////////// constructor TCustomDropMultiTarget.Create(AOwner: TComponent); begin inherited Create(AOwner); DragTypes := [dtLink, dtCopy]; GetDataOnEnter := False; FDataFormats := TDataFormats.Create; end; destructor TCustomDropMultiTarget.Destroy; var i : integer; begin // Delete all target formats owned by the object. for i := FDataFormats.Count-1 downto 0 do FDataFormats[i].Free; FDataFormats.Free; inherited Destroy; end; function TCustomDropMultiTarget.HasValidFormats(ADataObject: IDataObject): boolean; var GetNum , GotNum : longInt; FormatEnumerator : IEnumFormatEtc; i : integer; SourceFormatEtc : TFormatEtc; begin Result := False; if (ADataObject.EnumFormatEtc(DATADIR_GET, FormatEnumerator) <> S_OK) or (FormatEnumerator.Reset <> S_OK) then exit; GetNum := 1; // Get one format at a time. // Enumerate all data formats offered by the drop source. // Note: Depends on order of evaluation. while (not Result) and (FormatEnumerator.Next(GetNum, SourceFormatEtc, @GotNum) = S_OK) and (GetNum = GotNum) do begin // Determine if any of the associated clipboard formats can // read the current data format. for i := 0 to FDataFormats.Count-1 do if (FDataFormats[i].AcceptFormat(SourceFormatEtc)) and (FDataFormats[i].HasValidFormats(ADataObject)) then begin Result := True; DoAcceptFormat(FDataFormats[i], Result); if (Result) then break; end; end; end; procedure TCustomDropMultiTarget.ClearData; var i : integer; begin if (AsyncTransfer) then raise Exception.Create(sAsyncBusy); for i := 0 to DataFormats.Count-1 do DataFormats[i].Clear; end; function TCustomDropMultiTarget.DoGetData: boolean; var i: integer; Accept: boolean; begin Result := False; // Get data for all target formats for i := 0 to DataFormats.Count-1 do begin // This isn't strictly nescessary and adds overhead, but it reduces // unnescessary calls to DoAcceptData (format is asked if it can accept data // even though no data is available to the format). if not(FDataFormats[i].HasValidFormats(DataObject)) then continue; // Only get data from accepted formats. // TDropComboTarget uses the DoAcceptFormat method to filter formats and to // allow the user to disable formats via an event. Accept := True; DoAcceptFormat(DataFormats[i], Accept); if (not Accept) then Continue; Result := DataFormats[i].GetData(DataObject) or Result; end; end; procedure TCustomDropMultiTarget.DoAcceptFormat(const DataFormat: TCustomDataFormat; var Accept: boolean); begin if Assigned(FOnAcceptFormat) then FOnAcceptFormat(Self, DataFormat, Accept); end; end.
unit Ths.Erp.Database.Table.SatisTeklif; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, System.Rtti, Ths.Erp.Database, Ths.Erp.Database.Table, Ths.Erp.Database.Table.AyarHaneSayisi, Ths.Erp.Database.Table.SatisTeklifDetay, Ths.Erp.Database.TableDetailed, Ths.Erp.Database.Table.PersonelKarti, Ths.Erp.Database.Table.AyarEFaturaFaturaTipi, Ths.Erp.Database.Table.AyarTeklifTipi, Ths.Erp.Database.Table.AyarTeklifDurum, Ths.Erp.Database.Table.AyarOdemeBaslangicDonemi; type TSatisTeklif = class(TTableDetailed) private FSiparisID: TFieldDB; FIrsaliyeID: TFieldDB; FFaturaID: TFieldDB; FIsSiparislesti: TFieldDB; FIsTaslak: TFieldDB; FIsEFatura: TFieldDB; FTutar: TFieldDB; FIskontoTutar: TFieldDB; FAraToplam: TFieldDB; FGenelIskontoTutar: TFieldDB; FKDVTutar: TFieldDB; FGenelToplam: TFieldDB; FIslemTipiID: TFieldDB; FIslemTipi: TFieldDB; //veri tabanı alanı değil not a database field FTeklifNo: TFieldDB; FTeklifTarihi: TFieldDB; FTeslimTarihi: TFieldDB; FGecerlilikTarihi: TFieldDB; FMusteriKodu: TFieldDB; FMusteriAdi: TFieldDB; FAdresMusteriID: TFieldDB; FAdresMusteri: TFieldDB; //veri tabanı alanı değil not a database field FPostaKodu: TFieldDB; FVergiDairesi: TFieldDB; FVergiNo: TFieldDB; FMusteriTemsilcisiID: TFieldDB; FMusteriTemsilcisi: TFieldDB; //veri tabanı alanı değil not a database field FTeklifTipiID: TFieldDB; FTeklifTipi: TFieldDB; //veri tabanı alanı değil not a database field FAdresSevkiyatID: TFieldDB; FAdresSevkiyat: TFieldDB; //veri tabanı alanı değil not a database field FMuhattapAd: TFieldDB; FMuhattapSoyad: TFieldDB; FOdemeVadesi: TFieldDB; FReferans: TFieldDB; FTeslimatSuresi: TFieldDB; FTeklifDurumID: TFieldDB; FTeklifDurum: TFieldDB; //veri tabanı alanı değil not a database field FSevkTarihi: TFieldDB; FVadeGunSayisi: TFieldDB; FFaturaSevkTarihi: TFieldDB; FParaBirimi: TFieldDB; FDolarKur: TFieldDB; FEuroKur: TFieldDB; FOdemeBaslangicDonemiID: TFieldDB; FOdemeBaslangicDonemi: TFieldDB; //veri tabanı alanı değil not a database field FTeslimSartiID: TFieldDB; FTeslimSarti: TFieldDB; //veri tabanı alanı değil not a database field FGonderimSekliID: TFieldDB; FGonderimSekli: TFieldDB; //veri tabanı alanı değil not a database field FGonderimSekliDetay: TFieldDB; FOdemeSekliID: TFieldDB; FOdemeSekli: TFieldDB; //veri tabanı alanı değil not a database field FAciklama: TFieldDB; FProformaNo: TFieldDB; FArayanKisiID: TFieldDB; FArayanKisi: TFieldDB; //veri tabanı alanı değil not a database field FAramaTarihi: TFieldDB; FSonrakiAksiyonTarihi: TFieldDB; FAksiyonNotu: TFieldDB; FTevkifatKodu: TFieldDB; FTevkifatPay: TFieldDB; FTevkifatPayda: TFieldDB; FIhracKayitKodu: TFieldDB; //veri tabanı alanı değil FOrtakIskonto: TFieldDB; FOrtakKDV: TFieldDB; protected vMusteriTemsilcisi: TPersonelKarti; vIslemTipi: TAyarEFaturaFaturaTipi; vTeklifTipi: TAyarTeklifTipi; vTeklifDurum: TAyarTeklifDurum; vOdemeBaslangicDonemi: TAyarOdemeBaslangicDonemi; procedure BusinessSelect(pFilter: string; pLock, pPermissionControl: Boolean); override; procedure BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); override; procedure BusinessUpdate(pPermissionControl: Boolean); override; procedure BusinessDelete(pPermissionControl: Boolean); override; procedure RefreshHeader(); override; function ValidateDetay(pTable: TTable): Boolean; override; published constructor Create(pOwnerDatabase: TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean = True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean = True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean = True); override; procedure Update(pPermissionControl: Boolean = True); override; function Clone(): TTable; override; function ToSiparis(): TTable; function ToProforma(): TTable; procedure RefreshHeaderPublic(); procedure AddDetay(pTable: TTable); override; procedure UpdateDetay(pTable: TTable); override; procedure RemoveDetay(pTable: TTable); override; procedure DetayKopyala(pSelectedDetay: TSatisTeklifDetay); procedure SortDetaylar(); function DetayUrunMiktariniAnaUrunMiktarinaGoreOranla(pID: Integer; pAnaUrunArtisMiktari: Double): Boolean; procedure AnaUrunOzetFiyatlandir(); procedure FiyatlariGuncelle(); function ContainsAnaUrun(): Boolean; function CheckFarkliKDV(): Boolean; function ValidateTasiyiciDetayMiktar(pMalKodu: string; pMiktar: Double; pTasiyiciDetayID: Integer): Boolean; procedure UpdateAlisTeklifOnayi(pAlisOnayi: Boolean); Property SiparisID: TFieldDB read FSiparisID write FSiparisID; Property IrsaliyeID: TFieldDB read FIrsaliyeID write FIrsaliyeID; Property FaturaID: TFieldDB read FFaturaID write FFaturaID; Property IsSiparislesti: TFieldDB read FIsSiparislesti write FIsSiparislesti; Property IsTaslak: TFieldDB read FIsTaslak write FIsTaslak; Property IsEFatura: TFieldDB read FIsEFatura write FIsEFatura; Property Tutar: TFieldDB read FTutar write FTutar; Property IskontoTutar: TFieldDB read FIskontoTutar write FIskontoTutar; Property AraToplam: TFieldDB read FAraToplam write FAraToplam; Property GenelIskontoTutar: TFieldDB read FGenelIskontoTutar write FGenelIskontoTutar; Property KDVTutar: TFieldDB read FKDVTutar write FKDVTutar; Property GenelToplam: TFieldDB read FGenelToplam write FGenelToplam; Property IslemTipiID: TFieldDB read FIslemTipiID write FIslemTipiID; Property IslemTipi: TFieldDB read FIslemTipi write FIslemTipi; //veri tabanı alanı değil not a database field Property TeklifNo: TFieldDB read FTeklifNo write FTeklifNo; Property TeklifTarihi: TFieldDB read FTeklifTarihi write FTeklifTarihi; Property TeslimTarihi: TFieldDB read FTeslimTarihi write FTeslimTarihi; Property GecerlilikTarihi: TFieldDB read FGecerlilikTarihi write FGecerlilikTarihi; Property MusteriKodu: TFieldDB read FMusteriKodu write FMusteriKodu; Property MusteriAdi: TFieldDB read FMusteriAdi write FMusteriAdi; Property AdresMusteriID: TFieldDB read FAdresMusteriID write FAdresMusteriID; Property AdresMusteri: TFieldDB read FAdresMusteri write FAdresMusteri; //veri tabanı alanı değil not a database field Property PostaKodu: TFieldDB read FPostaKodu write FPostaKodu; Property VergiDairesi: TFieldDB read FVergiDairesi write FVergiDairesi; Property VergiNo: TFieldDB read FVergiNo write FVergiNo; Property MusteriTemsilcisiID: TFieldDB read FMusteriTemsilcisiID write FMusteriTemsilcisiID; Property MusteriTemsilcisi: TFieldDB read FMusteriTemsilcisi write FMusteriTemsilcisi; //veri tabanı alanı değil not a database field Property TeklifTipiID: TFieldDB read FTeklifTipiID write FTeklifTipiID; Property TeklifTipi: TFieldDB read FTeklifTipi write FTeklifTipi; //veri tabanı alanı değil not a database field Property AdresSevkiyatID: TFieldDB read FAdresSevkiyatID write FAdresSevkiyatID; Property AdresSevkiyat: TFieldDB read FAdresSevkiyat write FAdresSevkiyat; //veri tabanı alanı değil not a database field Property MuhattapAd: TFieldDB read FMuhattapAd write FMuhattapAd; Property MuhattapSoyad: TFieldDB read FMuhattapSoyad write FMuhattapSoyad; Property OdemeVadesi: TFieldDB read FOdemeVadesi write FOdemeVadesi; Property Referans: TFieldDB read FReferans write FReferans; Property TeslimatSuresi: TFieldDB read FTeslimatSuresi write FTeslimatSuresi; Property TeklifDurumID: TFieldDB read FTeklifDurumID write FTeklifDurumID; Property TeklifDurum: TFieldDB read FTeklifDurum write FTeklifDurum; //veri tabanı alanı değil not a database field Property SevkTarihi: TFieldDB read FSevkTarihi write FSevkTarihi; Property VadeGunSayisi: TFieldDB read FVadeGunSayisi write FVadeGunSayisi; Property FaturaSevkTarihi: TFieldDB read FFaturaSevkTarihi write FFaturaSevkTarihi; Property ParaBirimi: TFieldDB read FParaBirimi write FParaBirimi; Property DolarKur: TFieldDB read FDolarKur write FDolarKur; Property EuroKur: TFieldDB read FEuroKur write FEuroKur; Property OdemeBaslangicDonemiID: TFieldDB read FOdemeBaslangicDonemiID write FOdemeBaslangicDonemiID; Property OdemeBaslangicDonemi: TFieldDB read FOdemeBaslangicDonemi write FOdemeBaslangicDonemi; //veri tabanı alanı değil not a database field Property TeslimSartiID: TFieldDB read FTeslimSartiID write FTeslimSartiID; Property TeslimSarti: TFieldDB read FTeslimSarti write FTeslimSarti; //veri tabanı alanı değil not a database field Property GonderimSekliID: TFieldDB read FGonderimSekliID write FGonderimSekliID; Property GonderimSekli: TFieldDB read FGonderimSekli write FGonderimSekli; //veri tabanı alanı değil not a database field Property GonderimSekliDetay: TFieldDB read FGonderimSekliDetay write FGonderimSekliDetay; Property OdemeSekliID: TFieldDB read FOdemeSekliID write FOdemeSekliID; Property OdemeSekli: TFieldDB read FOdemeSekli write FOdemeSekli; //veri tabanı alanı değil not a database field Property Aciklama: TFieldDB read FAciklama write FAciklama; Property ProformaNo: TFieldDB read FProformaNo write FProformaNo; Property ArayanKisiID: TFieldDB read FArayanKisiID write FArayanKisiID; Property ArayanKisi: TFieldDB read FArayanKisi write FArayanKisi; //veri tabanı alanı değil not a database field Property AramaTarihi: TFieldDB read FAramaTarihi write FAramaTarihi; Property SonrakiAksiyonTarihi: TFieldDB read FSonrakiAksiyonTarihi write FSonrakiAksiyonTarihi; Property AksiyonNotu: TFieldDB read FAksiyonNotu write FAksiyonNotu; Property TevkifatKodu: TFieldDB read FTevkifatKodu write FTevkifatKodu; Property TevkifatPay: TFieldDB read FTevkifatPay write FTevkifatPay; Property TevkifatPayda: TFieldDB read FTevkifatPayda write FTevkifatPayda; Property IhracKayitKodu: TFieldDB read FIhracKayitKodu write FIhracKayitKodu; //veri tabanı alanı değil Property OrtakIskonto: TFieldDB read FOrtakIskonto write FOrtakIskonto; Property OrtakKDV: TFieldDB read FOrtakKDV write FOrtakKDV; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TSatisTeklif.Create(pOwnerDatabase:TDatabase); begin TableName := 'satis_teklif'; SourceCode := '1000'; inherited Create(pOwnerDatabase); FSiparisID := TFieldDB.Create('siparis_id', ftInteger, 0, 0, False, False); FIrsaliyeID := TFieldDB.Create('irsaliye_id', ftInteger, 0); FFaturaID := TFieldDB.Create('fatura_id', ftInteger, 0); FIsSiparislesti := TFieldDB.Create('is_siparislesti', ftBoolean, False, 0, False); FIsTaslak := TFieldDB.Create('is_taslak', ftBoolean, False, 0, False); FIsEFatura := TFieldDB.Create('is_efatura', ftBoolean, False, 0, False); FTutar := TFieldDB.Create('tutar', ftFloat, 0, 0, False); FIskontoTutar := TFieldDB.Create('iskonto_tutar', ftFloat, 0, 0, False); FAraToplam := TFieldDB.Create('ara_toplam', ftFloat, 0, 0, False); FGenelIskontoTutar := TFieldDB.Create('genel_iskonto_tutar', ftFloat, 0, 0, False); FKDVTutar := TFieldDB.Create('kdv_tutar', ftFloat, 0, 0, False); FGenelToplam := TFieldDB.Create('genel_toplam', ftFloat, 0, 0, False); FIslemTipiID := TFieldDB.Create('islem_tipi_id', ftInteger, 0); FIslemTipi := TFieldDB.Create('islem_tipi', ftString, ''); FTeklifNo := TFieldDB.Create('teklif_no', ftString, ''); FTeklifTarihi := TFieldDB.Create('teklif_tarihi', ftDateTime, 0); FTeslimTarihi := TFieldDB.Create('teslim_tarihi', ftDateTime, 0); FGecerlilikTarihi := TFieldDB.Create('gecerlilik_tarihi', ftDateTime, 0); FMusteriKodu := TFieldDB.Create('musteri_kodu', ftString, ''); FMusteriAdi := TFieldDB.Create('musteri_adi', ftString, ''); FAdresMusteriID := TFieldDB.Create('adres_musteri_id', ftInteger, 0); FAdresMusteri := TFieldDB.Create('adres_musteri', ftString, ''); FPostaKodu := TFieldDB.Create('posta_kodu', ftString, ''); FVergiDairesi := TFieldDB.Create('vergi_dairesi', ftString, ''); FVergiNo := TFieldDB.Create('vergi_no', ftString, ''); FMusteriTemsilcisiID := TFieldDB.Create('musteri_temsilcisi_id', ftInteger, 0); FMusteriTemsilcisi := TFieldDB.Create('musteri_temsilcisi', ftString, ''); FTeklifTipiID := TFieldDB.Create('teklif_tipi_id', ftInteger, 0); FTeklifTipi := TFieldDB.Create('teklif_tipi', ftString, ''); FAdresSevkiyat := TFieldDB.Create('adres_sevkiyat_id', ftInteger, 0); FAdresSevkiyat := TFieldDB.Create('adres_sevkiyat', ftString, ''); FMuhattapAd := TFieldDB.Create('muhattap_ad', ftString, ''); FMuhattapSoyad := TFieldDB.Create('muhattap_soyad', ftString, ''); FOdemeVadesi := TFieldDB.Create('odeme_vadesi', ftString, ''); FReferans := TFieldDB.Create('referans', ftString, ''); FTeslimatSuresi := TFieldDB.Create('teslimat_suresi', ftString, ''); FTeklifDurumID := TFieldDB.Create('teklif_durum_id', ftInteger, 0); FTeklifDurum := TFieldDB.Create('teklif_durum', ftString, ''); FSevkTarihi := TFieldDB.Create('sevk_tarihi', ftDateTime, 0); FVadeGunSayisi := TFieldDB.Create('vade_gun_sayisi', ftInteger, 0); FFaturaSevkTarihi := TFieldDB.Create('fatura_sevk_tarihi', ftString, ''); FParaBirimi := TFieldDB.Create('para_birimi', ftString, ''); FDolarKur := TFieldDB.Create('dolar_kur', ftFloat, 0); FEuroKur := TFieldDB.Create('euro_kur', ftFloat, 0); FOdemeBaslangicDonemiID := TFieldDB.Create('odeme_baslangic_donemi_id', ftInteger, 0); FOdemeBaslangicDonemi := TFieldDB.Create('odeme_baslangic_donemi', ftString, ''); FTeslimSartiID := TFieldDB.Create('teslim_sarti_id', ftInteger, 0); FTeslimSarti := TFieldDB.Create('teslim_sarti', ftString, ''); FGonderimSekliID := TFieldDB.Create('gonderim_sekli_id', ftInteger, 0); FGonderimSekli := TFieldDB.Create('gonderim_sekli', ftString, ''); FGonderimSekliDetay := TFieldDB.Create('gonderim_sekli_detay', ftString, ''); FOdemeSekliID := TFieldDB.Create('odeme_sekli_id', ftInteger, 0); FOdemeSekli := TFieldDB.Create('odeme_sekli', ftString, ''); FAciklama := TFieldDB.Create('aciklama', ftString, ''); FProformaNo := TFieldDB.Create('proforma_no', ftInteger, 0); FArayanKisiID := TFieldDB.Create('arayan_kisi_id', ftInteger, 0); FArayanKisi := TFieldDB.Create('arayan_kisi', ftString, ''); FAramaTarihi := TFieldDB.Create('arama_tarihi', ftDateTime, 0); FSonrakiAksiyonTarihi := TFieldDB.Create('sonraki_aksiyon_tarihi', ftDateTime, 0); FAksiyonNotu := TFieldDB.Create('aksiyon_notu', ftString, ''); FTevkifatKodu := TFieldDB.Create('tevkifat_kodu', ftString, ''); FTevkifatPay := TFieldDB.Create('tevkifat_pay', ftInteger, 0); FTevkifatPayda := TFieldDB.Create('tevkifat_payda', ftInteger, 0); FIhracKayitKodu := TFieldDB.Create('ihrac_kayit_kodu', ftString, ''); //veri tabanı alanı değil FOrtakIskonto := TFieldDB.Create('ortak_iskonto', ftFloat, 0); FOrtakKDV := TFieldDB.Create('ortak_kdv', ftFloat, 0); end; procedure TSatisTeklif.DetayKopyala(pSelectedDetay: TSatisTeklifDetay); begin // end; function TSatisTeklif.DetayUrunMiktariniAnaUrunMiktarinaGoreOranla(pID: Integer; pAnaUrunArtisMiktari: Double): Boolean; begin Result := False; end; procedure TSatisTeklif.FiyatlariGuncelle; begin // end; procedure TSatisTeklif.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin vMusteriTemsilcisi := TPersonelKarti.Create(Database); vIslemTipi := TAyarEFaturaFaturaTipi.Create(Database); vTeklifTipi := TAyarTeklifTipi.Create(Database); vTeklifDurum := TAyarTeklifDurum.Create(Database); vOdemeBaslangicDonemi := TAyarOdemeBaslangicDonemi.Create(Database); try Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FSiparisID.FieldName, TableName + '.' + FIrsaliyeID.FieldName, TableName + '.' + FFaturaID.FieldName, TableName + '.' + FIsSiparislesti.FieldName, TableName + '.' + FIsTaslak.FieldName, TableName + '.' + FIsEFatura.FieldName, TableName + '.' + FTutar.FieldName, TableName + '.' + FIskontoTutar.FieldName, TableName + '.' + FAraToplam.FieldName, TableName + '.' + FGenelIskontoTutar.FieldName, TableName + '.' + FKDVTutar.FieldName, TableName + '.' + FGenelToplam.FieldName, TableName + '.' + FIslemTipiID.FieldName, ColumnFromIDCol(vIslemTipi.Tip.FieldName, vIslemTipi.TableName, FIslemTipiID.FieldName, FIslemTipi.FieldName, TableName), TableName + '.' + FTeklifNo.FieldName, TableName + '.' + FTeklifTarihi.FieldName, TableName + '.' + FTeslimTarihi.FieldName, TableName + '.' + FGecerlilikTarihi.FieldName, TableName + '.' + FMusteriKodu.FieldName, TableName + '.' + FMusteriAdi.FieldName, TableName + '.' + FAdresMusteriID.FieldName, TableName + '.' + FAdresMusteri.FieldName, TableName + '.' + FPostaKodu.FieldName, TableName + '.' + FVergiDairesi.FieldName, TableName + '.' + FVergiNo.FieldName, TableName + '.' + FMusteriTemsilcisiID.FieldName, TableName + '.' + FTeklifTipiID.FieldName, ColumnFromIDCol(vTeklifTipi.Deger.FieldName, vTeklifTipi.TableName, FTeklifTipiID.FieldName, FTeklifTipi.FieldName, TableName), TableName + '.' + FAdresSevkiyatID.FieldName, TableName + '.' + FAdresSevkiyat.FieldName, TableName + '.' + FMuhattapAd.FieldName, TableName + '.' + FMuhattapSoyad.FieldName, TableName + '.' + FOdemeVadesi.FieldName, TableName + '.' + FReferans.FieldName, TableName + '.' + FTeslimatSuresi.FieldName, TableName + '.' + FTeklifDurumID.FieldName, ColumnFromIDCol(vTeklifDurum.Deger.FieldName, vTeklifDurum.TableName, FTeklifDurumID.FieldName, FTeklifDurum.FieldName, TableName), TableName + '.' + FSevkTarihi.FieldName, TableName + '.' + FVadeGunSayisi.FieldName, TableName + '.' + FFaturaSevkTarihi.FieldName, TableName + '.' + FParaBirimi.FieldName, TableName + '.' + FDolarKur.FieldName, TableName + '.' + FEuroKur.FieldName, TableName + '.' + FOdemeBaslangicDonemiID.FieldName, ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FTeslimSartiID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FGonderimSekliID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FGonderimSekliDetay.FieldName, TableName + '.' + FOdemeSekliID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FAciklama.FieldName, TableName + '.' + FProformaNo.FieldName, TableName + '.' + FArayanKisiID.FieldName, TableName + '.' + FAramaTarihi.FieldName, TableName + '.' + FSonrakiAksiyonTarihi.FieldName, TableName + '.' + FAksiyonNotu.FieldName, TableName + '.' + FTevkifatKodu.FieldName, TableName + '.' + FTevkifatPay.FieldName, TableName + '.' + FTevkifatPayda.FieldName, TableName + '.' + FIhracKayitKodu.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FSiparisID.FieldName).DisplayLabel := 'Sipariş ID'; Self.DataSource.DataSet.FindField(FIrsaliyeID.FieldName).DisplayLabel := 'İrsaliye ID'; Self.DataSource.DataSet.FindField(FFaturaID.FieldName).DisplayLabel := 'Fatura ID'; Self.DataSource.DataSet.FindField(FIsSiparislesti.FieldName).DisplayLabel := 'Siparişleşti?'; Self.DataSource.DataSet.FindField(FIsTaslak.FieldName).DisplayLabel := 'Taslak?'; Self.DataSource.DataSet.FindField(FIsEFatura.FieldName).DisplayLabel := 'E-Fatura?'; Self.DataSource.DataSet.FindField(FTutar.FieldName).DisplayLabel := 'Tutar'; Self.DataSource.DataSet.FindField(FIskontoTutar.FieldName).DisplayLabel := 'İskonto Tutar'; Self.DataSource.DataSet.FindField(FAraToplam.FieldName).DisplayLabel := 'Ara Toplam'; Self.DataSource.DataSet.FindField(FGenelIskontoTutar.FieldName).DisplayLabel := 'Genel İskonto Tutar'; Self.DataSource.DataSet.FindField(FKDVTutar.FieldName).DisplayLabel := 'KDV Tutar'; Self.DataSource.DataSet.FindField(FGenelToplam.FieldName).DisplayLabel := 'Genel Toplam'; Self.DataSource.DataSet.FindField(FIslemTipiID.FieldName).DisplayLabel := 'İşlem Tipi ID'; Self.DataSource.DataSet.FindField(FIslemTipi.FieldName).DisplayLabel := 'İşlem Tipi'; Self.DataSource.DataSet.FindField(FTeklifNo.FieldName).DisplayLabel := 'Teklif No'; Self.DataSource.DataSet.FindField(FTeklifTarihi.FieldName).DisplayLabel := 'Teklif Tarihi'; Self.DataSource.DataSet.FindField(FTeslimTarihi.FieldName).DisplayLabel := 'Teslim Tarihi'; Self.DataSource.DataSet.FindField(FGecerlilikTarihi.FieldName).DisplayLabel := 'Geçerlilik Tarihi'; Self.DataSource.DataSet.FindField(FMusteriKodu.FieldName).DisplayLabel := 'Müşteri Kodu'; Self.DataSource.DataSet.FindField(FMusteriAdi.FieldName).DisplayLabel := 'Müşteri Adı'; Self.DataSource.DataSet.FindField(FAdresMusteriID.FieldName).DisplayLabel := 'Adres Müşteri ID'; Self.DataSource.DataSet.FindField(FAdresMusteri.FieldName).DisplayLabel := 'Adres Müşteri'; Self.DataSource.DataSet.FindField(FPostaKodu.FieldName).DisplayLabel := 'Posta Kodu'; Self.DataSource.DataSet.FindField(FVergiDairesi.FieldName).DisplayLabel := 'Vergi Dairesi'; Self.DataSource.DataSet.FindField(FVergiNo.FieldName).DisplayLabel := 'Vergi No'; Self.DataSource.DataSet.FindField(FMusteriTemsilcisiID.FieldName).DisplayLabel := 'Müşteri Temsilci ID'; Self.DataSource.DataSet.FindField(FMusteriTemsilcisi.FieldName).DisplayLabel := 'Müşteri Temsilci'; Self.DataSource.DataSet.FindField(FTeklifTipiID.FieldName).DisplayLabel := 'Teklif Tipi ID'; Self.DataSource.DataSet.FindField(FTeklifTipi.FieldName).DisplayLabel := 'Teklif Tipi'; Self.DataSource.DataSet.FindField(FAdresSevkiyatID.FieldName).DisplayLabel := 'Adres Sevkiyat ID'; Self.DataSource.DataSet.FindField(FAdresSevkiyat.FieldName).DisplayLabel := 'Adres Sevkiyat'; Self.DataSource.DataSet.FindField(FMuhattapAd.FieldName).DisplayLabel := 'Muhattap Ad'; Self.DataSource.DataSet.FindField(FMuhattapSoyad.FieldName).DisplayLabel := 'Muhattap Soyad'; Self.DataSource.DataSet.FindField(FOdemeVadesi.FieldName).DisplayLabel := 'Ödeme Vadesi'; Self.DataSource.DataSet.FindField(FReferans.FieldName).DisplayLabel := 'Referans'; Self.DataSource.DataSet.FindField(FTeslimatSuresi.FieldName).DisplayLabel := 'Teslimat Süresi'; Self.DataSource.DataSet.FindField(FTeklifDurumID.FieldName).DisplayLabel := 'Teklif Durum ID'; Self.DataSource.DataSet.FindField(FTeklifDurum.FieldName).DisplayLabel := 'Teklif Durum'; Self.DataSource.DataSet.FindField(FSevkTarihi.FieldName).DisplayLabel := 'Sevk Tarihi'; Self.DataSource.DataSet.FindField(FVadeGunSayisi.FieldName).DisplayLabel := 'Vade Gün Sayısı'; Self.DataSource.DataSet.FindField(FFaturaSevkTarihi.FieldName).DisplayLabel := 'Fatura Sevk Tarihi'; Self.DataSource.DataSet.FindField(FParaBirimi.FieldName).DisplayLabel := 'Para Birimi'; Self.DataSource.DataSet.FindField(FDolarKur.FieldName).DisplayLabel := 'Dolar Kuru'; Self.DataSource.DataSet.FindField(FEuroKur.FieldName).DisplayLabel := 'Euro Kuru'; Self.DataSource.DataSet.FindField(FOdemeBaslangicDonemiID.FieldName).DisplayLabel := 'Ödeme Başlangıç Dönemi ID'; Self.DataSource.DataSet.FindField(FOdemeBaslangicDonemi.FieldName).DisplayLabel := 'Ödeme Başlangıç Dönemi'; Self.DataSource.DataSet.FindField(FTeslimSartiID.FieldName).DisplayLabel := 'Teslim Şartı ID'; // Self.DataSource.DataSet.FindField(FTeslimSarti.FieldName).DisplayLabel := 'Teslim Şartı'; Self.DataSource.DataSet.FindField(FGonderimSekliID.FieldName).DisplayLabel := 'Gönderim Şekli ID'; // Self.DataSource.DataSet.FindField(FGonderimSekli.FieldName).DisplayLabel := 'Gönderim Şekli'; Self.DataSource.DataSet.FindField(GonderimSekliDetay.FieldName).DisplayLabel := 'Gönderim Şekli Detay'; Self.DataSource.DataSet.FindField(FOdemeSekliID.FieldName).DisplayLabel := 'Ödeme Şekli ID'; // Self.DataSource.DataSet.FindField(FOdemeSekli.FieldName).DisplayLabel := 'Ödeme Şekli'; Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama'; Self.DataSource.DataSet.FindField(FProformaNo.FieldName).DisplayLabel := 'Proforma No'; Self.DataSource.DataSet.FindField(FArayanKisiID.FieldName).DisplayLabel := 'Arayan Kişi ID'; Self.DataSource.DataSet.FindField(FArayanKisi.FieldName).DisplayLabel := 'Arayan Kişi'; Self.DataSource.DataSet.FindField(FAramaTarihi.FieldName).DisplayLabel := 'Arama Tarihi'; Self.DataSource.DataSet.FindField(FSonrakiAksiyonTarihi.FieldName).DisplayLabel := 'Sonraki Aksiyon Tarihi'; Self.DataSource.DataSet.FindField(FAksiyonNotu.FieldName).DisplayLabel := 'Aksiyon Notu'; Self.DataSource.DataSet.FindField(FTevkifatKodu.FieldName).DisplayLabel := 'Tevkifat Kodu'; Self.DataSource.DataSet.FindField(FTevkifatPay.FieldName).DisplayLabel := 'Tevkifat Pay'; Self.DataSource.DataSet.FindField(FTevkifatPayda.FieldName).DisplayLabel := 'Tevkifat Payda'; Self.DataSource.DataSet.FindField(FIhracKayitKodu.FieldName).DisplayLabel := 'İhraç Kayıt Kodu'; finally vMusteriTemsilcisi.Free; vIslemTipi.Free; vTeklifTipi.Free; vTeklifDurum.Free; vOdemeBaslangicDonemi.Free; end; end; end; end; procedure TSatisTeklif.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin vMusteriTemsilcisi := TPersonelKarti.Create(Database); vIslemTipi := TAyarEFaturaFaturaTipi.Create(Database); vTeklifTipi := TAyarTeklifTipi.Create(Database); vTeklifDurum := TAyarTeklifDurum.Create(Database); vOdemeBaslangicDonemi := TAyarOdemeBaslangicDonemi.Create(Database); try Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FSiparisID.FieldName, TableName + '.' + FIrsaliyeID.FieldName, TableName + '.' + FFaturaID.FieldName, TableName + '.' + FIsSiparislesti.FieldName, TableName + '.' + FIsTaslak.FieldName, TableName + '.' + FIsEFatura.FieldName, TableName + '.' + FTutar.FieldName, TableName + '.' + FIskontoTutar.FieldName, TableName + '.' + FAraToplam.FieldName, TableName + '.' + FGenelIskontoTutar.FieldName, TableName + '.' + FKDVTutar.FieldName, TableName + '.' + FGenelToplam.FieldName, TableName + '.' + FIslemTipiID.FieldName, ColumnFromIDCol(vIslemTipi.Tip.FieldName, vIslemTipi.TableName, FIslemTipiID.FieldName, FIslemTipi.FieldName, TableName), TableName + '.' + FTeklifNo.FieldName, TableName + '.' + FTeklifTarihi.FieldName, TableName + '.' + FTeslimTarihi.FieldName, TableName + '.' + FGecerlilikTarihi.FieldName, TableName + '.' + FMusteriKodu.FieldName, TableName + '.' + FMusteriAdi.FieldName, TableName + '.' + FAdresMusteriID.FieldName, TableName + '.' + FAdresMusteri.FieldName, TableName + '.' + FPostaKodu.FieldName, TableName + '.' + FVergiDairesi.FieldName, TableName + '.' + FVergiNo.FieldName, TableName + '.' + FMusteriTemsilcisiID.FieldName, TableName + '.' + FTeklifTipiID.FieldName, ColumnFromIDCol(vTeklifTipi.Deger.FieldName, vTeklifTipi.TableName, FTeklifTipiID.FieldName, FTeklifTipi.FieldName, TableName), TableName + '.' + FAdresSevkiyatID.FieldName, TableName + '.' + FAdresSevkiyat.FieldName, TableName + '.' + FMuhattapAd.FieldName, TableName + '.' + FMuhattapSoyad.FieldName, TableName + '.' + FOdemeVadesi.FieldName, TableName + '.' + FReferans.FieldName, TableName + '.' + FTeslimatSuresi.FieldName, TableName + '.' + FTeklifDurumID.FieldName, ColumnFromIDCol(vTeklifDurum.Deger.FieldName, vTeklifDurum.TableName, FTeklifDurumID.FieldName, FTeklifDurum.FieldName, TableName), TableName + '.' + FSevkTarihi.FieldName, TableName + '.' + FVadeGunSayisi.FieldName, TableName + '.' + FFaturaSevkTarihi.FieldName, TableName + '.' + FParaBirimi.FieldName, TableName + '.' + FDolarKur.FieldName, TableName + '.' + FEuroKur.FieldName, TableName + '.' + FOdemeBaslangicDonemiID.FieldName, ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FTeslimSartiID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FGonderimSekliID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FGonderimSekliDetay.FieldName, TableName + '.' + FOdemeSekliID.FieldName, // ColumnFromIDCol(vOdemeBaslangicDonemi.Deger.FieldName, vOdemeBaslangicDonemi.TableName, FOdemeBaslangicDonemiID.FieldName, FOdemeBaslangicDonemi.FieldName, TableName), TableName + '.' + FAciklama.FieldName, TableName + '.' + FProformaNo.FieldName, TableName + '.' + FArayanKisiID.FieldName, TableName + '.' + FAramaTarihi.FieldName, TableName + '.' + FSonrakiAksiyonTarihi.FieldName, TableName + '.' + FAksiyonNotu.FieldName, TableName + '.' + FTevkifatKodu.FieldName, TableName + '.' + FTevkifatPay.FieldName, TableName + '.' + FTevkifatPayda.FieldName, TableName + '.' + FIhracKayitKodu.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FSiparisID.Value := FormatedVariantVal(FieldByName(FSiparisID.FieldName).DataType, FieldByName(FSiparisID.FieldName).Value); FIrsaliyeID.Value := FormatedVariantVal(FieldByName(FIrsaliyeID.FieldName).DataType, FieldByName(FIrsaliyeID.FieldName).Value); FFaturaID.Value := FormatedVariantVal(FieldByName(FFaturaID.FieldName).DataType, FieldByName(FFaturaID.FieldName).Value); FIsSiparislesti.Value := FormatedVariantVal(FieldByName(FIsSiparislesti.FieldName).DataType, FieldByName(FIsSiparislesti.FieldName).Value); FIsTaslak.Value := FormatedVariantVal(FieldByName(FIsTaslak.FieldName).DataType, FieldByName(FIsTaslak.FieldName).Value); FIsEFatura.Value := FormatedVariantVal(FieldByName(FIsEFatura.FieldName).DataType, FieldByName(FIsEFatura.FieldName).Value); FTutar.Value := FormatedVariantVal(FieldByName(FTutar.FieldName).DataType, FieldByName(FTutar.FieldName).Value); FIskontoTutar.Value := FormatedVariantVal(FieldByName(FIskontoTutar.FieldName).DataType, FieldByName(FIskontoTutar.FieldName).Value); FAraToplam.Value := FormatedVariantVal(FieldByName(FAraToplam.FieldName).DataType, FieldByName(FAraToplam.FieldName).Value); FGenelIskontoTutar.Value := FormatedVariantVal(FieldByName(FGenelIskontoTutar.FieldName).DataType, FieldByName(FGenelIskontoTutar.FieldName).Value); FKDVTutar.Value := FormatedVariantVal(FieldByName(FKDVTutar.FieldName).DataType, FieldByName(FKDVTutar.FieldName).Value); FGenelToplam.Value := FormatedVariantVal(FieldByName(FGenelToplam.FieldName).DataType, FieldByName(FGenelToplam.FieldName).Value); FIslemTipiID.Value := FormatedVariantVal(FieldByName(FIslemTipiID.FieldName).DataType, FieldByName(FIslemTipiID.FieldName).Value); FIslemTipi.Value := FormatedVariantVal(FieldByName(FIslemTipi.FieldName).DataType, FieldByName(FIslemTipi.FieldName).Value); FTeklifNo.Value := FormatedVariantVal(FieldByName(FTeklifNo.FieldName).DataType, FieldByName(FTeklifNo.FieldName).Value); FTeklifTarihi.Value := FormatedVariantVal(FieldByName(FTeklifTarihi.FieldName).DataType, FieldByName(FTeklifTarihi.FieldName).Value); FTeslimTarihi.Value := FormatedVariantVal(FieldByName(FTeslimTarihi.FieldName).DataType, FieldByName(FTeslimTarihi.FieldName).Value); FGecerlilikTarihi.Value := FormatedVariantVal(FieldByName(FGecerlilikTarihi.FieldName).DataType, FieldByName(FGecerlilikTarihi.FieldName).Value); FMusteriKodu.Value := FormatedVariantVal(FieldByName(FMusteriKodu.FieldName).DataType, FieldByName(FMusteriKodu.FieldName).Value); FMusteriAdi.Value := FormatedVariantVal(FieldByName(FMusteriAdi.FieldName).DataType, FieldByName(FMusteriAdi.FieldName).Value); FAdresMusteriID.Value := FormatedVariantVal(FieldByName(FAdresMusteriID.FieldName).DataType, FieldByName(FAdresMusteriID.FieldName).Value); FAdresMusteri.Value := FormatedVariantVal(FieldByName(FAdresMusteri.FieldName).DataType, FieldByName(FAdresMusteri.FieldName).Value); FPostaKodu.Value := FormatedVariantVal(FieldByName(FPostaKodu.FieldName).DataType, FieldByName(FPostaKodu.FieldName).Value); FVergiDairesi.Value := FormatedVariantVal(FieldByName(FVergiDairesi.FieldName).DataType, FieldByName(FVergiDairesi.FieldName).Value); FVergiNo.Value := FormatedVariantVal(FieldByName(FVergiNo.FieldName).DataType, FieldByName(FVergiNo.FieldName).Value); FMusteriTemsilcisiID.Value := FormatedVariantVal(FieldByName(FMusteriTemsilcisiID.FieldName).DataType, FieldByName(FMusteriTemsilcisiID.FieldName).Value); FMusteriTemsilcisi.Value := FormatedVariantVal(FieldByName(FMusteriTemsilcisi.FieldName).DataType, FieldByName(FMusteriTemsilcisi.FieldName).Value); FTeklifTipiID.Value := FormatedVariantVal(FieldByName(FTeklifTipiID.FieldName).DataType, FieldByName(FTeklifTipiID.FieldName).Value); FTeklifTipi.Value := FormatedVariantVal(FieldByName(FTeklifTipi.FieldName).DataType, FieldByName(FTeklifTipi.FieldName).Value); FAdresSevkiyatID.Value := FormatedVariantVal(FieldByName(FAdresSevkiyatID.FieldName).DataType, FieldByName(FAdresSevkiyatID.FieldName).Value); FAdresSevkiyat.Value := FormatedVariantVal(FieldByName(FAdresSevkiyat.FieldName).DataType, FieldByName(FAdresSevkiyat.FieldName).Value); FMuhattapAd.Value := FormatedVariantVal(FieldByName(FMuhattapAd.FieldName).DataType, FieldByName(FMuhattapAd.FieldName).Value); FMuhattapSoyad.Value := FormatedVariantVal(FieldByName(FMuhattapSoyad.FieldName).DataType, FieldByName(FMuhattapSoyad.FieldName).Value); FOdemeVadesi.Value := FormatedVariantVal(FieldByName(FOdemeVadesi.FieldName).DataType, FieldByName(FOdemeVadesi.FieldName).Value); FReferans.Value := FormatedVariantVal(FieldByName(FReferans.FieldName).DataType, FieldByName(FReferans.FieldName).Value); FTeslimatSuresi.Value := FormatedVariantVal(FieldByName(FTeslimatSuresi.FieldName).DataType, FieldByName(FTeslimatSuresi.FieldName).Value); FTeklifDurumID.Value := FormatedVariantVal(FieldByName(FTeklifDurumID.FieldName).DataType, FieldByName(FTeklifDurumID.FieldName).Value); FTeklifDurum.Value := FormatedVariantVal(FieldByName(FTeklifDurum.FieldName).DataType, FieldByName(FTeklifDurum.FieldName).Value); FSevkTarihi.Value := FormatedVariantVal(FieldByName(FSevkTarihi.FieldName).DataType, FieldByName(FSevkTarihi.FieldName).Value); FVadeGunSayisi.Value := FormatedVariantVal(FieldByName(FVadeGunSayisi.FieldName).DataType, FieldByName(FVadeGunSayisi.FieldName).Value); FFaturaSevkTarihi.Value := FormatedVariantVal(FieldByName(FFaturaSevkTarihi.FieldName).DataType, FieldByName(FFaturaSevkTarihi.FieldName).Value); FParaBirimi.Value := FormatedVariantVal(FieldByName(FParaBirimi.FieldName).DataType, FieldByName(FParaBirimi.FieldName).Value); FDolarKur.Value := FormatedVariantVal(FieldByName(FDolarKur.FieldName).DataType, FieldByName(FDolarKur.FieldName).Value); FEuroKur.Value := FormatedVariantVal(FieldByName(FEuroKur.FieldName).DataType, FieldByName(FEuroKur.FieldName).Value); FOdemeBaslangicDonemiID.Value := FormatedVariantVal(FieldByName(FOdemeBaslangicDonemiID.FieldName).DataType, FieldByName(FOdemeBaslangicDonemiID.FieldName).Value); FOdemeBaslangicDonemi.Value := FormatedVariantVal(FieldByName(FOdemeBaslangicDonemi.FieldName).DataType, FieldByName(FOdemeBaslangicDonemi.FieldName).Value); FTeslimSartiID.Value := FormatedVariantVal(FieldByName(FTeslimSartiID.FieldName).DataType, FieldByName(FTeslimSartiID.FieldName).Value); // FTeslimSarti.Value := FormatedVariantVal(FieldByName(FTeslimSarti.FieldName).DataType, FieldByName(FTeslimSarti.FieldName).Value); FGonderimSekliID.Value := FormatedVariantVal(FieldByName(FGonderimSekliID.FieldName).DataType, FieldByName(FGonderimSekliID.FieldName).Value); // FGonderimSekli.Value := FormatedVariantVal(FieldByName(FGonderimSekli.FieldName).DataType, FieldByName(FGonderimSekli.FieldName).Value); FGonderimSekliDetay.Value := FormatedVariantVal(FieldByName(FGonderimSekliDetay.FieldName).DataType, FieldByName(FGonderimSekliDetay.FieldName).Value); FOdemeSekliID.Value := FormatedVariantVal(FieldByName(FOdemeSekliID.FieldName).DataType, FieldByName(FOdemeSekliID.FieldName).Value); // FOdemeSekli.Value := FormatedVariantVal(FieldByName(FOdemeSekli.FieldName).DataType, FieldByName(FOdemeSekli.FieldName).Value); FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value); FProformaNo.Value := FormatedVariantVal(FieldByName(FProformaNo.FieldName).DataType, FieldByName(FProformaNo.FieldName).Value); FArayanKisiID.Value := FormatedVariantVal(FieldByName(FArayanKisiID.FieldName).DataType, FieldByName(FArayanKisiID.FieldName).Value); FArayanKisi.Value := FormatedVariantVal(FieldByName(FArayanKisi.FieldName).DataType, FieldByName(FArayanKisi.FieldName).Value); FAramaTarihi.Value := FormatedVariantVal(FieldByName(FAramaTarihi.FieldName).DataType, FieldByName(FAramaTarihi.FieldName).Value); FSonrakiAksiyonTarihi.Value := FormatedVariantVal(FieldByName(FSonrakiAksiyonTarihi.FieldName).DataType, FieldByName(FSonrakiAksiyonTarihi.FieldName).Value); FAksiyonNotu.Value := FormatedVariantVal(FieldByName(FAksiyonNotu.FieldName).DataType, FieldByName(FAksiyonNotu.FieldName).Value); FTevkifatKodu.Value := FormatedVariantVal(FieldByName(FTevkifatKodu.FieldName).DataType, FieldByName(FTevkifatKodu.FieldName).Value); FTevkifatPay.Value := FormatedVariantVal(FieldByName(FTevkifatPay.FieldName).DataType, FieldByName(FTevkifatPay.FieldName).Value); FTevkifatPayda.Value := FormatedVariantVal(FieldByName(FTevkifatPayda.FieldName).DataType, FieldByName(FTevkifatPayda.FieldName).Value); FIhracKayitKodu.Value := FormatedVariantVal(FieldByName(FIhracKayitKodu.FieldName).DataType, FieldByName(FIhracKayitKodu.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; finally vMusteriTemsilcisi.Free; vIslemTipi.Free; vTeklifTipi.Free; vTeklifDurum.Free; vOdemeBaslangicDonemi.Free; end; end; end; end; procedure TSatisTeklif.SortDetaylar; begin // end; function TSatisTeklif.ToProforma: TTable; begin Result := nil; end; function TSatisTeklif.ToSiparis: TTable; begin Result := nil; end; procedure TSatisTeklif.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FSiparisID.FieldName, FIrsaliyeID.FieldName, FFaturaID.FieldName, FIsSiparislesti.FieldName, FIsTaslak.FieldName, FIsEFatura.FieldName, FTutar.FieldName, FIskontoTutar.FieldName, FAraToplam.FieldName, FGenelIskontoTutar.FieldName, FKDVTutar.FieldName, FGenelToplam.FieldName, FIslemTipiID.FieldName, FTeklifNo.FieldName, FTeklifTarihi.FieldName, FTeslimTarihi.FieldName, FGecerlilikTarihi.FieldName, FMusteriKodu.FieldName, FMusteriAdi.FieldName, FAdresMusteriID.FieldName, FAdresMusteri.FieldName, FPostaKodu.FieldName, FVergiDairesi.FieldName, FVergiNo.FieldName, FMusteriTemsilcisiID.FieldName, FTeklifTipiID.FieldName, FAdresSevkiyatID.FieldName, FAdresSevkiyat.FieldName, FMuhattapAd.FieldName, FMuhattapSoyad.FieldName, FOdemeVadesi.FieldName, FReferans.FieldName, FTeslimatSuresi.FieldName, FTeklifDurumID.FieldName, FSevkTarihi.FieldName, FVadeGunSayisi.FieldName, FFaturaSevkTarihi.FieldName, FParaBirimi.FieldName, FDolarKur.FieldName, FEuroKur.FieldName, FOdemeBaslangicDonemiID.FieldName, FTeslimSartiID.FieldName, FGonderimSekliID.FieldName, FGonderimSekliDetay.FieldName, FOdemeSekliID.FieldName, FAciklama.FieldName, FProformaNo.FieldName, FArayanKisiID.FieldName, FAramaTarihi.FieldName, FSonrakiAksiyonTarihi.FieldName, FAksiyonNotu.FieldName, FTevkifatKodu.FieldName, FTevkifatPay.FieldName, FTevkifatPayda.FieldName, FIhracKayitKodu.FieldName ]); NewParamForQuery(QueryOfInsert, FSiparisID); NewParamForQuery(QueryOfInsert, FIrsaliyeID); NewParamForQuery(QueryOfInsert, FFaturaID); NewParamForQuery(QueryOfInsert, FIsSiparislesti); NewParamForQuery(QueryOfInsert, FIsTaslak); NewParamForQuery(QueryOfInsert, FIsEFatura); NewParamForQuery(QueryOfInsert, FTutar); NewParamForQuery(QueryOfInsert, FIskontoTutar); NewParamForQuery(QueryOfInsert, FAraToplam); NewParamForQuery(QueryOfInsert, FGenelIskontoTutar); NewParamForQuery(QueryOfInsert, FKDVTutar); NewParamForQuery(QueryOfInsert, FGenelToplam); NewParamForQuery(QueryOfInsert, FIslemTipiID); NewParamForQuery(QueryOfInsert, FTeklifNo); NewParamForQuery(QueryOfInsert, FTeklifTarihi); NewParamForQuery(QueryOfInsert, FTeslimTarihi); NewParamForQuery(QueryOfInsert, FGecerlilikTarihi); NewParamForQuery(QueryOfInsert, FMusteriKodu); NewParamForQuery(QueryOfInsert, FMusteriAdi); NewParamForQuery(QueryOfInsert, FAdresMusteriID); NewParamForQuery(QueryOfInsert, FAdresMusteri); NewParamForQuery(QueryOfInsert, FPostaKodu); NewParamForQuery(QueryOfInsert, FVergiDairesi); NewParamForQuery(QueryOfInsert, FVergiNo); NewParamForQuery(QueryOfInsert, FMusteriTemsilcisiID); NewParamForQuery(QueryOfInsert, FTeklifTipiID); NewParamForQuery(QueryOfInsert, FAdresSevkiyatID); NewParamForQuery(QueryOfInsert, FAdresSevkiyat); NewParamForQuery(QueryOfInsert, FMuhattapAd); NewParamForQuery(QueryOfInsert, FMuhattapSoyad); NewParamForQuery(QueryOfInsert, FOdemeVadesi); NewParamForQuery(QueryOfInsert, FReferans); NewParamForQuery(QueryOfInsert, FTeslimatSuresi); NewParamForQuery(QueryOfInsert, FTeklifDurumID); NewParamForQuery(QueryOfInsert, FSevkTarihi); NewParamForQuery(QueryOfInsert, FVadeGunSayisi); NewParamForQuery(QueryOfInsert, FFaturaSevkTarihi); NewParamForQuery(QueryOfInsert, FParaBirimi); NewParamForQuery(QueryOfInsert, FDolarKur); NewParamForQuery(QueryOfInsert, FEuroKur); NewParamForQuery(QueryOfInsert, FOdemeBaslangicDonemiID); NewParamForQuery(QueryOfInsert, FTeslimSartiID); NewParamForQuery(QueryOfInsert, FGonderimSekliID); NewParamForQuery(QueryOfInsert, FGonderimSekliDetay); NewParamForQuery(QueryOfInsert, FOdemeSekliID); NewParamForQuery(QueryOfInsert, FAciklama); NewParamForQuery(QueryOfInsert, FProformaNo); NewParamForQuery(QueryOfInsert, FArayanKisiID); NewParamForQuery(QueryOfInsert, FAramaTarihi); NewParamForQuery(QueryOfInsert, FSonrakiAksiyonTarihi); NewParamForQuery(QueryOfInsert, FAksiyonNotu); NewParamForQuery(QueryOfInsert, FTevkifatKodu); NewParamForQuery(QueryOfInsert, FTevkifatPay); NewParamForQuery(QueryOfInsert, FTevkifatPayda); NewParamForQuery(QueryOfInsert, FIhracKayitKodu); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSatisTeklif.RefreshHeader; var n1: Integer; // vTutarOndalik: Integer; vOndalikliHane: TAyarHaneSayisi; // vAgirlikliOpsiyon, vNetTutar: Double; begin vOndalikliHane := TAyarHaneSayisi.Create(Self.Database); try Self.SortDetaylar; vOndalikliHane.SelectToList('', False, False); // vTutarOndalik := vOndalikliHane.SatisTutar.Value; // Self.ToplamTutar := 0; // Self.ToplamIskontoTutar := 0; // Self.ToplamGenelIskontoTutar := 0; // Self.ToplamKDVTutar := 0; // Self.GenelToplam := 0; // // Self.OrtalamaOpsiyon := 0; // vAgirlikliOpsiyon := 0; // for n1 := 0 to Self.ListDetay.Count-1 do begin // vNetTutar := TGenel.RoundToX( (TTeklifDetay(self.ListDetay[nIndex]).NetFiyat * TTeklifDetay(self.ListDetay[nIndex]).Miktar), (-1)* tutar_ondalik); // // self.ToplamTutar := self.ToplamTutar + TTeklifDetay(self.ListDetay[nIndex]).Tutar; // self.ToplamIskontoTutar := self.ToplamIskontoTutar + TTeklifDetay(self.ListDetay[nIndex]).Tutar - netTutar; // self.ToplamKDVTutar := self.ToplamKDVTutar + TTeklifDetay(self.ListDetay[nIndex]).KDVTutar; // self.GenelToplam := self.GenelToplam + TTeklifDetay(self.ListDetay[nIndex]).ToplamTutar; // // dAgirlikliOpsiyon := dAgirlikliOpsiyon + (TTeklifDetay(self.ListDetay[nIndex]).Opsiyon * (TTeklifDetay(self.ListDetay[nIndex]).Tutar - TTeklifDetay(self.ListDetay[nIndex]).IskontoTutar + TTeklifDetay(self.ListDetay[nIndex]).KDVTutar)); end; // // //son 2 haneyi (ondalikli_hane.SatimTutar) dikkate alacak şekilde yuvarla sonucu, veri tabanında bu şekilde tutmaya çalışıyoruz // self.ToplamTutar := TGenel.RoundToX(self.ToplamTutar, -1*(tutar_ondalik)); // self.ToplamIskontoTutar := TGenel.RoundToX(self.ToplamIskontoTutar, -1*(tutar_ondalik)); // self.ToplamGenelIskontoTutar := TGenel.RoundToX(self.ToplamGenelIskontoTutar, -1*(tutar_ondalik)); // self.ToplamKDVTutar := TGenel.RoundToX(self.ToplamKDVTutar, -1*(tutar_ondalik)); // self.GenelToplam := TGenel.RoundToX(self.GenelToplam, -1*(tutar_ondalik)); // // // // Added by FERHAT 25.12.2015 17:40:00 // //oran varsa oran hesabını yaparak kulan. Oran yoksa ve tutar varsa tutara göre hesapla. // //fatura altı iskonto tutar için eklendi // if (not Self.CheckFarkliKDV) and (not Self.IsAlim) then // begin // if Self.GenelIskontoOrani <> 0 then // begin // //alt iskonto oranına göre tutarı hesapla // Self.ToplamGenelIskontoTutar := (Self.ToplamTutar - Self.ToplamIskontoTutar) * (Self.GenelIskontoOrani / 100); // self.ToplamGenelIskontoTutar := TGenel.RoundToX(self.ToplamGenelIskontoTutar, -1*(tutar_ondalik)); // end // else // if Self.GenelIskontoTutar <> 0 then // begin // //alt iskonto oran yerine direkt tutar bilgisini al // Self.ToplamGenelIskontoTutar := Self.GenelIskontoTutar; // self.ToplamGenelIskontoTutar := TGenel.RoundToX(self.ToplamGenelIskontoTutar, -1*(tutar_ondalik)); // end; // // // if (Self.GenelIskontoOrani <> 0) // or (Self.GenelIskontoTutar <> 0) then // begin // //alt iskonto tutar düşerek kdv yi hesapla // if Self.ListDetay.Count > 0 then // Self.ToplamKDVTutar := (self.ToplamTutar - self.ToplamIskontoTutar - Self.ToplamGenelIskontoTutar) * (TTeklifDetay(Self.ListDetay[0]).Kdv / 100) // else // Self.ToplamKDVTutar := (self.ToplamTutar - self.ToplamIskontoTutar - Self.ToplamGenelIskontoTutar) * (0); // self.ToplamKDVTutar := TGenel.RoundToX(self.ToplamKDVTutar, -1*(tutar_ondalik)); // // //hesaplanan kdv ile genel toplamı hesapla // self.GenelToplam := (self.ToplamTutar - self.ToplamIskontoTutar - Self.ToplamGenelIskontoTutar) + Self.ToplamKDVTutar; // self.GenelToplam := TGenel.RoundToX(self.GenelToplam, -1*(tutar_ondalik)); // end; // end // else // begin // Self.GenelIskontoOrani := 0; // Self.GenelIskontoTutar := 0; // Self.ToplamGenelIskontoTutar := 0; // end; // // // if (self.GenelToplam > 0) then // begin // self.OrtalamaOpsiyon := Round(dAgirlikliOpsiyon / self.GenelToplam); // end; finally vOndalikliHane.Free; end; end; procedure TSatisTeklif.RefreshHeaderPublic; begin // end; procedure TSatisTeklif.RemoveDetay(pTable: TTable); begin if pTable.Id.Value > 0 then ListSilinenDetay.Add(pTable); ListDetay.Remove(pTable); RefreshHeader; end; procedure TSatisTeklif.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FSiparisID.FieldName, FIrsaliyeID.FieldName, FFaturaID.FieldName, FIsSiparislesti.FieldName, FIsTaslak.FieldName, FIsEFatura.FieldName, FTutar.FieldName, FIskontoTutar.FieldName, FAraToplam.FieldName, FGenelIskontoTutar.FieldName, FKDVTutar.FieldName, FGenelToplam.FieldName, FIslemTipiID.FieldName, FTeklifNo.FieldName, FTeklifTarihi.FieldName, FTeslimTarihi.FieldName, FGecerlilikTarihi.FieldName, FMusteriKodu.FieldName, FMusteriAdi.FieldName, FAdresMusteriID.FieldName, FAdresMusteri.FieldName, FPostaKodu.FieldName, FVergiDairesi.FieldName, FVergiNo.FieldName, FMusteriTemsilcisiID.FieldName, FTeklifTipiID.FieldName, FAdresSevkiyatID.FieldName, FAdresSevkiyat.FieldName, FMuhattapAd.FieldName, FMuhattapSoyad.FieldName, FOdemeVadesi.FieldName, FReferans.FieldName, FTeslimatSuresi.FieldName, FTeklifDurumID.FieldName, FSevkTarihi.FieldName, FVadeGunSayisi.FieldName, FFaturaSevkTarihi.FieldName, FParaBirimi.FieldName, FDolarKur.FieldName, FEuroKur.FieldName, FOdemeBaslangicDonemiID.FieldName, FTeslimSartiID.FieldName, FGonderimSekliID.FieldName, FGonderimSekliDetay.FieldName, FOdemeSekliID.FieldName, FAciklama.FieldName, FProformaNo.FieldName, FArayanKisiID.FieldName, FAramaTarihi.FieldName, FSonrakiAksiyonTarihi.FieldName, FAksiyonNotu.FieldName, FTevkifatKodu.FieldName, FTevkifatPay.FieldName, FTevkifatPayda.FieldName, FIhracKayitKodu.FieldName ]); NewParamForQuery(QueryOfUpdate, FSiparisID); NewParamForQuery(QueryOfUpdate, FIrsaliyeID); NewParamForQuery(QueryOfUpdate, FFaturaID); NewParamForQuery(QueryOfUpdate, FIsSiparislesti); NewParamForQuery(QueryOfUpdate, FIsTaslak); NewParamForQuery(QueryOfUpdate, FIsEFatura); NewParamForQuery(QueryOfUpdate, FTutar); NewParamForQuery(QueryOfUpdate, FIskontoTutar); NewParamForQuery(QueryOfUpdate, FAraToplam); NewParamForQuery(QueryOfUpdate, FGenelIskontoTutar); NewParamForQuery(QueryOfUpdate, FKDVTutar); NewParamForQuery(QueryOfUpdate, FGenelToplam); NewParamForQuery(QueryOfUpdate, FIslemTipiID); NewParamForQuery(QueryOfUpdate, FTeklifNo); NewParamForQuery(QueryOfUpdate, FTeklifTarihi); NewParamForQuery(QueryOfUpdate, FTeslimTarihi); NewParamForQuery(QueryOfUpdate, FGecerlilikTarihi); NewParamForQuery(QueryOfUpdate, FMusteriKodu); NewParamForQuery(QueryOfUpdate, FMusteriAdi); NewParamForQuery(QueryOfUpdate, FAdresMusteriID); NewParamForQuery(QueryOfUpdate, FAdresMusteri); NewParamForQuery(QueryOfUpdate, FPostaKodu); NewParamForQuery(QueryOfUpdate, FVergiDairesi); NewParamForQuery(QueryOfUpdate, FVergiNo); NewParamForQuery(QueryOfUpdate, FMusteriTemsilcisiID); NewParamForQuery(QueryOfUpdate, FTeklifTipiID); NewParamForQuery(QueryOfUpdate, FAdresSevkiyatID); NewParamForQuery(QueryOfUpdate, FAdresSevkiyat); NewParamForQuery(QueryOfUpdate, FMuhattapAd); NewParamForQuery(QueryOfUpdate, FMuhattapSoyad); NewParamForQuery(QueryOfUpdate, FOdemeVadesi); NewParamForQuery(QueryOfUpdate, FReferans); NewParamForQuery(QueryOfUpdate, FTeslimatSuresi); NewParamForQuery(QueryOfUpdate, FTeklifDurumID); NewParamForQuery(QueryOfUpdate, FSevkTarihi); NewParamForQuery(QueryOfUpdate, FVadeGunSayisi); NewParamForQuery(QueryOfUpdate, FFaturaSevkTarihi); NewParamForQuery(QueryOfUpdate, FParaBirimi); NewParamForQuery(QueryOfUpdate, FDolarKur); NewParamForQuery(QueryOfUpdate, FEuroKur); NewParamForQuery(QueryOfUpdate, FOdemeBaslangicDonemiID); NewParamForQuery(QueryOfUpdate, FTeslimSartiID); NewParamForQuery(QueryOfUpdate, FGonderimSekliID); NewParamForQuery(QueryOfUpdate, FGonderimSekliDetay); NewParamForQuery(QueryOfUpdate, FOdemeSekliID); NewParamForQuery(QueryOfUpdate, FAciklama); NewParamForQuery(QueryOfUpdate, FProformaNo); NewParamForQuery(QueryOfUpdate, FArayanKisiID); NewParamForQuery(QueryOfUpdate, FAramaTarihi); NewParamForQuery(QueryOfUpdate, FSonrakiAksiyonTarihi); NewParamForQuery(QueryOfUpdate, FAksiyonNotu); NewParamForQuery(QueryOfUpdate, FTevkifatKodu); NewParamForQuery(QueryOfUpdate, FTevkifatPay); NewParamForQuery(QueryOfUpdate, FTevkifatPayda); NewParamForQuery(QueryOfUpdate, FIhracKayitKodu); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; procedure TSatisTeklif.AddDetay(pTable: TTable); begin Self.ListDetay.Add(pTable); end; procedure TSatisTeklif.AnaUrunOzetFiyatlandir; begin // end; procedure TSatisTeklif.BusinessDelete(pPermissionControl: Boolean); begin inherited; // end; procedure TSatisTeklif.BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); var n1, vID: Integer; begin Self.Insert(vID, True); for n1 := 0 to Self.ListDetay.Count-1 do begin TSatisTeklifDetay(Self.ListDetay[n1]).HeaderID.Value := vID; TSatisTeklifDetay(Self.ListDetay[n1]).Insert(vID, True); end; end; procedure TSatisTeklif.BusinessSelect(pFilter: string; pLock, pPermissionControl: Boolean); var vTeklifDetay: TSatisTeklifDetay; n1: Integer; begin FreeDetayListContent; Self.SelectToList(pFilter, pLock, pPermissionControl); vTeklifDetay := TSatisTeklifDetay.Create(Database); try vTeklifDetay.SelectToList(' AND ' + vTeklifDetay.TableName + '.' + vTeklifDetay.HeaderID.FieldName + '=' + VarToStr(Self.Id.Value), pLock, pPermissionControl); for n1 := 0 to vTeklifDetay.List.Count-1 do begin Self.ListDetay.Add(TSatisTeklifDetay(vTeklifDetay.List[n1]).Clone); end; finally vTeklifDetay.Free; end; end; procedure TSatisTeklif.BusinessUpdate(pPermissionControl: Boolean); var n1, vID: Integer; begin Self.Update(True); for n1 := 0 to Self.ListDetay.Count-1 do begin TSatisTeklifDetay(Self.ListDetay[n1]).HeaderID.Value := Self.Id.Value; if TSatisTeklifDetay(Self.ListDetay[n1]).Id.Value > 0 then begin TSatisTeklifDetay(Self.ListDetay[n1]).Update(True); end else begin TSatisTeklifDetay(Self.ListDetay[n1]).Insert(vID, True); end; end; for n1 := 0 to Self.ListSilinenDetay.Count-1 do if TSatisTeklifDetay(Self.ListSilinenDetay[n1]).Id.Value > 0 then TSatisTeklifDetay(Self.ListSilinenDetay[n1]).Delete(True); end; function TSatisTeklif.CheckFarkliKDV: Boolean; begin Result := False; end; procedure TSatisTeklif.UpdateAlisTeklifOnayi(pAlisOnayi: Boolean); begin // end; procedure TSatisTeklif.UpdateDetay(pTable: TTable); begin inherited; // end; function TSatisTeklif.ValidateDetay(pTable: TTable): Boolean; begin raise Exception.Create('DesteklenmeyenIslem'); end; function TSatisTeklif.ValidateTasiyiciDetayMiktar(pMalKodu: string; pMiktar: Double; pTasiyiciDetayID: Integer): Boolean; begin Result := False; end; function TSatisTeklif.Clone():TTable; begin Result := TSatisTeklif.Create(Database); Self.Id.Clone(TSatisTeklif(Result).Id); FSiparisID.Clone(TSatisTeklif(Result).FSiparisID); FIrsaliyeID.Clone(TSatisTeklif(Result).FIrsaliyeID); FFaturaID.Clone(TSatisTeklif(Result).FFaturaID); FIsSiparislesti.Clone(TSatisTeklif(Result).FIsSiparislesti); FIsTaslak.Clone(TSatisTeklif(Result).FIsTaslak); FIsEFatura.Clone(TSatisTeklif(Result).FIsEFatura); FTutar.Clone(TSatisTeklif(Result).FTutar); FIskontoTutar.Clone(TSatisTeklif(Result).FIskontoTutar); FAraToplam.Clone(TSatisTeklif(Result).FAraToplam); FGenelIskontoTutar.Clone(TSatisTeklif(Result).FGenelIskontoTutar); FKDVTutar.Clone(TSatisTeklif(Result).FKDVTutar); FGenelToplam.Clone(TSatisTeklif(Result).FGenelToplam); FIslemTipiID.Clone(TSatisTeklif(Result).FIslemTipiID); FIslemTipi.Clone(TSatisTeklif(Result).FIslemTipi); FTeklifNo.Clone(TSatisTeklif(Result).FTeklifNo); FTeklifTarihi.Clone(TSatisTeklif(Result).FTeklifTarihi); FTeslimTarihi.Clone(TSatisTeklif(Result).FTeslimTarihi); FGecerlilikTarihi.Clone(TSatisTeklif(Result).FGecerlilikTarihi); FMusteriKodu.Clone(TSatisTeklif(Result).FMusteriKodu); FMusteriAdi.Clone(TSatisTeklif(Result).FMusteriAdi); FAdresMusteriID.Clone(TSatisTeklif(Result).FAdresMusteriID); FAdresMusteri.Clone(TSatisTeklif(Result).FAdresMusteri); FPostaKodu.Clone(TSatisTeklif(Result).FPostaKodu); FVergiDairesi.Clone(TSatisTeklif(Result).FVergiDairesi); FVergiNo.Clone(TSatisTeklif(Result).FVergiNo); FMusteriTemsilcisiID.Clone(TSatisTeklif(Result).FMusteriTemsilcisiID); FMusteriTemsilcisi.Clone(TSatisTeklif(Result).FMusteriTemsilcisi); FTeklifTipiID.Clone(TSatisTeklif(Result).FTeklifTipiID); FTeklifTipi.Clone(TSatisTeklif(Result).FTeklifTipi); FAdresSevkiyatID.Clone(TSatisTeklif(Result).FAdresSevkiyatID); FAdresSevkiyat.Clone(TSatisTeklif(Result).FAdresSevkiyat); FMuhattapAd.Clone(TSatisTeklif(Result).FMuhattapAd); FMuhattapSoyad.Clone(TSatisTeklif(Result).FMuhattapSoyad); FOdemeVadesi.Clone(TSatisTeklif(Result).FOdemeVadesi); FReferans.Clone(TSatisTeklif(Result).FReferans); FTeslimatSuresi.Clone(TSatisTeklif(Result).FTeslimatSuresi); FTeklifDurumID.Clone(TSatisTeklif(Result).FTeklifDurumID); FTeklifDurum.Clone(TSatisTeklif(Result).FTeklifDurum); FSevkTarihi.Clone(TSatisTeklif(Result).FSevkTarihi); FVadeGunSayisi.Clone(TSatisTeklif(Result).FVadeGunSayisi); FFaturaSevkTarihi.Clone(TSatisTeklif(Result).FFaturaSevkTarihi); FParaBirimi.Clone(TSatisTeklif(Result).FParaBirimi); FDolarKur.Clone(TSatisTeklif(Result).FDolarKur); FEuroKur.Clone(TSatisTeklif(Result).FEuroKur); FOdemeBaslangicDonemiID.Clone(TSatisTeklif(Result).FOdemeBaslangicDonemiID); FOdemeBaslangicDonemi.Clone(TSatisTeklif(Result).FOdemeBaslangicDonemi); FTeslimSartiID.Clone(TSatisTeklif(Result).FTeslimSartiID); FTeslimSarti.Clone(TSatisTeklif(Result).FTeslimSarti); FGonderimSekliID.Clone(TSatisTeklif(Result).FGonderimSekliID); FGonderimSekli.Clone(TSatisTeklif(Result).FGonderimSekli); FGonderimSekliDetay.Clone(TSatisTeklif(Result).FGonderimSekliDetay); FOdemeSekliID.Clone(TSatisTeklif(Result).FOdemeSekliID); FOdemeSekli.Clone(TSatisTeklif(Result).FOdemeSekli); FAciklama.Clone(TSatisTeklif(Result).FAciklama); FProformaNo.Clone(TSatisTeklif(Result).FProformaNo); FArayanKisiID.Clone(TSatisTeklif(Result).FArayanKisiID); FArayanKisi.Clone(TSatisTeklif(Result).FArayanKisi); FAramaTarihi.Clone(TSatisTeklif(Result).FAramaTarihi); FSonrakiAksiyonTarihi.Clone(TSatisTeklif(Result).FSonrakiAksiyonTarihi); FAksiyonNotu.Clone(TSatisTeklif(Result).FAksiyonNotu); FTevkifatKodu.Clone(TSatisTeklif(Result).FTevkifatKodu); FTevkifatPay.Clone(TSatisTeklif(Result).FTevkifatPay); FTevkifatPayda.Clone(TSatisTeklif(Result).FTevkifatPayda); FIhracKayitKodu.Clone(TSatisTeklif(Result).FIhracKayitKodu); //veri tabanı alanı değil FOrtakIskonto.Clone(TSatisTeklif(Result).FOrtakIskonto); FOrtakKDV.Clone(TSatisTeklif(Result).FOrtakKDV); end; function TSatisTeklif.ContainsAnaUrun: Boolean; begin Result := False; end; end.
// Sample WebSnap Adapter that exposes information about // Web App Debugger executables. This information is available from the // registry. unit SvrInfoAdapter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, WebAdapt, WebComp, HTTPApp, SiteComp, Contnrs, AdaptReq; type TSvrInfoSortOrder = (soUnknown, soProgID, soFilePath); const SvrInfoSortOrderNames: array[TSvrInfoSortOrder] of string = ('Unsorted', 'SortProgID', 'SortFilePath'); type TSvrInfoList = class; TSvrInfoItem = class public ProgID: string; ClsID: string; FullFileName: string; FileExists: Boolean; List: TSvrInfoList; function FileName: string; function FilePath: string; procedure Clear; constructor Create(AList: TSvrInfoList); end; TSvrInfoList = class private FList: TObjectList; FSorted: Boolean; FSortOrder: TSvrInfoSortOrder; function GetItem(I: Integer): TSvrInfoItem; procedure SetSortOrder(const Value: TSvrInfoSortOrder); public constructor Create; destructor Destroy; override; function Count: Integer; function AddClassID(AClassID: TGUID): TSvrInfoItem; procedure Clear; procedure Sort; property Items[I: Integer]: TSvrInfoItem read GetItem; default; property SortOrder: TSvrInfoSortOrder read FSortOrder write SetSortOrder; end; TCustomSvrInfoAdapter = class(TDefaultFieldsAdapter, IIteratorSupport) private FList: TSvrInfoList; FIndex: Integer; function GetList: TSvrInfoList; protected { IWebAdapterEditor } function ImplCanAddFieldClass(AParent: TComponent; AClass: TClass): Boolean; override; function ImplCanAddActionClass(AParent: TComponent; AClass: TClass): Boolean; override; { IWebFormIteratorVariable } function StartIterator(var OwnerData: Pointer): Boolean; function NextIteration(var OwnerData: Pointer): Boolean; procedure EndIterator(OwnerData: Pointer); { ISiteDataFields } procedure ImplGetFieldsList(AList: TStrings); override; { ISiteActionsList } procedure ImplGetActionsList(AList: TStrings); override; { INotifyWebActivate } procedure ImplNotifyDeactivate; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CurrentItem: TSvrInfoItem; property List: TSvrInfoList read GetList; end; TSvrInfoAdapter = class(TCustomSvrInfoAdapter) end; // The following components are the default fields of the adapter. TSvrInfoField = class(TAdapterNamedDisplayField) private FAdapter: TCustomSvrInfoAdapter; protected function Adapter: TCustomSvrInfoAdapter; function Item: TSvrInfoItem; end; TSvrInfoClsIDField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoProgIDField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoFileNameField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoFilePathField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoFileExistsField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoMarkClsIDField = class(TSvrInfoField) protected function GetDefaultFieldName: string; override; end; TSvrInfoURLPathField = class(TSvrInfoField) protected function ImplGetValue: Variant; override; function GetDefaultFieldName: string; override; end; TSvrInfoAction = class(TImplementedAdapterAction, IWebSetActionName) private FActionName: string; protected function Adapter: TCustomSvrInfoAdapter; { ISiteSetActionName } procedure SetActionName(const Value: string); procedure ImplSetActionName(const Value: string); procedure ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); override; procedure ExecuteActionRequestParamStrings(const AStrings: TStrings); virtual; end; TSvrInfoItemAction = class(TSvrInfoAction) protected function Item: TSvrInfoItem; end; // The following components are the default actions of the adapter. TSvrInfoSortByProgIDAction = class(TSvrInfoAction) protected { IWebExecute } procedure ExecuteActionRequestParamStrings(const AStrings: TStrings); override; function GetDefaultActionName: string; override; end; TSvrInfoSortByFilePathAction = class(TSvrInfoAction) protected { IWebExecute } procedure ExecuteActionRequestParamStrings(const AStrings: TStrings); override; function GetDefaultActionName: string; override; end; TSvrInfoCleanMarkedAction = class(TSvrInfoItemAction) protected { IWebExecute } procedure ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); override; function GetDefaultActionName: string; override; end; TSvrInfoCleanMissingFilesAction = class(TSvrInfoItemAction) protected { IWebExecute } procedure ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); override; function GetDefaultActionName: string; override; { IWebEnabled } function ImplWebEnabled: Boolean; override; end; procedure Register; implementation uses ActiveX, ComObj, WebCat, WebCntxt, WebDisp; const sClsIDField = 'ClsID'; sProgIDField = 'ProgID'; sFileName = 'FileName'; sFilePath = 'FilePath'; sURLPath = 'URLPath'; sFileExists = 'FileExists'; sCleanMarkedAction = 'CleanMarked'; sCleanMissingFilesAction = 'CleanMissingFiles'; sSortProgIDAction = 'SortProgID'; sSortFilePathAction = 'SortFilePath'; sMarkClsID = 'MarkClsID'; sSortOrderCookie = 'SortDetails'; // Define the default fields procedure ListSvrInfoFields(AList: TStrings); begin AList.Clear; AList.AddObject(sClsIDField, TObject(TSvrInfoClsIDField)); AList.AddObject(sProgIDField, TObject(TSvrInfoProgIDField)); AList.AddObject(sFileName, TObject(TSvrInfoFileNameField)); AList.AddObject(sFilePath, TObject(TSvrInfoFilePathField)); AList.AddObject(sURLPath, TObject(TSvrInfoURLPathField)); AList.AddObject(sFileExists, TObject(TSvrInfoFileExistsField)); AList.AddObject(sMarkClsID, TObject(TSvrInfoMarkClsIDField)); end; // Define the default actions procedure ListSvrInfoActions(AList: TStrings); begin AList.Clear; AList.AddObject(sCleanMarkedAction, TObject(TSvrInfoCleanMarkedAction)); AList.AddObject(sCleanMissingFilesAction, TObject(TSvrInfoCleanMissingFilesAction)); AList.AddObject(sSortProgIDAction, TObject(TSvrInfoSortByProgIDAction)); AList.AddObject(sSortFilePathAction, TObject(TSvrInfoSortByFilePathAction)); end; // Extract information from the registry procedure GetWebAppList(List: TSvrInfoList; const RegCheck: string); var EnumGUID: IEnumGUID; Fetched: Cardinal; Guid: TGUID; Rslt: HResult; CatInfo: ICatInformation; I, BufSize: Integer; ClsIDKey: HKey; S: string; Buffer: array[0..255] of Char; begin List.Clear; Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil, CLSCTX_INPROC_SERVER, ICatInformation, CatInfo); if Succeeded(Rslt) then begin OleCheck(CatInfo.EnumClassesOfCategories(1, @CATID_WebAppServer, 0, nil, EnumGUID)); while EnumGUID.Next(1, Guid, Fetched) = S_OK do begin if RegCheck <> '' then begin S := SClsid + GuidToString(Guid) + '\'; if GetRegStringValue(S, RegCheck) <> SFlagOn then continue; end; try List.AddClassID(Guid); except // Ignore end; end; end else begin if RegOpenKey(HKEY_CLASSES_ROOT, 'CLSID', ClsIDKey) <> 0 then try I := 0; while RegEnumKey(ClsIDKey, I, Buffer, SizeOf(Buffer)) = 0 do begin S := Format('%s\Implemented Categories\%s',[Buffer, { do not localize } GUIDToString(CATID_WebAppServer)]); if RegQueryValue(ClsIDKey, PChar(S), nil, BufSize) = 0 then begin if RegCheck <> '' then begin BufSize := 256; SetLength(S, BufSize); if RegQueryValueEx(ClsIDKey, PChar(RegCheck), nil, nil, PByte(PChar(S)), @BufSize) = ERROR_SUCCESS then SetLength(S, BufSize - 1) else S := ''; if GetRegStringValue(S, RegCheck) <> SFlagOn then continue; end; List.AddClassID(StringToGUID(Buffer)); end; Inc(I); end; finally RegCloseKey(ClsIDKey); end; end; if List.FSortOrder <> soUnknown then List.Sort; end; function GetDetails(AClassID: TGuid; ADetails: TSvrInfoItem): string; begin ADetails.Clear; ADetails.ClsID := GuidToString(AClassID); ADetails.ProgID := ClassIDToProgID(AClassID); if ADetails.ClsID <> '' then begin ADetails.FullFileName := GetRegStringValue('CLSID\' + ADetails.ClsID + '\LocalServer32', ''); if ADetails.FullFileName <> '' then begin ADetails.FileExists := FileExists(ADetails.FullFileName); end; end; end; function TCustomSvrInfoAdapter.ImplCanAddActionClass( AParent: TComponent; AClass: TClass): Boolean; begin Result := inherited ImplCanAddActionClass(AParent, AClass) or AClass.InheritsFrom(TSvrInfoAction); end; function TCustomSvrInfoAdapter.ImplCanAddFieldClass(AParent: TComponent; AClass: TClass): Boolean; begin Result := inherited ImplCanAddActionClass(AParent, AClass) or AClass.InheritsFrom(TSvrInfoField); end; // Support iteration with server-side script procedure TCustomSvrInfoAdapter.EndIterator( OwnerData: Pointer); begin end; function TCustomSvrInfoAdapter.NextIteration( var OwnerData: Pointer): Boolean; begin Inc(FIndex); Result := FIndex < FList.Count; end; function TCustomSvrInfoAdapter.StartIterator( var OwnerData: Pointer): Boolean; begin FIndex := 0; Result := GetList.Count > 0; end; procedure TCustomSvrInfoAdapter.ImplGetFieldsList(AList: TStrings); begin ListSvrInfoFields(AList); end; procedure TCustomSvrInfoAdapter.ImplGetActionsList(AList: TStrings); begin ListSvrInfoActions(AList); end; procedure Register; begin RegisterComponents('WebSnap Samples', [TSvrInfoAdapter]); RegisterWebComponents([TSvrInfoClsIDField, TSvrInfoProgIDField, TSvrInfoFileNameField, TSvrInfoFilePathField, TSvrInfoFileExistsField, TSvrInfoURLPathField, TSvrInfoSortByProgIDAction, TSvrInfoSortByFilePathAction, TSvrInfoCleanMarkedAction, TSvrInfoCleanMissingFilesAction, TSvrInfoMarkClsIDField]); end; constructor TCustomSvrInfoAdapter.Create(AOwner: TComponent); begin inherited; FList := TSvrInfoList.Create; end; destructor TCustomSvrInfoAdapter.Destroy; begin inherited; FList.Free; end; { TSvrInfoField } function TSvrInfoField.Adapter: TCustomSvrInfoAdapter; var C: TComponent; begin if (csDesigning in ComponentState) or (FAdapter = nil) then begin FAdapter := nil; C := FindAdapterInParent(Self); if C <> nil then FAdapter := C as TCustomSvrInfoAdapter; end; Result := FAdapter; end; function TSvrInfoField.Item: TSvrInfoItem; begin Result := Adapter.CurrentItem; end; { TSvrInfoDetails } procedure TSvrInfoItem.Clear; begin ProgID := ''; ClsID := ''; FullFileName := ''; FileExists := False; end; { TSvrInfoClsIDField } function TSvrInfoClsIDField.GetDefaultFieldName: string; begin Result := sClsIDField; end; function TSvrInfoClsIDField.ImplGetValue: Variant; begin Result := Item.ClsID; end; { TSvrInfoProgIDField } function TSvrInfoProgIDField.GetDefaultFieldName: string; begin Result := sProgIDField; end; function TSvrInfoProgIDField.ImplGetValue: Variant; begin Result := Item.ProgID; end; { TSvrInfoFileNameField } function TSvrInfoFileNameField.GetDefaultFieldName: string; begin Result := sFileName; end; function TSvrInfoFileNameField.ImplGetValue: Variant; begin Result := Item.FileName; end; { TSvrInfoFilePathField } function TSvrInfoFilePathField.GetDefaultFieldName: string; begin Result := sFilePath; end; function TSvrInfoFilePathField.ImplGetValue: Variant; begin Result := Item.FilePath; end; { TSvrInfoFileExistsField } function TSvrInfoFileExistsField.GetDefaultFieldName: string; begin Result := sFileExists; end; function TSvrInfoFileExistsField.ImplGetValue: Variant; begin Result := Item.FileExists; end; { TSvrInfoPathField } function TSvrInfoURLPathField.GetDefaultFieldName: string; begin Result := sURLPath; end; function TSvrInfoURLPathField.ImplGetValue: Variant; begin Result := '/' end; { TSvrInfoCleanMarkedAction } function TSvrInfoCleanMarkedAction.GetDefaultActionName: string; begin Result := sCleanMarkedAction; end; procedure CleanRegistry(AProgID, AClassID, AServerKey: string); begin if AProgID <> '' then begin DeleteRegKey(AProgID + '\Clsid'); DeleteRegKey(AProgID); end; if AClassID <> '' then begin DeleteRegKey('CLSID\' + AClassID + '\ProgID'); DeleteRegKey('CLSID\' + AClassID + '\' + AServerKey); DeleteRegKey('CLSID\' + AClassID + '\' + 'Implemented Categories'); DeleteRegKey('CLSID\' + AClassID); end; end; // Remote entries from the registry procedure CleanClsID(const ClassID: TGUID); var CatReg: ICatRegister; Rslt: HResult; SClassID: string; ProgID: string; begin SClassID := GUIDToString(ClassID); ProgID := ClassIDToProgID(ClassID); CleanRegistry(ProgID, SClassID, 'LocalServer32'); Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil, CLSCTX_INPROC_SERVER, ICatRegister, CatReg); if Succeeded(Rslt) then begin OleCheck(CatReg.UnRegisterClassImplCategories(ClassID, 1, @CATID_WebAppServer)); DeleteRegKey(Format(SCatImplBaseKey, [SClassID])); end; end; procedure TSvrInfoCleanMarkedAction.ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); var Value: IActionFieldValue; ActionFieldValues: IActionFieldValues; I: Integer; ClsID: string; begin if not Supports(AActionRequest, IActionFieldValues, ActionFieldValues) then Assert(False); Value := ActionFieldValues.ValueOfField(sMarkClsID); if Value <> nil then begin for I := 0 to Value.ValueCount - 1 do begin ClsID := Value.Values[I]; CleanClsID(StringToGuid(ClsID)); end; end; Adapter.FList.Clear; end; { TSvrInfoItemAction } function TSvrInfoItemAction.Item: TSvrInfoItem; begin Result := Adapter.CurrentItem; end; { TSvrInfoList } function TSvrInfoList.AddClassID(AClassID: TGuid): TSvrInfoItem; begin Result := TSvrInfoItem.Create(Self); FList.Add(Result); GetDetails(AClassID, Result); end; procedure TSvrInfoList.Clear; begin FList.Clear; end; function TSvrInfoList.Count: Integer; begin Result := FList.Count; end; constructor TSvrInfoList.Create; begin FList := TObjectList.Create(True {Owned}); end; destructor TSvrInfoList.Destroy; begin inherited; FList.Free; end; function TSvrInfoList.GetItem(I: Integer): TSvrInfoItem; begin Result := FList.Items[I] as TSvrInfoItem; end; function TCustomSvrInfoAdapter.CurrentItem: TSvrInfoItem; begin Result := FList[FIndex]; end; resourcestring sUnknownSortOrder = 'Unknown sort order'; function SortCompare(Item1, Item2: Pointer): Integer; var Info1, Info2: TSvrInfoItem; begin Info1 := TSvrInfoItem(Item1); Info2 := TSvrInfoItem(Item2); case Info1.List.FSortOrder of soProgID: Result := AnsiCompareText(Info1.ProgID, Info2.ProgID); soFilePath: Result := AnsiCompareText(Info1.FilePath, Info2.FilePath); else raise Exception.Create(sUnknownSortOrder); end; end; procedure TSvrInfoList.SetSortOrder(const Value: TSvrInfoSortOrder); begin if FSortOrder <> Value then begin FSortOrder := Value; if FSortOrder <> soUnknown then Sort; end; end; procedure TSvrInfoList.Sort; begin if FSortOrder <> soUnknown then begin FList.Sort(SortCompare); FSorted := True; end; end; { TSvrInfoAction } function TSvrInfoAction.Adapter: TCustomSvrInfoAdapter; var A: TComponent; begin A := inherited Adapter; if A <> nil then Result := A as TCustomSvrInfoAdapter else Result := nil; end; (* jmt.!!! function TSvrInfoAction.ActionParamsAsStrings( AActionParams: IAdapterRequestParams): TStrings; var I: Integer; begin Result := TStringList.Create; for I := 0 to AActionParams.ParamCount - 1 do Result.Add(Format('%s=%s', [AActionParams.ParamNames[I], AActionParams.ParamValues[I]])); end; procedure TSvrInfoAction.ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); var S: TStrings; begin try S := ActionParamsAsStrings(AActionRequest.ActionParams); try WebExecuteParams(S); finally S.Free; end; except // Add to error list. The errors can be accessed using // server-side script on E: Exception do begin Errors.AddError(E); end; end; end; procedure TSvrInfoAction.WebExecuteParams(const AStrings: TStrings); begin // Descendent must implement end; *) constructor TSvrInfoItem.Create(AList: TSvrInfoList); begin List := AList; inherited Create; end; procedure TSvrInfoAction.ImplSetActionName(const Value: string); begin if Value = GetDefaultActionName then FActionName := '' else FActionName := Value; end; procedure TSvrInfoAction.SetActionName(const Value: string); begin ImplSetActionName(Value); end; procedure TSvrInfoAction.ImplExecuteActionRequest(AActionRequest: IActionRequest; AActionResponse: IActionResponse); var S: TStrings; begin S := AdapterRequestParamsAsStrings(AActionRequest); try ExecuteActionRequestParamStrings(S); finally S.Free; end; end; procedure TSvrInfoAction.ExecuteActionRequestParamStrings( const AStrings: TStrings); begin Assert(False); // Descendent must implement end; { TSvrInfoSortByProgIDAction } function TSvrInfoSortByProgIDAction.GetDefaultActionName: string; begin Result := sSortProgIDAction; end; procedure SaveSortOrder(S: TSvrInfoSortOrder); begin with WebContext.Response.Cookies.Add do begin Name := sSortOrderCookie; Path := WebContext.Response.HTTPRequest.InternalScriptName; Value := SvrInfoSortOrderNames[S]; end; end; procedure TSvrInfoSortByProgIDAction.ExecuteActionRequestParamStrings( const AStrings: TStrings); begin Adapter.List.SortOrder := soProgID; SaveSortOrder(Adapter.List.FSortOrder); end; { TSvrInfoSortByFilePathAction } function TSvrInfoSortByFilePathAction.GetDefaultActionName: string; begin Result := sSortFilePathAction; end; procedure TSvrInfoSortByFilePathAction.ExecuteActionRequestParamStrings( const AStrings: TStrings); begin Adapter.List.SortOrder := soFilePath; SaveSortOrder(Adapter.List.FSortOrder); end; function TSvrInfoItem.FileName: string; begin Result := ExtractFileName(FullFileName); end; function TSvrInfoItem.FilePath: string; begin Result := ExtractFilePath(FullFileName); end; { TSvrInfoMarkClsIDField } function TSvrInfoMarkClsIDField.GetDefaultFieldName: string; begin Result := sMarkClsID; end; { TSvrInfoCleanMissingFilesAction } function TSvrInfoCleanMissingFilesAction.GetDefaultActionName: string; begin Result := sCleanMissingFilesAction; end; function TSvrInfoCleanMissingFilesAction.ImplWebEnabled: Boolean; var I: Integer; begin for I := 0 to Adapter.List.Count - 1 do begin if not Adapter.List[I].FileExists then begin Result := True; Exit; end; end; Result := False; end; procedure TSvrInfoCleanMissingFilesAction.ImplExecuteActionRequest( AActionRequest: IActionRequest; AActionResponse: IActionResponse); var I: Integer; begin for I := 0 to Adapter.List.Count - 1 do begin if not Adapter.List[I].FileExists then CleanClsID(StringToGuid(Adapter.List[I].ClsID)); end; end; procedure TCustomSvrInfoAdapter.ImplNotifyDeactivate; begin FList.Clear; FList.FSortOrder := soUnknown; end; function TCustomSvrInfoAdapter.GetList: TSvrInfoList; var S: String; I: TSvrInfoSortOrder; begin if FList.Count = 0 then begin if FList.SortOrder = soUnknown then if WebContext <> nil then if WebContext.Request <> nil then begin S := WebContext.Request.CookieFields.Values[sSortOrderCookie]; for I := Low(TSvrInfoSortOrder) to High(TSvrInfoSortOrder) do if SvrInfoSortOrderNames[I] = S then begin FList.SortOrder := I; break; end; end; GetWebAppList(FList, ''); end; Result := FList; end; initialization finalization UnregisterWebComponents([TSvrInfoField, TSvrInfoClsIDField, TSvrInfoProgIDField, TSvrInfoFileNameField, TSvrInfoFilePathField, TSvrInfoFileExistsField, TSvrInfoURLPathField, TSvrInfoSortByProgIDAction, TSvrInfoSortByFilePathAction, TSvrInfoCleanMarkedAction, TSvrInfoCleanMissingFilesAction, TSvrInfoMarkClsIDField]); end.
unit uDiagnosisService; interface uses Classes, SysUtils, ShlObj, Windows, Device.PhysicalDrive, Device.PhysicalDrive.List, Global.LanguageString, OS.EnvironmentVariable, Getter.PhysicalDrive.ListChange, MeasureUnit.Datasize, AverageLogger.Count, AverageLogger.Write, Support, Getter.PhysicalDrive.PartitionList; type TDiagnosisService = class private PhysicalDriveList: TPhysicalDriveList; LastChanges: TChangesList; IsFirstDiagnosis: Boolean; ErrorFilePath: String; procedure SetPhysicalDriveList; procedure FreeLastChanges; function GetLogLine(Timestamp: TDateTime; const Content: String): String; function IsNeedDiagnosis: Boolean; procedure LogAndCheckSMART; procedure RefreshReplacedSectorLog(Entry: IPhysicalDrive); procedure RefreshTotalWriteLog(Entry: IPhysicalDrive); procedure AlertIfNeedToReplacedSectors(Entry: IPhysicalDrive; IsReplacedSectorDifferent: Boolean); function GetAlertFile: TStringList; function GetPartitionLetters(Entry: IPhysicalDrive): String; procedure SaveWriteBufferCheckResult(WriteBufferErrors: TStringList); procedure RefreshReadWriteErrorLog(Entry: IPhysicalDrive); procedure AlertIfNeedToReadEraseError(Entry: IPhysicalDrive; IsReadWriteErrorDifferent: Boolean); public constructor Create; destructor Destroy; override; procedure InitializePhysicalDriveList; procedure Diagnosis; function IsThereAnySupportedDrive: Boolean; end; implementation { TDiagnosisService } constructor TDiagnosisService.Create; begin EnvironmentVariable.SetPath(nil); DetermineLanguage; ErrorFilePath := EnvironmentVariable.AllDesktopPath + '\!!!SSDError!!!.err'; IsFirstDiagnosis := true; end; procedure TDiagnosisService.SetPhysicalDriveList; var ListChangeGetter: TListChangeGetter; begin FreeLastChanges; if PhysicalDriveList = nil then PhysicalDriveList := TPhysicalDriveList.Create; ListChangeGetter := TListChangeGetter.Create; ListChangeGetter.IsOnlyGetSupportedDrives := true; LastChanges := ListChangeGetter.ServiceRefreshListWithResultFrom(PhysicalDriveList); FreeAndNil(ListChangeGetter); end; procedure TDiagnosisService.InitializePhysicalDriveList; begin SetPhysicalDriveList; end; procedure TDiagnosisService.FreeLastChanges; begin if LastChanges.Added <> nil then FreeAndNil(LastChanges.Added); if LastChanges.Deleted <> nil then FreeAndNil(LastChanges.Deleted); end; function TDiagnosisService.IsThereAnySupportedDrive: Boolean; begin result := PhysicalDriveList.Count > 0; end; function TDiagnosisService.GetLogLine(Timestamp: TDateTime; const Content: String): String; begin result := FormatDateTime('[yy/mm/dd hh:nn:ss]', Timestamp) + Content; end; function TDiagnosisService.IsNeedDiagnosis: Boolean; begin result := IsFirstDiagnosis or (FormatDateTime('mm', Now) = '00'); if not IsFirstDiagnosis then IsFirstDiagnosis := true; end; procedure TDiagnosisService.SaveWriteBufferCheckResult( WriteBufferErrors: TStringList); var AlertFile: TStringList; CurrentLine: Integer; begin if WriteBufferErrors.Count > 0 then begin AlertFile := GetAlertFile; for CurrentLine := 0 to WriteBufferErrors.Count - 1 do AlertFile.Add( GetLogLine(Now, ' !!!!! ' + WriteBufferErrors[CurrentLine] + ' ' + CapWrongBuf[CurrLang] + ' !!!!! ' + CapWrongBuf2[CurrLang])); AlertFile.SaveToFile(ErrorFilePath); FreeAndNil(AlertFile); end; FreeAndNil(WriteBufferErrors); end; procedure TDiagnosisService.RefreshTotalWriteLog(Entry: IPhysicalDrive); var TotalWriteLog: TAverageWriteLogger; begin if Entry.SupportStatus.TotalWriteType <> TTotalWriteType.WriteSupportedAsValue then exit; TotalWriteLog := TAverageWriteLogger.Create( TAverageWriteLogger.BuildFileName( EnvironmentVariable.AppPath, Entry.IdentifyDeviceResult.Serial)); TotalWriteLog.ReadAndRefresh(UIntToStr( MBToLiteONUnit( Entry.SMARTInterpreted.TotalWrite.InValue.ValueInMiB))); FreeAndNil(TotalWriteLog); end; function TDiagnosisService.GetAlertFile: TStringList; begin result := TStringList.Create; if FileExists(ErrorFilePath) then result.LoadFromFile(ErrorFilePath); end; function TDiagnosisService.GetPartitionLetters(Entry: IPhysicalDrive): String; var PartitionList: TPartitionList; CurrentPartition: Integer; begin PartitionList := Entry.GetPartitionList; result := ''; for CurrentPartition := 0 to (PartitionList.Count - 1) do result := result + ' ' + PartitionList[CurrentPartition].Letter; FreeAndNil(PartitionList); end; procedure TDiagnosisService.AlertIfNeedToReplacedSectors(Entry: IPhysicalDrive; IsReplacedSectorDifferent: Boolean); var AlertFile: TStringList; AllMountedPartitions: String; begin if (not Entry.SMARTInterpreted.SMARTAlert.ReplacedSector) or (not IsReplacedSectorDifferent) then exit; AlertFile := GetAlertFile; AllMountedPartitions := GetPartitionLetters(Entry); AlertFile.Add( GetLogLine(Now, ' !!!!! ' + AllMountedPartitions + ' ' + CapBck[CurrLang] + ' !!!!! ' + CapBckRepSector[CurrLang] + '(' + UIntToStr(Entry.SMARTInterpreted.ReplacedSectors) + CapCount[CurrLang] + ') ' + CapOcc[CurrLang])); AlertFile.SaveToFile(ErrorFilePath); FreeAndNil(AlertFile); end; procedure TDiagnosisService.AlertIfNeedToReadEraseError(Entry: IPhysicalDrive; IsReadWriteErrorDifferent: Boolean); var AlertFile: TStringList; AllMountedPartitions: String; begin if (not Entry.SMARTInterpreted.SMARTAlert.ReadEraseError) or (not IsReadWriteErrorDifferent) then exit; AlertFile := GetAlertFile; AllMountedPartitions := GetPartitionLetters(Entry); AlertFile.Add( GetLogLine(Now, ' !!!!! ' + AllMountedPartitions + ' ' + CapBck[CurrLang] + ' !!!!! ' + CapBckREError[CurrLang] + '(' + UIntToStr(Entry.SMARTInterpreted.ReadEraseError.Value) + CapCount[CurrLang] + ') ' + CapOcc[CurrLang])); AlertFile.SaveToFile(ErrorFilePath); FreeAndNil(AlertFile); end; procedure TDiagnosisService.RefreshReplacedSectorLog(Entry: IPhysicalDrive); var ReplacedSectorLog: TAverageCountLogger; begin ReplacedSectorLog := TAverageCountLogger.Create( TAverageCountLogger.BuildFileName( EnvironmentVariable.AppPath, Entry.IdentifyDeviceResult.Serial + 'RSLog')); ReplacedSectorLog.ReadAndRefresh(UIntToStr( Entry.SMARTInterpreted.ReplacedSectors)); AlertIfNeedToReplacedSectors(Entry, ReplacedSectorLog.GetFormattedTodayDelta <> '0.0'); FreeAndNil(ReplacedSectorLog); end; procedure TDiagnosisService.RefreshReadWriteErrorLog(Entry: IPhysicalDrive); var ReadWriteErrorLog: TAverageCountLogger; begin ReadWriteErrorLog := TAverageCountLogger.Create( TAverageCountLogger.BuildFileName( EnvironmentVariable.AppPath, Entry.IdentifyDeviceResult.Serial + 'RELog')); ReadWriteErrorLog.ReadAndRefresh(UIntToStr( Entry.SMARTInterpreted.ReplacedSectors)); AlertIfNeedToReadEraseError(Entry, ReadWriteErrorLog.GetFormattedTodayDelta <> '0.0'); FreeAndNil(ReadWriteErrorLog); end; procedure TDiagnosisService.LogAndCheckSMART; var CurrentEntry: IPhysicalDrive; begin for CurrentEntry in PhysicalDriveList do begin if not CurrentEntry.IsDriveAvailable then begin SetPhysicalDriveList; exit; end; RefreshTotalWriteLog(CurrentEntry); RefreshReplacedSectorLog(CurrentEntry); RefreshReadWriteErrorLog(CurrentEntry); end; end; procedure TDiagnosisService.Diagnosis; begin if not IsNeedDiagnosis then exit; LogAndCheckSMART; end; destructor TDiagnosisService.Destroy; begin FreeLastChanges; if PhysicalDriveList <> nil then FreeAndNil(PhysicalDriveList); inherited; end; end.
unit IdSimpleServer; interface uses Classes, IdTCPConnection, IdStackConsts; const ID_SIMPLE_SERVER_BOUND_PORT = 0; type TIdSimpleServer = class(TIdTCPConnection) protected FAbortedRequested: Boolean; FAcceptWait: Integer; FBoundIP: string; FBoundPort: Integer; FListenHandle: TIdStackSocketHandle; FListening: Boolean; public procedure Abort; virtual; procedure BeginListen; virtual; procedure Bind; virtual; constructor Create(AOwner: TComponent); override; function Listen: Boolean; virtual; procedure ResetConnection; override; // property AcceptWait: integer read FAcceptWait write FAcceptWait; property ListenHandle: TIdStackSocketHandle read FListenHandle; published property BoundIP: string read FBoundIP write FBoundIP; property BoundPort: Integer read FBoundPort write FBoundPort default ID_SIMPLE_SERVER_BOUND_PORT; end; implementation uses IdStack; procedure TIdSimpleServer.Abort; begin FAbortedRequested := true; end; procedure TIdSimpleServer.BeginListen; begin ResetConnection; if ListenHandle = Id_INVALID_SOCKET then begin Bind; end; Binding.Listen(1); FListening := True; end; procedure TIdSimpleServer.Bind; begin with Binding do begin try AllocateSocket; FListenHandle := Handle; IP := BoundIP; Port := BoundPort; Bind; except FListenHandle := Id_INVALID_SOCKET; raise; end; end; end; constructor TIdSimpleServer.Create(AOwner: TComponent); begin inherited; FBoundPort := ID_SIMPLE_SERVER_BOUND_PORT; FListenHandle := Id_INVALID_SOCKET; end; function TIdSimpleServer.Listen: boolean; begin result := false; if not FListening then begin BeginListen; end; with Binding do begin while (FAbortedRequested = false) and (result = false) do begin result := Readable(AcceptWait); end; if result then begin Accept(Handle); end; GStack.WSCloseSocket(ListenHandle); FListenHandle := Id_INVALID_SOCKET; end; end; procedure TIdSimpleServer.ResetConnection; begin inherited; FAbortedRequested := False; FListening := False; end; end.
unit osWizFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, osUtils, ActnList, osActionList, osFrm, System.Actions, System.UITypes; type TosWizForm = class(TosForm) Panel2: TPanel; Panel1: TPanel; btnCancelar: TButton; btnAvancar: TButton; btnVoltar: TButton; pgcWizard: TPageControl; Bevel1: TBevel; TabSheet1: TTabSheet; lblPag1Det: TLabel; lbLog: TListBox; Panel3: TPanel; lblTitulo: TLabel; lblTituloDetalhe: TLabel; memTitulos: TMemo; ActionList2: TosActionList; OnConclusion: TAction; OnEnterPage: TAction; OnLeavePage: TAction; OnInit: TAction; procedure btnVoltarClick(Sender: TObject); procedure btnAvancarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure pgcWizardChanging(Sender: TObject; var AllowChange: Boolean); private FMovingForward: boolean; FCompleteAction: boolean; FMudarTela: Boolean; function GetIndexLastPage: integer; protected procedure UpdatePage; virtual; public procedure WizardConclusion; virtual; procedure NextPage; virtual; procedure PreviousPage; virtual; procedure FirstPage; virtual; procedure LastPage; virtual; procedure GotoPage(index : integer); virtual; function PageIndex : integer; function PageCount : integer; procedure Log(const PMessage: string; const Args: array of const; const PTime: boolean = True); property IndexLastPage: integer read GetIndexLastPage; property MovingForward: boolean read FMovingForward; property CompleteAction: boolean read FCompleteAction write FCompleteAction; property MudarTela: boolean read FMudarTela write FMudarTela; end; const constConcluirCaption = 'C&oncluir'; constFecharCaption = '&Fechar'; constAvancarCaption = '&Avanšar >'; constCancelarCaption = '&Cancelar'; implementation uses acCustomSQLMainDataUn; {$R *.DFM} procedure TosWizForm.UpdatePage; var iLinha: integer; begin if pgcWizard.Visible then begin if PageIndex < IndexLastPage then btnAvancar.Caption := constAvancarCaption else btnAvancar.Caption := constConcluirCaption; btnVoltar.Enabled := not(PageIndex = 0); iLinha := PageIndex; end else iLinha := PageIndex + 1; lblTitulo.Caption := GetWord(memTitulos.Lines[iLinha], 1, '|'); lblTituloDetalhe.Caption := GetWord(memTitulos.Lines[iLinha], 2, '|'); end; procedure TosWizForm.btnVoltarClick(Sender: TObject); begin inherited; FMudarTela := True; CompleteAction := True; FMovingForward := False; OnLeavePage.Execute; if CompleteAction then PreviousPage; end; procedure TosWizForm.btnAvancarClick(Sender: TObject); begin inherited; FMudarTela := True; CompleteAction := True; FMovingForward := True; OnLeavePage.Execute; if CompleteAction then begin if btnAvancar.Caption = constConcluirCaption then begin pgcWizard.Visible := False; try btnVoltar.Enabled := False; NextPage; UpdatePage; btnAvancar.Enabled := False; btnCancelar.Caption := constFecharCaption; btnCancelar.Enabled := False; WizardConclusion; except pgcWizard.Visible := True; raise; end; Close; end else NextPage; end; end; procedure TosWizForm.btnCancelarClick(Sender: TObject); begin inherited; if btnCancelar.Caption = constFecharCaption then begin ModalResult := mrOK; Close; end else if MessageDlg(PChar('Cancelar o ' + Caption + '?'), mtConfirmation, mbYesNo, 0) = mrYes then begin ModalResult := mrCancel; Close; end; end; procedure TosWizForm.FirstPage; begin pgcWizard.ActivePage := pgcWizard.Pages[0]; UpdatePage; end; procedure TosWizForm.LastPage; begin pgcWizard.ActivePage := pgcWizard.Pages[IndexLastPage]; UpdatePage; end; procedure TosWizForm.NextPage; begin if pgcWizard.Visible then begin pgcWizard.SelectNextPage(True); UpdatePage; OnEnterPage.Execute; end; end; procedure TosWizForm.PreviousPage; begin pgcWizard.SelectNextPage(False); UpdatePage; OnEnterPage.Execute; end; function TosWizForm.PageIndex: integer; begin Result := pgcWizard.ActivePage.PageIndex; end; function TosWizForm.PageCount: integer; begin Result := pgcWizard.PageCount; end; procedure TosWizForm.GotoPage(index : integer); begin if index > PageCount then exit; if index < 0 then exit; OnLeavePage.Execute; pgcWizard.ActivePage := pgcWizard.Pages[index]; UpdatePage; OnEnterPage.Execute; end; procedure TosWizForm.WizardConclusion; begin OnConclusion.Execute; end; function TosWizForm.GetIndexLastPage: integer; begin with pgcWizard do begin Result := PageCount - 1; while (not Pages[Result].TabVisible) and (Result > 0) do Dec(Result); end; end; procedure TosWizForm.FormShow(Sender: TObject); begin FMudarTela := False; btnAvancar.Enabled := True; btnCancelar.Caption := constCancelarCaption; btnCancelar.Enabled := True; btnAvancar.Default := False; pgcWizard.Visible := True; FirstPage; OnInit.Execute; end; procedure TosWizForm.Log(const PMessage: string; const Args: array of const; const PTime: boolean); var sAux: string; begin if PTime then sAux := FormatDateTime('hh:nn:ss', acCustomSQLMainData.GetServerDatetime) + ' - ' else sAux := ''; lbLog.Items.Add(sAux + Format(PMessage, Args)); Application.ProcessMessages; end; procedure TosWizForm.pgcWizardChanging(Sender: TObject; var AllowChange: Boolean); begin if not FMudarTela then AllowChange := False; FMudarTela := False; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.APIDocResource; interface uses System.SysUtils, System.Classes, System.JSON, EMS.ResourceAPI, EMS.ResourceTypes, System.JSON.Writers, EMSHosting.APIDocConsts; const sAPIDoc = 'API'; sAPIDocYAML = 'GetAPIYAMLFormat'; sAPIDocJSON = 'GetAPIJSONFormat'; sYAMLSuffix = 'apidoc.yaml'; sJSONSuffix = 'apidoc.json'; type [ResourceName(sAPIDoc)] {$METHODINFO ON} TAPIDocResource = class private procedure GetAPIDoc(const AAPIDoc: TAPIDoc; const LoadJSONDefinitions: Boolean; const ASegmentPath: string = ''); published [EndpointName(sAPIDoc)] [EndPointRequestSummary(cAPIDocTag, cGetAPITitle, cGetAPIDesc, cApplicationJSON, '')] [EndPointResponseDetails(200, cResponseOK, TAPIDoc.TPrimitiveType.spNull, TAPIDoc.TPrimitiveFormat.None, '', '')] procedure GetDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [EndpointName(sAPIDocYAML + ' EndPoint')] [ResourceSuffix('{item}/' + sYAMLSuffix)] [EndPointRequestSummary(cAPIDocTag, cGetOneAPITitle, cGetOneAPIDesc, cApplicationJSON, '')] [EndPointRequestParameter(TAPIDocParameter.TParameterIn.Path, 'item', cEndPointPath, true, TAPIDoc.TPrimitiveType.spString, TAPIDoc.TPrimitiveFormat.None, TAPIDoc.TPrimitiveType.spNull, '', '')] [EndPointResponseDetails(200, cResponseOK, TAPIDoc.TPrimitiveType.spNull, TAPIDoc.TPrimitiveFormat.None, '', '')] procedure GetDocYamlItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [EndpointName(sAPIDocYAML)] [ResourceSuffix(sYAMLSuffix)] [EndPointRequestSummary(cAPIDocTag, cGetAPIYAMLTitle, cGetAPIYAMLDesc, '', '')] [EndPointResponseDetails(200, cResponseOK, TAPIDoc.TPrimitiveType.spNull, TAPIDoc.TPrimitiveFormat.None, '', '')] procedure GetYamlDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [EndpointName(sAPIDocJSON)] [ResourceSuffix(sJSONSuffix)] [EndPointRequestSummary(cAPIDocTag, cGetAPIJSONTitle, cGetAPIJSONDesc, '', '')] [EndPointResponseDetails(200, cResponseOK, TAPIDoc.TPrimitiveType.spNull, TAPIDoc.TPrimitiveFormat.None, '', '')] procedure GetJSONDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; {$METHODINFO OFF} procedure RegisterAPIDocResource; implementation uses EMSHosting.Helpers, System.JSON.Builders, System.Generics.Defaults, System.Generics.Collections, System.Variants; procedure RegisterAPIDocResource; begin RegisterResource(TypeInfo(TAPIDocResource)); end; { TVersionResource } procedure TAPIDocResource.GetAPIDoc(const AAPIDoc: TAPIDoc; const LoadJSONDefinitions: Boolean; const ASegmentPath: string); var LEMSEndpointManager: TEMSEndpointManager; LEMSResource: TEMSResource; LEMSTypeInfoResource: TEMSTypeInfoResource; LAPIDocPath: TAPIDocPath; LDefinitions: string; LJSONObject: TJSONObject; LAddDefinitions: Boolean; begin LEMSEndpointManager := TEMSEndpointManager.Instance; for LEMSResource in LEMSEndpointManager.Resources do if LEMSResource is TEMSTypeInfoResource then begin LEMSTypeInfoResource := TEMSTypeInfoResource(LEMSResource); LAddDefinitions := False; for LAPIDocPath in LEMSTypeInfoResource.APIDocPaths do if (ASegmentPath = '') or (LAPIDocPath.Path.StartsWith('/' + ASegmentPath)) then begin AAPIDoc.AddPath(LAPIDocPath); LAddDefinitions := True; end; if LAddDefinitions then if not LoadJSONDefinitions then AAPIDoc.Definitions := AAPIDoc.Definitions + LEMSTypeInfoResource.YAMLDefinitions else if LEMSTypeInfoResource.JSONDefinitions <> '' then begin LJSONObject := TJSONObject.ParseJSONValue(LEMSTypeInfoResource.JSONDefinitions) as TJSONObject; if LJSONObject = nil then raise Exception.Create('Wrong deinitions. Invalid JSON Objects') else LJSONObject.Free; LDefinitions := LEMSTypeInfoResource.JSONDefinitions.Trim; LDefinitions := LDefinitions.Remove(0, 1); LDefinitions := LDefinitions.Remove(LDefinitions.Length -1, 1); if AAPIDoc.Definitions = '' then AAPIDoc.Definitions := LDefinitions else AAPIDoc.Definitions := AAPIDoc.Definitions + ',' + sLineBreak + LDefinitions; end; end; AAPIDoc.SortPaths; end; procedure TAPIDocResource.GetDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LBuilderArray: TJSONArrayBuilder; begin LBuilderArray := TJSONArrayBuilder.Create(AResponse.Body.JSONWriter); try LBuilderArray.BeginArray; LBuilderArray.ParentArray.BeginObject; LBuilderArray.ParentObject.Add('apicall',sYAMLSuffix); LBuilderArray.ParentObject.EndObject; LBuilderArray.ParentArray.BeginObject; LBuilderArray.ParentObject.Add('apicall',sJSONSuffix); LBuilderArray.ParentObject.EndObject; LBuilderArray.ParentArray.EndArray; finally LBuilderArray.Free; end; end; procedure TAPIDocResource.GetJSONDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LAPIDoc: TAPIDoc; LHost, LBasePath: string; begin LBasePath := ARequest.BasePath; LHost := ARequest.ServerHost; LAPIDoc := TAPIDoc.Create(LHost, LBasePath); try GetAPIDoc(LAPIDoc, True); LAPIDoc.WriteAPIDocJson(AResponse.Body.JSONWriter); finally LAPIDoc.Free; end; end; procedure TAPIDocResource.GetYamlDoc(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LAPIDoc: TAPIDoc; LHost, LBasePath: string; LItem: string; begin ARequest.Params.TryGetValue('item', LItem); LBasePath := ARequest.BasePath; LHost := ARequest.ServerHost; LAPIDoc := TAPIDoc.Create(LHost, LBasePath); try GetAPIDoc(LAPIDoc, False, LItem); AResponse.Body.SetStream(TStringStream.Create(LAPIDoc.GetAPIDocYaml, TEncoding.UTF8), 'text/plain; charset=utf-8', True); finally LAPIDoc.Free; end; end; procedure TAPIDocResource.GetDocYamlItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin GetYamlDoc(AContext, ARequest, AResponse); end; initialization TResourceStringsTable.Add(cResponseOK, sResponseOK); TResourceStringsTable.Add(cGetAPITitle, sGetAPITitle); TResourceStringsTable.Add(cGetAPIDesc, sGetAPIDesc); TResourceStringsTable.Add(cGetAPIYAMLTitle, sGetAPIYAMLTitle); TResourceStringsTable.Add(cGetAPIJSONTitle, sGetAPIJSONTitle); TResourceStringsTable.Add(cGetAPIYAMLDesc, sGetAPIYAMLDesc); TResourceStringsTable.Add(cGetAPIJSONDesc, sGetAPIJSONDesc); TResourceStringsTable.Add(cGetOneAPITitle, sGetOneAPITitle); TResourceStringsTable.Add(cGetOneAPIDesc, sGetOneAPIDesc); TResourceStringsTable.Add(cEndPointPath, sEndPointPath); end.
{*******************************************************} { } { Delphi VCL Extensions (RX) } { } { Copyright (c) 1996 AO ROSNO } { Copyright (c) 1997, 1998 Master-Bank } { } { Patched by Polaris Software } {*******************************************************} unit RxTimer; interface {$I RX.INC} uses Windows, Messages, SysUtils, Classes, Controls; type { TRxTimer } TRxTimer = class(TComponent) private FEnabled: Boolean; FInterval: Cardinal; FOnTimer: TNotifyEvent; FWindowHandle: HWND; FSyncEvent: Boolean; FThreaded: Boolean; FTimerThread: TThread; FThreadPriority: TThreadPriority; procedure SetThreaded(Value: Boolean); procedure SetThreadPriority(Value: TThreadPriority); procedure SetEnabled(Value: Boolean); procedure SetInterval(Value: Cardinal); procedure SetOnTimer(Value: TNotifyEvent); procedure UpdateTimer; procedure WndProc(var Msg: TMessage); protected procedure Timer; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Synchronize(Method: TThreadMethod); published property Enabled: Boolean read FEnabled write SetEnabled default True; property Interval: Cardinal read FInterval write SetInterval default 1000; property SyncEvent: Boolean read FSyncEvent write FSyncEvent default True; property Threaded: Boolean read FThreaded write SetThreaded default True; property ThreadPriority: TThreadPriority read FThreadPriority write SetThreadPriority default tpNormal; property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer; end; implementation uses Forms, Consts, rxVCLUtils; { TTimerThread } type TTimerThread = class(TThread) private FOwner: TRxTimer; FInterval: Cardinal; FException: Exception; procedure HandleException; protected procedure Execute; override; public constructor Create(Timer: TRxTimer; Enabled: Boolean); end; constructor TTimerThread.Create(Timer: TRxTimer; Enabled: Boolean); begin FOwner := Timer; inherited Create(not Enabled); FInterval := 1000; FreeOnTerminate := True; end; procedure TTimerThread.HandleException; begin if not (FException is EAbort) then begin if Assigned(Application.OnException) then Application.OnException(Self, FException) else Application.ShowException(FException); end; end; procedure TTimerThread.Execute; function ThreadClosed: Boolean; begin Result := Terminated or Application.Terminated or (FOwner = nil); end; begin repeat if not ThreadClosed then if SleepEx(FInterval, False) = 0 then begin if not ThreadClosed and FOwner.FEnabled then with FOwner do if SyncEvent then Synchronize(Timer) else try Timer; except on E: Exception do begin FException := E; HandleException; end; end; end; until Terminated; end; { TRxTimer } constructor TRxTimer.Create(AOwner: TComponent); begin inherited Create(AOwner); FEnabled := True; FInterval := 1000; FSyncEvent := True; FThreaded := True; FThreadPriority := tpNormal; FTimerThread := TTimerThread.Create(Self, False); end; destructor TRxTimer.Destroy; begin Destroying; FEnabled := False; FOnTimer := nil; {TTimerThread(FTimerThread).FOwner := nil;} while FTimerThread.Suspended do FTimerThread.Resume; FTimerThread.Terminate; {if not SyncEvent then FTimerThread.WaitFor;} if FWindowHandle <> 0 then begin KillTimer(FWindowHandle, 1); {$IFDEF RX_D6}Classes.{$ENDIF}DeallocateHWnd(FWindowHandle); // Polaris end; inherited Destroy; end; procedure TRxTimer.WndProc(var Msg: TMessage); begin with Msg do if Msg = WM_TIMER then try Timer; except Application.HandleException(Self); end else Result := DefWindowProc(FWindowHandle, Msg, wParam, lParam); end; procedure TRxTimer.UpdateTimer; begin if FThreaded then begin if FWindowHandle <> 0 then begin KillTimer(FWindowHandle, 1); {$IFDEF RX_D6}Classes.{$ENDIF}DeallocateHWnd(FWindowHandle); // Polaris FWindowHandle := 0; end; if not FTimerThread.Suspended then FTimerThread.Suspend; TTimerThread(FTimerThread).FInterval := FInterval; if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then begin FTimerThread.Priority := FThreadPriority; while FTimerThread.Suspended do FTimerThread.Resume; end; end else begin if not FTimerThread.Suspended then FTimerThread.Suspend; if FWindowHandle = 0 then FWindowHandle := {$IFDEF RX_D6}Classes.{$ENDIF}AllocateHWnd(WndProc) // Polaris else KillTimer(FWindowHandle, 1); if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then if SetTimer(FWindowHandle, 1, FInterval, nil) = 0 then raise EOutOfResources.Create(ResStr(SNoTimers)); end; end; procedure TRxTimer.SetEnabled(Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; UpdateTimer; end; end; procedure TRxTimer.SetInterval(Value: Cardinal); begin if Value <> FInterval then begin FInterval := Value; UpdateTimer; end; end; procedure TRxTimer.SetThreaded(Value: Boolean); begin if Value <> FThreaded then begin FThreaded := Value; UpdateTimer; end; end; procedure TRxTimer.SetThreadPriority(Value: TThreadPriority); begin if Value <> FThreadPriority then begin FThreadPriority := Value; if FThreaded then UpdateTimer; end; end; procedure TRxTimer.Synchronize(Method: TThreadMethod); begin if (FTimerThread <> nil) then begin with TTimerThread(FTimerThread) do begin if Suspended or Terminated then Method else TTimerThread(FTimerThread).Synchronize(Method); end; end else Method; end; procedure TRxTimer.SetOnTimer(Value: TNotifyEvent); begin if Assigned(FOnTimer) <> Assigned(Value) then begin FOnTimer := Value; UpdateTimer; end else FOnTimer := Value; end; procedure TRxTimer.Timer; begin if FEnabled and not (csDestroying in ComponentState) and Assigned(FOnTimer) then FOnTimer(Self); end; end.
unit SettingsTestGroupsUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, LKSL_Settings_Groups, LKSL_Settings_Fields; type { TSettingsTestGroups } TSettingsTestGroups= class(TTestCase) private FGroups: TLKSettingsGroups; protected procedure SetUp; override; procedure TearDown; override; published procedure TestGroupsCount; procedure TestGroupsClear; end; implementation procedure TSettingsTestGroups.SetUp; begin FGroups:= TLKSettingsGroups.Create(nil); end; procedure TSettingsTestGroups.TearDown; begin FGroups.Free; end; procedure TSettingsTestGroups.TestGroupsCount; var Group: TLKSettingsGroup; begin Group:= TLKSettingsGroup.Create(FGroups); FGroups.Add(Group); AssertEquals('Number of groups in list', 1 , FGroups.Count); end; procedure TSettingsTestGroups.TestGroupsClear; var Group: TLKSettingsGroup; begin Group:= TLKSettingsGroup.Create(FGroups); FGroups.Add(Group); AssertEquals('Inserted groups in list', 1 , FGroups.Count); FGroups.Clear; AssertEquals('Cleared number of Groups in list', 0 , FGroups.Count); end; initialization RegisterTest(TSettingsTestGroups); end.
{Ejercicio 7 Dada la definición de tipo para representar cadenas de caracteres de largo M y N : CONST N = . . .; CONST M = . . .; M < N . . . TYPE CadenaM = ARRAY[1..M] Of Char; CadenaN = ARRAY[1..N] Of Char; Implementar un programa que lea dos cadenas de la entrada estándar de largo M y N respectivamente, y determine si la primer cadena ocurre como parte de la segunda cadena. El programa debe funcionar para cualquier valor positivo que puedan tomar M y N, considerando la restricción M < N. Ejemplo de entrada para N=6, M=3: tor totora Ejemplo de salida: El texto 'tor' se encuentra dentro del texto 'totora'. Ejemplo de entrada: tos totora Ejemplo de salida: El texto 'tos' no se encuentra dentro del texto 'totora'.} program ejercicio7; const M = 3; const N = 6; type rangoM = 1..M+1; rangoN = 1..N+1; cadenaM = array[rangoM] of char; cadenaN = array[rangoN] of char; cadenaTemp = array[rangoM] of boolean; var j : rangoM; b : cadenaM; i : rangoN; a : cadenaN; temp : cadenaTemp; begin // writeln('Ingrese una palabra de ', N,' letras.'); for i := 1 to N do begin read(a[i]); // writeln(a[i]); end; writeln('--------------------------'); // writeln('Ingrese una palabra de ', M,' letras.'); read(b[1]); for j := 1 to M do begin read(b[j]); // writeln(b[j]); end; writeln('--------------------------'); writeln(a,'<----Entrada1'); writeln(b,'<----Entrada2'); for j := 1 to M do temp[j] := false; for i := 1 to N do begin for j := 1 to M do if (a[i] = b[j]) then begin temp[j] := true; writeln(temp[j],' <---temp[',j,'] '); i := i + 1; end else begin for j := 1 to M do temp[j] := false; writeln(temp[j],' <---temp[',j,'] '); end; end; end.
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,N-,E+} unit Output; interface uses Global; procedure oBack(N : Byte); procedure oBackspace(C : Char); procedure oBeep; procedure oClrEol; procedure oClrScr; procedure oCWrite(S : String); procedure oCWriteLn(S : String); procedure oDnLn(Ln : Byte); procedure oGotoXY(X,Y : Integer); procedure oMoveUp(C : Byte); procedure oMoveDown(C : Byte); procedure oMoveRight(C : Byte); procedure oMoveLeft(C : Byte); procedure oPause; procedure oPosX(X : Integer); procedure oPosY(Y : Integer); procedure oPromptKey; procedure oRestoreCursor; procedure oSaveCursor; procedure oSetBack(C : Byte); procedure oSetBlink(B : Boolean); procedure oSetCol(C : Byte); procedure oSetColor(F,B : Byte); procedure oSetColRec(T : tColorRec); procedure oSetFore(C : Byte); function oStr(S : String) : Boolean; procedure oStrCtr(S : String); procedure oStrCtrLn(S : String); procedure oString(Z : Word); procedure oStringLn(Z : Word); procedure oStrLn(S : String); procedure oUpPause(R : Word); function oWhereX : Byte; function oWhereY : Byte; procedure oWrite(S : String); procedure oWriteAnsi(S : String); procedure oWriteChar(C : Char); procedure oWriteLn(S : String); procedure oWritePw(S : String); procedure oWriteRem(S : String); implementation uses Misc, FastIO, Emulate, StrProc, WinDos, Input, ShowFile, IPLx, MciCodes, eComm; const ansiFore : array[0..15] of String[2] = ('30','34','32','36','31','35','33','37', '30','34','32','36','31','35','33','37'); ansiBack : array[0..7] of String[2] = ('40','44','42','46','41','45','43','47'); function oAnsiCode(F,T : tColorRec) : String; var S : String; cF, cB, cBl : Boolean; begin cF := F.Fore <> T.Fore; cB := F.Back <> T.Back; cBl := F.Blink <> T.Blink; oAnsiCode := ''; if not (cF or cB or cBl) then Exit; S := #27+'['; if (cBl and T.Blink) or ((cF) and (F.Fore >= 8) and (T.Fore <= 7)) then begin S := S+'0;'; cBl := T.Blink; cB := T.Back <> 0; cF := T.Fore <> 7; end; if cF then begin if (F.Fore <= 7) and (T.Fore >= 8) then S := S+'1;'+ansiFore[T.Fore]+';' else S := S+ansiFore[T.Fore]+';'; end; if cB then S := S+ansiBack[T.Back]+';'; if cBl then S := S+'5;'; S[Ord(S[0])] := 'm'; oAnsiCode := S; end; procedure oSetColRec(T : tColorRec); begin if not emuAnsi then Exit; if (not LocalIO) and (RemoteOut) then begin if emuTextFX then begin ioTextColRec(T); putstring(#27'M'+char(colAttr)); end else if emuAvatar then begin ioTextColRec(T); putstring(^V^A+char(colAttr)); end else begin begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); procedure oWriteChar(C : Char); begin ioWriteChar(C); if (not LocalIO) and (RemoteOut) then eputchar(C); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); end; procedure oWrite(S : String); begin ioWrite(S); if (not LocalIO) and (RemoteOut) then putstring(S); end; procedure oWriteLn(S : String); begin ioWriteLn(S); if (not LocalIO) and (RemoteOut) then putstring(S+#13#10); end; procedure oClrScr; begin if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'J') else if emuAnsi then putstring(#27+'[2J') else putstring(#12); end; emuAnsiInit; mClearScr(False); end; procedure oSetBlink(B : Boolean); var C : tColorRec; begin C := col; C.Blink := B; oSetColRec(C); end; procedure oGotoXY(X,Y : Integer); begin if not emuAnsi then Exit; ioGotoXY(X,Y); if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'H'+char(X)+char(Y)) else if emuAvatar then putstring(^V^H+char(Y)+char(X)) else putstring(#27'['+St(Y)+';'+St(X)+'H'); end; end; procedure oBeep; begin oWrite(#7); end; procedure oCWrite(S : String); var C1, C2 : Char; N, CP : Integer; CS : String; begin CP := 0; C1 := ' '; C2 := ' '; CS := ''; for N := 1 to Length(S) do begin case S[N] of '|' : if (UpCase(S[N+1]) in ['0'..'9','B','U']) and (S[N+2] in ['0'..'9']) then CP := 1 else oWriteChar(S[N]); else if CP = 0 then oWriteChar(S[N]) else if CP = 1 then begin C1 := S[N]; Inc(CP,1); end else if CP = 2 then begin C2 := S[N]; CS := UpStr(C1+C2); if CS = '00' then oSetFore(0) else if CS = '01' then oSetFore(1) else if CS = '02' then oSetFore(2) else if CS = '03' then oSetFore(3) else if CS = '04' then oSetFore(4) else if CS = '05' then oSetFore(5) else if CS = '06' then oSetFore(6) else if CS = '07' then oSetFore(7) else if CS = '08' then oSetFore(8) else if CS = '09' then oSetFore(9) else if CS = '10' then oSetFore(10) else if CS = '11' then oSetFore(11) else if CS = '12' then oSetFore(12) else if CS = '13' then oSetFore(13) else if CS = '14' then oSetFore(14) else if CS = '15' then oSetFore(15) else if CS = 'U0' then oSetCol(colError) else if CS = 'U1' then oSetCol(colText) else if CS = 'U2' then oSetCol(colTextLo) else if CS = 'U3' then oSetCol(colTextHi) else if CS = 'U4' then oSetCol(colInfo) else if CS = 'U5' then oSetCol(colInfoLo) else if CS = 'U6' then oSetCol(colInfoHi) else if CS = 'U7' then oSetCol(colItem) else if CS = 'U8' then oSetCol(colItemSel) else if CS = 'U9' then oSetCol(colBorder) else if CS = '16' then oSetBack(0) else if CS = '17' then oSetBack(1) else if CS = '18' then oSetBack(2) else if CS = '19' then oSetBack(3) else if CS = '20' then oSetBack(4) else if CS = '21' then oSetBack(5) else if CS = '22' then oSetBack(6) else if CS = '23' then oSetBack(7) else if CS = 'B0' then oSetBack(0) else if CS = 'B1' then oSetBack(1) else if CS = 'B2' then oSetBack(2) else if CS = 'B3' then oSetBack(3) else if CS = 'B4' then oSetBack(4) else if CS = 'B5' then oSetBack(5) else if CS = 'B6' then oSetBack(6) else if CS = 'B7' then oSetBack(7) else oWrite('|'+CS); CP := 0; end; end; end; end; procedure oSetFore(C : Byte); var cl : tColorRec; begin cl := col; cl.Fore := C; oSetColRec(Cl); end; procedure oSetBack(C : Byte); var cl : tColorRec; begin cl := col; cl.Back := C; oSetColRec(Cl); end; procedure oSetColor(F,B : Byte); var cl : tColorRec; begin cl := col; cl.Fore := F; cl.Back := B; oSetColRec(Cl); end; procedure oSetCol(C : Byte); begin oSetColRec(User^.Color[C]); end; procedure oCWriteLn(S : String); begin oCWrite(S); oWriteChar(#13); oWriteChar(#10); end; procedure oDnLn(Ln : Byte); var x : Byte; begin for x := 1 to Ln do begin oWriteChar(#13); oWriteChar(#10); end; end; procedure oBackspace(C : Char); begin oWrite(#8+C+#8); end; procedure oWriteAnsi(S : String); var N : Byte; begin for N := 1 to byte(s[0]) do emuAnsiWriteChar(S[N]); if (not LocalIO) and (RemoteOut) then putstring(S); end; procedure oPause; var Ch : Char; C : tColorRec; begin if not (acPause in User^.acFlag) then Exit; C := Col; oString(strPause); Ch := UpCase(iReadKey); PauseAbort := Ch in ['Q','S','N',#27]; if Ch = 'C' then PausePos := 0; if Cfg^.RemovePause then oBack(oWhereX); oSetColRec(C); end; procedure oPromptKey; begin oString(strHitAKey); iReadKey; if Cfg^.RemovePause then oBack(oWhereX); end; procedure oMoveUp(C : Byte); begin ioGotoXY(ioWhereX,ioWhereY-C); if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'A'+char(c)) else if emuAvatar then putstring(^V^H+char(ioWhereY)+char(ioWhereX)) else putstring(#27+'['+St(C)+'A'); end; end; begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); procedure oMoveDown(C : Byte); begin ioGotoXY(ioWhereX,ioWhereY+C); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'B'+char(c)) else if emuAvatar then putstring(^V^H+char(ioWhereY)+char(ioWhereX)) else putstring(#27+'['+St(C)+'B'); end; end; procedure oMoveRight(C : Byte); begin if C+ioWhereX > 80 then C := 80-ioWhereX; ioGotoXY(ioWhereX+C,ioWhereY); if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'C'+char(c)) else if emuAvatar then putstring(^V^H+char(ioWhereY)+char(ioWhereX)) else putstring(#27+'['+St(C)+'C'); end; end; procedure oMoveLeft(C : Byte); begin if C > ioWhereX-1 then C := ioWhereX-1; ioGotoXY(ioWhereX-C,ioWhereY); if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'D'+char(c)) else if emuAvatar then putstring(^V^H+char(ioWhereY)+char(ioWhereX)) else putstring(#27+'['+St(C)+'D'); end; end; function oStr(S : String) : Boolean; var Cd, z, x : String; ct : Integer; mciPad : Boolean; mciLimit, nps, n, ex, ey : Byte; ec : tColorRec; begin N := 0; oStr := False; if HangUp then Exit; oStr := True; if S = '' then Exit; mciPad := False; mciLimit := 255; z := s[1]+s[2]; nps := 0; ex := 0; if z = '%%' then begin sfShowTextFile(Copy(S,3,255),ftNormal); oStr := False; Exit; end else if z = '%!' then begin x := Copy(s,3,255); while x[1] = ' ' do Dec(x[0]); ct := Pos(' ',x); if ct > 0 then begin s := Copy(x,ct+1,255); Delete(x,ct,255); end else s := ''; iplExecute(x,s); oStr := False; Exit; end else if z = '%|' then begin Delete(s,1,2); ct := centerPos(s); if ct < 1 then ct := 1; if ct > 39 then ct := 39; oPosX(ct); end else if z = '%>' then begin Delete(s,1,2); ct := 80-Length(noColor(s)); if ct < 1 then ct := 1; oPosX(ct); end; while N < Ord(s[0]) do begin Inc(N); if nps > 0 then begin Dec(nps); oWriteChar(s[N]); end else if S[N] = mciHeader then begin if mciProcessMCICode(Copy(S,N,3)) then begin Delete(S,N,3); if mciPad then mciString := Resize(mciString,mciLimit) else mciString := strSquish(mciString,mciLimit); Insert(mciString,S,N); nps := Ord(mciString[0]); Dec(N); end else oWriteChar(S[N]); end else if S[N] = ctrHeader then begin if copy(s,n+1,2) = '**' then begin ex := oWhereX; ey := oWhereY; ec := col; Delete(S,N,3); Dec(n); end else if mciProcessControlCode(Copy(S,N,3)) then begin Delete(S,N,3); Dec(N); end else oWriteChar(S[N]); end else if S[N] in [posHeader,rowHeader,limHeader,padHeader] then begin if (S[N+1] in ['0'..'9']) and (S[N+2] in ['0'..'9']) then begin case S[n] of posHeader : oPosX(strToInt(S[N+1]+S[N+2])); rowHeader : oPosY(strToInt(S[N+1]+S[N+2])); limHeader : begin mciPad := False; mciLimit := StrToInt(S[N+1]+S[N+2]); end; padHeader : begin mciPad := True; mciLimit := StrToInt(S[N+1]+S[N+2]); end; end; Delete(S,N,3); Dec(N); end else oWriteChar(S[N]); end else oWriteChar(S[N]); end; if ex <> 0 then begin oGotoXY(ex,ey); oSetColRec(ec); end; end; procedure oStrLn(S : String); begin if oStr(S) then oDnLn(1); end; procedure oStrCtr(S : String); var Cd : String; N, ex, ey : Byte; ec : tColorRec; begin N := 0; ex := 0; while (S <> '') and (N < Length(S)) do begin Inc(N,1); if S[N] = ctrHeader then begin if copy(s,n+1,2) = '**' then begin ex := oWhereX; ey := oWhereY; ec := col; Delete(S,N,3); Dec(n); end else if mciProcessControlCode(Copy(S,N,3)) then begin Delete(S,N,3); Dec(n); end else oWriteChar(S[N]); end else oWriteChar(S[N]); end; if ex <> 0 then begin oGotoXY(ex,ey); oSetColRec(ec); end; end; procedure oStrCtrLn(S : String); begin oStrCtr(S); if not HangUp then oDnLn(1); end; { procedure oStrLn(S : String); begin oStr(S); oDnLn(1); end; } procedure oString(Z : Word); begin { if NoColor(mStr(Z]) = mStr(Z] then oSetCol(colInfo);} oStr(mStr(Z)); end; procedure oStringLn(Z : Word); begin { if NoColor(mStr(Z]) = mStr(Z] then oSetCol(colInfo);} oStrLn(mStr(Z)); end; function oWhereX : Byte; begin oWhereX := ioWhereX; end; function oWhereY : Byte; begin oWhereY := ioWhereY; end; procedure oBack(N : Byte); var Z : Byte; begin for Z := 1 to N do oBackspace(' '); end; procedure oClrEol; begin ioClrEol; if (not LocalIO) and (RemoteOut) then begin if emuTextFX then putstring(#27'K') else if emuAvatar then putstring(^V^K) else putstring(#27+'[K'); end; end; procedure oSaveCursor; begin savX := oWhereX; savY := oWhereY; end; procedure oRestoreCursor; begin oGotoXY(savX,savY); end; procedure oWriteRem(S : String); begin if (not LocalIO) and (RemoteOut) then putstring(S); end; procedure oWritePw(S : String); begin if Cfg^.ShowPwLocal then ioWrite(S) else ioWrite(strEcho(S)); if (not LocalIO) and (RemoteOut) then putstring(strEcho(S)); end; procedure oUpPause(R : Word); begin begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); if PausePos = 0 then Exit; Inc(PausePos,R); if PausePos >= User^.PageLength then begin PausePos := 1; oPause; end; end; begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); procedure oPosX(X : Integer); var P : Integer; begin P := oWhereX; if X > P then oMoveRight(X-P) else begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); if X < P then oMoveLeft(P-X); end; procedure oPosY(Y : Integer); var P : Integer; begin P := oWhereY; if Y > P then oMoveDown(Y-P) else if Y < P then oMoveUp(P-Y); end; end. begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char); begin putstring(oAnsiCode(col,T)); ioTextColRec(T); end; end else ioTextColRec(T); end; procedure oWriteChar(C : Char);
unit uConstant; interface type TAzRotator = (az450, az360); TElRotator = (el180, el90, elNone); TRotateMode = (gsNormal, gsOverlap, gsFlip, gsCrossing); TControlMode = (ctNone, ctManual, ctTracking); const cnCalsat: string = 'CALSAT32'; cnCalsatText: string = 'CALSAT32(SGP)'; cnNodeMain: string ='/Main'; cnNodeAlert: string ='/Alert'; cnRegistry: string = '/Registry'; cnNodeOptions: string = '/Options'; cnNodeApp: string = '/Options/App'; cnNodeCom: string = '/Options/Com'; cnNodeGs232: string = '/Options/GS232'; cnInterval: string = 'Interval'; cnApp: string ='App'; cnLeft: string ='Left'; cnTop: string = 'Top'; cnTabIndex: string = 'TabIndex'; cnInifile: string = 'Inifile'; cnElements: string = 'Elements'; cnRegKey: string = 'RegKey'; cnComPort: string = 'ComPort'; cnBaudRate: string = 'BaudRate'; cnDataBits: string = 'DataBits'; cnParity: string = 'Parity'; cnStopBits: string = 'StopBits'; cnFlowControl: string = 'FlowControl'; cnAzRotator: string = 'AzRotator'; cnElRotator: string = 'ElRotator'; cnParkingAz: string = 'ParkingAz'; cnParkingEl: string = 'ParkingEl'; cnGoParking: string = 'GoParking'; cnRotateSpeed: string = 'RotateSpeed'; cnAzOffset: string = 'AzOffset'; cnRotateMode: string = 'RotateMode'; cnRotateModeName: array[0..3] of string = ('Normal', 'Overlap', 'Flip', 'Crossing'); cnPreAOSTime: string = 'PreAosTime'; cnAlert: string = 'Alert'; implementation end.
Unit morphio; Interface uses SysUtils; const {$IFDEF MSWINDOWS} PathSeparator='\'; {$ELSE} PathSeparator='/'; {$ENDIF} {$IFDEF MSWINDOWS} CrLf=#13#10; {$ELSE} CrLf=#10; {$ENDIF} Const // Stream access/permission flags smRead = 1; smWrite = 2; smDynamic = 4; smShared = 8; smAppend = 16; smDefault = 7; //lfRead Or lfWrite or lfDynamic Type FilePointer=File; LStreamParseMethod=Function(Var Buffer;Size:Integer):Integer Of Object; LStreamStringParseMethod=Procedure(Var S:String) Of Object; LStreamParseMode=(spRead,spWrite); LStreamByteOrder=(sbLittleEndian, sbBigEndian); LStream=Class Protected _Offset:Integer; _Pos:Integer; _Mode:Integer; _Order:LStreamByteOrder; _Size:Integer; _Name:String; b3d_stack:array[0..100]of integer; b3d_tos:Integer; Procedure _WriteString(Var S:String); Function GetEOF:Boolean;Virtual; Public Parse:LStreamParseMethod; ParseString:LStreamStringParseMethod; ParseMode:LStreamParseMode; Procedure WriteTag(S:String); procedure b3dBeginChunk(tag:string); procedure b3dEndChunk(); Constructor Create(StreamMode:Integer=smDefault); Destructor Destroy;Reintroduce;Virtual;Abstract; Function Read(Var Buffer; Length:Integer):Integer;Virtual;Abstract; Function Write(Var Buffer; Length:Integer):Integer;Virtual;Abstract; Procedure EndianSwapWord(Var N:Word); Procedure EndianSwapLong(Var N:Cardinal); Procedure ReadString(Var S:String);Virtual; Procedure ReadLine(Var S:String);Virtual; Procedure WriteString(S:String);Virtual; Procedure WriteLine(S:String='');Virtual; Procedure Copy(Dest:LStream);Overload; Procedure Copy(Dest:LStream;Offset,Count:Integer);Overload; Procedure CopyText(Dest:LStream); Procedure SetParseMode(Mode:LStreamParseMode); Procedure Seek(NewPosition:Integer);Virtual; Procedure Skip(Size:Integer);Virtual; Procedure Truncate;Virtual; function writeInt(v: integer) : Integer; function writefloat(v: single) : Integer; function WriteByte( value: integer) : integer; function writeShort(v: byte) : integer; function writeChar(v: integer) : integer; function readint() : Integer; function readfloat() : single; function ReadChar():string; Property Position:Integer Read _Pos Write Seek; Property Size:Integer Read _Size; Property Mode:Integer Read _Mode; Property ByteOrder:LStreamByteOrder Read _Order Write _Order; Property EOF:Boolean Read GetEOF; Property Name:String Read _Name Write _Name; End; LFileStream=Class(LStream) Protected _File:FilePointer; _Open:Boolean; Public Constructor Create(FileName:String; StreamMode:Integer=smDefault);Overload; Constructor Open(FileName:String; StreamMode:Integer=smDefault; Offset:Integer=0; MaxSize:Integer=-1); Destructor Destroy;Override; Destructor Delete; Procedure Rename(NewName:String); Procedure Truncate;Override; Function Read(Var Buffer; Length:Integer):Integer;Override; Function Write(Var Buffer; Length:Integer):Integer;Override; Procedure Seek(NewPosition:Integer);Override; End; LMemoryStream=Class(LStream) Protected _Buffer:Pointer; Public Constructor Create(BufferSize:Integer; StreamMode:Integer=smDefault);Overload; Constructor Create(BufferSize:Integer;Buffer:Pointer; StreamMode:Integer=smDefault);Overload; Constructor Open(FileName:String; StreamMode:Integer=smDefault);Overload; Destructor Destroy;Override; Procedure SetBuffer(BufferSize:Integer;Buffer:Pointer); Function Read(Var Buffer; Length:Integer):Integer;Override; Function Write(Var Buffer; Length:Integer):Integer;Override; function ReadBuffer(var Buffer; Count: Longint): Longint; Procedure Truncate;Override; Procedure Seek(NewPosition:Integer);Override; procedure LoadFromStream(Stream: LStream); function ReadInt8(Var value: Byte) : boolean; function ReadInt16(Var value: Word) : boolean; overload; function ReadInt16(Var value: SmallInt) : boolean; overload; function ReadInt32(Var value: Longword) : boolean; overload; function ReadInt32(Var value: Longint) : boolean; overload; Property Buffer:Pointer Read _Buffer; End; Type XMLTagType=(xmlBeginTag,xmlEndTag,xmlData); XMLStatus=(xmlWriting,xmlReading); XMLType=(xmlString, xmlBoolean, xmlInteger, xmlCardinal, xmlByte, xmlWord, xmlSingle, xmlVector, xmlColor, xmlTime); XMLDocument=Class; XMLNode=Class; XMLDescriptor=Object Name:String; Address:Pointer; ElementCount:Integer; XMLType:XMLType; Default:String; Found:Boolean; Procedure Read(Node:XMLNode); Procedure Write(Document:XMLDocument; Node:XMLNode); End; XMLElement = Class Protected _Descriptors:Array Of XMLDescriptor; _DescriptorCount:Integer; _Status:XMLStatus; Procedure XMLRegisterElement(Name:String; Address:Pointer; XMLType:XMLType; Default:String=''); Procedure XMLRegisterArrayElement(Name:String; Address:Pointer; XMLType:XMLType; Size:Integer); Procedure XMLLoadElements(Source:XMLNode);Overload; Procedure XMLSaveElements(Document:XMLDocument; Parent:XMLNode=Nil); Public Procedure XMLRegisterStructure; Virtual; Procedure XMLClearStructure; Procedure XMLSynchronize; Virtual; Procedure XMLLoad(Node:XMLNode);Overload; Procedure XMLLoad(Document:XMLDocument);Overload; Procedure XMLSave(Document:XMLDocument);Overload; Procedure XMLLoad(Source:LStream);Overload; Procedure XMLSave(Dest:LStream);Overload; Procedure XMLLoad(FileName:String);Overload; Procedure XMLSave(FileName:String);Overload; Function XMLGetPropertyCount:Integer; Function XMLGetProperty(Index:Integer):XMLDescriptor; Overload; Function XMLGetProperty(Name:String):XMLDescriptor; Overload; Function XMLNewElement(Name:String):XMLElement;Virtual; Function XMLGetElement(Index:Integer):XMLElement;Virtual; Function XMLGetElementCount():Integer;Virtual; Property XMLStatus:XMLStatus Read _Status; End; XMLNode = Class Protected _Name:String; _Value:String; _Childs:Array Of XMLNode; _ChildCount:Integer; _Parent:XMLNode; Procedure Save(Dest:LStream); Function Read(Source:LStream):String; Function GetTagType(S:String):XMLTagType; Function GetTagName(S:String):String; Function GetPath:String; Function GetParentCount:Integer; Public Constructor Create(Name:String; Value:String = ''); Overload; Constructor Create(Source:LStream);Overload; Destructor Destroy;Reintroduce; Function AddTag(Name,Value:String):XMLNode; Procedure AddNode(Node:XMLNode); Function GetNode(Name:String):XMLNode; Function GetChild(Index:Integer):XMLNode; Property Name:String Read _Name; Property Value:String Read _Value Write _Value; Property ChildCount:Integer Read _ChildCount; End; XMLDocument = Class Protected _Root:XMLNode; Public Destructor Destroy;Reintroduce; Procedure Load(Source:LStream);Overload; Procedure Save(Dest:LStream);Overload; Procedure Load(FileName:String);Overload; Procedure Save(FileName:String);Overload; Procedure AddNode(Node:XMLNode; Parent:XMLNode=Nil); Function GetNode(Name:String):XMLNode; Function AddString(Name:String; Value:String=''; Parent:XMLNode=Nil):XMLNode; Function AddBoolean(Name:String; Value:Boolean; Parent:XMLNode=Nil):XMLNode; Function AddInteger(Name:String; Value:Integer; Parent:XMLNode=Nil):XMLNode; Function AddCardinal(Name:String; Value:Cardinal; Parent:XMLNode=Nil):XMLNode; Function AddSingle(Name:String; Value:Single; Parent:XMLNode=Nil):XMLNode; Property Root:XMLNode Read _Root; End; {$R-} Const // LZSS Parameters _N=4096; // Size of string buffer _F=60; // Size of look-ahead buffer THRESHOLD=2; _NULL=_N; // End of tree's node // Huffman coding parameters N_CHAR=(256-THRESHOLD+_F); // character code (:= 0..N_CHAR-1) _T=(N_CHAR * 2 - 1); // Size of table _R=(_T - 1); // root position MAX_FREQ=$8000; //update when cumulative frequency reaches to this value Type //TCompressedStream private types Freqtype=Array[0.._T] Of Word; FreqPtr=^FreqType; PntrType=Array[0..PRED(_T + N_Char)] Of SmallInt; PntrPtr=^PntrType; SonType=Array[0..PRED(_T)] Of SmallInt; SonPtr=^SonType; TextBufType=Array[0.._N + _F - 2] Of Byte; TBufPtr=^TextBufType; WordRay=Array[0.._N] Of SmallInt; WordRayPtr=^WordRay; BWordRay=Array[0.._N + 256] Of SmallInt; BWordRayPtr=^BWordRay; LStreamCompressor=Class Private Code,Len:Word; GetBuf:Word; GetLen:Byte; PutLen:Byte; PutBuf:Word; TextSize:Longint; CodeSize:Longint; PrintCount:Longint; Match_Position:SmallInt; Match_Length:SmallInt; Text_Buf:TBufPtr; Lson,Dad:WordRayPtr; Rson:BWordRayPtr; Freq:FreqPtr; // cumulative freq table Prnt:PntrPtr; Son:SonPtr; // pointing children nodes (son[], son[] + 1) StreamSize:Integer; SourceTarget:LStream; DestTarget:LStream; Procedure InitTree; Procedure InsertNode(R:SmallInt); Procedure DeleteNode(P:SmallInt); Procedure GetBytes(Var Data;Count:Word;Var ReadCount:Word); Procedure PutBytes(Var Data;Count:Word;Var WriteCount:Word); Procedure Update(C:SmallInt); Procedure StartHuff; Procedure Putcode(L:SmallInt;C:Word); Procedure Reconst; Procedure EncodeChar(C:Word); Procedure EncodePosition(C:Word); Procedure EncodeEnd; Function GetBit:SmallInt; Function GetByte:SmallInt; Function DecodeChar:SmallInt; Function DecodePosition:Word; Public Constructor Create; Destructor Destroy;Override; Function Compress(Source,Dest:LStream; PadSize:Integer=4):Integer; Function Decompress(Source,Dest:LStream; PadSize:Integer=4):Integer; Function GetDecompressedSize(Source:LStream; PadSize:Integer=4):Integer; End; type LObjectType=Array[1..4]Of Char; Const leafHeader:LObjectType='SDLK'; resFile:LObjectType= 'FILE'; // User defined file format resSDLKPackage:LObjectType= 'PACK'; // LEAF package lfcAutoLoad=1; //Resource should be autoloaded at start lfcCompressed=2; //Resource is compressed Type LPackageVersion=Packed Record Case Byte Of 0:(Value:Word); 1:(Major,Minor:Byte); End; PResourceInfo=^LResourceInfo; LResourceInfo=Record Tag:LObjectType; // Resource type tag Name:String; // Resource name FileName:String; // Resource filename Offset:Longint; // Offset of the resource Size:Longint; // Size of the resource (bytes) Flags:Byte; // Flags-Not used yet End; LResourceTable=Array Of LResourceInfo; LPackage=Class Private _Offset:Cardinal; // Position of the package within the file _DataOffset:Cardinal; // Header size, files data starts here _TableOffset:Cardinal; // Table position in the file _Version:LPackageVersion; _Size:Longint; // Size of the package, may differ from the file size _FileName:String; // File containing the package _Name:String; // Package name _Table:LResourceTable; // List of all resources within the file _TableSize:Integer; // Number of resources in the table _Loader:LMemoryStream; // Writes the package header to the file Procedure RebuildHeader(Dest:LStream); // Rebuild internal file table Procedure RebuildFileTable(Dest:LStream); Function GetNewOffset(Size:Integer):Integer; Public Path:String; // File override path Constructor Create();overload; Constructor Create(FileName,PackageName:String); overload;// Creates a new empty package function OpenAsset(FileName:String):boolean; Constructor OpenMemory(str:pointer;size:integer); destructor Destroy(); procedure ListFiles(); function GetFile(name:string;var buffer:pointer;var buffersize:integer):boolean;overload; function GetFile(name:string;Var Dest:LStream):boolean;overload; Function FindResource(ResourceName:String):PResourceInfo; Function GetResource(ResourceName:String):PResourceInfo; // Loads a resource into a stream // Note: If resource file is found in search path the is loaded from there // This can be used for patches/mods Procedure LoadResource(Resource:PResourceInfo;Var Dest:LStream); // Loads a resource into a stream // Unlike resource, this always gets the resource from the package Procedure ExtractResource(Resource:PResourceInfo;Var Dest:LStream); // Get file stream containing the resource Function OpenResource(Resource:PResourceInfo):LFileStream; //Adds a resource to the package Function AddResource(ResourceName:String;ResourceType:LObjectType;Resource:LStream;ResourceFlags:Byte=0):PResourceInfo; Function AddFile(FileName:String):PResourceInfo; Function Add(FileName:String):boolean; Procedure DeleteResource(Resource:PResourceInfo); // Package name Property Name:String Read _Name; Property FileName:String Read _FileName; Property ItemCount:Integer Read _TableSize; Property Size:Integer Read _Size; Property Version:LPackageVersion Read _Version; End; Function IntMax(Const A,B:Integer):Integer; Function IntMin(Const A,B:Integer):Integer; Function LongMax(Const A,B:Cardinal):Cardinal; Function LongMin(Const A,B:Cardinal):Cardinal; Function GetNextLine(Var S:String):String; Function GetNextWord(Var S:String; Separator:Char=' '):String; Function GetNextArg(Var S:String):String; Function GetNextToken(Var S:String; Separator:Char=','; Op:Char='(';Ed:Char=')'):String; Function FindCloseBracket(Const S:String; Op:Char='(';Ed:Char=')'):Integer; Function TrimLeft(Const S:String):String; Function TrimRight(Const S:String):String; Function UpStr(Const S:String):String; Function LowStr(Const S:String):String; Function CapStr(Const S:String):String; Function StrLPad(S:String;N:Integer; Token:Char='0'):String; Function StrRPad(S:String;N:Integer; Token:Char='0'):String; Function StrClean(Const S:String):String; Function IntToString(Const N:Integer):String; Function LongToString(Const N:Cardinal):String;Overload; Function FloatToString(Const N:Single):String; Function BoolToString(Const N:Boolean):String;Overload; Function TicksToString(Const N:Cardinal):String;Overload; Function MemoryToString(Const N:Cardinal):String; Function HexStr(Const Value:Byte):String;Overload; Function HexStr(Const Value:Word):String;Overload; Function HexStr(Const Value:Cardinal):String;Overload; Function StringToBase64(Buf:String):String; Function Base64ToString(B64:String):String; Procedure ReplaceText(Const Token,Value:String; Var S:String); Procedure ReplaceAllText(Const Token,Value:String; Var S:String); Function PosRev(Const SubStr,Str:String):Integer; Function UnicodeChar(Code:Word):String; Function StringToInt(Const S:String):Integer; Function StringToLong(Const S:String):Cardinal; Function StringToBool(Const S:String):Boolean; Function StringToFloat(Const S:String):Single; Function GetFilePath(FileName:String):String; Function GetLastFilePath(FileName:String):String; Function GetFirstFilePath(FileName:String):String; Function GetFileName(FileName:String;Const RemoveExt:Boolean):String; Function GetFileExt(FileName:String):String; //Function GetCRC32(Source:LStream):Cardinal;overload; //Function GetCRC32(Source:LStream; Start,Length:Integer):Cardinal;overload; function FileExists(Const FileName:String):Boolean; Function OpenFileStream(FileName:String; StreamMode:Integer=smDefault):LStream; Implementation Function OpenFileStream(FileName:String; StreamMode:Integer=smDefault):LStream; Begin Result:=LFileStream.Open(FileName, StreamMode); End; Function FileExists(Const FileName:String): Boolean; Begin Result:=(FileAge(FileName)<>-1); End; Procedure RaiseError(Const Desc:String); Begin writeln(Desc); End; Procedure FileSeek(Var F:FilePointer; Offset:Integer); Begin System.Seek(F, Offset); End; Procedure FileTruncate(Var F:FilePointer); Begin System.Truncate(F); End; Procedure FileRename(Var F:FilePointer; Name:String); Begin System.Rename(F, Name); End; Function DefaultFileExists(Const FileName:String): Boolean; Begin Result:=(FileAge(FileName)<>-1); End; Var SystemEndian:LStreamByteOrder; Function ByteSwap32(Const A:Cardinal):Cardinal; Var B1,B2,B3,B4:Byte; Begin B1:=A And 255; B2:=(A Shr 8) And 255; B3:=(A Shr 16)And 255; B4:=(A Shr 24)And 255; Result:=(Cardinal(B1)Shl 24) + (Cardinal(B2) Shl 16) + (Cardinal(B3) Shl 8) + B4; End; Function ByteSwap16(A:Word):Word; Var B1,B2:Byte; Begin B1:=A And 255; B2:=(A Shr 8) And 255; Result:=(B1 Shl 8)+B2; End; //{$ENDIF} {***************** TStream Object *****************} Constructor LStream.Create(StreamMode:Integer=smDefault); Begin _Name:=''; _Mode:=StreamMode; _Order:=SystemEndian; _Pos:=0; _Offset:=0; b3d_tos:=0; End; procedure LStream.b3dBeginChunk(tag:string); begin Inc(b3d_tos); WriteTag(tag); writeInt(0); b3d_stack[b3d_tos]:=Position; end; procedure LStream.b3dEndChunk(); var n:Integer; begin n:=Position; Seek(b3d_stack[b3d_tos]-4); writeInt(n-b3d_stack[b3d_tos]); Seek(n); b3d_tos:=b3d_tos-1; end; Procedure LStream.EndianSwapWord(Var N:Word); Begin If ByteOrder=SystemEndian Then Exit; N:=ByteSwap16(N); End; Procedure LStream.EndianSwapLong(Var N:Cardinal); Begin If ByteOrder=SystemEndian Then Exit; N:=ByteSwap32(N); End; Procedure LStream.SetParseMode(Mode:LStreamParseMode); Begin ParseMode:=Mode; Case Mode Of spRead: Begin Parse:=Read; ParseString:=ReadString; End; spWrite:Begin Parse:=Write; ParseString:=_WriteString; End; End; End; Function IntMax(Const A,B:Integer):Integer; Begin If A>B Then Result:=A Else Result:=B; End; Function IntMin(Const A,B:Integer):Integer; Begin If A<B Then Result:=A Else Result:=B; End; Procedure LStream.Copy(Dest:LStream); Var Count,BytesRead:Integer; Buffer:Pointer; BufferSize:Integer; BlockSize:Integer; A,B:Integer; Begin If (Self.ByteOrder<>Dest.ByteOrder) Then writeln('IO','Destination byte order differs from source.'); Seek(0); Count:=Self.Size; If (Dest.Size-Dest.Position<Count)And(Dest.Mode And smDynamic=0) Then Count:=Dest.Size-Dest.Position; BufferSize:=65534; If Count<BufferSize Then BufferSize:=Count; GetMem(Buffer,BufferSize); BytesRead:=0; While BytesRead<Count Do Begin A:=Self.Size-Self.Position; B:=Dest.Size-Dest.Position; If Dest.Mode And smDynamic<>0 Then B:=A; BlockSize:=IntMin(IntMin(BufferSize,Count-BytesRead), IntMin(A,B)); Read(Buffer^,BlockSize); Dest.Write(Buffer^,BlockSize); Inc(BytesRead,BlockSize); End; FreeMem(Buffer,BufferSize); End; Procedure LStream.Copy(Dest:LStream;Offset,Count:Integer); Var BytesRead:Integer; Buffer:Pointer; BufferSize:Integer; BlockSize:Integer; A,B:Integer; Begin If (Self.ByteOrder<>Dest.ByteOrder) Then writeln('IO','Destination byte order differs from source.'); Seek(Offset); If (Dest.Size-Dest.Position<Count)And(Dest.Mode And smDynamic=0) Then Count:=Dest.Size-Dest.Position; BufferSize:=65534; If Count<BufferSize Then BufferSize:=Count; GetMem(Buffer,BufferSize); BytesRead:=0; While BytesRead<Count Do Begin A:=Self.Size-Self.Position; If A=0 Then Begin writeln('Buffer too small.'); Exit; End; B:=Dest.Size-Dest.Position; If Dest.Mode And smDynamic<>0 Then B:=A; BlockSize:=IntMin(IntMin(BufferSize,Count-BytesRead), IntMin(A,B)); Read(Buffer^,BlockSize); Dest.Write(Buffer^,BlockSize); Inc(BytesRead,BlockSize); End; FreeMem(Buffer,BufferSize); End; Procedure LStream.CopyText(Dest:LStream); Var C:Char; S:String; Begin S:=''; While Self.Position<Self.Size Do Begin Read(C,1); If (C=#10) Then Dest.WriteString(S) Else S:=S+C; End; End; Procedure LStream.Seek(NewPosition:Integer); Begin _Pos:=NewPosition; End; Procedure LStream.Skip(Size:Integer); Begin If Size=0 Then Exit; Seek(_Pos+Size); End; Procedure LStream.Truncate; Begin writeln('IO','Method not supported in this stream.'); End; Procedure LStream.ReadString(Var S:String); Var Len:Word; N:Byte; Begin Read(N,1); If N=255 Then Read(Len,2) Else Len:=N; SetLength(S,Len); If Len>0 Then Read(S[1],Len); End; function LStream.WriteByte( value: integer) : integer; begin write(value, 1); Result:=1; end; function LStream.writeShort( v: byte) : integer; begin WriteByte( (v shr 8) and $ff); WriteByte( (v shr 0) and $ff); Result:=2; end; function LStream.writeChar( v: integer) : integer; begin WriteByte( (v shr 8) and $ff); WriteByte( (v shr 0) and $ff); Result:=4; end; { function LStream.writeInt( v: integer) : Integer; begin WriteByte( (v shr 24) and $ff); WriteByte( (v shr 16) and $ff); WriteByte( (v shr 8) and $ff); WriteByte( (v shr 0) and $ff); Result:=8; end; } function LStream.ReadChar():string; var i:Integer; begin i:=readint(); SetLength(Result,i); read(PChar(result)^,i); end; Procedure LStream.WriteString(S:String); Var N:Byte; i:Integer; len: cardinal; oString: UTF8String; begin { len:=Length(s); Writeln(len); WriteInt(len); for i:=1 to len do write(s[i], 1); } i:=Length(s); writeInt(i); Write(PChar(s)^,i); { Len:=Length(S); If Len<255 Then N:=Len Else N:=255; Write(N,1); If Len>=255 Then Write(Len,2); If Len>0 Then Write(S[1],Len);} End; Procedure LStream.WriteTag(S:String); Var len: cardinal; begin Len:=Length(S); Write(PChar(s)^,len); End; Procedure LStream._WriteString(Var S:String); Begin WriteString(S); End; Procedure LStream.WriteLine(S:String); Begin S:=S+#13#10; Write(S[1],Length(S)); End; function LStream.writeInt(v: integer) : Integer; begin write(v,4); end; function LStream.readint() : Integer; begin read(result,4); end; function LStream.readfloat() : single; begin read(result,4); end; function LStream.writefloat(v: single) : Integer; begin write(v,4); end; Procedure LStream.ReadLine(Var S:String); Var C:Char; Begin S:=''; C:=#0; While (C<>#10)And(Position<Size) Do Begin Read(C,1); If (C<>#10)Or(C<>#13) Then S:=S+C; End; S:=TrimRight(S); End; Function LStream.GetEOF:Boolean; Begin Result:=Position>=Size; End; {************************** TFileStream Object **************************} Constructor LFileStream.Create(FileName:String; StreamMode:Integer=smDefault); Begin Inherited Create(StreamMode); // writeln('IO','Opening '+FileName); If StreamMode=0 Then writeln('Invalid file mode.['+FileName+']') Else Begin _Name:=FileName; FileMode:=2; AssignFile(_File,_Name); Rewrite(_File,1); _Size:=0; _Open:=True; End; End; Constructor LFileStream.Open(FileName:String; StreamMode:Integer=smDefault; Offset:Integer=0; MaxSize:Integer=-1); Begin Inherited Create(StreamMode); _Open:=False; _Name:=FileName; If StreamMode=0 Then Begin writeln('Invalid file mode. ['+FileName+']'); Exit; End Else Begin _Offset:=Offset; AssignFile(_File,_Name); Reset(_File,1); _Size:=FileSize(_File); If (MaxSize>0) And (MaxSize<_Size) Then _Size:=MaxSize; If _Offset>0 Then FileSeek(_File,_Offset); _Open:=True; End; End; Destructor LFileStream.Destroy; Begin If Not _Open Then Exit; CloseFile(_File); End; Destructor LFileStream.Delete; Begin If Not _Open Then Exit; CloseFile(_File); Erase(_File); End; Procedure LFileStream.Truncate; Begin If Not _Open Then Exit; FileTruncate(_File); _Size:=_Pos; End; Procedure LFileStream.Rename(NewName:String); Begin If Not _Open Then Exit; _Name:=NewName; CloseFile(_File); Erase(_File); FileRename(_File,_Name); AssignFile(_File,_Name); Reset(_File,1); Seek(Position); End; Function LFileStream.Read(Var Buffer; Length:Integer):Integer; Begin If (Length=0)Or(Not _Open) Then Begin Result:=0; Exit; End; If (_Mode And smRead=0)Or(_Pos>=_Size) Then Begin Result:=0; writeln('Cannot read from file. ['+_Name+']'); Exit; End; If (_Pos+Length>_Size)Then Length:=_Size-_Pos; BlockRead(_File,Buffer, Length); Inc(_Pos, Length); Result:=Length; Case Length Of 2:EndianSwapWord(Word(Buffer)); 4:EndianSwapLong(Cardinal(Buffer)); End; End; Function LFileStream.Write(Var Buffer; Length:Integer):Integer; Begin Result:=0; If (Not _Open) Then Exit; If (_Mode And smWrite=0)Then Begin writeln('File is write protected.['+_Name+']'); Exit; End; If (_Pos>=_Size)And(_Mode And smDynamic=0) Then Begin writeln('Cannot write to file.['+_Name+']'); Exit; End; // Swap the bytes to proper order If (ByteOrder<>SystemEndian) Then Begin Case Length Of 2:EndianSwapWord(Word(Buffer)); 4:EndianSwapLong(Cardinal(Buffer)); {Else If (Length>4) Then RaiseError(ltWarning,'IO','FileStream.Write','Possible data corruption. Endian doesn''''t match.');} End; End; BlockWrite(_File,Buffer,Length); Inc(_Pos, Length); If _Pos>_Size Then _Size:=_Pos; // Restore the bytes order If (ByteOrder<>SystemEndian) Then Begin Case Length Of 2:EndianSwapWord(Word(Buffer)); 4:EndianSwapLong(Cardinal(Buffer)); End; End; Result:=Length; End; Procedure LFileStream.Seek(NewPosition:Integer); Begin If _Pos>_Size Then Begin writeln('Cannot seek in file.['+_Name+']'); Exit; End; _Pos:=NewPosition; FileSeek(_File, _Pos+_Offset); End; {*************************** TMemoryStream object ***************************} Constructor LMemoryStream.Create(BufferSize:Integer; StreamMode:Integer=smDefault); Begin //RaiseError('IO','MemoryStream.Create','Allocating '+MemStr(Size)); If (StreamMode And smDynamic<>0) Then StreamMode:=StreamMode Xor smDynamic; If (StreamMode And smShared<>0) Then StreamMode:=StreamMode Xor smShared; Inherited Create(StreamMode); _Size:=BufferSize; GetMem(_Buffer,_Size); _Pos:=0; End; Constructor LMemoryStream.Create(BufferSize:Integer; Buffer:Pointer; StreamMode:Integer=smDefault); Begin If (StreamMode And smShared=0) Then StreamMode:=StreamMode Or smShared; Inherited Create(StreamMode); _Size:=BufferSize; _Buffer:=Buffer; _Pos:=0; End; Constructor LMemoryStream.Open(FileName:String; StreamMode:Integer=smDefault); Var F:FilePointer; Begin Inherited Create(StreamMode); AssignFile(F,FileName); Reset(F,1); _Size:=FileSize(F); Create(_Size, StreamMode); BlockRead(F,_Buffer^,_Size); CloseFile(F); End; Destructor LMemoryStream.Destroy; Begin If _Mode And smShared=0 Then Begin //RaiseError('IO','MemoryStream.Destroy','Releasing '+MemStr(Size)); FreeMem(_Buffer,_Size); End; _Buffer:=Nil; End; { function LMemoryStream.ReadString(Var text: String) : boolean; var readedOk: boolean; lenChar: Word; character: Char; begin lenChar := SizeOf(Char); character := Char(1); text := ''; readedOk := (ReadBuffer(character, lenChar)>0); while((readedOk) and (character <> Char(0))) do begin text := text + character; readedOk := (ReadBuffer(character, lenChar)>0); end; result := readedOk; end; } function LMemoryStream.ReadInt8(Var value: Byte) : boolean; begin result := (ReadBuffer(value, SizeOf(Byte))>0); end; function LMemoryStream.ReadInt16(Var value: Word) : boolean; begin result := (ReadBuffer(value, SizeOf(Word))>0); end; function LMemoryStream.ReadInt16(Var value: SmallInt) : boolean; begin result := (ReadBuffer(value, SizeOf(SmallInt))>0); end; function LMemoryStream.ReadInt32(Var value: Longword) : boolean; begin result := (ReadBuffer(value, SizeOf(Longword))>0); end; function LMemoryStream.ReadInt32(Var value: Longint) : boolean; begin result := (ReadBuffer(value, SizeOf(Longint))>0); end; function LMemoryStream.ReadBuffer(var Buffer; Count: Longint): Longint; begin if (_Pos >= 0) and (Count >= 0) then begin Result := _Size - _Pos; if Result > 0 then begin if Result > Count then Result := Count; Move(Pointer(Longint(_Buffer) + _Pos)^, Buffer, Result); Inc(_Pos, Result); Exit; end; end; Result := 0; end; Function LMemoryStream.Read(Var Buffer; Length:Integer):Integer; Var P:Pointer; Begin If (Length=0) Then Begin Result:=0; Exit; End; If Not Assigned(_Buffer) Then Begin writeln('Buffer not assigned.'); Result:=0; Exit; End; If (_Pos>=_Size) Then Begin writeln('Cannot read from memory.'); Result:=0; Exit; End; If (_Pos+Length>_Size)Then Length:=_Size-_Pos; P:=Pointer(Integer(_Buffer)+_Pos); Case Length Of 1: Begin Byte(Buffer):=Byte(P^); End; 2: Begin Word(Buffer):=Word(P^); EndianSwapWord(Word(Buffer)); End; 4: Begin Cardinal(Buffer):=Cardinal(P^); EndianSwapLong(Cardinal(Buffer)); End; Else Begin Move(P^,Buffer,Length); End; End; Inc(_Pos,Length); Result:=Length; End; procedure LMemoryStream.LoadFromStream(Stream: LStream); var Count: Longint; begin Stream.Position := 0; Count := Stream.Size; _Size:=Count; if Count <> 0 then Stream.Read(buffer^, Count); end; Function LMemoryStream.Write(Var Buffer; Length:Integer):Integer; Var P:Pointer; Begin Result:=0; If Not Assigned(_Buffer) Then Begin writeln('Buffer not assigned.'); Exit; End; If (_Pos>=_Size) Then Begin writeln('Cannot write to memory.'); Exit; End; If (_Pos+Length>_Size)Then Length:=_Size-_Pos; P:=Pointer(Integer(_Buffer)+_Pos); Case Length Of 1: Begin Byte(P^):=Byte(Buffer); End; 2: Begin Word(P^):=Word(Buffer); EndianSwapWord(Word(P^)); End; 4: Begin Cardinal(P^):=Cardinal(Buffer); EndianSwapLong(Cardinal(P^)); End; Else Begin Move(Buffer,P^,Length); {If (Size>4) Then RaiseError(ltWarning,'IO','MemoryStream.Write','Possible data corruption. Endian doesn''''t match.');} End; End; Inc(_Pos, Length); Result:=Length; End; Procedure LMemoryStream.Seek(NewPosition:Integer); Begin If Position>_Size Then Begin writeln('Cannot seek in memory.'); Exit; End; _Pos:=NewPosition; End; Procedure LMemoryStream.Truncate; Var Ptr:Pointer; Begin GetMem(Ptr,_Pos); Move(_Buffer^,Ptr^,_Pos); FreeMem(_Buffer,_Size); _Size:=_Pos; _Buffer:=Ptr; End; Procedure LMemoryStream.SetBuffer(BufferSize:Integer;Buffer:Pointer); Begin _Size:=BufferSize; _Buffer:=Buffer; _Pos:=0; End; Function DefaultOpenFileStream(FileName:String; StreamMode:Integer=smDefault):LStream; Begin Result:=LFileStream.Open(FileName, StreamMode); End; Procedure DetectSystemEndian; Var I:Cardinal; P:PByte; Begin I:=1; P:=@I; If (P^=1) Then // Lowest address contains the least significant byte SystemEndian:=sbLittleEndian Else SystemEndian:=sbBigEndian; End; Const // Tables FOR encoding/decoding upper 6 bits of sliding dictionary pointer // Encoder table P_Len:Array[0..63] Of Byte = ($03, $04, $04, $04, $05, $05, $05, $05, $05, $05, $05, $05, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08); P_Code:Array[0..63] Of Byte = ($00, $20, $30, $40, $50, $58, $60, $68, $70, $78, $80, $88, $90, $94, $98, $9C, $A0, $A4, $A8, $AC, $B0, $B4, $B8, $BC, $C0, $C2, $C4, $C6, $C8, $CA, $CC, $CE, $D0, $D2, $D4, $D6, $D8, $DA, $DC, $DE, $E0, $E2, $E4, $E6, $E8, $EA, $EC, $EE, $F0, $F1, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA, $FB, $FC, $FD, $FE, $FF); // decoder table D_Code:Array[0..255] Of Byte = ($00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $01, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $04, $04, $04, $04, $04, $04, $04, $04, $05, $05, $05, $05, $05, $05, $05, $05, $06, $06, $06, $06, $06, $06, $06, $06, $07, $07, $07, $07, $07, $07, $07, $07, $08, $08, $08, $08, $08, $08, $08, $08, $09, $09, $09, $09, $09, $09, $09, $09, $0A, $0A, $0A, $0A, $0A, $0A, $0A, $0A, $0B, $0B, $0B, $0B, $0B, $0B, $0B, $0B, $0C, $0C, $0C, $0C, $0D, $0D, $0D, $0D, $0E, $0E, $0E, $0E, $0F, $0F, $0F, $0F, $10, $10, $10, $10, $11, $11, $11, $11, $12, $12, $12, $12, $13, $13, $13, $13, $14, $14, $14, $14, $15, $15, $15, $15, $16, $16, $16, $16, $17, $17, $17, $17, $18, $18, $19, $19, $1A, $1A, $1B, $1B, $1C, $1C, $1D, $1D, $1E, $1E, $1F, $1F, $20, $20, $21, $21, $22, $22, $23, $23, $24, $24, $25, $25, $26, $26, $27, $27, $28, $28, $29, $29, $2A, $2A, $2B, $2B, $2C, $2C, $2D, $2D, $2E, $2E, $2F, $2F, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $3E, $3F); D_Len:Array[0..255] Of Byte = ($03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $03, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $04, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $05, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $06, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $07, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08, $08); Constructor LStreamCompressor.Create; Begin GetBuf:=0; GetLen:=0; PutLen:=0; PutBuf:=0; TextSize:=0; CodeSize:=0; PrintCount:=0; Match_Position:=0; Match_Length:=0; New(LSon); New(Dad); New(RSon); New(Text_Buf); New(Freq); New(Prnt); New(Son); End; Destructor LStreamCompressor.Destroy; Begin Dispose(Son); Dispose(Prnt); Dispose(Freq); Dispose(Text_buf); Dispose(RSon); Dispose(Dad); Dispose(LSon); End; Procedure LStreamCompressor.GetBytes; Begin If SourceTarget.Position+Count>SourceTarget.Size Then Count:=SourceTarget.Size-SourceTarget.Position; SourceTarget.Read(Data,Count); ReadCount:=Count; End; Procedure LStreamCompressor.PutBytes; Begin DestTarget.Write(Data,Count); WriteCount:=Count; End; Procedure LStreamCompressor.InitTree; Var I:SmallInt; Begin For I:=_N + 1 To _N + 256 Do RSon^[i]:=_NULL; // root For I:=0 To _N Do Dad^[i]:=_NULL; // node End; Procedure LStreamCompressor.InsertNode; Var Tmp,i,p,Cmp:SmallInt; Key:TBufPtr; C:Word; Begin Cmp:=1; Key:=@Text_Buf^[r]; P:=Succ(_N)+Key^[0]; RSon^[r]:=_NULL; LSon^[r]:=_NULL; Match_Length:=0; While Match_Length<_F Do Begin If (Cmp>=0) Then Begin If (RSon^[p]<>_NULL)Then Begin p:=rson^[p]; End Else Begin RSon^[p] := r; Dad^[r] := p; Exit; End; End Else Begin If (lson^[p]<>_NULL)Then Begin p:=lson^[p]; End Else Begin lson^[p] := r; dad^[r] := p; Exit; End; End; i:=0; Cmp:=0; While (i < _F)And (Cmp = 0)Do Begin Inc(i); Cmp:=Key^[i] - text_buf^[p + i]; End; If (i > THRESHOLD) Then Begin tmp:=Pred((r - p) And Pred(_N)); If (i>Match_length)Then Begin Match_Position:=tmp; Match_Length:=i; End; If (Match_Length<_F)And(i=Match_length)Then Begin c:=Tmp; If (c<Match_Position)Then Match_Position:=C; End; End; { if i > threshold } End; { WHILE match_length < F } Dad^[r]:=Dad^[p]; LSon^[r]:=LSon^[p]; RSon^[r]:=RSon^[p]; Dad^[LSon^[p]]:=r; Dad^[RSon^[p]]:=r; If(RSon^[dad^[p]] = p)Then Begin RSon^[dad^[p]]:=r; End Else Begin LSon^[dad^[p]]:=r; End; Dad^[p]:=_NULL; // remove p End; Procedure LStreamCompressor.DeleteNode; Var Q:SmallInt; Begin If (Dad^[p]=_NULL)Then Exit; // unregistered If (RSon^[p]=_NULL) Then Begin q:=LSon^[p]; End Else Begin If (LSon^[p]=_NULL)Then Begin q:=RSon^[p]; End Else Begin q:=LSon^[p]; If (RSon^[q]<>_NULL)Then Begin Repeat q:=RSon^[q]; Until (RSon^[q]=_NULL); RSon^[dad^[q]]:=LSon^[q]; Dad^[lson^[q]] := dad^[q]; LSon^[q] := lson^[p]; Dad^[lson^[p]] := q; End; RSon^[q]:=RSon^[p]; Dad^[rson^[p]]:=q; End; End; Dad^[q]:=Dad^[p]; If (RSon^[Dad^[p]]=p)Then RSon^[dad^[p]] := q Else LSon^[dad^[p]] := q; Dad^[p]:=_NULL; End; Function LStreamCompressor.GetBit; Var i:Byte; i2:SmallInt; Wresult:Word; Begin While (GetLen<=8) Do Begin GetBytes(i, 1, Wresult); If WResult=1 Then i2:=i Else i2:=0; GetBuf:=Getbuf Or (i2 Shl (8 - getlen)); Inc(GetLen,8); End; i2:=GetBuf; GetBuf:=GetBuf shl 1; Dec(GetLen); GetBit:=SmallInt((i2 < 0)); End; Function LStreamCompressor.GetByte; Var j:Byte; i,Wresult:Word; Begin While (Getlen <= 8)Do Begin GetBytes(j, 1, Wresult); If Wresult = 1 then i:=j Else i:=0; Getbuf := getbuf or (i shl (8 - getlen)); Inc(GetLen, 8); End; i:=GetBuf; Getbuf:=GetBuf Shl 8; Dec(getlen,8); GetByte:=SmallInt(i Shr 8); end; Procedure LStreamCompressor.Update; Var i,j,k,l:SmallInt; Begin If (Freq^[_R]=MAX_FREQ) Then Reconst; c:=Prnt^[c + _T]; Repeat Inc(freq^[c]); K:=Freq^[c]; // swap nodes to keep the tree freq-ordered L:=Succ(C); If (k>Freq^[l])Then Begin While (k>Freq^[l])Do Inc(l); Dec(l); Freq^[c]:=Freq^[l]; Freq^[l]:=k; i:=Son^[c]; Prnt^[i]:=l; If (i < _T) Then Prnt^[Succ(i)] := l; J:=Son^[l]; Son^[l]:=i; Prnt^[j]:=c; If (j < _T)Then Prnt^[Succ(j)] := c; Son^[c]:=j; C:=l; End; c:=Prnt^[c]; Until (c=0); // REPEAT it until reaching the root End; Procedure LStreamCompressor.StartHuff; Var I,J:SmallInt; Begin For I:=0 To Pred(N_CHAR)Do Begin Freq^[i]:=1; Son^[i]:=i + _T; Prnt^[i + _T]:=i; End; I:=0; J:=N_CHAR; While (j <= _R)Do Begin Freq^[j]:=Freq^[i] + Freq^[i + 1]; Son^[j]:=i; Prnt^[i]:=j; Prnt^[i + 1]:=j; Inc(I,2); Inc(J); End; Freq^[_T]:=$FFFF; Prnt^[_R]:=0; End; Procedure LStreamCompressor.PutCode; Var Temp:Byte; Got:Word; Begin PutBuf:=PutBuf Or(C Shr PutLen); Inc(PutLen,L); If (PutLen>=8)Then Begin Temp:=PutBuf Shr 8; PutBytes(Temp, 1, Got); Dec(putlen, 8); If (PutLen >= 8)Then Begin Temp := Lo(PutBuf); PutBytes(Temp, 1, Got); Inc(codesize, 2); Dec(putlen, 8); PutBuf:=C Shl (L-PutLen); End Else Begin PutBuf:=PutBuf Shl 8; Inc(CodeSize); End; End; End; Procedure LStreamCompressor.Reconst; Var I,J,K,Tmp:SmallInt; F,L:Word; Begin // halven cumulative freq FOR leaf nodes j:=0; For i:=0 To Pred(_T)Do Begin If (Son^[i]>=_T)Then Begin Freq^[j] := Succ(Freq^[i]) Div 2; {@@ Bug Fix MOD -> DIV @@} Son^[j] := Son^[i]; Inc(j); End; End; // make a tree : first, connect children nodes i:=0; j:=N_CHAR; While (j < _T)Do Begin k:=Succ(i); f := freq^[i] + freq^[k]; Freq^[j] := f; k:=Pred(j); While f<Freq^[k] Do Dec(K); Inc(k); l := (j - k) shl 1; tmp := SUCC(k); Move(freq^[k], freq^[tmp], l); Freq^[k] := f; Move(son^[k], son^[tmp], l); Son^[k] := i; Inc(i, 2); Inc(j); End; // connect parent nodes For i:=0 To Pred(_T)Do Begin k:=Son^[i]; If (k >= _T)Then Begin Prnt^[k] := i; End Else Begin Prnt^[k] := i; Prnt^[SUCC(k)] := i; End; End; End; Procedure LStreamCompressor.EncodeChar; Var i:Word; j,k:SmallInt; Begin i:=0; j:=0; k:=Prnt^[c + _T]; // search connections from leaf node to the root Repeat i:=i Shr 1; { IF node's address is odd, output 1 ELSE output 0 } If Boolean(k And 1)Then Inc(i,$8000); Inc(j); k:=Prnt^[k]; Until (k=_R); Putcode(j, i); Code:=i; Len:=j; Update(c); End; Procedure LStreamCompressor.EncodePosition; Var i,j:Word; Begin // output upper 6 bits with encoding i:=c Shr 6; j:=p_code[i]; PutCode(p_len[i],j Shl 8); // output lower 6 bits directly PutCode(6, (c And $3F) Shl 10); End; Procedure LStreamCompressor.EncodeEnd; Var Temp:Byte; Got:Word; Begin If Boolean(PutLen) Then Begin Temp:=Lo(PutBuf Shr 8); PutBytes(Temp,1,Got); Inc(CodeSize); End; End; Function LStreamCompressor.DecodeChar; Var C:Word; Begin c:=Son^[_R]; { * start searching tree from the root to leaves. * choose node #(son[]) IF input bit = 0 * ELSE choose #(son[]+1) (input bit = 1) } While (c < _T) Do Begin c:=c + GetBit; c:=Son^[c]; End; c:=c - _T; Update(c); DecodeChar:=SmallInt(c); End; Function LStreamCompressor.DecodePosition; Var I,J,C:Word; Begin // decode upper 6 bits from given table i:=GetByte; c:=Word(d_code[i] shl 6); j:=d_len[i]; // input lower 6 bits directly Dec(j, 2); While j <> 0 Do Begin i:=(i Shl 1) + GetBit; Dec(J); End; DecodePosition:=c Or i And $3F; End; Function LStreamCompressor.Compress(Source,Dest:LStream; PadSize:Integer=4):Integer; Var Ct:Byte; i,L,R,S,Last_Match_Length:SmallInt; Got:Word; SourceSize:Longint; Begin SourceTarget:=Source; DestTarget:=Dest; Source.Seek(0); TextSize:=0; // rewind and rescan StartHuff; InitTree; s:=0; r:=_N - _F; FillChar(Text_buf^[0], r, ' '); L:=0; Got:=1; While(L < _F)And(Got <> 0)Do Begin GetBytes(ct, 1, Got); If Got <> 0 Then Begin Text_buf^[r+L] := ct; Inc(l); End; End; Textsize := len; For i:=1 To _F Do InsertNode(r - i); InsertNode(r); Repeat If (Match_Length > L)Then Match_Length:=L; If (Match_Length<=THRESHOLD)Then Begin Match_Length:=1; EncodeChar(text_buf^[r]); End Else Begin EncodeChar(255 - THRESHOLD + match_length); EncodePosition(match_position); End; Last_Match_Length:=Match_length; i:=0; Got:=1; While (i < last_match_length)And (Got <> 0) Do Begin GetBytes(ct, 1, Got); If Got <> 0 Then Begin DeleteNode(s); text_buf^[s] := ct; If (s < Pred(_F))Then text_buf^[s + _N]:=ct; s:=Succ(s) And Pred(_N); r:=Succ(r) And Pred(_N); InsertNode(r); Inc(i); End; End; Inc(textsize, i); While (i<Last_Match_Length)Do Begin Inc(i); DeleteNode(s); s:=Succ(s) And Pred(_N); r:=Succ(r) And Pred(_N); Dec(l); If Boolean(Len)Then InsertNode(r); End; Until (L<= 0); EncodeEnd; StreamSize:=TextSize; SourceSize:=Source.Size; Case PadSize Of 1: Begin Ct:=Byte(SourceSize); Dest.Write(Ct,1); End; 2: Begin Got:=Word(SourceSize); Dest.Write(Got,2); End; 4: Dest.Write(SourceSize,SizeOf(SourceSize)); Else writeln('Invalid padsize.'); End; Result:=TextSize; End; Function LStreamCompressor.GetDecompressedSize(Source:LStream; PadSize:Integer=4):Integer; Var N:Byte; W:Word; Begin Source.Seek(Source.Size-SizeOf(StreamSize)); Case PadSize Of 1: Begin Source.Read(N,1); Result:=N; End; 2: Begin Source.Read(W,2); Result:=W; End; 4: Source.Read(Result,SizeOf(Result)); Else writeln('Invalid padsize.'); End; Source.Seek(0); End; Function LStreamCompressor.Decompress(Source,Dest:LStream; PadSize:Integer=4):Integer; Var c,i,j,k,r:SmallInt; c2:Byte; count:Longint; Put:Word; Begin StreamSize:=GetDecompressedSize(Source, PadSize); Result:=StreamSize; SourceTarget:=Source; DestTarget:=Dest; StartHuff; r:=_N - _F; FillChar(text_buf^[0], r, ' '); Count := 0; While Count<StreamSize Do Begin c:=DecodeChar; If (c < 256)Then Begin c2:=Lo(c); PutBytes(c2, 1, Put); text_buf^[r] := c; Inc(r); r:=r And Pred(_N); Inc(count); End Else Begin {c >= 256 } i:=(r - Succ(DecodePosition)) And Pred(_N); j:=c - 255 + THRESHOLD; For K:=0 To Pred(j) Do Begin c:=text_buf^[(i + k) And Pred(_N)]; c2:=Lo(c); PutBytes(c2, 1, Put); text_buf^[r] := c; Inc(r); r:=r And Pred(_N); Inc(count); End; End; End; End; //LPackage class Procedure LPackage.RebuildHeader; Var Tag:LObjectType; Begin Tag:=leafHeader; Dest.Seek(_Offset); Dest.Write(Tag,SizeOf(Tag)); Dest.WriteString(_Name); //Write the name of the package Dest.Write(_TableSize,SizeOf(_TableSize)); //Write tablesize Dest.Write(_TableOffset,SizeOf(_TableOffset)); //Write table offset End; Procedure LPackage.RebuildFileTable(Dest:LStream); Var I:Integer; Begin // SortFileTable; Dest.Seek(_TableOffset); For I:=0 To Pred(_TableSize)Do With _Table[I] Do Begin Dest.Write(Tag,SizeOf(Tag)); //Write resource type tag Dest.WriteString(FileName); //Write resource name Dest.Write(Offset,SizeOf(Offset)); //Write offset of the resource Dest.Write(Size,SizeOf(Size)); //Write size of the resource Dest.Write(Flags,SizeOf(Flags)); //Write flags End; _Version.Major:=2; _Version.Minor:=0; Dest.Write(_Version,SizeOf(_Version)); End; destructor LPackage.Destroy(); begin SetLength(_Table,0); if assigned(_Loader) then _Loader.Destroy; end; Constructor LPackage.Create(FileName,PackageName:String); Var Dest:LFileStream; Begin PackageName:='PACKAGE'; _FileName:=FileName; _Name:=PackageName; _TableSize:=0; _Offset:=0; _TableOffset:=SizeOf(LObjectType)+Succ(Length(_Name))+SizeOf(_TableSize)+SizeOf(_TableOffset); Dest:=LFileStream.Create(FileName); RebuildHeader(Dest); _Size:=Dest.Position; _DataOffset:=Dest.Position; Dest.Destroy; End; Constructor LPackage.Create(); Begin End; function LPackage.OpenAsset(FileName:String):boolean; Var Tag:LObjectType; I,J:Integer; S:String; Begin _FileName:=FileName; If Not FileExists(_FileName) Then Begin RaiseError('File not found. ['+_FileName+']'); result:=false; Exit; End; _Loader:=LMemoryStream.Open(_FileName,smRead); _Size:=_Loader.Size; _Loader.Read(Tag,SizeOf(Tag)); If Tag<>leafHeader Then Begin RaiseError('Invalid header. ['+_FileName+']'); result:=false; Exit; End; _Loader.ReadString(S); //Read package name _Name:=S; _Loader.Read(_TableSize,SizeOf(_TableSize)); //Read filetable info _Loader.Read(_TableOffset,SizeOf(_TableOffset)); _DataOffset:=_Loader.Position; _Loader.Seek(_TableOffset); SetLength(_Table,_TableSize); For I:=0 To Pred(_TableSize)Do With _Table[I] Do Begin _Loader.Read(Tag,SizeOf(Tag)); //Read resource type tag _Loader.ReadString(S); //Read resource name FileName:=S; writeln(s); Name:=UpStr(GetFileName(S,True)); For J:=0 To Pred(I) Do If _Table[J].Name=Name Then Begin RaiseError('Duplicated resource ['+Name+'] in package '+Self._Name+'.'); result:=false; Exit; End; _Loader.Read(Offset,SizeOf(Offset)); // Read offset of the resource _Loader.Read(Size,SizeOf(Size)); // Size of the resource _Loader.Read(Flags,SizeOf(Flags)); // Read flags End; If _Loader.Position<_Loader.Size Then _Loader.Read(_Version,SizeOf(_Version)) Else Begin _Version.Major:=1; _Version.Minor:=0; End; result:=true; End; function LPackage.GetFile(name:string;Var Dest:LStream):boolean; Var Resource:PResourceInfo; Begin Resource:=GetResource(name); if assigned(Resource) then begin // Source:=LFileStream.Open(_FileName,smDefault,_Offset,_Size); _Loader.Copy(Dest,Resource.Offset,Resource.Size); // Source.Destroy; end else begin Assert(Assigned(Resource),'ExtractResource(): Null resource'); result:=false; end; End; function LPackage.GetFile(name:string;var buffer:pointer;var buffersize:integer):boolean; Var Resource:PResourceInfo; Dest:LStream; Begin Resource:=GetResource(name); if assigned(Resource) then begin getmem(buffer,size); buffersize:=Resource.Size; _Loader.Seek(Resource.Offset); _Loader.Read(buffer^,buffersize); result:=true; end else begin Assert(Assigned(Resource),'ExtractResource(): Null '+name); result:=false; end; End; Constructor LPackage.OpenMemory(str:pointer;size:integer); Var Tag:LObjectType; I,J:Integer; S:String; Begin _FileName:='memory'; // Source:=LFileStream.Open(_FileName,smDefault Or smAppend); _Loader:=LMemoryStream.Create(size,str,smRead); // _Loader:=LMemoryStream.Open('pack.sdlk',smRead); _Size:=_Loader.Size; _Loader.Read(Tag,SizeOf(Tag)); If Tag<>leafHeader Then Begin RaiseError('Invalid header. ['+_FileName+']'); Exit; End; _Loader.ReadString(S); //Read package name _Name:=S; _Loader.Read(_TableSize,SizeOf(_TableSize)); //Read filetable info _Loader.Read(_TableOffset,SizeOf(_TableOffset)); _DataOffset:=_Loader.Position; _Loader.Seek(_TableOffset); SetLength(_Table,_TableSize); For I:=0 To Pred(_TableSize)Do With _Table[I] Do Begin _Loader.Read(Tag,SizeOf(Tag)); //Read resource type tag _Loader.ReadString(S); //Read resource name FileName:=S; writeln(s); Name:=UpStr(GetFileName(S,True)); For J:=0 To Pred(I) Do If _Table[J].Name=Name Then Begin RaiseError('Duplicated resource ['+Name+'] in package '+Self._Name+'.'); Exit; End; _Loader.Read(Offset,SizeOf(Offset)); // Read offset of the resource _Loader.Read(Size,SizeOf(Size)); // Size of the resource _Loader.Read(Flags,SizeOf(Flags)); // Read flags End; If _Loader.Position<_Loader.Size Then _Loader.Read(_Version,SizeOf(_Version)) Else Begin _Version.Major:=1; _Version.Minor:=0; End; End; procedure LPackage.ListFiles() ; Var I:Integer; res:PResourceInfo; Begin Res:=Nil; For I:=0 To Pred(_TableSize) Do begin res:=@(_Table[I]); writeln(i); writeln(res.Name); writeln(res.FileName); writeln(res.Offset); writeln(res.size); end; If Not Assigned(res)Then RaiseError('Package'+ 'Resource not found.'); end; //Searches for a resource within the file table //If not found returns nil Function LPackage.FindResource(ResourceName:String):PResourceInfo; Var I:Integer; Begin ResourceName:=UpStr(GetFileName(ResourceName,True)); Result:=Nil; For I:=0 To Pred(_TableSize) Do If _Table[I].Name=ResourceName Then Begin Result:=@(_Table[I]); Break; End; // If Not Assigned(Result)Then // RaiseError('Package'+ 'Resource not found.['+ResourceName+']'); End; Function LPackage.GetResource(ResourceName:String):PResourceInfo; Var I:Integer; Begin ResourceName:=UpStr(GetFileName(ResourceName,True)); Result:=Nil; For I:=0 To Pred(_TableSize) Do If _Table[I].Name=ResourceName Then Begin Result:=@(_Table[I]); writeln('load resource .'); writeln(_Table[I].Name); writeln(_Table[I].FileName); Break; End; If Not Assigned(Result)Then RaiseError('Package'+ 'Resource not found.['+ResourceName+']'); End; //Loads a resource from the package into a stream Procedure LPackage.LoadResource(Resource:PResourceInfo;Var Dest:LStream); Var Source:LFileStream; Begin Assert(Assigned(Resource),'Package.LoadResource(): Null resource'); If FileExists(Path+Resource.FileName) Then Begin Source:=LFileStream.Open(Path+Resource.FileName); If Dest.Size<Source.Size Then Begin Dest.Destroy; Dest:=LMemoryStream.Create(Source.Size); End; Source.Copy(Dest); End Else Begin Source:=LFileStream.Open(_FileName,smDefault,_Offset,_Size); Source.Copy(Dest,Resource.Offset,Resource.Size); End; Source.Destroy; End; //Loads a resource from the package into a stream Procedure LPackage.ExtractResource(Resource:PResourceInfo;Var Dest:LStream); Var Source:LFileStream; Begin Assert(Assigned(Resource),'ExtractResource(): Null resource'); Source:=LFileStream.Open(_FileName,smDefault,_Offset,_Size); Source.Copy(Dest,Resource.Offset,Resource.Size); Source.Destroy; End; // Get file stream containing the resource Function LPackage.OpenResource(Resource:PResourceInfo):LFileStream; Begin Assert(Assigned(Resource),'Package.LoadResource(): Null resource'); Result:=LFileStream.Open(_FileName,smDefault,Resource.Offset,Resource.Size); Result.Name:=Result.Name+':'+Resource.FileName; End; Function LPackage.Add(FileName:String):boolean; Var Stream:LStream; Tag:LObjectType; res:PResourceInfo; Begin Result:=false; If Not FileExists(FileName) Then Begin RaiseError('File not found. ['+FileName+']'); Result:=false; Exit; End; Stream:=LFileStream.Open(FileName, smDefault Or smAppend); Tag:=resFile; res:=AddResource(GetFileName(FileName,False),Tag,Stream); Stream.Destroy; End; Function LPackage.AddFile(FileName:String):PResourceInfo; Var Stream:LStream; Tag:LObjectType; Begin Result:=Nil; If Not FileExists(FileName) Then Begin RaiseError('File not found. ['+FileName+']'); Result:=Nil; Exit; End; Stream:=LFileStream.Open(FileName, smDefault Or smAppend); Tag:=resFile; Result:=AddResource(GetFileName(FileName,False),Tag,Stream); Stream.Destroy; End; // Adds a resource to the package Function LPackage.AddResource(ResourceName:String;ResourceType:LObjectType;Resource:LStream;ResourceFlags:Byte):PResourceInfo; Var Dest:LFileStream; Info:PResourceInfo; Begin Info:=FindResource(ResourceName); If Assigned(Info) Then DeleteResource(Info); SetLength(_Table,Succ(_TableSize)); With _Table[_TableSize] Do Begin Result:=@(_Table[_TableSize]); FileName:=ResourceName; Name:=UpStr(GetFileName(ResourceName,True)); FileName:=ResourceName; Tag:=ResourceType; Size:=Resource.Size-Resource.Position; Offset:=GetNewOffset(Size); Flags:=ResourceFlags; //Start copying the resource into the package file Dest:=LFileStream.Open(_FileName, smDefault Or smAppend); Dest.Seek(Offset); Resource.Copy(Dest, Resource.Position, Size); Inc(_TableSize); Inc(_Size,SizeOf(LObjectType)+Succ(Length(Name))+SizeOf(Longint)+SizeOf(Longint)+SizeOf(Byte)); Inc(_Size,Size); End; _TableOffset:=Dest.Position; // Filetable was overwritten by new resource, so rebuild it RebuildHeader(Dest); RebuildFileTable(Dest); Dest.Destroy; End; //Removes a resource from the package Procedure LPackage.DeleteResource(Resource:PResourceInfo); Var I:Integer; Stream:LStream; Begin Assert(Assigned(Resource),'DeleteResource(): Null resource.'); I:=0; While I<_TableSize Do If _Table[I].Name=Resource.Name Then Begin _Table[I]:=_Table[Pred(_TableSize)]; Dec(_TableSize); Break; End Else Inc(I); Stream:=LFileStream.Open(FileName, smDefault Or smAppend); RebuildFileTable(Stream); Stream.Destroy; End; Function LPackage.GetNewOffset(Size: Integer): Integer; Var DataStart,I:Integer; Begin If _TableSize=0 Then Begin Result:=_DataOffset; Exit; End; // Check for fragmented holes to fill For I:=0 To Pred(_TableSize) Do Begin If I=0 Then DataStart:=_DataOffset Else DataStart:=_Table[Pred(I)].Offset+_Table[Pred(I)].Size; If (_Table[I].Offset-DataStart>=Size) Then Begin Result:=DataStart; Exit; End; End; //Otherwise calculate new offset from last file in table Result:=_Table[Pred(_TableSize)].Offset+_Table[Pred(_TableSize)].Size End; // LXMLNode Constructor XMLNode.Create(Name:String; Value:String=''); Begin Self._Name:=Name; Self._Value:=Value; End; Constructor XMLNode.Create(Source:LStream); Var S, S2:String; Tag, Value:String; I:Integer; ShortTag:Boolean; Node:XMLNode; Begin _Value := ''; Repeat If (Source.EOF) Then Exit; S := Read(Source); Until (Length(S)>=2) And (S[2]<>'?'); If GetTagType(S)<>xmlBeginTag Then Begin RaiseError ('Invalid XML sintax!'); Exit; End; ShortTag := S[Pred(Length(S))] = '/'; S := GetTagName(S); I := Pos(' ', S); If (I>0) Then Begin S2 := Copy(S, Succ(I), MaxInt); S := Copy(S, 1, Pred(I)); Self._Name := S; S := S2; If (S[Length(S)]='/') Then SetLength(S, Pred(Length(S))); While (S<>'') Do Begin S2 := GetNextWord(S, ' '); I := Pos('=', S2); Tag := Copy(S2, 1, Pred(I)); Value := Copy(S2, I+1, MaxInt); Value := TrimRight(TrimLeft(Value)); Value := Copy(Value, 2, Length(Value)-2); Node := XMLNode.Create(Tag, Value); AddNode(Node); End; End Else Self._Name := S; If (ShortTag) Then Exit; Repeat S := Read(Source); Case GetTagType(S) Of xmlBeginTag: Begin Source.Skip(-Length(S)); Node := XMLNode.Create(Source); AddNode(Node); End; xmlEndTag: Break; xmlData: _Value:=S; End; Until False; End; Destructor XMLNode.Destroy; Var I:Integer; Begin For I:=0 To Pred(_ChildCount) Do _Childs[I].Destroy; SetLength(_Childs,0); _ChildCount:=0; End; Function XMLNode.GetTagType(S:String):XMLTagType; Begin If (S='')Or(S[1]<>'<')Or(S[Length(S)]<>'>') Then Result:=xmlData Else If (S[2]='/') Then Result:=xmlEndTag Else Result:=xmlBeginTag; End; Function XMLNode.GetTagName(S:String):String; Begin Result:=Copy(S,2,Length(S)-2); End; Function XMLNode.GetParentCount:Integer; Var Node:XMLNode; Begin Node:=Self; Result:=-1; While Assigned(Node) Do Begin Inc(Result); Node:=Node._Parent; End; End; Function XMLNode.GetPath:String; Var Node:XMLNode; Begin Node:=Self; Result:=''; While Assigned(Node) Do Begin If Result<>'' Then Result:='.'+Result; Result:=Node._Name+Result; Node:=Node._Parent; End; End; Function XMLNode.GetChild(Index:Integer):XMLNode; Begin If (Index<0) Or (Index>=_ChildCount) Then Result := Nil Else Result := _Childs[Index]; End; Function XMLNode.GetNode(Name:String):XMLNode; Var I:Integer; Begin Name:=UpStr(Name); Result:=Nil; For I:=0 To Pred(_ChildCount) Do If UpStr(_Childs[I].Name)=Name Then Begin Result:=_Childs[I]; Exit; End; End; Function XMLNode.Read(Source:LStream):String; Const BufferSize = 1024; Var S:String; C:Char; Begin S := ''; Repeat If (Source.EOF) Then Break; Source.Read(C, 1); If (C='<') And (S<>'') Then Begin Source.Skip(-1); Break; End; S := S+C; Until (C='>'); Result := TrimLeft(S); End; Procedure XMLNode.Save(Dest:LStream); Var Tabs:String; I:Integer; Begin Tabs:=''; For I:=1 To GetParentCount Do Tabs:=Tabs+#9; If Value<>'' Then Begin Dest.WriteLine(Tabs+'<'+Name+'>'+Value+'</'+Name+'>'); End Else Begin Dest.WriteLine(Tabs+'<'+Name+'>'); For I:=0 To Pred(_ChildCount) Do _Childs[I].Save(Dest); Dest.WriteLine(Tabs+'</'+Name+'>'); End; End; Procedure XMLNode.AddNode(Node:XMLNode); Begin Node._Parent:=Self; Inc(_ChildCount); SetLength(_Childs,_ChildCount); _Childs[Pred(_ChildCount)]:=Node; End; Function XMLNode.AddTag(Name, Value: String): XMLNode; Var Node:XMLNode; Begin Node := XMLNode.Create(Name,Value); AddNode(Node); Result:=Node; End; // LXMLDocument Destructor XMLDocument.Destroy; Begin If Assigned(_Root) Then _Root.Destroy; End; Function XMLDocument.GetNode(Name:String):XMLNode; Begin Result:=Nil; If Assigned(_Root) Then Result:=_Root.GetNode(Name); End; Procedure XMLDocument.AddNode(Node:XMLNode; Parent:XMLNode=Nil); Begin If Assigned(Parent) Then Parent.AddNode(Node) Else Begin If Not Assigned(_Root) Then _Root:=Node Else _Root.AddNode(Node); End; End; Function XMLDocument.AddString(Name:String; Value:String=''; Parent:XMLNode=Nil):XMLNode; Begin If Assigned(Parent) Then Result:=Parent.AddTag(Name,Value) Else Begin If Not Assigned(_Root) Then Begin _Root := XMLNode.Create(Name,Value); Result := _Root; End Else Result := _Root.AddTag(Name,Value); End; End; Function XMLDocument.AddBoolean(Name:String; Value:Boolean; Parent:XMLNode=Nil):XMLNode; Begin Result := AddString(Name, BoolToString(Value), Parent); End; Function XMLDocument.AddInteger(Name:String; Value:Integer; Parent:XMLNode=Nil):XMLNode; Begin Result := AddString(Name, IntToString(Value), Parent); End; Function XMLDocument.AddCardinal(Name:String; Value:Cardinal; Parent:XMLNode=Nil):XMLNode; Begin Result := AddString(Name, LongToString(Value), Parent); End; Function XMLDocument.AddSingle(Name:String; Value:Single; Parent:XMLNode=Nil):XMLNode; Begin Result := AddString(Name, FloatToString(Value), Parent); End; Procedure XMLDocument.Load(Source:LStream); Begin _Root := XMLNode.Create(Source); End; Procedure XMLDocument.Save(Dest:LStream); Begin _Root.Save(Dest); End; Procedure XMLDocument.Load(FileName:String); Var Source:LFileStream; Begin Source := LFileStream.Open(FileName); Load(Source); Source.Destroy; End; Procedure XMLDocument.Save(FileName:String); Var Dest:LFileStream; Begin Dest := LFileStream.Create(FileName); Save(Dest); Dest.Destroy; End; // XMLElement Procedure XMLElement.XMLRegisterStructure; Begin End; Procedure XMLElement.XMLSynchronize; Begin End; Function XMLElement.XMLGetPropertyCount:Integer; Begin If (Self._DescriptorCount=0) Then XMLRegisterStructure; Result := _DescriptorCount; End; Function XMLElement.XMLGetProperty(Index:Integer):XMLDescriptor; Begin Result := _Descriptors[Index]; End; Function XMLElement.XMLGetProperty(Name:String):XMLDescriptor; Var S:String; I:Integer; Begin Name := UpStr(Name); I := Pos('.', Name); If (I>0) Then Begin S := Copy(Name, Succ(I), MaxInt); Name := Copy(Name, 1, Pred(I)); Result := XMLGetProperty(Name); If (S='X') Then Begin Inc(PByte(Result.Address), 0); Result.XMLType := xmlSingle; End Else If (S='Y') Then Begin Inc(PByte(Result.Address), 4); Result.XMLType := xmlSingle; End Else If (S='Z') Then Begin Inc(PByte(Result.Address), 8); Result.XMLType := xmlSingle; End Else If (S='RED') Or (S='R') Then Begin Inc(PByte(Result.Address), 0); Result.XMLType := xmlByte; End Else If (S='GREEN') Or (S='G') Then Begin Inc(PByte(Result.Address), 1); Result.XMLType := xmlByte; End Else If (S='BLUE') Or (S='B') Then Begin Inc(PByte(Result.Address), 2); Result.XMLType := xmlByte; End Else If (S='ALPHA') Or (S='A') Then Begin Inc(PByte(Result.Address), 3); Result.XMLType := xmlByte; End Else RaiseError('XML: Unknow type component ['+S+']'); Exit; End; For I:=0 To Pred(_DescriptorCount) Do If (UpStr(_Descriptors[I].Name) = Name) Then Result := _Descriptors[I]; End; Function XMLElement.XMLGetElement(Index:Integer):XMLElement; Begin Result := Nil; End; Function XMLElement.XMLGetElementCount():Integer; Begin Result := 0; End; Function XMLElement.XMLNewElement(Name:String):XMLElement; Begin Result := Nil; End; Procedure XMLElement.XMLRegisterElement(Name:String; Address:Pointer; XMLType:XMLType; Default:String=''); Begin Inc(_DescriptorCount); SetLength(_Descriptors,_DescriptorCount); _Descriptors[Pred(_DescriptorCount)].Name:=Name; _Descriptors[Pred(_DescriptorCount)].Address:=Address; _Descriptors[Pred(_DescriptorCount)].XMLType:=XMLType; _Descriptors[Pred(_DescriptorCount)].ElementCount:=1; _Descriptors[Pred(_DescriptorCount)].Default:=Default; _Descriptors[Pred(_DescriptorCount)].Found:=False; End; Procedure XMLElement.XMLRegisterArrayElement(Name:String; Address:Pointer; XMLType:XMLType; Size:Integer); Begin Inc(_DescriptorCount); SetLength(_Descriptors,_DescriptorCount); _Descriptors[Pred(_DescriptorCount)].Name:=Name; _Descriptors[Pred(_DescriptorCount)].Address:=Address; _Descriptors[Pred(_DescriptorCount)].XMLType:=XMLType; _Descriptors[Pred(_DescriptorCount)].ElementCount:=Size; _Descriptors[Pred(_DescriptorCount)].Default:=''; _Descriptors[Pred(_DescriptorCount)].Found:=False; End; Procedure XMLElement.XMLClearStructure; Begin _DescriptorCount := 0; SetLength(_Descriptors, 0); End; Procedure XMLDescriptor.Read(Node:XMLNode); Var S,S2:String; K:Integer; Begin Found:=True; S:=Node.Value; For K:=1 To ElementCount Do Begin If ElementCount=1 Then Begin S2:=S; S:=''; End Else S2:=GetNextWord(S,','); If (S2='') Then Begin RaiseError('Number of array elements differs from declaration! ['+Node.GetPath+']'); Exit; End; Case XMLType Of xmlString: Begin PString(Address)^:=S2; Inc(PString(Address)); End; xmlBoolean: Begin PBoolean(Address)^:=StringToBool(S2); Inc(PBoolean(Address)); End; xmlInteger: Begin PInteger(Address)^:=StringToInt(S2); Inc(PInteger(Address)); End; xmlCardinal: Begin PCardinal(Address)^:=StringToLong(S2); Inc(PCardinal(Address)); End; xmlByte: Begin PByte(Address)^:=StringToInt(S2); Inc(PByte(Address)); End; xmlWord: Begin PWord(Address)^:=StringToLong(S2); Inc(PWord(Address)); End; xmlSingle: Begin PSingle(Address)^ := StringToFloat(S2); Inc(PSingle(Address)); End; Else RaiseError('XML'+ 'Invalid XML type '+ IntToString(Cardinal(XMLType))); End; End; If (S<>'') Then RaiseError('XML'+ 'Extra array elements discarded! ['+Node.GetPath+']'); End; Procedure XMLDescriptor.Write(Document:XMLDocument; Node:XMLNode); Var S:String; J:Integer; Begin S:=''; Begin For J:=1 To ElementCount Do Begin If J>1 Then S:=S+','; Case XMLType Of xmlString: Begin S:=S+PString(Address)^; Inc(PString(Address)); End; xmlBoolean: Begin S:=S+BoolToString(PBoolean(Address)^); Inc(PBoolean(Address)); End; xmlInteger: Begin S:=S+IntToString(PInteger(Address)^); Inc(PInteger(Address)); End; xmlCardinal: Begin S:=S+LongToString(PCardinal(Address)^); Inc(PCardinal(Address)); End; xmlByte: Begin S:=S+IntToString(PByte(Address)^); Inc(PByte(Address)); End; xmlWord: Begin S:=S+LongToString(PWord(Address)^); Inc(PWord(Address)); End; xmlSingle: Begin S := S + FloatToString(PSingle(Address)^); Inc(PSingle(Address)); End; Else RaiseError( 'Invalid XML type '+ IntToString(Cardinal(XMLType))); End; End; If (S<>Default) Then Node.AddTag(Name, S); End; End; Procedure XMLElement.XMLLoadElements(Source:XMLNode); Var Found:Boolean; I,J:Integer; Node:XMLNode; Element:XMLElement; Begin Self._Status:=xmlReading; XMLClearStructure; XMLRegisterStructure; For I:=0 To Pred(Source._ChildCount) Do Begin Node := Source._Childs[I]; Found := False; For J:=0 To Pred(_DescriptorCount) Do If (UpStr(_Descriptors[J].Name)=UpStr(Node.Name)) Then Begin _Descriptors[J].Read(Node); Found := True; Break; End; If Not Found Then Begin Element := XMLNewElement(Node.Name); If Not Assigned(Element) Then Begin RaiseError( 'Could not create XML element! ['+Node.Name+']'); Exit; End; Element.XMLLoadElements(Node); Found := True; Break; End; End; For J:=0 To Pred(_DescriptorCount) Do If (Not _Descriptors[J].Found) And (_Descriptors[J].Default<>'') Then Begin Node := XMLNode.Create(_Descriptors[J].Name, _Descriptors[J].Default); _Descriptors[J].Read(Node); Node.Destroy; End; XMLSynchronize; End; Procedure XMLElement.XMLSaveElements(Document:XMLDocument; Parent:XMLNode=Nil); Var I,J, Count:Integer; Node:XMLNode; Element:XMLElement; Begin Self._Status:=xmlWriting; XMLClearStructure; XMLRegisterStructure; Node := XMLNode.Create(Self.ClassName); For I:=0 To Pred(_DescriptorCount) Do _Descriptors[I].Write(Document, Node); Count := XMLGetElementCount(); For J:=0 To Pred(Count) Do Begin Element := XMLGetElement(J); If Not Assigned(Element) Then Begin RaiseError('XML element not avaliable! ['+IntToString(J)+']'); Exit; End; Element.XMLSaveElements(Document, Node); End; Document.AddNode(Node, Parent); End; Procedure XMLElement.XMLLoad(Node:XMLNode); Begin XMLLoadElements(Node); End; Procedure XMLElement.XMLLoad(Document:XMLDocument); Begin XMLLoadElements(Document.Root); End; Procedure XMLElement.XMLSave(Document: XMLDocument); Begin XMLSaveElements(Document); End; Procedure XMLElement.XMLLoad(Source:LStream); Var Document:XMLDocument; Begin Document := XMLDocument.Create; Document.Load(Source); XMLLoad(Document); Document.Destroy; End; Procedure XMLElement.XMLSave(Dest:LStream); Var Document: XMLDocument; Begin Document := XMLDocument.Create; XMLSave(Document); Document.Save(Dest); Document.Destroy; End; Procedure XMLElement.XMLLoad(FileName:String); Var Source:LStream; Begin Source := LFileStream.Open(FileName); XMLLoad(Source); Source.Destroy; End; Procedure XMLElement.XMLSave(FileName: String); Var Dest:LStream; Begin Dest := LFileStream.Create(FileName); XMLSave(Dest); Dest.Destroy; End; Function GetNextLine(Var S:String):String; Var I:Integer; Begin If S='' Then Begin Result:=''; Exit; End; I:=Pos(#13#10,S); If I<=0 Then Begin Result:=S; S:=''; End Else Begin Result:=Copy(S,1,Pred(I)); S:=Copy(S,I+2,MaxInt); End; End; Function GetNextWord(Var S:String; Separator:Char=' '):String; Var I:Integer; Begin S:=TrimLeft(S); If S='' Then Begin Result:=''; Exit; End; I:=Pos(Separator,S); If I<=0 Then Begin Result:=S; S:=''; End Else Begin Result:=Copy(S,1,Pred(I)); S:=Copy(S,Succ(I),MaxInt); End; S:=TrimLeft(S); End; Function GetNextToken(Var S:String; Separator:Char=','; Op:Char='(';Ed:Char=')'):String; Var I,J,K:Integer; Begin S:=TrimLeft(S); If S='' Then Begin Result:=''; Exit; End; If S[1]=Op Then Begin J:=FindCloseBracket(S, Op, Ed); If J=0 Then Begin Result:=S; S:=''; End Else Begin Result:=Copy(S,1,J); S:=Copy(S,J+1,Length(S)-J); End; End Else Begin I:=Pos(Separator,S); J:=Pos(Op,S); K:=Pos(Ed,S); If (J<I)And(J>0)Or(I=0)Then I:=J; If (K<I)And(K>0)Or(I=0)Then I:=K; If I=0 Then Begin Result:=S; S:=''; End Else Begin If I=1 Then K:=1 Else K:=I-1; Result:=Copy(S,1,K); S:=Copy(S,I,Length(S)-I+1); End; End; S:=TrimLeft(S); End; Function GetNextArg(Var S:String):String; Var I:Integer; Begin I:=Pos(',',S); If I=0 Then Begin Result:=S; S:=''; End Else Begin Result:=Copy(S,1,Pred(I)); S:=Copy(S,Succ(I),Length(S)); End; End; Function GetFileExt(FileName:String):String; Var I:Integer; Begin Result:=''; Repeat I:=Pos('.',FileName); If I<>0 Then Begin Result:=Copy(FileName,I+1,Length(FileName)-I); FileName:=Copy(FileName, Succ(I), MaxInt); End; Until I<=0; End; Function FindCloseBracket(Const S:String; Op:Char='(';Ed:Char=')'):Integer; Var K,I:Integer; Begin K:=0; Result:=0; For I:=1 To Length(S) Do If S[I]=Op Then Inc(K) Else If S[I]=Ed Then Begin If K=1 Then Begin Result:=I; Break; End Else Dec(K); End; End; Function StrClean(Const S:String):String; Var I,N:Integer; Begin N:=Length(S); For I:=1 To N Do If (S[I]<' ') Then Begin N:=Pred(I); Break; End; Result:=Copy(S,1,N); End; Function TrimLeft(Const S:String):String; Var I,L:Integer; Begin L:=Length(S); I:=1; While (I <= L) And (S[I]<=' ') Do Inc(I); Result:=Copy(S,I,Maxint); End; Function TrimRight(Const S:String):String; Var I:Integer; Begin I:=Length(S); While (I>0) And (S[I]<=' ') Do Dec(I); Result:=Copy(S,1,I); End; //Converts a string to upcase Function UpStr(Const S:String):String; Var I:Integer; C:Char; Begin Result:=''; For I:=1 To Length(S) Do Begin C:=S[I]; If (C>='a')And(C<='z') Then Dec(C,32); Result:=Result+C; End; End; //Converts a string to lowercase Function LowStr(Const S:String):String; Var I:Integer; C:Char; Begin Result:=''; For I:=1 To Length(S) Do Begin C:=S[I]; If (C>='A')And(C<='Z') Then Inc(C,32); Result:=Result+C; End; End; Function CapStr(Const S:String):String; Begin Result:=LowStr(S); If Result<>'' Then Result[1]:=UpCase(Result[1]); End; Function StringToInt(Const S:String):Integer; Var K:Integer; Begin Val(S,Result,K); End; Function StringToLong(Const S:String):Cardinal; Var K:Integer; Begin Val(S,Result,K); End; Function StringToBool(Const S:String):Boolean; Begin // Result:=(S=iTrue); End; //Converts a string to an Single Function StringToFloat(Const S:String):Single; Var I:Integer; X:Single; Begin System.Val(S,X,I); Result := X; End; Function StrLPad(S:String;N:Integer; Token:Char='0'):String; Begin While Length(S)<N Do S:=Token+S; Result:=S; End; Function StrRPad(S:String;N:Integer; Token:Char='0'):String; Begin While Length(S)<N Do S:=S+Token; Result:=S; End; Function IntToString(Const N:Integer):String; Var S:String; Begin Str(N,S); Result:=S; End; Function BoolToString(Const N:Boolean):String; Begin If N Then Result:='True' Else Result:='False'; End; Function LongToString(Const N:Cardinal):String; Var S:String; Begin Str(N,S); Result:=S; End; Function FloatToString(Const N:Single):String; Var P,X:Single; A,B:Integer; Begin P:=N; A:=Trunc(P); X:=Abs(Frac(P)); Repeat X:=X*10; Until Frac(X)=0; B:=Trunc(X); Result:=IntToString(A)+'.'+IntToString(B); If (StringToFloat(Result)<>N) Then Str(P,Result); End; Function TicksToString(Const N:Cardinal):String; Var Ext:String; X:Single; Int,Rem:Integer; Begin If (N>=60000)Then Begin X:=N/60000; Int:=Trunc(X); Rem:=Trunc(Frac(X)*10); Ext:='m'; End Else If (N>=1000)Then Begin X:=N/1000; Int:=Trunc(X); Rem:=Trunc(Frac(X)*10); Ext:='s'; End Else Begin Int:=N; Rem:=0; Ext:='ms'; End; Result:=IntToString(Int); If Rem>0 Then Result:=Result+'.'+IntToString(Rem); Result:=Result+' '+Ext; End; Function MemoryToString(Const N:Cardinal):String; Var Ext:Char; X:Single; Int,Rem:Integer; Begin If (N>=1 Shl 30)Then Begin X:=N/(1 Shl 30); Int:=Trunc(X); Rem:=Trunc(Frac(X)*10); Ext:='G'; End Else If (N>=1 Shl 20)Then Begin X:=N/(1 Shl 20); Int:=Trunc(X); Rem:=Trunc(Frac(X)*10); Ext:='M'; End Else If (N>=1 Shl 10)Then Begin X:=N/(1 Shl 10); Int:=Trunc(X); Rem:=Trunc(Frac(X)*10); Ext:='K'; End Else Begin Int:=N; Rem:=0; Ext:=#0; End; Result:=IntToString(Int); If Rem>0 Then Result:=Result+'.'+IntToString(Rem); Result:=Result+' '; If Ext<>#0 Then Result:=Result+Ext; Result:=Result+'b'; End; Function GetVersionID(Const Major,Minor,Build:Word):Word; Begin Result:=(Major*1000)+(Minor*100)+Build; End; Procedure ReplaceText(Const Token,Value:String; Var S:String); Var I:Integer; S2:String; Begin If (Token = Value) Then Exit; I := Pos(Upstr(Token),Upstr(S)); While (I>0) Do Begin S2:=Copy(S,I+Length(Token),Length(S)-I); S:=Copy(S,1,Pred(I)); S:=S+Value+S2; I:=Pos(Upstr(Token),Upstr(S)); End; End; Procedure ReplaceAllText(Const Token,Value:String; Var S:String); Begin If (Token = Value) Then Exit; While Pos(Token, S)>0 Do ReplaceText(Token, Value, S); End; Function HexStr(Const Value:Byte):String; Const Hex:Array[0..15] Of AnsiChar='0123456789ABCDEF'; Var txt:String[2]; Begin txt[0] := Char(2); txt[1] := Hex[(value SHR 4) AND $0F]; txt[2] := Hex[value AND $0F]; Result:= txt; End; Function HexStr(Const Value:Word):String; Const Hex:Array[0..15] Of AnsiChar='0123456789ABCDEF'; Var txt:String[4]; Begin txt[0]:= Char(4); txt[1]:= Hex[(value SHR 12) AND $0F]; txt[2]:= Hex[(value SHR 8) AND $0F]; txt[3]:= Hex[(value SHR 4) AND $0F]; txt[4]:= Hex[value AND $0F]; Result:= txt; End; Function HexStr(Const Value:Cardinal):String; Const Hex : Array[0..15] of AnsiChar = '0123456789ABCDEF'; Var txt : String[8]; Begin txt[0]:= Char(8); txt[1]:= Hex[(value SHR 28) AND $0F]; txt[2]:= Hex[(value SHR 24) AND $0F]; txt[3]:= Hex[(value SHR 20) AND $0F]; txt[4]:= Hex[(value SHR 16) AND $0F]; txt[5]:= Hex[(value SHR 12) AND $0F]; txt[6]:= Hex[(value SHR 8) AND $0F]; txt[7]:= Hex[(value SHR 4) AND $0F]; txt[8]:= Hex[value AND $0F]; Result:= txt; End; Const Base64Code= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ 'abcdefghijklmnopqrstuvwxyz'+ '0123456789+/'; Pad = '='; Function StringToBase64(Buf:String):String; Var I:Integer; x1,x2,x3,x4:Byte; PadCount:Integer; Begin PadCount:=0; // we need at least 3 input bytes... While Length(Buf)<3 Do Begin Buf := Buf + #0; Inc( PadCount ); End; // ...and all input must be an even multiple of 3 While ( length( Buf ) mod 3 ) <> 0 do Begin Buf:=Buf+#0; // if not, zero padding is added Inc(PadCount); End; Result:= ''; I:=1; // process 3-byte blocks or 24 bits While (I<=Length(Buf)-2) Do Begin // each 3 input bytes are transformed into 4 index values // in the range of 0..63, by taking 6 bits each step // 6 high bytes of first char x1 := ( Ord( Buf[i] ) shr 2 ) and $3F; // 2 low bytes of first char + 4 high bytes of second char x2 := ( ( Ord( Buf[i] ) shl 4 ) and $3F ) or Ord( Buf[i + 1] ) shr 4; // 4 low bytes of second char + 2 high bytes of third char x3 := ( ( Ord( Buf[i + 1] ) shl 2 ) and $3F ) or Ord( Buf[i + 2] ) shr 6; // 6 low bytes of third char x4 := Ord( Buf[i + 2] ) and $3F; // the index values point into the code array Result:=Result + Base64Code[x1 + 1] + Base64Code[x2 + 1] + Base64Code[x3 + 1] + Base64Code[x4 + 1]; Inc(i,3); End; // if needed, finish by forcing padding chars ('=') // at end of string If PadCount>0 Then For i := Length( Result ) downto 1 do Begin Result[i]:=Pad; Dec(PadCount); If PadCount=0 Then Break; End; End; // helper : given a char, returns the index in code table Function Char2IDx(c:Char):Byte; Var I:Integer; Begin For I:=1 To Length(Base64Code) Do If Base64Code[i]=c Then Begin Result:=Pred(I); Exit; End; Result:=Ord(Pad); End; Function Base64ToString(B64:String):String; Var I,PadCount:Integer; Block:String[3]; N:Integer; A,B,C,D:Byte; Begin // input _must_ be at least 4 chars long, // or multiple of 4 chars If (Length(B64)<4) Or (Length(B64) Mod 4<>0) Then Begin Result:=''; Exit; End; PadCount:=0; I:=Length(B64); // count padding chars, if any While (B64[i]=Pad) And (i>0) Do Begin Inc(PadCount); Dec(I); End; Result:=''; i:=1; SetLength(Block,3); While i<=Length(B64)-3 Do Begin A:=Char2Idx(B64[I+0]); B:=Char2IDx(B64[I+1]); C:=Char2IDx(B64[I+2]); D:=Char2IDx(B64[I+3]); // reverse process of above N:=(A Shl 2) Or (B Shr 4); Result:=Result+Chr(N); N:=(B Shl 4) Or (C Shr 2); Result:=Result+Chr(N); N:=(C Shl 6 ) Or D; Result:=Result+Chr(N); Inc(i,4); End; // delete padding, if any While PadCount>0 Do Begin Delete(Result, Length(Result), 1); Dec(PadCount); End; End; Function UnicodeChar(Code:Word):String; Var A,B:Byte; Begin A := Byte(Code And $FF); B := Byte((Code Shr 8) And $FF); Result := #255 + Chr(B) + Chr(A); End; //Returns the position of a substring inside of a string //Search starts from the end of the string. Function PosRev(Const SubStr,Str:String):Integer; Var I,K,N:Integer; Begin K:=0; N:=Length(SubStr); For I:=Length(Str) DownTo 1 Do Begin If Str[I]=SubStr[N] Then Begin If N=1 Then Begin K:=I; Break; End Else Dec(N); End Else N:=Length(SubStr); End; Result:=K; End; Procedure SetFlag(Var N:Byte; Const Flag:Byte; Const Value:Boolean); Begin If (((N And Flag)<>0)<>Value)Then N:=N Xor Flag; End; Procedure FillByte(Var Dest; Count:Integer; Value:Byte); Var P:PByte; Begin P:=@Dest; While (Count>0) Do Begin P^:=Value; Inc(P); Dec(Count); End; End; Procedure FillWord(Var Dest; Count:Integer; Value:Word); Var P:PWord; Begin P:=@Dest; While (Count>0) Do Begin P^:=Value; Inc(P); Dec(Count); End; End; Procedure FillLong(Var Dest; Count:Integer; Value:Cardinal); Var P:PCardinal; Begin P:=@Dest; While (Count>0) Do Begin P^:=Value; Inc(P); Dec(Count); End; End; Function MatchRegEx(S, Expression:String):Boolean; Var I, J:Integer; Begin I := 1; J := 1; Result := False; While (I<=Length(S)) And (J<=Length(Expression)) Do Begin If (Expression[J] = '*') Then Begin While (Expression[J] = '*') Do Begin If (J>=Length(Expression)) Then Begin Result := True; Exit; End; Inc(J); End; While (S[I]<>Expression[J]) Do Begin Inc(I); If (I>Length(S)) Then Exit; End; Inc(I); Inc(J); End Else If (S[I]=Expression[J]) Then Begin Inc(I); Inc(J); End Else Exit; End; Result := True; End; Function LongMin(Const A,B:Cardinal):Cardinal; {$IFDEF FPC} Inline; {$ENDIF} Begin If A<B Then Result:=A Else Result:=B; End; Function LongMax(Const A,B:Cardinal):Cardinal; {$IFDEF FPC} Inline; {$ENDIF} Begin If A>B Then Result:=A Else Result:=B; End; Function GetFilePath(FileName:String):String; Var I:Integer; S:String; Begin I:=Pos(PathSeparator,FileName); S:=''; While I<>0 Do Begin S:=S+Copy(FileName,1,I); FileName:=Copy(FileName,I+1,Length(FileName)-I); I:=Pos(PathSeparator,FileName); End; Result:=S; End; Function GetLastFilePath(FileName:String):String; Var I:Integer; Begin Result:=GetFilePath(FileName); Result:=Copy(Result, 1, Pred(Length(Result))); I:=Pos('\', Result); While (I>0) Do Begin Result:=Copy(Result, Succ(I), MaxInt); I:=Pos('\', Result); End; End; Function GetFirstFilePath(FileName:String):String; Var I:Integer; S:String; Begin S:=GetFilePath(FileName); S:=Copy(S, 1, Pred(Length(S))); I:=Pos('\', S); Result:=''; While (I>0) Do Begin Result:=Result+Copy(S, 1, I); S:=Copy(S, Succ(I), MaxInt); I:=Pos('\', S); End; End; Function GetFileName(FileName:String;Const RemoveExt:Boolean):String; Var I:Integer; Begin I:=Pos(':',FileName); If I>0 Then FileName:=Copy(FileName,Succ(I),MaxInt); I:=Pos(PathSeparator,FileName); While I<>0 Do Begin FileName:=Copy(FileName,I+1,Length(FileName)-I); I:=PosRev(PathSeparator,FileName); End; Result:=FileName; If RemoveExt Then Begin I:=PosRev('.',FileName); If I<>0 Then Result:=Copy(FileName,1,I-1); End; End; Function GetCurrentDir:String; Begin Result:=''; GetDir(0,Result); End; { Const Polynomial=$EDB88320; Var CRC_Table:Array[0..255]Of Cardinal; Procedure GenerateCRC_Table; Var I:Integer; Count:Integer; CRC:Cardinal; Begin For I:=0 To 255 Do Begin CRC:=I; For Count:=8 DownTo 1 Do Begin If (CRC And 1)>0 Then CRC:=(CRC Shr 1) Xor Polynomial Else CRC:=CRC Shr 1; End; CRC_Table[I]:=CRC; End; End; Function GetCRC32(Source:LStream; Start,Length:Integer):Cardinal; Const BufferSize=1024*32; Var I:Integer; OP,Pos,Size:Integer; CRC:Cardinal; Buffer:Array[0..Pred(BufferSize)]Of Byte; BlockSize:Word; Begin CRC:=$FFFFFFFF; OP:=Source.Position; Source.Seek(Start); Size:=Length; Pos:=0; While (Pos<Size)Do Begin BlockSize:=IntMin(BufferSize,Source.Size-Source.Position); Source.Read(Buffer[0],BlockSize); For I:=0 To Pred(BlockSize)Do CRC:=(CRC Shr 8) Xor CRC_Table[(CRC Xor Buffer[I])And $FF]; Inc(Pos,BlockSize); End; CRC:=CRC Xor $FFFFFFFF; Source.Seek(OP); Result:=CRC; End; Function GetCRC32(Source:LStream):Cardinal; Begin Result:=GetCRC32(Source, 0, Source.Size); End; Begin GenerateCRC_Table; } End.
unit Requester; {$mode objfpc}{$H+} interface uses Classes, SysUtils, HKCompPacksTypes, fpjson, IdHTTP; type TRequestCallback=procedure(Sender:TObject; aRequest:TIdHTTPRequest; aResponse:TIdHTTPResponse; aRespContent:TJSONData)of object; { TJsonRequester } TJsonRequester=class(TIdCustomHTTP) private FBaseUrl: String; FonDebugMsg: TOnDebugMessage; FOnPrepareData: TNotifyEvent; FOnProcessRequestFinished: TNotifyEvent; FOnProcessRequestStart: TNotifyEvent; FonRequestCallback: TRequestCallback; FonResponseTokenInvalid: TNotifyEvent; FToken: String; FTokenName: String; procedure SetBaseUrl(AValue: String); procedure SetonDebugMsg(AValue: TOnDebugMessage); procedure SetOnPrepareData(AValue: TNotifyEvent); procedure SetOnProcessRequestFinished(AValue: TNotifyEvent); procedure SetOnProcessRequestStart(AValue: TNotifyEvent); procedure SetonRequestCallback(AValue: TRequestCallback); procedure SetonResponseTokenInvalid(AValue: TNotifyEvent); procedure SetToken(AValue: String); procedure SetTokenName(AValue: String); protected procedure doDebug(aMessage:String; aDebugType:TDebugType);virtual; function ProcessResponse(aResponse, aDoc: String): TJSONData; function ProcessJsonResp(aJson: TJSONObject; aDoc: String): TJSONData; procedure doProcessRequestStart;virtual; procedure doProcessRequestFinished;virtual; procedure doPrepareData;virtual; procedure doCallback(aData:TJSONData); procedure Prepare; public function JsonGet(aDoc:String):TJSONData; function JsonPost(aDoc:String; data:TJSONObject):TJSONData; published property BaseUrl:String read FBaseUrl write SetBaseUrl; property onDebugMsg:TOnDebugMessage read FonDebugMsg write SetonDebugMsg; property Token:String read FToken write SetToken; property TokenName:String read FTokenName write SetTokenName; property OnProcessRequestStart:TNotifyEvent read FOnProcessRequestStart write SetOnProcessRequestStart; property OnProcessRequestFinished:TNotifyEvent read FOnProcessRequestFinished write SetOnProcessRequestFinished; property OnPrepareData:TNotifyEvent read FOnPrepareData write SetOnPrepareData; property onRequestCallback:TRequestCallback read FonRequestCallback write SetonRequestCallback; property onResponseTokenInvalid:TNotifyEvent read FonResponseTokenInvalid write SetonResponseTokenInvalid; end; //TRequesterThread=class; { TAsyncJsonRequester } TAsyncJsonRequester=class(TJsonRequester) private FThread:TThread; FDebugMsg:String; FDebugType:TDebugType; protected procedure SyncDebug; procedure SyncProcessReqFinish; procedure SyncProcessReqStart; procedure doDebug(aMessage: String; aDebugType: TDebugType); override; procedure doProcessRequestFinished; override; procedure doProcessRequestStart; override; procedure doPrepareData; override; public Procedure AsyncJsonGet(aDoc:String; aCallback:TRequestCallback); Procedure AsyncJsonPost(ADoc:String; aBody:TJSONObject; aCallback:TRequestCallback); constructor Create(AOwner: TComponent); reintroduce; overload; end; { TGetRequesterThread } TGetRequesterThread=class(TThread) private fRequester:TAsyncJsonRequester; fCallback:TRequestCallback; fDoc:String; protected fResp:TJSONData; procedure Execute; override; procedure doCallback; public constructor Create(ARequester:TAsyncJsonRequester; ADoc:String; aCallback:TRequestCallback); destructor Destroy; override; end; { TPostRequesterThread } TPostRequesterThread=class(TGetRequesterThread) private fBody:TJSONObject; protected procedure Execute; override; public constructor Create(ARequester:TAsyncJsonRequester; ADoc:String; aCallback:TRequestCallback;ABody:TJSONObject); destructor Destroy; override; end; implementation { TPostRequesterThread } procedure TPostRequesterThread.Execute; begin fResp:=fRequester.JsonPost(fDoc, fBody); Synchronize(@doCallback); end; constructor TPostRequesterThread.Create(ARequester: TAsyncJsonRequester; ADoc: String; aCallback: TRequestCallback; ABody: TJSONObject); begin fBody:=ABody; inherited Create(ARequester, ADoc, aCallback); end; destructor TPostRequesterThread.Destroy; begin inherited Destroy; end; { TGetRequesterThread } procedure TGetRequesterThread.Execute; begin fResp:=fRequester.JsonGet(fDoc); Synchronize(@doCallback); end; procedure TGetRequesterThread.doCallback; begin if Assigned(fCallback)then fCallback(fRequester, fRequester.Request, fRequester.Response, fResp); end; constructor TGetRequesterThread.Create(ARequester: TAsyncJsonRequester; ADoc: String; aCallback: TRequestCallback); begin fRequester:=ARequester; fDoc:=ADoc; fCallback:=aCallback; FreeOnTerminate:=True; inherited Create(False); end; destructor TGetRequesterThread.Destroy; begin fRequester.Free; inherited Destroy; end; { TAsyncJsonRequester } procedure TAsyncJsonRequester.SyncDebug; begin inherited doDebug(FDebugMsg, FDebugType); end; procedure TAsyncJsonRequester.SyncProcessReqFinish; begin inherited doProcessRequestFinished; end; procedure TAsyncJsonRequester.SyncProcessReqStart; begin inherited doProcessRequestStart; end; procedure TAsyncJsonRequester.doDebug(aMessage: String; aDebugType: TDebugType); begin FDebugMsg:=aMessage; FDebugType:=aDebugType; if (Assigned(FThread))and (FThread<>nil) then TThread.Synchronize(FThread, @SyncDebug); end; procedure TAsyncJsonRequester.doProcessRequestFinished; begin if (Assigned(FThread))and (FThread<>nil) then TThread.Synchronize(FThread, @SyncProcessReqFinish); end; procedure TAsyncJsonRequester.doProcessRequestStart; begin if (Assigned(FThread))and (FThread<>nil) then TThread.Synchronize(FThread ,@SyncProcessReqStart); end; procedure TAsyncJsonRequester.doPrepareData; begin inherited doPrepareData; end; procedure TAsyncJsonRequester.AsyncJsonGet(aDoc: String; aCallback: TRequestCallback); begin FThread:=TGetRequesterThread.Create(Self, aDoc, aCallback); end; procedure TAsyncJsonRequester.AsyncJsonPost(ADoc: String; aBody: TJSONObject; aCallback: TRequestCallback); begin FThread:=TPostRequesterThread.Create(Self, ADoc, aCallback, aBody); end; constructor TAsyncJsonRequester.Create(AOwner: TComponent); begin inherited Create(AOwner); end; { TJsonRequester } procedure TJsonRequester.SetBaseUrl(AValue: String); begin if FBaseUrl=AValue then Exit; FBaseUrl:=AValue; end; procedure TJsonRequester.SetonDebugMsg(AValue: TOnDebugMessage); begin if FonDebugMsg=AValue then Exit; FonDebugMsg:=AValue; end; procedure TJsonRequester.SetOnPrepareData(AValue: TNotifyEvent); begin if FOnPrepareData=AValue then Exit; FOnPrepareData:=AValue; end; procedure TJsonRequester.SetOnProcessRequestFinished(AValue: TNotifyEvent); begin if FOnProcessRequestFinished=AValue then Exit; FOnProcessRequestFinished:=AValue; end; procedure TJsonRequester.SetOnProcessRequestStart(AValue: TNotifyEvent); begin if FOnProcessRequestStart=AValue then Exit; FOnProcessRequestStart:=AValue; end; procedure TJsonRequester.SetonRequestCallback(AValue: TRequestCallback); begin if FonRequestCallback=AValue then Exit; FonRequestCallback:=AValue; end; procedure TJsonRequester.SetonResponseTokenInvalid(AValue: TNotifyEvent); begin if FonResponseTokenInvalid=AValue then Exit; FonResponseTokenInvalid:=AValue; end; procedure TJsonRequester.SetToken(AValue: String); begin if FToken=AValue then Exit; FToken:=AValue; end; procedure TJsonRequester.SetTokenName(AValue: String); begin if FTokenName=AValue then Exit; FTokenName:=AValue; end; procedure TJsonRequester.doDebug(aMessage: String; aDebugType: TDebugType); begin if Assigned(FonDebugMsg) then FonDebugMsg(Self, aMessage, aDebugType); end; function TJsonRequester.ProcessResponse(aResponse, aDoc: String): TJSONData; var aJson: TJSONObject; begin aJson:=GetJSON(aResponse) as TJSONObject; try Result:=ProcessJsonResp(aJson, aDoc); finally FreeAndNil(aJson); end; end; function TJsonRequester.ProcessJsonResp(aJson: TJSONObject; aDoc:String): TJSONData; var errCode: Integer; res: TJSONData; errMessage: String; begin Result:=nil; errCode:=GetJsonNumberValue(aJson, 'error'); if errCode=0 then begin if aJson.FindPath('data')<>nil then begin res:=aJson.FindPath('data'); Result:=GetJSON(res.AsJSON); end; end else if (errCode=403)or(errCode=401) then begin doDebug(format('Response %s Error [ Token Invalid/Expired ]',[aDoc]), DTError); if Assigned(FonResponseTokenInvalid)then FonResponseTokenInvalid(Self); end else begin errMessage:=GetJsonStringValue(aJson, 'message'); doDebug(format('Response %s Error [%s]',[aDoc, errMessage]), DTError); end; end; procedure TJsonRequester.doProcessRequestStart; begin if Assigned(OnProcessRequestStart) then OnProcessRequestStart(Self); end; procedure TJsonRequester.doProcessRequestFinished; begin if Assigned(OnProcessRequestFinished) then OnProcessRequestFinished(Self); end; procedure TJsonRequester.doPrepareData; begin if Assigned(OnPrepareData) then OnPrepareData(Self); end; procedure TJsonRequester.doCallback(aData: TJSONData); begin if Assigned(onRequestCallback) then onRequestCallback(Self, Request, Response, aData); end; procedure TJsonRequester.Prepare; begin Request.ContentType:='application/json'; if Token<>'' then Request.CustomHeaders.Values[TokenName]:=Token; doPrepareData; end; function TJsonRequester.JsonGet(aDoc: String): TJSONData; var resp: String; begin Result:=nil; Prepare; doDebug(Format('GET Command "%s" ',[aDoc]), DTInfo3); doProcessRequestStart; try try resp:=Get(BaseUrl+aDoc); Result:=ProcessResponse(resp, aDoc); doDebug(Format('GET Command "%s" Success',[aDoc]), DTInfo3); //doCallback(Result); except on e:exception do doDebug(Format('GET Command "%s" Error [%s]',[aDoc, e.Message]), DTException); end; finally doProcessRequestFinished; Disconnect; end; end; function TJsonRequester.JsonPost(aDoc: String; data: TJSONObject): TJSONData; var stream: TStringStream; resp: String; strJson: String; len: Integer; begin Result:=nil; Prepare; strJson:=data.AsJSON; len:=Length(strJson); doDebug(Format('POST Command URL "%s" Body: %s',[aDoc, strJson]), DTInfo3); stream:=TStringStream.Create(strJson); doProcessRequestStart; try try resp:=Post(BaseUrl+aDoc, stream); Result:=ProcessResponse(resp, aDoc); doDebug(Format('POST Command URL "%s" Success',[aDoc]), DTInfo3); except on e:exception do doDebug(Format('POST Command "%s" Error [%s]',[aDoc, e.Message]), DTException); end; finally doProcessRequestFinished; data.Free; stream.Free; Disconnect; end; end; end.
unit dxStandardControlsSkinHelper; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxSkinsCore, dxSkinsDefaultPainters, cxLookAndFeels, dxSkinsForm, cxControls, cxContainer, cxEdit, cxGroupBox, cxRadioGroup, Menus, cxScrollBox, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, dxSkinsLookAndFeelPainter, cxTextEdit, cxMemo, dxDockControl, dxSkinInfo, cxPC, cxButtonEdit, cxLabel; type {{Внутренняя ошибка приложения. Проблема при чтении свойств скина} ESkinHelperException = class(Exception); TdxStandardControlsSkinHelper = class(TObject) private FPrevRootLookAndFeelChanged: TcxLookAndFeelChangedEvent; FLeftOffsetForDxEdit: Integer; constructor PrivateCreate(); function NeedProcess: Boolean; procedure SetLeftOffsetForDxEdit(const Value: Integer); protected procedure ProcessScreen; procedure ProcessForm(AForm: TCustomForm); procedure ProcessControl(AControl: TControl); virtual; procedure ActiveFormChanged(Sender: TObject); procedure RootLookAndFeelChanged(Sender: TcxLookAndFeel; AChangedValues: TcxLookAndFeelValues); public constructor Create(); destructor Destroy;override; procedure AssignEventHandlers; procedure ResetEventHandlers; {{Singleton pattern} class function GetInstance(): TdxStandardControlsSkinHelper; {{ Настройка в соответствии со скином Если контрол содержит в себе другие контролы, то настраиваем и их тоже} procedure ProcessControls(AControl: TControl); {{Отступ слева, между границей контрола и текстом, который будет задан для всех наследников от TcxCustomEdit. Можно задать это св-во в -1, чтобы не присваивался} property LeftOffsetForDxEdit: Integer read FLeftOffsetForDxEdit write SetLeftOffsetForDxEdit; end; ECantGetSkinElementEsException = class(ESkinHelperException); {{Позволяет считывать элементы из скина} TesSkinElementGetter = class {{groupName - имя группы в скине. elementName - имя элемента в группе. Если не удалось найти группу/элемент, выбрасывает ECantGetColorEsException} class function GetElement(const groupName, elementName: string): TdxSkinElement; end; {{Позволяет считывать цвета из скина} TesSkinColorGetter = class(TesSkinElementGetter) public {{groupName - имя группы в скине. elementName - имя элемента в группе. Если не удалось найти группу/элемент, выбрасывает ECantGetColorEsException} class function GetColor(const groupName, elementName: string): TColor; class function ColorByName(const colorName: string): TColor; end; function GetSkinFormContentColor(): TColor; implementation var StandardControlsSkinHelper: TdxStandardControlsSkinHelper; procedure RegisterStandardControlsSkinHelper; begin StandardControlsSkinHelper := TdxStandardControlsSkinHelper.PrivateCreate(); StandardControlsSkinHelper.AssignEventHandlers; end; procedure UnregisterStandardControlsSkinHelper; begin if StandardControlsSkinHelper <> nil then begin StandardControlsSkinHelper.ResetEventHandlers; FreeAndNil(StandardControlsSkinHelper); end; end; var FFormColor: TColor = clNone; function GetSkinFormContentColor(): TColor; begin if FFormColor = clNone then FFormColor := TesSkinColorGetter.GetColor('Form', 'FormContent'); Result := FFormColor; end; { TesSkinColorGetter } class function TesSkinColorGetter.GetColor(const groupName, elementName: string): TColor; begin Result := GetElement(groupName, elementName).Color; end; class function TesSkinColorGetter.ColorByName(const colorName: string): TColor; var ASkinInfo: TdxSkinInfo; skinColor: TdxSkinColor; begin if Trim(colorName) = '' then raise ECantGetSkinElementEsException.Create('Empty colorName'); if not RootLookAndFeel.SkinPainter.GetPainterData(ASkinInfo) then raise ECantGetSkinElementEsException.Create('not RootLookAndFeel.SkinPainter.GetPainterData(ASkinInfo)'); skinColor := ASkinInfo.Skin.GetColorByName(colorName); if skinColor = nil then raise ECantGetSkinElementEsException.CreateFmt('skinColor = nil for colorName= "%s"', [colorName]); Result:= skinColor.Value; end; { TdxStandardControlsSkinHelper } constructor TdxStandardControlsSkinHelper.PrivateCreate; begin inherited Create(); LeftOffsetForDxEdit:= 4; end; constructor TdxStandardControlsSkinHelper.Create; begin PrivateCreate(); raise ESkinHelperException.Create('Предполагается, что это Singleton. Use TdxStandardControlsSkinHelper.GetInstance() instead'); end; destructor TdxStandardControlsSkinHelper.Destroy; begin inherited; end; class function TdxStandardControlsSkinHelper.GetInstance: TdxStandardControlsSkinHelper; begin Result:= StandardControlsSkinHelper; end; procedure TdxStandardControlsSkinHelper.ActiveFormChanged(Sender: TObject); begin if NeedProcess and Assigned(Sender) then ProcessForm((Sender as TScreen).ActiveCustomForm) end; function TdxStandardControlsSkinHelper.NeedProcess: Boolean; begin Result := RootLookAndFeel.Painter.InheritsFrom(TdxSkinLookAndFeelPainter); end; type THackcxCustomEdit = class(TcxCustomEdit); procedure TdxStandardControlsSkinHelper.ProcessControl(AControl: TControl); procedure TuneCxCustomEdit(edit: THackcxCustomEdit); begin if (edit = nil) or (edit.InnerControl = nil) then exit; if LeftOffsetForDxEdit> 0 then // а не поплывут ли вычисляемые контролом размеры? SendMessage(edit.InnerControl.Handle, EM_SETMARGINS, EC_LEFTMARGIN + EC_RIGHTMARGIN, LeftOffsetForDxEdit*$20001+$10000); if edit.Properties.ReadOnly and not (svColor in edit.Style.AssignedValues) then edit.Style.Color := GetSkinFormContentColor(); end; begin if AControl is TcxLabel then TcxLabel(AControl).Transparent := True; if (AControl is TcxCustomEdit) then TuneCxCustomEdit(THackcxCustomEdit(aControl)); if (AControl.Parent is TForm) or (AControl.Parent is TFrame) then begin if (AControl is TPanel) and TPanel(AControl).ParentColor then TPanel(AControl).Color := GetSkinFormContentColor(); if (AControl is TcxGroupBox) and TcxGroupBox(AControl).ParentColor then TcxGroupBox(AControl).Style.Color := GetSkinFormContentColor(); if (AControl is TcxScrollBox) and TcxScrollBox(AControl).ParentColor then TcxScrollBox(AControl).Color := GetSkinFormContentColor(); if (AControl is TcxRadioButton) and TcxRadioButton(AControl).ParentColor then TcxRadioButton(AControl).Color := GetSkinFormContentColor(); if (AControl is TFrame) and TFrame(AControl).ParentColor then TFrame(AControl).Color := GetSkinFormContentColor(); end; end; procedure TdxStandardControlsSkinHelper.ProcessControls(AControl: TControl); var i: integer; begin if AControl = nil then Exit; ProcessControl(AControl); if AControl is TWinControl then begin for i := 0 to TWinControl(AControl).ControlCount - 1 do ProcessControls(TWinControl(AControl).Controls[i]); end; if AControl is TdxCustomDockControl then begin for i := 0 to TdxCustomDockControl(AControl).ControlCount - 1 do ProcessControls(TdxCustomDockControl(AControl).Controls[i]); end; end; procedure TdxStandardControlsSkinHelper.ProcessForm(AForm: TCustomForm); begin if AForm = nil then Exit; ProcessControls(AForm); end; procedure TdxStandardControlsSkinHelper.ProcessScreen; var I: Integer; begin for I := 0 to Screen.FormCount - 1 do ProcessForm(Screen.Forms[I]); end; procedure TdxStandardControlsSkinHelper.RootLookAndFeelChanged( Sender: TcxLookAndFeel; AChangedValues: TcxLookAndFeelValues); begin if NeedProcess then ProcessScreen; if Assigned(FPrevRootLookAndFeelChanged) then FPrevRootLookAndFeelChanged(Sender, AChangedValues); end; procedure TdxStandardControlsSkinHelper.SetLeftOffsetForDxEdit(const Value: Integer); begin if Value > 20 then raise ESkinHelperException.CreateFmt('Value is too big (%d). 20 is max', [Value]); FLeftOffsetForDxEdit := Value; end; procedure TdxStandardControlsSkinHelper.ResetEventHandlers; begin RootLookAndFeel.OnChanged := FPrevRootLookAndFeelChanged; end; procedure TdxStandardControlsSkinHelper.AssignEventHandlers; begin FPrevRootLookAndFeelChanged := RootLookAndFeel.OnChanged; RootLookAndFeel.OnChanged := RootLookAndFeelChanged; Screen.OnActiveFormChange := ActiveFormChanged; end; { TesSkinElementGetter } class function TesSkinElementGetter.GetElement(const groupName, elementName: string): TdxSkinElement; var ASkinInfo: TdxSkinInfo; group: TdxSkinControlGroup; element: TdxSkinElement; begin if Trim(groupName) = '' then raise ECantGetSkinElementEsException.Create('Empty groupName'); if Trim(elementName) = '' then raise ECantGetSkinElementEsException.Create('Empty elementName'); if not RootLookAndFeel.SkinPainter.GetPainterData(ASkinInfo) then raise ECantGetSkinElementEsException.Create('not RootLookAndFeel.SkinPainter.GetPainterData(ASkinInfo)'); group:= ASkinInfo.Skin.GetGroupByName(groupName); if group = nil then raise ECantGetSkinElementEsException.CreateFmt('group = nil for groupName= "%s"', [groupName]); element:= group.GetElementByName(elementName); if element = nil then raise ECantGetSkinElementEsException.CreateFmt('element = nil for elementName= "%s"', [elementName]); Result:= Element; end; initialization RegisterStandardControlsSkinHelper; finalization UnregisterStandardControlsSkinHelper; end.
unit servmain; { This is "Application Server" for this demo. You must compile and run this program once before running the client application. The remote data module (ServData) implments the actual OLE server that the client communicates with. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Grids, DBGrids, Db; type TMainForm = class(TForm) Panel1: TPanel; QueryCount: TLabel; ClientCount: TLabel; private FQueryCount: Integer; FClientCount: Integer; public procedure UpdateClientCount(Incr: Integer); procedure IncQueryCount; end; var MainForm: TMainForm; implementation {$R *.dfm} { These procedures update the display of the application server to show how many clients are connected and how many queries have been exectued. } procedure TMainForm.UpdateClientCount(Incr: Integer); begin FClientCount := FClientCount + Incr; ClientCount.Caption := IntToStr(FClientCount); end; procedure TMainForm.IncQueryCount; begin Inc(FQueryCount); QueryCount.Caption := IntToStr(FQueryCount); end; end.
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Модуль реализации Unit Task для Bollinger Bands для подбора размера канала и периода History: -----------------------------------------------------------------------------} unit FC.StockChart.UnitTask.BB.AdjustWidth; interface {$I Compiler.inc} uses SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses FC.StockChart.UnitTask.BB.AdjustWidthDialog; type //Специальный Unit Task для автоматического подбора размеров грани и длины периода. //Подюор оусщестьвляется прямым перебором. TStockUnitTaskBBAdjustWidth = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskBBAdjustWidth } function TStockUnitTaskBBAdjustWidth.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorBB); if result then aOperationName:='BB: Adjust Channel Width'; end; procedure TStockUnitTaskBBAdjustWidth.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmAdjustWidthDialog.Run(aIndicator as ISCIndicatorBB); end; initialization //Регистрируем Unit Task StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskBBAdjustWidth.Create); end.
unit HGM.GraphQL; interface uses System.Classes, REST.Client, REST.Json.Types, System.StrUtils, REST.Types, System.SysUtils, System.JSON, HGM.GraphQL.Query; type TGraphQLClient = class(TComponent) private FClient: TRESTClient; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Call(out Response: TJSONObject; Query: TGraphQuery; Variables: TJSONObject = nil): Integer; overload; function Call(out Response: TJSONObject; const OperationName, Query: string; Variables: TJSONObject = nil): Integer; overload; function Call(const OperationName, Query: string; Variables: TJSONObject = nil): Integer; overload; property Client: TRESTClient read FClient; end; implementation uses System.NetConsts; { TGraphQLClient } function TGraphQLClient.Call(out Response: TJSONObject; const OperationName, Query: string; Variables: TJSONObject): Integer; var Body: TJSONObject; Request: TRESTRequest; begin Response := nil; Body := TJSONObject.Create; Body.AddPair('operationName', OperationName); Body.AddPair('query', Query); if Assigned(Variables) then Body.AddPair('variables', Variables); Request := TRESTRequest.Create(nil); Request.Client := Client; try //raise Exception.Create(Body.ToJSON); Request.AddBody(Body); Request.Method := TRESTRequestMethod.rmPOST; Request.Execute; with Request.Response do begin Response := TJSONObject(TJSONObject.ParseJSONValue(Content)); Result := StatusCode; end; finally Request.Free; Body.Free; end; end; function TGraphQLClient.Call(const OperationName, Query: string; Variables: TJSONObject): Integer; var Response: TJSONObject; begin Result := Call(Response, OperationName, Query, Variables); if Assigned(Response) then Response.Free; end; function TGraphQLClient.Call(out Response: TJSONObject; Query: TGraphQuery; Variables: TJSONObject): Integer; begin Result := Call(Response, Query.Name, Query.ToString, Variables); end; constructor TGraphQLClient.Create(AOwner: TComponent); begin inherited; FClient := TRESTClient.Create(nil); FClient.RaiseExceptionOn500 := False; FClient.ContentType := CONTENTTYPE_APPLICATION_JSON; end; destructor TGraphQLClient.Destroy; begin FClient.Free; inherited; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLODECustomColliders<p> Custom ODE collider implementations.<p> <b>Credits : </b><font size=-1><ul> <li>Heightfield collider code originally adapted from Mattias Fagerlund's DelphiODE terrain collision demo. Website: http://www.cambrianlabs.com/Mattias/DelphiODE </ul> <b>History : </b><font size=-1><ul> <li>19/06/14 - PW - Changed some types from Single to TdReal to permit ODE be double based in ODEImport.pas <li>10/11/12 - PW - Added CPP compatibility: restored records with arrays instead of vector arrays <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>17/11/09 - DaStr - Improved Unix compatibility (thanks Predator) (BugtrackerID = 2893580) <li>08/11/09 - DaStr - Improved FPC compatibility (thanks Predator) (BugtrackerID = 2893580) <li>12/04/08 - DaStr - Cleaned up uses section (thanks Sandor Domokos) (BugtrackerID = 1808373) <li>06/02/08 - Mrqzzz - Upgrade to ODE 0.9 (by Paul Robello) Fixed reference to odeimport <li>25/12/07 - DaStr - Fixed memory leak in TGLODECustomCollider.Destroy() (thanks Sandor Domokos) (BugtrackerID = 1808373) <li>10/10/07 - Mrqzzz - Fixed reference ODEGL.ODERToGLSceneMatrix <li>07/10/07 - Mrqzzz - Added reference to ODEGL <li>11/09/07 - Mrqzzz - Added reference to ODEImport <li>07/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) Added $I GLScene.inc <li>08/12/04 - SG - Added contact point rendering to TGLODECustomCollider. <li>07/12/04 - SG - Added new TGLODECustomCollider class, Geom collide code now uses Resolution to determine the number of contact points to generate. <li>19/11/04 - SG - Changed TGLODETerrainCollider to TGLODEHeightField which now inherits from TGLODEBehaviour and works for both TGLTerrainRenderer and TGLHeightField objects. Added Capsule, Cylinder and Cone collider code for the heightfield collider. <li>23/04/04 - SG - Removed freeform static collider <li>29/10/03 - SG - Fix for GLODETerrainCollider (Matheus Degiovani) <li>30/07/03 - SG - Creation. </ul> } unit GLODECustomColliders; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, System.Math, // GLS GLODEManager, ODEGL, ODEImport, GLVectorGeometry, GLVectorLists, GLScene, GLTerrainRenderer, GLGraph, XCollection, OpenGLTokens, GLContext, GLTexture, GLColor, GLRenderContextInfo, GLState; type TContactPoint = class public Position, Normal: TAffineVector; Depth: Single; end; // TGLODECustomCollider // {: The custom collider is designed for generic contact handling. There is a contact point generator for sphere, box, capped cylinder, cylinder and cone geoms.<p> Once the contact points for a collision are generated the abstract Collide function is called to generate the depth and the contact position and normal. These points are then sorted and the deepest are applied to ODE. } TGLODECustomCollider = class(TGLODEBehaviour) private { Private Declarations } FGeom: PdxGeom; FContactList, FContactCache: TList; FTransform: TMatrix; FContactResolution: Single; FRenderContacts: Boolean; FContactRenderPoints: TAffineVectorList; FPointSize: Single; FContactColor: TGLColor; protected { Protected Declarations } procedure Initialize; override; procedure Finalize; override; procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; //: Test a position for a collision and fill out the contact information. function Collide(aPos: TAffineVector; var Depth: Single; var cPos, cNorm: TAffineVector): Boolean; virtual; abstract; //: Clears the contact list so it's ready for another collision. procedure ClearContacts; //: Add a contact point to the list for ApplyContacts to processes. procedure AddContact(x, y, z: TdReal); overload; procedure AddContact(pos: TAffineVector); overload; //: Sort the current contact list and apply the deepest to ODE. function ApplyContacts(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; {: Set the transform used that transforms contact points generated with AddContact. } procedure SetTransform(ATransform: TMatrix); procedure SetContactResolution(const Value: Single); procedure SetRenderContacts(const Value: Boolean); procedure SetPointSize(const Value: Single); procedure SetContactColor(const Value: TGLColor); public { Public Declarations } constructor Create(AOwner: TXCollection); override; destructor Destroy; override; procedure Render(var rci: TRenderContextInfo); override; property Geom: PdxGeom read FGeom; published {: Defines the resolution of the contact points created for the colliding Geom. The number of contact points generated change base don the size of the object and the ContactResolution. Lower values generate higher resolution contact boundaries, and thus smoother but slower collisions. } property ContactResolution: Single read FContactResolution write SetContactResolution; {: Toggle contact point rendering on and off. (Rendered through the assigned Manager.RenderPoint. } property RenderContacts: Boolean read FRenderContacts write SetRenderContacts; //: Contact point rendering size (in pixels). property PointSize: Single read FPointSize write SetPointSize; //: Contact point rendering color. property ContactColor: TGLColor read FContactColor write SetContactColor; end; // TGLODEHeightField // {: Add this behaviour to a TGLHeightField or TGLTerrainRenderer to enable height based collisions for spheres, boxes, capped cylinders, cylinders and cones. } TGLODEHeightField = class(TGLODECustomCollider) protected { Protected Declarations } procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; function Collide(aPos: TAffineVector; var Depth: Single; var cPos, cNorm: TAffineVector): Boolean; override; public { Public Declarations } constructor Create(AOwner: TXCollection); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: Boolean; override; class function CanAddTo(collection: TXCollection): Boolean; override; end; function GetODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField; function GetOrCreateODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField; //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ implementation //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ var vCustomColliderClass: TdGeomClass; vCustomColliderClassNum: Integer; // GetODEHeightField // function GetODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField; begin result := TGLODEHeightField(obj.Behaviours.GetByClass(TGLODEHeightField)); end; // GetOrCreateODEHeightField // function GetOrCreateODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField; begin result := TGLODEHeightField(obj.GetOrCreateBehaviour(TGLODEHeightField)); end; // GetColliderFromGeom // function GetColliderFromGeom(aGeom: PdxGeom): TGLODECustomCollider; var temp: TObject; begin Result := nil; temp := dGeomGetData(aGeom); if Assigned(temp) then if temp is TGLODECustomCollider then Result := TGLODECustomCollider(temp); end; // ContactSort // function ContactSort(Item1, Item2: Pointer): Integer; var c1, c2: TContactPoint; begin c1 := TContactPoint(Item1); c2 := TContactPoint(Item2); if c1.Depth > c2.Depth then result := -1 else if c1.Depth = c2.Depth then result := 0 else result := 1; end; // CollideSphere // function CollideSphere(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; cdecl; var Collider: TGLODECustomCollider; i, j, res: Integer; pos: PdVector3; R: PdMatrix3; rmat, mat: TMatrix; rad, dx, dy, dz: TdReal; begin Result := 0; Collider := GetColliderFromGeom(o1); if not Assigned(Collider) then exit; pos := dGeomGetPosition(o2); R := dGeomGetRotation(o2); ODEGL.ODERToGLSceneMatrix(mat, R^, pos^); Collider.SetTransform(mat); rad := dGeomSphereGetRadius(o2); res := Round(10 * rad / Collider.ContactResolution); if res < 8 then res := 8; Collider.AddContact(0, 0, -rad); Collider.AddContact(0, 0, rad); rmat := CreateRotationMatrixZ(2 * Pi / res); for i := 0 to res - 1 do begin mat := MatrixMultiply(rmat, mat); Collider.SetTransform(mat); for j := -(res div 2) + 1 to (res div 2) - 1 do begin dx := rad * cos(j * Pi / res); dy := 0; dz := rad * sin(j * Pi / res); Collider.AddContact(dx, dy, dz); end; end; Result := Collider.ApplyContacts(o1, o2, flags, contact, skip); Collider.SetTransform(IdentityHMGMatrix); end; // CollideBox // function CollideBox(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; cdecl; var Collider: TGLODECustomCollider; i, j, res: Integer; rcpres, len1, len2: Single; s: TdVector3; pos: PdVector3; R: PdMatrix3; mat: TMatrix; begin Result := 0; Collider := GetColliderFromGeom(o1); if not Assigned(Collider) then exit; pos := dGeomGetPosition(o2); R := dGeomGetRotation(o2); ODEGL.ODERToGLSceneMatrix(mat, R^, pos^); Collider.SetTransform(mat); dGeomBoxGetLengths(o2, s); res := Round(Sqrt(MaxFloat([s[0], s[1], s[2]])) / Collider.ContactResolution); if res < 1 then res := 1; rcpres := 1 / res; s[0] := 0.5 * s[0]; s[1] := 0.5 * s[1]; s[2] := 0.5 * s[2]; with Collider do begin // Corners AddContact(s[0], s[1], s[2]); AddContact(s[0], s[1], -s[2]); AddContact(s[0], -s[1], s[2]); AddContact(s[0], -s[1], -s[2]); AddContact(-s[0], s[1], s[2]); AddContact(-s[0], s[1], -s[2]); AddContact(-s[0], -s[1], s[2]); AddContact(-s[0], -s[1], -s[2]); // Edges for i := -(res - 1) to (res - 1) do begin len1 := i * rcpres * s[0]; AddContact(len1, s[1], s[2]); AddContact(len1, s[1], -s[2]); AddContact(len1, -s[1], s[2]); AddContact(len1, -s[1], -s[2]); len1 := i * rcpres * s[1]; AddContact(s[0], len1, s[2]); AddContact(s[0], len1, -s[2]); AddContact(-s[0], len1, s[2]); AddContact(-s[0], len1, -s[2]); len1 := i * rcpres * s[2]; AddContact(s[0], s[1], len1); AddContact(s[0], -s[1], len1); AddContact(-s[0], s[1], len1); AddContact(-s[0], -s[1], len1); end; // Faces for i := -(res - 1) to (res - 1) do for j := -(res - 1) to (res - 1) do begin len1 := i * rcpres * s[0]; len2 := j * rcpres * s[1]; AddContact(len1, len2, s[2]); AddContact(len1, len2, -s[2]); len2 := j * rcpres * s[2]; AddContact(len1, s[1], len2); AddContact(len1, -s[1], len2); len1 := i * rcpres * s[1]; AddContact(s[0], len1, len2); AddContact(-s[0], len1, len2); end; end; Result := Collider.ApplyContacts(o1, o2, flags, contact, skip); Collider.SetTransform(IdentityHMGMatrix); end; // CollideCapsule // function CollideCapsule(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; cdecl; var Collider: TGLODECustomCollider; i, j, res: Integer; pos: PdVector3; R: PdMatrix3; mat, rmat: TMatrix; rad, len, dx, dy, dz: TdReal; begin Result := 0; Collider := GetColliderFromGeom(o1); if not Assigned(Collider) then exit; pos := dGeomGetPosition(o2); R := dGeomGetRotation(o2); ODEGL.ODERToGLSceneMatrix(mat, R^, pos^); Collider.SetTransform(mat); dGeomCapsuleGetParams(o2, rad, len); res := Round(5 * MaxFloat(4 * rad, len) / Collider.ContactResolution); if res < 8 then res := 8; rmat := CreateRotationMatrixZ(2 * Pi / res); with Collider do begin AddContact(0, 0, -rad - 0.5 * len); AddContact(0, 0, rad + 0.5 * len); for i := 0 to res - 1 do begin mat := MatrixMultiply(rmat, mat); SetTransform(mat); for j := 0 to res do AddContact(rad, 0, len * (j / res - 0.5)); for j := 1 to (res div 2) - 1 do begin dx := rad * cos(j * Pi / res); dy := 0; dz := rad * sin(j * Pi / res); Collider.AddContact(dx, dy, -dz - 0.5 * len); Collider.AddContact(dx, dy, dz + 0.5 * len); end; end; end; Result := Collider.ApplyContacts(o1, o2, flags, contact, skip); Collider.SetTransform(IdentityHMGMatrix); end; // CollideCylinder // function CollideCylinder(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; cdecl; var Collider: TGLODECustomCollider; i, j, res: Integer; pos: PdVector3; R: PdMatrix3; mat: TMatrix; rad, len, dx, dy: TdReal; begin Result := 0; Collider := GetColliderFromGeom(o1); if not Assigned(Collider) then exit; pos := dGeomGetPosition(o2); R := dGeomGetRotation(o2); ODEGL.ODERToGLSceneMatrix(mat, R^, pos^); Collider.SetTransform(mat); dGeomCylinderGetParams(o2, rad, len); res := Round(5 * MaxFloat(4 * rad, len) / Collider.ContactResolution); if res < 8 then res := 8; with Collider do begin AddContact(0, -0.5 * len, 0); AddContact(0, 0.5 * len, 0); for i := 0 to res - 1 do begin SinCosine(2 * Pi * i / res, rad, dy, dx); AddContact(dx, -0.5 * len, dy); AddContact(dx, 0, dy); AddContact(dx, 0.5 * len, dy); for j := 0 to res do AddContact(dx, len * (j / res - 0.5), dy); for j := 1 to (res div 2) - 1 do begin SinCosine(2 * Pi * i / res, rad * j / (res div 2), dy, dx); AddContact(dx, -0.5 * len, dy); AddContact(dx, 0.5 * len, dy); end; end; end; Result := Collider.ApplyContacts(o1, o2, flags, contact, skip); Collider.SetTransform(IdentityHMGMatrix); end; // GetCustomColliderFn // function GetCustomColliderFn(num: Integer): TdColliderFn; cdecl; begin if num = dSphereClass then Result := CollideSphere else if num = dBoxClass then Result := CollideBox else if num = dCapsuleClass then Result := CollideCapsule else if num = dCylinderClass then Result := CollideCylinder else Result := nil; end; // --------------- // --------------- TGLODECustomCollider -------------- // --------------- // Create // constructor TGLODECustomCollider.Create(AOwner: TXCollection); begin inherited; FContactList := TList.Create; FContactCache := TList.Create; FContactResolution := 1; FRenderContacts := False; FContactRenderPoints := TAffineVectorList.Create; FContactColor := TGLColor.CreateInitialized(Self, clrRed, NotifyChange); FPointSize := 3; end; // Destroy // destructor TGLODECustomCollider.Destroy; var i: integer; begin FContactList.Free; for i := 0 to FContactCache.Count - 1 do TContactPoint(FContactCache[i]).Free; FContactCache.Free; FContactRenderPoints.Free; FContactColor.Free; inherited; end; // Initialize // procedure TGLODECustomCollider.Initialize; begin if not Assigned(Manager) then exit; if not Assigned(Manager.Space) then exit; if vCustomColliderClassNum = 0 then begin with vCustomColliderClass do begin bytes := 0; collider := GetCustomColliderFn; aabb := dInfiniteAABB; aabb_test := nil; dtor := nil; end; vCustomColliderClassNum := dCreateGeomClass(vCustomColliderClass); end; FGeom := dCreateGeom(vCustomColliderClassNum); dGeomSetData(FGeom, Self); dSpaceAdd(Manager.Space, FGeom); inherited; end; // Finalize // procedure TGLODECustomCollider.Finalize; begin if not Initialized then exit; if Assigned(FGeom) then begin dGeomDestroy(FGeom); FGeom := nil; end; inherited; end; // WriteToFiler // procedure TGLODECustomCollider.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive version WriteFloat(FContactResolution); WriteBoolean(FRenderContacts); WriteFloat(FPointSize); Write(PByte(FContactColor.AsAddress)^, 4); end; end; // ReadFromFiler // procedure TGLODECustomCollider.ReadFromFiler(reader: TReader); var archiveVersion: Integer; begin inherited; with reader do begin archiveVersion := ReadInteger; Assert(archiveVersion = 0); // Archive version FContactResolution := ReadFloat; FRenderContacts := ReadBoolean; FPointSize := ReadFloat; Read(PByte(FContactColor.AsAddress)^, 4); end; end; // ClearContacts // procedure TGLODECustomCollider.ClearContacts; begin FContactList.Clear; end; // AddContact (x,y,z) // procedure TGLODECustomCollider.AddContact(x, y, z: TdReal); begin AddContact(AffineVectorMake(x, y, z)); end; // AddContact (pos) // procedure TGLODECustomCollider.AddContact(pos: TAffineVector); var absPos, colPos, colNorm: TAffineVector; depth: Single; ContactPoint: TContactPoint; begin absPos := AffineVectorMake(VectorTransform(PointMake(pos), FTransform)); if Collide(absPos, depth, colPos, colNorm) then begin if FContactList.Count < FContactCache.Count then ContactPoint := FContactCache[FContactList.Count] else begin ContactPoint := TContactPoint.Create; FContactCache.Add(ContactPoint); end; ContactPoint.Position := colPos; ContactPoint.Normal := colNorm; ContactPoint.Depth := depth; FContactList.Add(ContactPoint); end; if FRenderContacts and Manager.Visible and Manager.VisibleAtRunTime then FContactRenderPoints.Add(absPos); end; // ApplyContacts // function TGLODECustomCollider.ApplyContacts(o1, o2: PdxGeom; flags: Integer; contact: PdContactGeom; skip: Integer): Integer; var i, maxContacts: integer; begin FContactList.Sort(ContactSort); Result := 0; maxContacts := flags and $FFFF; try for i := 0 to FContactList.Count - 1 do begin if Result >= maxContacts then Exit; with TContactPoint(FContactList[i]) do begin contact.depth := Depth; contact.pos[0] := Position.V[0]; contact.pos[1] := Position.V[1]; contact.pos[2] := Position.V[2]; contact.pos[3] := 1; contact.normal[0] := -Normal.V[0]; contact.normal[1] := -Normal.V[1]; contact.normal[2] := -Normal.V[2]; contact.normal[3] := 0; end; contact.g1 := o1; contact.g2 := o2; contact := PdContactGeom(Integer(contact) + skip); Inc(Result); end; finally ClearContacts; end; end; // SetTransform // procedure TGLODECustomCollider.SetTransform(ATransform: TMatrix); begin FTransform := ATransform; end; // SetContactResolution // procedure TGLODECustomCollider.SetContactResolution(const Value: Single); begin FContactResolution := Value; if FContactResolution <= 0 then FContactResolution := 0.01; end; // Render // procedure TGLODECustomCollider.Render(var rci: TRenderContextInfo); var i: Integer; begin if FRenderContacts and (FContactRenderPoints.Count > 0) then begin GL.Color3fv(FContactColor.AsAddress); rci.GLStates.PointSize := FPointSize; GL.Begin_(GL_POINTS); for i := 0 to FContactRenderPoints.Count - 1 do GL.Vertex3fv(@FContactRenderPoints.List[i]); GL.End_; end; FContactRenderPoints.Clear; end; // SetRenderContacts // procedure TGLODECustomCollider.SetRenderContacts(const Value: Boolean); begin if Value <> FRenderContacts then begin FRenderContacts := Value; NotifyChange(Self); end; end; // SetContactColor // procedure TGLODECustomCollider.SetContactColor(const Value: TGLColor); begin FContactColor.Assign(Value); end; // SetPointSize // procedure TGLODECustomCollider.SetPointSize(const Value: Single); begin if Value <> FPointSize then begin FPointSize := Value; NotifyChange(Self); end; end; // --------------- // --------------- TGLODEHeightField -------------- // --------------- // Create // constructor TGLODEHeightField.Create(AOwner: TXCollection); var Allow: Boolean; begin Allow := False; if Assigned(AOwner) then begin if Assigned(AOwner.Owner) then begin if ((AOwner.Owner) is TGLTerrainRenderer) or ((AOwner.Owner) is TGLHeightField) then Allow := True; end; end; if not Allow then raise Exception.Create('This element must be a behaviour of a TGLTerrainRenderer or TGLHeightField'); inherited Create(AOwner); end; // WriteToFiler // procedure TGLODEHeightField.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive version end; end; // ReadFromFiler // procedure TGLODEHeightField.ReadFromFiler(reader: TReader); var archiveVersion: Integer; begin inherited; with reader do begin archiveVersion := ReadInteger; Assert(archiveVersion = 0); // Archive version end; end; // FriendlyName // class function TGLODEHeightField.FriendlyName: string; begin Result := 'ODE HeightField Collider'; end; // FriendlyDescription // class function TGLODEHeightField.FriendlyDescription: string; begin Result := 'A custom ODE collider powered by it''s parent TGLTerrainRenderer or TGLHeightField'; end; // UniqueItem // class function TGLODEHeightField.UniqueItem: Boolean; begin Result := True; end; // CanAddTo // class function TGLODEHeightField.CanAddTo(collection: TXCollection): Boolean; begin Result := False; if collection is TGLBehaviours then if Assigned(TGLBehaviours(collection).Owner) then if (TGLBehaviours(collection).Owner is TGLHeightField) or (TGLBehaviours(collection).Owner is TGLTerrainRenderer) then Result := True; end; // Collide // function TGLODEHeightField.Collide(aPos: TAffineVector; var Depth: Single; var cPos, cNorm: TAffineVector): Boolean; function AbsoluteToLocal(vec: TVector): TVector; var mat: TMatrix; begin if Owner.Owner is TGLHeightField then Result := TGLHeightField(Owner.Owner).AbsoluteToLocal(vec) else if Owner.Owner is TGLTerrainRenderer then begin mat := TGLTerrainRenderer(Owner.Owner).AbsoluteMatrix; NormalizeMatrix(mat); InvertMatrix(mat); Result := VectorTransform(vec, mat); end else Assert(False); end; function LocalToAbsolute(vec: TVector): TVector; var mat: TMatrix; begin if Owner.Owner is TGLHeightField then Result := TGLHeightField(Owner.Owner).LocalToAbsolute(vec) else if Owner.Owner is TGLTerrainRenderer then begin mat := TGLTerrainRenderer(Owner.Owner).AbsoluteMatrix; NormalizeMatrix(mat); Result := VectorTransform(vec, mat); end else Assert(False); end; function GetHeight(pos: TVector; var height: Single): Boolean; var dummy1: TVector; dummy2: TTexPoint; begin Result := False; if Owner.Owner is TGLTerrainRenderer then begin height := TGLTerrainRenderer(Owner.Owner).InterpolatedHeight(LocalToAbsolute(pos)); Result := True; end else if Owner.Owner is TGLHeightField then begin if Assigned(TGLHeightField(Owner.Owner).OnGetHeight) then begin TGLHeightField(Owner.Owner).OnGetHeight(pos.V[0], pos.V[1], height, dummy1, dummy2); Result := True; end; end; end; const cDelta = 0.1; var localPos: TVector; height: Single; temp1, temp2: TAffineVector; begin localPos := AbsoluteToLocal(PointMake(aPos)); if GetHeight(localPos, height) then begin Depth := height - localPos.V[2]; Result := (Depth > 0); if Result then begin localPos.V[2] := height; cPos := AffineVectorMake(LocalToAbsolute(localPos)); temp1.V[0] := localPos.V[0] + cDelta; temp1.V[1] := localPos.V[1]; temp1.V[2] := localPos.V[2]; GetHeight(PointMake(temp1), temp1.V[2]); temp2.V[0] := localPos.V[0]; temp2.V[1] := localPos.V[1] + cDelta; temp2.V[2] := localPos.V[2]; GetHeight(PointMake(temp2), temp2.V[2]); cNorm := CalcPlaneNormal(AffineVectorMake(localPos), temp1, temp2); cNorm := AffineVectorMake(LocalToAbsolute(VectorMake(cNorm))); end; end else Result := False; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterXCollectionItemClass(TGLODEHeightField); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ finalization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ UnregisterXCollectionItemClass(TGLODEHeightField); end.
unit LuaStream; interface Uses ExtCtrls, Controls, Classes, LuaPas, LuaControl; function CreateStream(L: Plua_State): Integer; cdecl; type TLuaStream = class(TMemoryStream) L:Plua_State; published property Position: Int64 read GetPosition write SetPosition; property Size: Int64 read GetSize write SetSize64; end; implementation Uses Lua, LuaProperties, TypInfo; // ************ STREAM ******************** // function LoadStreamFromFile(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 2); lStream := TLuaStream(GetLuaObject(L, 1)); try lStream.LoadFromFile(lua_tostring(L,2)); lStream.Position := 0; lua_pushnumber(L,lStream.Size); except lua_pushnil(L); end; result := 1; end; function SaveStreamToFile(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 2); lStream := TLuaStream(GetLuaObject(L, 1)); try if (lStream<>nil) then begin lStream.Position := 0; lStream.SaveToFile(lua_tostring(L,2)); lua_pushnumber(L,lStream.Size); end; except lua_pushnil(L); end; result := 1; end; function StreamGet(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 1); lStream := TluaStream(GetLuaObject(L, 1)); if (lStream<>nil) then begin lStream.Position := 0; lua_pushlightuserdata(L,lStream); end else lua_pushnil(L); Result := 1; end; function StreamFree(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 1); lStream := TluaStream(GetLuaObject(L, 1)); if lStream <> nil then lStream.Free; LuaSetTableClear(L, 1); Result := 0; end; function StreamGetPos(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 1); lStream := TluaStream(GetLuaObject(L, 1)); if (lStream<>nil) then begin lua_pushnumber(L,lStream.Position); end else lua_pushnil(L); Result := 1; end; function StreamSetPos(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; pos: Int64; begin CheckArg(L, 2); lStream := TluaStream(GetLuaObject(L, 1)); pos := Int64(lua_tonumber(L, 2)); if (lStream<>nil) then lStream.Position := pos; Result := 0; end; function StreamGetSize(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; begin CheckArg(L, 1); lStream := TluaStream(GetLuaObject(L, 1)); if (lStream<>nil) then begin lua_pushnumber(L,lStream.Size); end else lua_pushinteger(L,0); Result := 1; end; function StreamSetSize(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; size: Int64; begin CheckArg(L, 2); lStream := TluaStream(GetLuaObject(L, 1)); size := Int64(lua_toNumber(L, 2)); if (lStream<>nil) then lStream.Size := size; Result := 0; end; function CreateStream(L: Plua_State): Integer; cdecl; var lStream:TLuaStream; Index: Integer; begin lStream := TLuaStream.Create; Index := -1; lua_newtable(L); LuaSetTableLightUserData(L, Index, HandleStr, Pointer(lStream)); LuaSetTableFunction(L, index, 'LoadFromFile', LoadStreamFromFile); LuaSetTableFunction(L, index, 'SaveToFile', SaveStreamToFile); LuaSetTableFunction(L, index, 'Get', StreamGet); LuaSetTableFunction(L, index, 'GetPosition', StreamGetPos); LuaSetTableFunction(L, index, 'SetPosition', StreamSetPos); LuaSetTableFunction(L, index, 'GetSize', StreamGetSize); LuaSetTableFunction(L, index, 'SetSize', StreamSetSize); LuaSetTableFunction(L, index, 'Free', StreamFree); Result := 1; end; end.
unit StreamUtils; {$WEAKPACKAGEUNIT ON} { Stream helpers. Cached readers/writers. Some comments are in Russian, deal with it *puts on glasses*. (c) himselfv, me@boku.ru. } interface uses SysUtils, Classes{$IFDEF DCC}, UniStrUtils, Windows{$ENDIF}; type EStreamException = class(Exception); const sCannotReadData = 'Cannot read data from the stream'; sCannotWriteData = 'Cannot write data to the stream'; type { Extends TStream with helper methods to read various data format. They're not very efficient by themselves so better use this on fast streams (TMemoryStream, memory-mapped file, cached stream) } TStreamHelper = class helper for TStream public function ReadInt: integer; function ReadInt64: int64; function ReadAnsiChar(out c: AnsiChar): boolean; function ReadWideChar(out c: WideChar): boolean; function ReadAnsiLine: AnsiString; function ReadUniLine: UnicodeString; //assumes Windows UTF-16 procedure WriteInt(const Value: integer); procedure WriteIn64(const Value: int64); function WriteAnsiChar(const c: AnsiChar): boolean; function WriteWideChar(const c: WideChar): boolean; procedure WriteAnsiString(const s: AnsiString); procedure WriteUniString(const s: UnicodeString); end; { A class to speed up reading from low latency streams (usually file streams). Every time you request something from TFileStream, it reads the data from a file. Even with drive cache enabled, it's a kernel-mode operation which is slow. This class tries to overcome the problem by reading data in large chunks. Whenever you request your byte or two, it reads the whole chunk and stores it in local memory. Next time you request another two bytes you'll get them right away, because they're already here. Please remember that you CAN'T use StreamReader on a Stream "for a while". The moment you read your first byte through StreamReader the underlying stream is NOT YOURS ANYMORE. You shouldn't make any reads to the Stream except than through StreamReader. } const DEFAULT_CHUNK_SIZE = 4096; type TStreamReader = class(TStream) protected FStream: TStream; FOwnStream: boolean; FBytesRead: int64; public property Stream: TStream read FStream; property OwnStream: boolean read FOwnStream; property BytesRead: int64 read FBytesRead; protected flag_reallocbuf: boolean; FNextChunkSize: integer; //size of a chunk we'll try to read next time FChunkSize: integer; //size of current chunk buf: pbyte; //cached data ptr: pbyte; //current location in buf adv: integer; //number of bytes read from buf rem: integer; //number of bytes remaining in buf. //adv+rem not always equals to FChunkSize since we could have read only //partial chunk or FChunkSize could have been changed after that. function NewChunk: integer; function UpdateChunk: integer; procedure SetChunkSize(AValue: integer); procedure ResetBuf; function ReallocBuf(ASize: integer): boolean; procedure FreeBuf; public property ChunkSize: integer read FChunkSize write SetChunkSize; property ChunkBytesRemaining: integer read rem; public constructor Create(AStream: TStream; AOwnStream: boolean = false); destructor Destroy; override; procedure JoinStream(AStream: TStream; AOwnsStream: boolean = false); procedure ReleaseStream; protected function GetSize: Int64; override; function GetInternalPosition: integer; function LocalSeek(Offset: Int64; Origin: TSeekOrigin): boolean; public function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Read(var Buffer; Count: Longint): Longint; override; function ReadBuf(ABuf: pbyte; ALen: integer): integer; inline; function Write(const Buffer; Count: Longint): Longint; override; function Peek(var Buffer; ASize: integer): integer; function PeekByte(out b: byte): boolean; end; TStreamWriter = class(TStream) protected FStream: TStream; FOwnStream: boolean; FBytesWritten: int64; public property Stream: TStream read FStream; property OwnStream: boolean read FOwnStream; property BytesWritten: int64 read FBytesWritten; protected FChunkSize: integer; buf: pbyte; ptr: pbyte; used: integer; procedure ResetBuf; procedure FreeBuf; procedure SetChunkSize(AValue: integer); public property ChunkSize: integer read FChunkSize write SetChunkSize; public constructor Create(AStream: TStream; AOwnStream: boolean = false); destructor Destroy; override; procedure JoinStream(AStream: TStream; AOwnsStream: boolean = false); procedure ReleaseStream; protected function GetSize: Int64; override; procedure SetSize(NewSize: Longint); overload; override; procedure SetSize(const NewSize: Int64); overload; override; function GetInternalPosition: integer; public function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function WriteBuf(ABuf: PByte; ALen: integer): integer; inline; procedure Flush; end; { TStringStream Stores or retrieves raw data from a string. If you pass a string, it will be read/updated, else internal buffer is used. } { Don't instantiate } TCustomStringStream = class(TStream) protected FPtr: PByte; FPos: integer; //in bytes function RemainingSize: integer; public function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; end; { Single-byte strings } TAnsiStringStream = class(TCustomStringStream) protected FOwnBuffer: AnsiString; FString: PAnsiString; function GetString: AnsiString; function GetSize: Int64; override; procedure SetSize(NewSize: Longint); override; public constructor Create(AString: PAnsiString = nil); property Data: AnsiString read GetString; end; { Double-byte strings } TUnicodeStringStream = class(TCustomStringStream) protected FOwnBuffer: UnicodeString; FString: PUnicodeString; function GetString: UnicodeString; function GetSize: Int64; override; procedure SetSize(NewSize: Longint); override; public constructor Create(AString: PUnicodeString = nil); property Data: UnicodeString read GetString; end; TStringStream = TUnicodeStringStream; { Cached read/write char-by-char. } const BOM_UTF16LE = WideChar($FEFF); BOM_UTF16BE = WideChar($FFFE); BOM_UTF8 = $BFBBEF; //full version it's EF BB BF type TCharSet = ( csAnsi, csUtf16Le, csUtf16Be, csUtf8 //requires at least 4 bytes of buffer! ); type TCharReader = class(TStreamReader) protected Charset: TCharSet; function DetectCharset: TCharset; public //Create with autodetected encoding constructor Create(AStream: TStream; AOwnStream: boolean = false); overload; //Create with specified encoding (if you don't want auto, set to your default one) constructor Create(AStream: TStream; ACharSet: TCharSet; AOwnStream: boolean = false); overload; function ReadChar(out c: WideChar): boolean; function PeekChar(out c: WideChar): boolean; function ReadLine(out s: UnicodeString): boolean; end; TCharWriter = class(TStreamWriter) protected Charset: TCharset; public //Create with default encoding (UTF16LE) constructor Create(AStream: TStream; AOwnStream: boolean = false); overload; //Create with specified encoding constructor Create(AStream: TStream; ACharSet: TCharSet; AOwnStream: boolean = false); overload; destructor Destroy; override; procedure WriteBom; procedure WriteChar(const c: WideChar); procedure WriteChars(c: PWideChar; len: integer); procedure WriteString(const c: UnicodeString); procedure WriteLine(const s: UnicodeString); end; type TStreamReader2 = class(TStreamReader) public destructor Destroy; override; protected //These are used for ReadStr. Instead of reallocating temporary pchar //every time, we just keep this buffer up while alive. tmpstr_ansi_s: PAnsiChar; tmpstr_ansi_sz: cardinal; tmpstr_wide_s: PWideChar; tmpstr_wide_sz: cardinal; procedure FreeTmpStr; public function TryReadLineA(var s: PAnsiChar; var sz: cardinal): boolean; function TryReadLineW(var s: PWideChar; var sz: cardinal): boolean; procedure ReadLineA(var s: PAnsiChar; var sz: cardinal); procedure ReadLineW(var s: PWideChar; var sz: cardinal); function TryReadStrA(out s: AnsiString): boolean; function TryReadStrW(out s: WideString): boolean; function ReadStrA: AnsiString; function ReadStrW: WideString; public function ReadAnsiChar(out c: AnsiChar): boolean; function ReadWideChar(out c: WideChar): boolean; function ReadUtf8Char(out c: WideChar): boolean; end; implementation { UTF8 Utils } { Parts based on JWBConvert by Fillip Karbt taken from Wakan source code. } const UTF8_VALUE1 = $00; // Value for set bits for single byte UTF-8 Code. UTF8_MASK1 = $80; // Mask (i.e. bits not set by the standard) 0xxxxxxx UTF8_WRITE1 = $ff80; // Mask of bits we cannot allow if we are going to write one byte code UTF8_VALUE2 = $c0; // Two byte codes UTF8_MASK2 = $e0; // 110xxxxx 10yyyyyy UTF8_WRITE2 = $f800; // Mask of bits we cannot allow if we are going to write two byte code UTF8_VALUE3 = $e0; // Three byte codes UTF8_MASK3 = $f0; // 1110xxxx 10yyyyyy 10zzzzzz UTF8_VALUE4 = $f0; // Four byte values UTF8_MASK4 = $f8; // 11110xxx ---- (These values are not supported by JWPce). UTF8_VALUEC = $80; // Continueation byte (10xxxxxx). UTF8_MASKC = $c0; { In both of the following functions UTF8 character sequences are stored as integer. Remember, lowest byte first. You may want to cast this for easy access: } type TUTF8Bytes = array[0..3] of byte; { Converts UCS2-LE character into UTF8 sequence of up to 4 bytes. Returns the number of bytes used } function UCS2toUTF8(const ch: WideChar; out uch: integer): integer; inline; begin if (word(ch) and UTF8_WRITE1)=0 then begin Result:=1; uch:=byte(ch); end else if (word(ch) and UTF8_WRITE2)=0 then begin Result := 2; uch := (UTF8_VALUE2 or byte(word(ch) shr 6)) + (UTF8_VALUEC or byte(word(ch) and $3f)) shl 8; end else begin Result := 3; uch := (UTF8_VALUE3 or byte(word(ch) shr 12)) + (UTF8_VALUEC or byte((word(ch) shr 6) and $3f)) shl 8 + (UTF8_VALUEC or byte(word(ch) and $3f)) shl 16; end; end; { Converts a sequence of up to 4 bytes in UTF8, all of which must be present, to one UCS2-LE character, or puts DefaultChar there if the conversion is impossible. Returns the number of bytes this UTF8 symbol occupied. } function UTF8toUCS2(const uch: integer; const DefaultChar: WideChar; out ch: WideChar): integer; inline; var b: TUTF8Bytes absolute uch; begin if (b[0] and UTF8_MASK1)=UTF8_VALUE1 then begin ch := WideChar(b[0]); Result := 1; end else if (b[0] and UTF8_MASK2)=UTF8_VALUE2 then begin ch := WideChar(((b[0] and $1f) shl 6) or (b[1] and $3f)); Result := 2; end else if (b[0] and UTF8_MASK3)=UTF8_VALUE3 then begin ch := WideChar(((b[0] and $0f) shl 12) or ((b[1] and $3f) shl 6) or (b[2] and $3f)); Result := 3; end else if (b[0] and UTF8_MASK4)=UTF8_VALUE4 then begin ch := DefaultChar; Result := 4; end else begin //Invalid character ch := DefaultChar; Result := 1;//because we don't know what else to do end; end; { TStreamHelper } function TStreamHelper.ReadInt: integer; begin if Read(Result, SizeOf(Result))<>SizeOf(Result) then raise EStreamException.Create(sCannotReadData); end; function TStreamHelper.ReadInt64: int64; begin if Read(Result, SizeOf(Result))<>SizeOf(Result) then raise EStreamException.Create(sCannotReadData); end; procedure TStreamHelper.WriteInt(const Value: integer); begin if Write(Value, SizeOf(Value))<>SizeOf(Value) then raise EStreamException.Create(sCannotWriteData); end; procedure TStreamHelper.WriteIn64(const Value: int64); begin if Write(Value, SizeOf(Value))<>SizeOf(Value) then raise EStreamException.Create(sCannotWriteData); end; function TStreamHelper.ReadAnsiChar(out c: AnsiChar): boolean; begin Result := Self.Read(c, SizeOf(c)) = SizeOf(c); end; function TStreamHelper.ReadWideChar(out c: WideChar): boolean; begin Result := Self.Read(c, SizeOf(c)) = SizeOf(c); end; function TStreamHelper.ReadAnsiLine: AnsiString; var c: AnsiChar; begin Result := ''; while ReadAnsiChar(c) and (c <> #13) and (c <> #10) do Result := Result + c; end; function TStreamHelper.ReadUniLine: UnicodeString; var c: WideChar; begin Result := ''; while ReadWideChar(c) and (c <> #13) and (c <> #10) do Result := Result + c; end; function TStreamHelper.WriteAnsiChar(const c: AnsiChar): boolean; begin Result := Self.Write(c, SizeOf(c))=SizeOf(c); end; function TStreamHelper.WriteWideChar(const c: WideChar): boolean; begin Result := Self.Write(c, SizeOf(c))=SizeOf(c); end; { Throws exception if it could not write the whole string. There's no function which returns false or the number of characters written, since we can't tell how many characters there were - we write bytes. And returning the number of bytes isn't much helpful to the client (what if we wrote half of a 4-byte char?) and can lead to misunderstandings and usage errors. If you want to write byte-by-byte, just use standard Write(var Buffer) instead. } procedure TStreamHelper.WriteAnsiString(const s: AnsiString); begin if Write(s[1], Length(s)*SizeOf(AnsiChar)) <> Length(s)*SizeOf(AnsiChar) then raise Exception.Create('Cannot write a line to '+self.ClassName); end; procedure TStreamHelper.WriteUniString(const s: UnicodeString); begin if Write(s[1], Length(s)*SizeOf(WideChar)) <> Length(s)*SizeOf(WideChar) then raise Exception.Create('Cannot write a line to '+self.ClassName); end; { TStreamReader } constructor TStreamReader.Create(AStream: TStream; AOwnStream: boolean = false); begin inherited Create; FStream := AStream; FOwnStream := AOwnStream; buf := nil; ptr := nil; adv := 0; rem := 0; FChunkSize := 0; SetChunkSize(DEFAULT_CHUNK_SIZE); end; destructor TStreamReader.Destroy; begin FreeBuf; if OwnStream then FreeAndNil(FStream) else FStream := nil; inherited; end; procedure TStreamReader.JoinStream(AStream: TStream; AOwnsStream: boolean = false); begin ReleaseStream; FStream := AStream; FOwnStream := AOwnsStream; ResetBuf; end; //Releases the stream and synchronizes it's position with the expected one procedure TStreamReader.ReleaseStream; begin if FStream=nil then exit; //Scroll back (Seek support required!) FStream.Seek(int64(-adv-rem), soCurrent); //Release the stream FStream := nil; FOwnStream := false; ResetBuf; end; procedure TStreamReader.SetChunkSize(AValue: integer); begin //If we can't realloc right now, set delayed reallocation if ReallocBuf(AValue) then FChunkSize := AValue else begin flag_reallocbuf := true; FNextChunkSize := AValue; end; end; { Downloads a complete new chunk of data. Returns the number of bytes read. } function TStreamReader.NewChunk: integer; begin //Delayed reallocation if flag_reallocbuf and ReallocBuf(FNextChunkSize) then begin FChunkSize := FNextChunkSize; flag_reallocbuf := false; end; rem := FStream.Read(buf^, FChunkSize); adv := 0; ptr := buf; Result := rem; end; { Moves remaining data to the beginning of the cache and downloads more. Returns the number of bytes read. } function TStreamReader.UpdateChunk: integer; var DataPtr: Pbyte; begin //Full cache download if rem <= 0 then begin Result := NewChunk; exit; end; //Partial download Move(ptr^, buf^, rem); ptr := buf; adv := 0; if flag_reallocbuf and ReallocBuf(FNextChunkSize) then begin FChunkSize := FNextChunkSize; flag_reallocbuf := false; end; DataPtr := PByte(cardinal(buf) + cardinal(adv+rem)); Result := Stream.Read(DataPtr^, FChunkSize-adv-rem); rem := rem + Result; end; //Clears the contents of the cache procedure TStreamReader.ResetBuf; begin adv := 0; rem := 0; ptr := buf; end; function TStreamReader.ReallocBuf(ASize: integer): boolean; begin //We can't decrease buffer size cause there's still data inside. if adv + rem > ASize then begin Result := false; exit; end; ReallocMem(buf, ASize); ptr := pointer(IntPtr(buf) + adv); Result := true; end; procedure TStreamReader.FreeBuf; begin if Assigned(buf) then FreeMem(buf); end; function TStreamReader.GetSize: Int64; begin Result := FStream.Size; end; function TStreamReader.GetInternalPosition: integer; begin Result := FStream.Position - rem; end; //If possible, try to Seek inside the buffer function TStreamReader.LocalSeek(Offset: Int64; Origin: TSeekOrigin): boolean; var pos,sz: Int64; begin if Origin=soEnd then begin sz := FStream.Size; //Convert to from beginning Offset := sz - Offset; Origin := soBeginning; end; if Origin=soBeginning then begin pos := FStream.Position; if (Offset>=pos) or (Offset<pos-adv-rem) then begin Result := false; //not in this chunk exit; end; //Convert to relative Offset := rem-(pos-Offset); Origin := soCurrent; end; if Origin=soCurrent then begin if (Offset<-adv) or (Offset>=rem) then begin Result := false; exit; end; adv := adv+Offset; rem := rem-Offset; Inc(ptr, Offset); Result := true; end else Result := false; end; function TStreamReader.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin //TStream calls Seek(0,soCurrent) to determine Position, so be fast in this case if (Origin=soCurrent) and (Offset=0) then Result := GetInternalPosition() else if LocalSeek(Offset, Origin) then Result := GetInternalPosition() else begin Result := FStream.Seek(Offset, Origin); ResetBuf; end; end; function TStreamReader.Read(var Buffer; Count: Longint): Longint; var pbuf: PByte; begin if Count=0 then begin Result := 0; exit; end; //The most common case if Count <= rem then begin Move(ptr^, Buffer, Count); Inc(ptr, Count); Inc(adv, Count); Dec(rem, Count); Inc(FBytesRead, Count); Result := Count; exit; end; //Read first part pbuf := @Buffer; if rem > 0 then begin Move(ptr^, pbuf^, rem); Inc(ptr, rem); Inc(adv, rem); //Update variables Inc(pbuf, rem); Dec(Count, rem); Result := rem; rem := 0; end else Result := 0; //Download the remaining part //If it's smaller than a chunk, read the whole chunk if Count < FChunkSize then begin NewChunk; if rem < Count then //rem was already updated in NewChunk Count := rem; Move(ptr^, pbuf^, Count); Inc(ptr, Count); Inc(adv, Count); Dec(rem, Count); Inc(Result, Count); end else //Else just read it from stream Result := Result + FStream.Read(pbuf^, Count); Inc(FBytesRead, Result); end; function TStreamReader.ReadBuf(ABuf: pbyte; ALen: integer): integer; begin Result := Read(ABuf^, ALen); end; function TStreamReader.Write(const Buffer; Count: Longint): Longint; begin raise Exception.Create('StreamReader cannot write.'); end; //Won't Peek for more than CacheSize function TStreamReader.Peek(var Buffer; ASize: integer): integer; begin //If the data is in cache, it's simple if ASize <= rem then begin Move(ptr^, Buffer, ASize); Result := ASize; exit; end; //Else return the best possible amount. Make the cache completely fresh if rem <= FChunkSize then UpdateChunk; //If the complete data fit, return it if ASize <= rem then begin Move(ptr^, Buffer, ASize); Result := ASize; exit; end; //Didn't fit => return all that's available Move(ptr^, Buffer, rem); Result := rem; end; //Уж один-то байт мы всегда можем подсмотреть, если в файле осталось. function TStreamReader.PeekByte(out b: byte): boolean; begin //Если буфер непуст, берём первый байт if rem >= 0 then begin b := ptr^; Result := true; exit; end; //Иначе буфер пуст. Качаем следующий кусочек. NewChunk; if rem >= 0 then begin b := ptr^; Result := true; end else Result := false; end; { TStreamWriter } constructor TStreamWriter.Create(AStream: TStream; AOwnStream: boolean = false); begin inherited Create; FStream := AStream; FOwnStream := AOwnStream; FChunkSize := 0; buf := nil; ptr := nil; used := 0; SetChunkSize(DEFAULT_CHUNK_SIZE); end; destructor TStreamWriter.Destroy; begin Flush(); FreeBuf; if OwnStream then FreeAndNil(FStream) else FStream := nil; inherited; end; procedure TStreamWriter.JoinStream(AStream: TStream; AOwnsStream: boolean = false); begin //Освобождаем старый поток ReleaseStream; //Цепляемся к потоку FStream := AStream; FOwnStream := AOwnsStream; //Сбрасываем буфер на всякий случай ResetBuf; end; //Освобождает поток, синхронизируя его положение с ожидаемым procedure TStreamWriter.ReleaseStream; begin if FStream=nil then exit; //Сбрасываем Flush; //Отпускаем поток FStream := nil; FOwnStream := false; end; //Сбрасывает на диск содержимое буфера и обнуляет буфер. procedure TStreamWriter.Flush; begin if used <= 0 then exit; FStream.Write(buf^, used); ptr := buf; used := 0; end; procedure TStreamWriter.ResetBuf; begin ptr := buf; used := 0; end; procedure TStreamWriter.FreeBuf; begin if Assigned(buf) then FreeMem(buf); buf := nil; ptr := nil; used := 0; end; procedure TStreamWriter.SetChunkSize(AValue: integer); begin //Если в новый буфер текущие данные не влезают, сбрасываем их в поток if AValue < used then Flush; FChunkSize := AValue; ReallocMem(buf, FChunkSize); //Обновляем указатель на текущий байт ptr := pointer(IntPtr(buf) + used); end; //Use this instead of underlying Stream's Position function TStreamWriter.GetInternalPosition: integer; begin Result := FStream.Position + used; end; function TStreamWriter.GetSize: Int64; begin Result := FStream.Size + used; end; procedure TStreamWriter.SetSize(NewSize: Longint); begin SetSize(int64(NewSize)); end; procedure TStreamWriter.SetSize(const NewSize: Int64); begin Flush(); FStream.Size := NewSize; end; function TStreamWriter.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin if (Origin=soCurrent) and (Offset=0) then Result := GetInternalPosition() //TStream uses this to determine Position else begin Flush; Result := FStream.Seek(Offset, Origin); end; end; function TStreamWriter.Read(var Buffer; Count: Longint): Longint; begin raise Exception.Create('StreamWriter cannot read.'); end; function TStreamWriter.Write(const Buffer; Count: Longint): Longint; var rem: integer; pbuf: PByte; begin if Count<=0 then begin Result := 0; exit; end; //Если влезает в кэш, кладём туда rem := FChunkSize - used; if Count <= rem then begin Move(Buffer, ptr^, Count); Inc(used, Count); Inc(ptr, Count); Result := Count; Inc(FBytesWritten, Count); exit; end; //Иначе нас просят записать нечто большее. Вначале добиваем текущий буфер pbuf := @Buffer; if used > 0 then begin if rem > 0 then begin Move(pbuf^, ptr^, rem); Inc(ptr, rem); Inc(used, rem); //Update variables Inc(pbuf, rem); Dec(Count, rem); Result := rem; end else Result := 0; Flush; end else Result := 0; //Если остаток меньше буфера, сохраняем его в буфер if Count < FChunkSize then begin Move(pbuf^, ptr^, Count); Inc(ptr, Count); Inc(used, Count); Inc(Result, Count); end else //Иначе пишем его напрямую Result := Result + FStream.Write(pbuf^, Count); Inc(FBytesWritten, Result); end; function TStreamWriter.WriteBuf(ABuf: PByte; ALen: integer): integer; begin Result := Write(ABuf^, ALen); end; { TCustomStringStream } function TCustomStringStream.RemainingSize: integer; begin Result := Self.Size-FPos; end; function TCustomStringStream.Read(var Buffer; Count: Longint): Longint; begin if Count>RemainingSize then Count := RemainingSize; Move(PByte(IntPtr(FPtr)+FPos)^,Buffer,Count); Inc(FPos,Count); Result := Count; end; function TCustomStringStream.Write(const Buffer; Count: Longint): Longint; begin if RemainingSize<Count then SetSize(FPos+Count); Move(Buffer,PByte(IntPtr(FPtr)+FPos)^,Count); Inc(FPos,Count); Result := Count; end; function TCustomStringStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin if Origin=soCurrent then begin if Offset=0 then begin Result := FPos; exit; end; Result := FPos+Offset; end else if Origin=soEnd then begin Result := GetSize-Offset; end else Result := Offset; if Result<0 then Result := 0 else if Result>GetSize then Result := GetSize; FPos := Result; end; { TAnsiStringStream } constructor TAnsiStringStream.Create(AString: PAnsiString = nil); begin inherited Create(); if AString=nil then FString := @FOwnBuffer else FString := AString; FPos := 0; FPtr := pointer(FString^); end; function TAnsiStringStream.GetString: AnsiString; begin Result := FString^; end; function TAnsiStringStream.GetSize: Int64; begin Result := Length(FString^)*SizeOf(AnsiChar); end; procedure TAnsiStringStream.SetSize(NewSize: Longint); begin SetLength(FString^, NewSize); FPtr := pointer(FString^); end; { TUnicodeStringStream } constructor TUnicodeStringStream.Create(AString: PUnicodeString = nil); begin inherited Create(); if AString=nil then FString := @FOwnBuffer else FString := AString; FPos := 0; FPtr := pointer(FString^); end; function TUnicodeStringStream.GetString: UnicodeString; begin Result := FString^; end; function TUnicodeStringStream.GetSize: Int64; begin Result := Length(FString^)*SizeOf(WideChar); end; procedure TUnicodeStringStream.SetSize(NewSize: Longint); begin if NewSize mod 2 = 0 then SetLength(FString^, NewSize div SizeOf(WideChar)) else SetLength(FString^, NewSize div SizeOf(WideChar) + 1); //no choice but to allocate one more symbol FPtr := pointer(FString^); end; { TCharReader } function SwapChar(c: WideChar): WideChar; inline; begin Result := WideChar(byte(c) shl 8 + word(c) shr 8); end; procedure SwapCharsIn(s: PWideChar; len: integer); inline; var i: integer; begin for i := 0 to len - 1 do begin s^ := SwapChar(s^); Inc(s); end; end; function SwapChars(s: PWideChar; len: integer): WideString; var i: integer; begin SetLength(Result, len); for i := 0 to len - 1 do begin Result[i+1] := SwapChar(s^); Inc(s); end; end; constructor TCharReader.Create(AStream: TStream; AOwnStream: boolean = false); begin inherited Create(AStream, AOwnStream); Charset := DetectCharset; end; constructor TCharReader.Create(AStream: TStream; ACharSet: TCharSet; AOwnStream: boolean = false); begin inherited Create(AStream, AOwnStream); Charset := ACharset; end; //Детектируем бом и сразу вычитываем. function TCharReader.DetectCharset: TCharset; var Bom: WideChar; Bom3: integer; begin //No data => ANSI if Peek(Bom, 2) < 2 then Result := csAnsi else if Bom = BOM_UTF16LE then begin Result := csUtf16Le; Read(Bom, 2); end else if Bom = BOM_UTF16BE then begin Result := csUtf16Be; Read(Bom, 2); end else if word(Bom) = word(BOM_UTF8) then begin //full bom check -- 3 bytes Result := csUtf8; Bom3 := 0; Peek(Bom3, 3); if Bom3=BOM_UTF8 then Read(Bom3, 3); end else //No BOM => ANSI Result := csAnsi; end; function TCharReader.ReadChar(out c: WideChar): boolean; var _c: AnsiChar; u, sz: integer; begin case Charset of csAnsi: begin Result := (Read(_c, 1) = 1); {$IFDEF DCC} c := ToWideChar(_c, CP_ACP); {$ELSE} c := _c; //TODO: Use proper conversion. {$ENDIF} end; csUtf16Be: begin Result := (Read(c, 2) = 2); c := SwapChar(c); end; csUtf8: begin Result := (Peek(u, 4) = 4); sz := UTF8toUCS2(u, WideChar($FFFF), c); Read(u, sz); end else //Utf16Le Result := (Read(c, 2) = 2); end; end; function TCharReader.PeekChar(out c: WideChar): boolean; var _c: AnsiChar; u: integer; begin case Charset of csAnsi: begin Result := (Peek(_c, 1) = 1); {$IFDEF DCC} c := ToWideChar(_c, CP_ACP); {$ELSE} c := _c; //TODO: Use proper conversion {$ENDIF} end; csUtf16Be: begin Result := (Peek(c, 2) = 2); c := SwapChar(c); end; csUtf8: begin Result := (Peek(u, 4) = 4); UTF8toUCS2(u, WideChar($FFFF), c); end else //Utf16Le Result := (Peek(c, 2) = 2); end; end; (* Читает строку из потока, возвращает true, если удалось. *) function TCharReader.ReadLine(out s: UnicodeString): boolean; var c: WideChar; begin s := ''; Result := ReadChar(c); if not Result then exit; {больше ничего нет} {иначе строчка точно есть} while Result do begin if c=#13 then begin if PeekChar(c) and (c=#10) then ReadChar(c); break; end else if c=#10 then begin if PeekChar(c) and (c=#13) then ReadChar(c); break; end else s := s + c; Result := ReadChar(c); end; Result := true; {уж что-то мы прочитали} end; { TCharWriter } constructor TCharWriter.Create(AStream: TStream; AOwnStream: boolean = false); begin inherited Create(AStream, AOwnStream); Charset := csUtf16Le; end; constructor TCharWriter.Create(AStream: TStream; ACharSet: TCharSet; AOwnStream: boolean = false); begin inherited Create(AStream, AOwnStream); CharSet := ACharSet; end; destructor TCharWriter.Destroy; begin Flush(); inherited; end; procedure TCharWriter.WriteChar(const c: WideChar); var _c: AnsiChar; _c_be: WideChar; u, sz: integer; begin case Charset of csAnsi: begin {$IFDEF DCC} _c := ToChar(c, CP_ACP); {$ELSE} _c := c; //TODO: Use proper conversion. {$ENDIF} Write(_c, 1); end; csUtf16Le: Write(c, 2); csUtf16Be: begin //Swap bytes _c_be := SwapChar(c); Write(_c_be, 2); end; csUtf8: begin sz := UCS2toUTF8(c, u); Write(u, sz); end end; end; procedure TCharWriter.WriteChars(c: PWideChar; len: integer); var _c: AnsiString; _c_be: WideString; begin case Charset of csAnsi: begin {$IFDEF DCC} _c := BufToString(c, len, CP_ACP); {$ELSE} _c := c; //TODO: Use proper conversion. {$ENDIF} Write(_c[1], Length(_c)*SizeOf(AnsiChar)); end; csUtf16Le: Write(c^, len*SizeOf(WideChar)); csUtf16Be: begin _c_be := SwapChars(c, len); Write(_c_be[1], len*SizeOf(WideChar)); end; csUtf8: while len>0 do begin WriteChar(c^); Inc(c); Dec(len); end; end; end; procedure TCharWriter.WriteString(const c: UnicodeString); begin WriteChars(@c[1], Length(c)); end; procedure TCharWriter.WriteLine(const s: UnicodeString); const CRLF: UnicodeString = #$000D#$000A; begin WriteString(s); WriteString(CRLF); end; procedure TCharWriter.WriteBom; var Bom: WideChar; Bom3: integer; begin case Charset of //Nothing to write csAnsi: begin end; csUtf16Le: begin Bom := BOM_UTF16LE; Write(Bom, SizeOf(Bom)); end; csUtf16Be: begin Bom := BOM_UTF16BE; Write(Bom, SizeOf(Bom)); end; csUtf8: begin Bom3 := BOM_UTF8; Write(Bom3, 3); end; end; end; //////////////////////////////////////////////////////////////////////////////// /// Misc useful read functions destructor TStreamReader2.Destroy; begin FreeTmpStr; inherited; end; //Reads everything up to #13#10 into the buffer + sets terminating NULL. //If the buffer length in chars (received in "sz") is enough, it's left as it is. //Else the buffer is expanded, and the "sz" is updated accordingly. function TStreamReader2.TryReadLineA(var s: PAnsiChar; var sz: cardinal): boolean; var c: AnsiChar; l_used: cardinal; begin l_used := 0; while (Read(c, SizeOf(c))=SizeOf(c)) and (c <> #13) do begin //Reallocate memory, if needed if l_used >= sz then begin sz := 2*sz + 10; ReallocMem(s, sz*SizeOf(AnsiChar)); end; s[l_used] := c; Inc(l_used); end; if not (c=#13) then //If we've read nothing this time if l_used = 0 then begin Result := false; exit; end else begin s[l_used] := #00; Result := true; exit; end; if not (Read(c, SizeOf(c)) = SizeOf(c)) or not (c = #10) then raise Exception.Create('Illegal linebreak detected at symbol ' + IntToStr(Position)); //Reallocate memory, if needed if l_used >= sz then begin sz := 2*sz + 1; ReallocMem(s, sz); end; s[l_used] := #00; Result := true; end; function TStreamReader2.TryReadLineW(var s: PWideChar; var sz: cardinal): boolean; var c: WideChar; l_used: cardinal; begin l_used := 0; while (Read(c, SizeOf(c))=SizeOf(c)) and (c <> #10) do begin //Reallocate memory, if needed if l_used >= sz then begin sz := 2*sz + 10; ReallocMem(s, sz*SizeOf(WideChar)); end; s[l_used] := c; Inc(l_used); end; if not (c=#10) then //If we've read nothing this time if l_used = 0 then begin Result := false; exit; end; //Reallocate memory, if needed if l_used >= sz then begin sz := 2*sz + 1; ReallocMem(s, sz); end; s[l_used] := #00; Result := true; end; procedure TStreamReader2.ReadLineA(var s: PAnsiChar; var sz: cardinal); begin if not TryReadLineA(s, sz) then raise Exception.Create('Cannot read line of text.'); end; procedure TStreamReader2.ReadLineW(var s: PWideChar; var sz: cardinal); begin if not TryReadLineW(s, sz) then raise Exception.Create('Cannot read line of text.'); end; function TStreamReader2.ReadStrA: AnsiString; begin ReadLineA(tmpstr_ansi_s, tmpstr_ansi_sz); Result := tmpstr_ansi_s; end; function TStreamReader2.ReadStrW: WideString; begin ReadLineW(tmpstr_wide_s, tmpstr_wide_sz); Result := tmpstr_wide_s; end; function TStreamReader2.TryReadStrA(out s: AnsiString): boolean; begin Result := TryReadLineA(tmpstr_ansi_s, tmpstr_ansi_sz); if Result then s := tmpstr_ansi_s; end; function TStreamReader2.TryReadStrW(out s: WideString): boolean; begin Result := TryReadLineW(tmpstr_wide_s, tmpstr_wide_sz); if Result then s := tmpstr_wide_s; end; procedure TStreamReader2.FreeTmpStr; begin FreeMem(tmpstr_ansi_s); FreeMem(tmpstr_wide_s); tmpstr_ansi_s := nil; tmpstr_wide_s := nil; tmpstr_ansi_sz := 0; tmpstr_wide_sz := 0; end; //////////////////////////////////////////////////////////////////////////////// //Пытается прочесть один байт, интерпретирует его как AnsiChar. function TStreamReader2.ReadAnsiChar(out c: AnsiChar): boolean; begin Result := (Read(c, SizeOf(c))=SizeOf(AnsiChar)); end; //Пытается прочесть два байта, интерпретирует их как WideChar. function TStreamReader2.ReadWideChar(out c: WideChar): boolean; begin Result := (Read(c, SizeOf(c))=SizeOf(WideChar)); end; const REPL_CHAR = WideChar($FFFD); //Пытается прочесть несколько байт, интерпретирует их как Utf8-char, преобразует в WideChar. //Возвращает false, если поток кончился, а прочесть не удалось. //Возвращает REPL_CHAR, если символ не влез в UCS2 или закодирован неверно. function TStreamReader2.ReadUtf8Char(out c: WideChar): boolean; var c1, c2, c3: byte; begin Result := (Read(c1, 1)=1); if not Result then exit; //Один байт: 0xxxxxxx if (c1 and $80) = 0 then begin c := WideChar(c1); Result := true; exit; end; //Два байта: 110xxxxxx 10yyyyyy Result := (Read(c2, 1)=1); if not Result then exit; //У ведомых байт должно быть 10xxxxxx if (c2 and $C0 <> $80) then begin c := REPL_CHAR; exit; end; c1 := c1 and $3F; //сбрасываем в нули два левых бита if (c1 and $20) = 0 then begin //не стоит третий бит c := WideChar((c1 shl 6) or (c2 and $3F)); Result := true; exit; end; //Три байта: 1110xxxx 10yyyyyy 10zzzzzz Result := (Read(c3, 1)=1); if not Result then exit; //У ведомых байт должно быть 10xxxxxx if (c3 and $C0 <> $80) then begin c := REPL_CHAR; exit; end; c1 := c1 and $1F; //сбрасываем в ноль третий бит if (c1 and $10) = 0 then begin //не стоит четвёртый бит c := WideChar((c1 shl 12) or ((c2 and $3F) shl 6) or (c3 and $3F)); Result := true; exit; end; //Четыре байта: у нас не поддерживается. Но мы прочтём четвёртый. Result := (Read(c1, 1)=1); //уже неважно, куда if not Result then exit; c := REPL_CHAR; //Больше четырёх байт мы в страшном сне представить не можем. end; end.
unit caTextStream; interface uses Classes, Sysutils; type //--------------------------------------------------------------------------- // TcaBufferStream   //--------------------------------------------------------------------------- TcaBufferStreamState = (bsUnknown, bsRead, bsWrite); TcaBufferStream = class(TStream) private // private fields  FStream: TStream; // property fields  FBufEnd: PChar; FBuffer: PChar; FBufPtr: PChar; FBufSize: Cardinal; FState: TcaBufferStreamState; // event property fields  FOnFillBuffer: TNotifyEvent; FOnFlushBuffer: TNotifyEvent; // private methods  function GetBufPosition: Integer; protected // protected methods  function FillBuffer: Boolean; virtual; function FlushBuffer: Boolean; virtual; procedure AfterFillBuffer; virtual; procedure AfterFlushBuffer; virtual; procedure PutBack(Ch: Char); virtual; // protected properties  property BufEnd: PChar read FBufEnd; property Buffer: PChar read FBuffer; property BufPosition: Integer read GetBufPosition; property BufPtr: PChar read FBufPtr; property BufSize: Cardinal read FBufSize; property State: TcaBufferStreamState read FState; property Stream: TStream read FStream; public // create/destroy  constructor Create(AStream: TStream); overload; virtual; destructor Destroy; override; // public methods  function IsEOF: Boolean; function Read(var ABuffer; Count: Integer): Integer; override; function Seek(Offset: Integer; Origin: Word): Integer; override; function Write(const ABuffer; Count: Integer): Integer; override; // event properties  property OnFillBuffer: TNotifyEvent read FOnFillBuffer write FOnFillBuffer; property OnFlushBuffer: TNotifyEvent read FOnFlushBuffer write FOnFlushBuffer; end; //--------------------------------------------------------------------------- // TcaTextStream   //--------------------------------------------------------------------------- TcaTextStream = class(TcaBufferStream) private // private fields  FFilename: string; // property fields  FOwnStream: Boolean; // private methods  procedure FreeStream; virtual; protected // protected properties  property Filename: string read FFilename; property OwnStream: Boolean read FOwnStream write FOwnStream; public // create/destroy  constructor Create(const AFilename: string; AMode: Word); overload; destructor Destroy; override; // public methods  function GetChar: Char; function GetFloat: Extended; function GetInteger: LongInt; function GetLine: string; function GetToken(const Delimiters: string): string; function PutChar(Ch: Char): TcaTextStream; function PutEndOfLine: TcaTextStream; function PutFloat(Flt: Extended): TcaTextStream; function PutInteger(Int: LongInt): TcaTextStream; function PutLine(const Str: string): TcaTextStream; function PutPChar(const Str: PChar): TcaTextStream; function PutSpace: TcaTextStream; function PutString(const Str: string): TcaTextStream; function PutTab: TcaTextStream; function PutWideChar(WCh: WideChar): TcaTextStream; procedure Format(const Fmt: string; Args: array of const); procedure FormatLn(const Fmt: string; Args: array of const); procedure SkipSpaces; procedure WriteArgs(Args: array of const); procedure WriteLn(Args: array of const); end; implementation const cBufferSize: Integer = 8192 * 4; //--------------------------------------------------------------------------- // TcaTextStream   //--------------------------------------------------------------------------- // create/destroy  constructor TcaBufferStream.Create(AStream: TStream); begin inherited Create; FStream := AStream; FBufSize := cBufferSize; GetMem(FBuffer, FBufSize); FBufEnd := FBuffer + FBufSize; FState := bsUnknown; end; destructor TcaBufferStream.Destroy; begin if FState = bsWrite then FlushBuffer; FreeMem(FBuffer, FBufSize); inherited; end; // public methods  function TcaBufferStream.IsEOF: Boolean; begin Result := (FBufPtr = FBufEnd) and (FStream.Position = FStream.Size); end; function TcaBufferStream.Read(var ABuffer; Count: Integer): Integer; var Ptr: PChar; NumBytes: Cardinal; begin if FState = bsWrite then FlushBuffer else begin if FBufPtr = nil then FBufPtr := FBufEnd; // empty buffer, so force a FillBuffer call  end; // The user might ask for more than one bufferful   // Prepare to loop until all the requested bytes have been read  Ptr := @ABuffer; Result := 0; while Count > 0 do begin // If the buffer is empty, then fill it  if FBufPtr = FBufEnd then if not FillBuffer then Break; NumBytes := FBufEnd - FBufPtr; if Cardinal(Count) < NumBytes then NumBytes := Count; // Copy the buffer to the user's memory  Move(BufPtr^, Ptr^, NumBytes); // Increment the pointers. The stream’s buffer is always within a single  // segment, but the user's buffer might cross segment boundaries   Dec(Count, NumBytes); Inc(FBufPtr, NumBytes); Inc(Result, NumBytes); Ptr := Ptr + NumBytes; end; end; function TcaBufferStream.Seek(Offset: Integer; Origin: Word): Integer; var CurrentPosition: LongInt; begin CurrentPosition := FStream.Position + GetBufPosition; case Origin of soFromBeginning: Result := Offset; soFromCurrent: Result := FStream.Position + GetBufPosition + Offset; soFromEnd: Result := FStream.Size - Offset; else raise Exception.CreateFmt('Invalid stream origin: %d', [Origin]); end; if Result <> CurrentPosition then begin // Flush a partial write  if (FState = bsWrite) and not FlushBuffer then raise EStreamError.Create('Seek error'); FStream.Position := Result; FBufPtr := nil; FState := bsUnknown; end; end; function TcaBufferStream.Write(const ABuffer; Count: Integer): Integer; var Ptr: Pointer; NumBytes: Cardinal; begin // If the stream is for reading, then ignore the current buffer  // by forcing the position of the underlying stream to match   // the buffered stream's position   if FState = bsRead then FStream.Position := Position else begin if FBufPtr = nil then begin // Unknown state, so start with an empty buffer  FBufPtr := FBuffer; FBufEnd := FBuffer + FBufSize; end; end; // The user might write more than one bufferful   // Prepare to loop until all the requested bytes have been written  Ptr := @ABuffer; Result := 0; // Total number of bytes written  while Count > 0 do begin NumBytes := FBufEnd - FBufPtr; if Cardinal(Count) < NumBytes then NumBytes := Count; Move(Ptr^, FBufPtr^, NumBytes); Dec(Count, NumBytes); Inc(FBufPtr, NumBytes); Inc(Result, NumBytes); Ptr := PChar(Ptr) + NumBytes; if FBufPtr = FBufEnd then if not FlushBuffer then Break; end; if FBufPtr <> FBuffer then FState := bsWrite; end; // protected methods  function TcaBufferStream.FillBuffer: Boolean; var NumBytes: Cardinal; begin NumBytes := FStream.Read(FBuffer^, FBufSize); FBufPtr := FBuffer; FBufEnd := FBuffer + NumBytes; // If nothing was read, it must be the end of file  Result := NumBytes > 0; if Result then FState := bsRead else FState := bsUnknown; AfterFillBuffer; end; function TcaBufferStream.FlushBuffer: Boolean; var NumBytes: Cardinal; begin NumBytes := FBufPtr - FBuffer; Result := NumBytes = Cardinal(FStream.Write(FBuffer^, NumBytes)); FBufPtr := FBuffer; FState := bsUnknown; AfterFlushBuffer; end; procedure TcaBufferStream.AfterFillBuffer; begin if Assigned(FOnFillBuffer) then FOnFillBuffer(Self); end; procedure TcaBufferStream.AfterFlushBuffer; begin if Assigned(FOnFlushBuffer) then FOnFlushBuffer(Self); end; procedure TcaBufferStream.PutBack(Ch: Char); begin if FBufPtr <= FBuffer then raise EStreamError.Create('PutBack overflow'); Dec(FBufPtr); FBufPtr[0] := Ch; end; // private methods  function TcaBufferStream.GetBufPosition: Integer; begin Result := 0; case FState of bsUnknown: Result := 0; bsRead: Result := FBufPtr - FBufEnd; bsWrite: Result := FBufPtr - FBuffer; end; end; //--------------------------------------------------------------------------- // TcaTextStream   //--------------------------------------------------------------------------- // create/destroy  constructor TcaTextStream.Create(const AFilename: string; AMode: Word); begin inherited Create(TFileStream.Create(AFilename, AMode)); FFilename := AFilename; FOwnStream := True; end; destructor TcaTextStream.Destroy; begin inherited Destroy; FreeStream; end; // public methods  function TcaTextStream.GetChar: Char; begin ReadBuffer(Result, 1); end; function TcaTextStream.GetFloat: Extended; begin SkipSpaces; Result := StrToFloat(GetToken('')); end; function TcaTextStream.GetInteger: LongInt; begin SkipSpaces; Result := StrToInt(GetToken('')); end; function TcaTextStream.GetLine: string; var Ch: Char; begin Result := ''; while (Read(Ch, 1) = 1) and not (Ch in [#10, #13]) do Result := Result + Ch; if Ch = #13 then begin if (Read(Ch, 1) = 1) and (Ch <> #10) then PutBack(Ch); end; end; function TcaTextStream.GetToken(const Delimiters: string): string; var Ch: Char; begin Result := ''; while Read(Ch, 1) = 1 do begin if (Length(Delimiters) = 0) and (Ch < ' ') then begin Putback(Ch); Break; end else begin if (Length(Delimiters) > 0) and (Pos(Ch, Delimiters) > 0) then begin Putback(Ch); Break; end; end; Result := Result + Ch; end; end; function TcaTextStream.PutChar(Ch: Char): TcaTextStream; begin WriteBuffer(Ch, 1); Result := Self; end; function TcaTextStream.PutEndOfLine: TcaTextStream; begin PutChar(#13); PutChar(#10); Result := Self; end; function TcaTextStream.PutFloat(Flt: Extended): TcaTextStream; begin PutString(FloatToStr(Flt)); Result := Self; end; function TcaTextStream.PutInteger(Int: Integer): TcaTextStream; begin PutString(IntToStr(Int)); Result := Self; end; function TcaTextStream.PutLine(const Str: string): TcaTextStream; begin WriteBuffer(Str[1], Length(Str)); PutEndOfLine; Result := Self; end; function TcaTextStream.PutPChar(const Str: PChar): TcaTextStream; begin WriteBuffer(Str[0], StrLen(Str)); Result := Self; end; function TcaTextStream.PutSpace: TcaTextStream; begin PutChar(#32); Result := Self; end; function TcaTextStream.PutString(const Str: string): TcaTextStream; begin WriteBuffer(Str[1], Length(Str)); Result := Self; end; function TcaTextStream.PutTab: TcaTextStream; begin PutChar(#9); Result := Self; end; function TcaTextStream.PutWideChar(WCh: WideChar): TcaTextStream; begin WriteBuffer(WCh, SizeOf(WCh)); Result := Self; end; procedure TcaTextStream.Format(const Fmt: string; Args: array of const); begin PutString(SysUtils.Format(Fmt, Args)); end; procedure TcaTextStream.FormatLn(const Fmt: string; Args: array of const); begin PutString(SysUtils.Format(Fmt, Args)); PutEndOfLine; end; procedure TcaTextStream.SkipSpaces; var C: Char; begin while Read(C, 1) = 1 do begin if C > #32 then begin Putback(C); Break; end; end; end; procedure TcaTextStream.WriteArgs(Args: array of const); var I: Integer; begin for I := Low(Args) to High(Args) do begin case Args[I].VType of vtInteger: PutInteger(Args[I].VInteger); vtBoolean: if Args[I].VBoolean then PutString('True') else PutString('False'); vtChar: PutChar(Args[I].VChar); vtExtended: PutFloat(Args[I].VInteger); vtString: PutString(Args[I].VString^); vtPointer: Format('%p', [Args[I].VPointer]); vtPChar: PutPChar(Args[I].VPChar); vtClass: PutString(Args[I].VClass.ClassName); vtObject: begin PutChar('('); PutString(Args[I].VObject.ClassName); PutChar(')'); end; vtAnsiString: PutString(string(Args[I].VAnsiString)); vtWideChar: PutWideChar(Args[I].VWideChar); vtCurrency: PutFloat(Args[I].VCurrency^); vtVariant: PutString(Args[I].VVariant^); end; if (I < High(Args)) and (Args[I].VType <> vtChar) then PutSpace; end; end; procedure TcaTextStream.WriteLn(Args: array of const); begin WriteArgs(Args); PutEndOfLine; end; // private methods  procedure TcaTextStream.FreeStream; begin if FOwnStream then begin FStream.Free; FStream := nil; end; end; end.
program TEST; {$N+,E+} uses MathLib0; CONST NumBands = 100; {this determines how close an estimator this table is} tolerance = 0.000005; VAR NormTable : ARRAY[0..NumBands] OF myFloat; { NormTable is an array containing fractions of positive Std. Deviations } { from a mean which are evenly spaced in terms of probability in a } { normal distribution } procedure IterateNormal; VAR n : Cardinal; BEGIN for n := 0 to 30 do writeln(n/10:3:1,Normal(n/10):10:5); END; {------------------------------------------------------------} procedure CreateNormalTable; { To pull out a Std. Dev. from a normal distribution: 1. Create this table. 2. Select a random integer, n | 0 < n <= NumBands. 3. Select a random real, d | NormTable[n-1] <= d <= NormTable[n]. 4. Select a random integer, s | s=-1, s= 1. 5. s*d is a deviation from the mean which is randomly distributed. } VAR n : Cardinal; LowDev, HiDev, LowProb, HiProb : myFLOAT; ProbIncr: myFLOAT; {find std devs. every ProbIncr pct. probability} BEGIN LowDev := 0.0; { 0.0 deviation from mean of distribution } HiDev := 0.01; {starting guess} LowProb := Normal(LowDev); ProbIncr := 0.5 / NumBands; { we're using 50% of the distribution} NormTable[0] := LowDev; for n := 1 to NumBands do BEGIN HiProb := LowProb + ProbIncr; SeekGoal(HiProb,tolerance,HiDev,Normal); NormTable[n] := HiDev; LowProb := HiProb; END; END; {------------------------------------------------------------} BEGIN {MAIN} Writeln; CreateNormalTable; END. 
unit fAResize; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fPage, ExtCtrls, VA508AccessibilityManager; type TfrmAutoResize = class(TfrmPage) procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); private FSizes: TList; protected procedure Loaded; override; end; var frmAutoResize: TfrmAutoResize; implementation uses VA508AccessibilityRouter; {$R *.DFM} type TSizeRatio = class // records relative sizes and positions for resizing logic public CLeft: Extended; CTop: Extended; CWidth: Extended; CHeight: Extended; constructor Create(ALeft, ATop, AWidth, AHeight: Extended); end; { TSizeRatio methods } constructor TSizeRatio.Create(ALeft, ATop, AWidth, AHeight: Extended); begin CLeft := ALeft; CTop := ATop; CWidth := AWidth; CHeight := AHeight; end; { TfrmAutoResize methods } procedure TfrmAutoResize.Loaded; { record initial size & position info for resizing logic } var SizeRatio: TSizeRatio; i,H,W: Integer; begin FSizes := TList.Create; H := ClientHeight; W := ClientWidth; for i := 0 to ControlCount - 1 do with Controls[i] do begin SizeRatio := TSizeRatio.Create(Left/W, Top/H, Width/W, Height/H); FSizes.Add(SizeRatio); end; inherited Loaded; end; procedure TfrmAutoResize.FormResize(Sender: TObject); { resize child controls using their design time proportions } var SizeRatio: TSizeRatio; i,H,W: Integer; begin inherited; H := Height; W := Width; with FSizes do for i := 0 to ControlCount - 1 do begin SizeRatio := Items[i]; with SizeRatio do if Controls[i] is TLabel then with Controls[i] do SetBounds(Round(CLeft*W), Round(CTop*H), Width, Height) else Controls[i].SetBounds(Round(CLeft*W), Round(CTop*H), Round(CWidth*W), Round(CHeight*H)); end; {with FSizes} end; procedure TfrmAutoResize.FormDestroy(Sender: TObject); { destroy objects used to record size and position information for controls } var SizeRatio: TSizeRatio; i: Integer; begin inherited; with FSizes do for i := 0 to Count-1 do begin SizeRatio := Items[i]; SizeRatio.Free; end; FSizes.Free; end; initialization SpecifyFormIsNotADialog(TfrmAutoResize); end.
unit oPKIEncryptionDataDEAOrder; interface uses System.Classes, oPKIEncryption, oPKIEncryptionData, TRPCB; type TPKIEncryptionDataDEAOrder = class(TPKIEncryptionData, IPKIEncryptionDataDEAOrder) private fIsDEASig: boolean; fIssuanceDate: string; fPatientName: string; fPatientAddress: string; fDrugName: string; fQuantity: string; fDirections: string; fDetoxNumber: string; fProviderName: string; fProviderAddress: string; fDEANumber: string; fOrderNumber: string; function getDEANumber: string; function getDetoxNumber: string; function getDirections: string; function getDrugName: string; function getIsDEASig: boolean; function getIssuanceDate: string; function getOrderNumber: string; function getPatientAddress: string; function getPatientName: string; function getProviderAddress: string; function getProviderName: string; function getQuantity: string; procedure setDEANumber(const aValue: string); procedure setDetoxNumber(const aValue: string); procedure setDirections(const aValue: string); procedure setDrugName(const aValue: string); procedure setIsDEASig(const aValue: boolean); procedure setIssuanceDate(const aValue: string); procedure setOrderNumber(const aValue: string); procedure setPatientAddress(const aValue: string); procedure setPatientName(const aValue: string); procedure setProviderAddress(const aValue: string); procedure setProviderName(const aValue: string); procedure setQuantity(const aValue: string); protected function getBuffer: string; override; procedure setBuffer(const aValue: string); override; final; public constructor Create; destructor Destroy; override; procedure Clear; override; procedure Validate; override; procedure LoadFromVistA(aRPCBroker: TRPCBroker; aPatientDFN, aUserDUZ, aCPRSOrderNumber: string); end; implementation uses MFunStr, uLockBroker; { TPKIEncryptionDataDEAOrder } constructor TPKIEncryptionDataDEAOrder.Create; begin inherited Create; end; destructor TPKIEncryptionDataDEAOrder.Destroy; begin inherited; end; function TPKIEncryptionDataDEAOrder.getBuffer: string; begin Result := fDEANumber + // 10 // fDetoxNumber + // 7 fDirections + // 6 fDrugName + // 4 fIssuanceDate + // 1 fOrderNumber + // fPatientAddress + // 3 fPatientName + // 2 fProviderAddress + // 9 fProviderName + // 8 fQuantity; // 5 end; procedure TPKIEncryptionDataDEAOrder.setBuffer(const aValue: string); begin raise EPKIEncryptionError.Create(DLG_89802039); end; procedure TPKIEncryptionDataDEAOrder.Clear; begin inherited; fIsDEASig := false; fIssuanceDate := ''; fPatientName := ''; fPatientAddress := ''; fDrugName := ''; fQuantity := ''; fDirections := ''; fDetoxNumber := ''; fProviderName := ''; fProviderAddress := ''; fDEANumber := ''; fOrderNumber := ''; end; procedure TPKIEncryptionDataDEAOrder.Validate; begin inherited; if getBuffer = '' then raise EPKIEncryptionError.Create(DLG_89802000); if not fIsDEASig then raise EPKIEncryptionError.Create(DLG_89802038); if fDEANumber = '' then raise EPKIEncryptionError.Create(DLG_89802001); end; procedure TPKIEncryptionDataDEAOrder.LoadFromVistA(aRPCBroker: TRPCBroker; aPatientDFN, aUserDUZ, aCPRSOrderNumber: string); var aResults: TStringList; begin try Clear; aResults := TStringList.Create; try LockBroker; try aRPCBroker.RemoteProcedure := 'ORDEA HASHINFO'; aRPCBroker.Param[0].value := aPatientDFN; aRPCBroker.Param[0].PType := literal; aRPCBroker.Param[1].value := aUserDUZ; aRPCBroker.Param[1].PType := literal; aRPCBroker.lstCall(aResults); finally UnlockBroker; end; while aResults.Count > 0 do begin if Piece(aResults[0], ':', 1) = 'IssuanceDate' then fIssuanceDate := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'PatientName' then fPatientName := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'PatientAddress' then fPatientAddress := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'DetoxNumber' then fDetoxNumber := '' else if Piece(aResults[0], ':', 1) = 'ProviderName' then fProviderName := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'ProviderAddress' then fProviderAddress := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'DeaNumber' then fDEANumber := Piece(aResults[0], ':', 2, 30); aResults.Delete(0); end; LockBroker; try aRPCBroker.RemoteProcedure := 'ORDEA ORDHINFO'; aRPCBroker.Param[0].value := aCPRSOrderNumber; aRPCBroker.Param[0].PType := literal; aRPCBroker.lstCall(aResults); finally UnlockBroker; end; while aResults.Count > 0 do begin if Piece(aResults[0], ':', 1) = 'DrugName' then fDrugName := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'Quantity' then fQuantity := Piece(aResults[0], ':', 2, 30) else if Piece(aResults[0], ':', 1) = 'Directions' then fDirections := Piece(aResults[0], ':', 2, 30); aResults.Delete(0); end; // Last but not least :) fIsDEASig := True; fOrderNumber := aCPRSOrderNumber; finally aResults.Free; end; except raise EPKIEncryptionError.Create('Error loading DEA Order Components from VistA'); end; end; { Generic Property Getters and Setters } function TPKIEncryptionDataDEAOrder.getDEANumber: string; begin Result := fDEANumber; end; function TPKIEncryptionDataDEAOrder.getDetoxNumber: string; begin Result := fDetoxNumber; end; function TPKIEncryptionDataDEAOrder.getDirections: string; begin Result := fDirections; end; function TPKIEncryptionDataDEAOrder.getDrugName: string; begin Result := fDrugName; end; function TPKIEncryptionDataDEAOrder.getIsDEASig: boolean; begin Result := fIsDEASig; end; function TPKIEncryptionDataDEAOrder.getIssuanceDate: string; begin Result := fIssuanceDate; end; function TPKIEncryptionDataDEAOrder.getOrderNumber: string; begin Result := fOrderNumber; end; function TPKIEncryptionDataDEAOrder.getPatientAddress: string; begin Result := fPatientAddress; end; function TPKIEncryptionDataDEAOrder.getPatientName: string; begin Result := fPatientName; end; function TPKIEncryptionDataDEAOrder.getProviderAddress: string; begin Result := fProviderAddress; end; function TPKIEncryptionDataDEAOrder.getProviderName: string; begin Result := fProviderName; end; function TPKIEncryptionDataDEAOrder.getQuantity: string; begin Result := fQuantity; end; procedure TPKIEncryptionDataDEAOrder.setDEANumber(const aValue: string); begin fDEANumber := aValue; end; procedure TPKIEncryptionDataDEAOrder.setDetoxNumber(const aValue: string); begin fDetoxNumber := aValue; end; procedure TPKIEncryptionDataDEAOrder.setDirections(const aValue: string); begin fDirections := aValue; end; procedure TPKIEncryptionDataDEAOrder.setDrugName(const aValue: string); begin fDrugName := aValue; end; procedure TPKIEncryptionDataDEAOrder.setIsDEASig(const aValue: boolean); begin fIsDEASig := aValue; end; procedure TPKIEncryptionDataDEAOrder.setIssuanceDate(const aValue: string); begin fIssuanceDate := aValue; end; procedure TPKIEncryptionDataDEAOrder.setOrderNumber(const aValue: string); begin fOrderNumber := aValue; end; procedure TPKIEncryptionDataDEAOrder.setPatientAddress(const aValue: string); begin fPatientAddress := aValue; end; procedure TPKIEncryptionDataDEAOrder.setPatientName(const aValue: string); begin fPatientName := aValue; end; procedure TPKIEncryptionDataDEAOrder.setProviderAddress(const aValue: string); begin fProviderAddress := aValue; end; procedure TPKIEncryptionDataDEAOrder.setProviderName(const aValue: string); begin fProviderName := aValue; end; procedure TPKIEncryptionDataDEAOrder.setQuantity(const aValue: string); begin fQuantity := aValue; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSProxyRest; interface uses Data.DBXCommon, System.JSON, Data.DBXJSONReflect, Datasnap.DSClientRest, Datasnap.DSCommonProxy; type TDSRestClient = class protected FInstanceOwner: Boolean; [Weak]FConnection: TDSCustomRestConnection; public constructor Create(AConnection: TDSCustomRestConnection); overload; constructor Create(AConnection: TDSCustomRestConnection; AInstanceOwner: Boolean); overload; property InstanceOwner: Boolean read FInstanceOwner; end; TDSRestProxyMetaDataLoader = class(TInterfacedObject, IDSProxyMetaDataLoader) private FConnection: TDSCustomRestConnection; { IDSProxyMetaDataLoader } procedure Load(MetaData: TDSProxyMetadata); procedure LoadFromConnection(AConnection: TDSCustomRestConnection; AMetaData: TDSProxyMetadata); public constructor Create(AConnection: TDSCustomRestConnection); end; /// <summary>Base class for generated proxies that implements the most /// important DSAdmin functions.</summary> TDSAdminRestClient = class(TDSRestClient) protected FDConnection: TDSRestCommand; FMarshal: TJSONMarshal; FUnMarshal: TJSONUnMarshal; private FGetPlatformNameCommand: TDSRestCommand; FClearResourcesCommand: TDSRestCommand; FFindPackagesCommand: TDSRestCommand; FFindClassesCommand: TDSRestCommand; FFindMethodsCommand: TDSRestCommand; FListClassesCommand: TDSRestCommand; FDescribeClassCommand: TDSRestCommand; FListMethodsCommand: TDSRestCommand; FDescribeMethodCommand: TDSRestCommand; FGetServerMethodsCommand: TDSRestCommand; FGetServerMethodParametersCommand: TDSRestCommand; FGetDatabaseConnectionPropertiesCommand: TDSRestCommand; FConsumeClientChannelCommand: TDSRestCommand; FConsumeClientChannelTimeoutCommand: TDSRestCommand; FCloseClientChannelCommand: TDSRestCommand; FRegisterClientCallbackServerCommand: TDSRestCommand; FUnregisterClientCallbackCommand: TDSRestCommand; FBroadcastToChannelCommand: TDSRestCommand; FBroadcastObjectToChannelCommand: TDSRestCommand; FNotifyCallbackCommand: TDSRestCommand; FNotifyObjectCommand: TDSRestCommand; FClearSessionCommand: TDSRestCommand; public constructor Create(AConnection: TDSCustomRestConnection); overload; constructor Create(AConnection: TDSCustomRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function GetPlatformName: string; function ClearResources: Boolean; function FindPackages: TDBXReader; function FindClasses(PackageName: string; ClassPattern: string): TDBXReader; function FindMethods(PackageName: string; ClassPattern: string; MethodPattern: string): TDBXReader; function ListClasses: TJSONArray; function DescribeClass(ClassName: string): TJSONObject; function ListMethods(ClassName: string): TJSONArray; function DescribeMethod(ServerMethodName: string): TJSONObject; function GetServerMethods: TDBXReader; function GetServerMethodParameters: TDBXReader; function GetDatabaseConnectionProperties: TDBXReader; function ConsumeClientChannel(ChannelName, ClientManagerId, CallbackId, ChannelNames: string; ResponseData: TJSONValue): TJSONValue; function ConsumeClientChannelTimeout(ChannelName, ClientManagerId, CallbackId, ChannelNames: string; Timeout: Integer; ResponseData: TJSONValue): TJSONValue; function CloseClientChannel(ChannelId: string): Boolean; function RegisterClientCallbackServer(ChannelId, CallbackId, ChannelNames: string): Boolean; function UnregisterClientCallback(ChannelId, CallbackId: string): Boolean; function BroadcastToChannel(ChannelName: string; Msg: TJSONValue): Boolean; function BroadcastObjectToChannel(ChannelName: string; Msg: TObject): Boolean; function NotifyCallback(ClientId: string; CallbackId: string; Msg: TJSONValue; out Response: TJSONValue): Boolean; function NotifyObject(ClientId: string; CallbackId: string; Msg: TObject; out Response: TObject): Boolean; procedure ClearSession; end; var GDSProxyRestSecurityToken: string = ' '; const DSAdmin_GetPlatformName: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); DSAdmin_ClearResources: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_FindPackages: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_FindClasses: array [0..2] of TDSRestParameterMetaData = ( (Name: 'PackageName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ClassPattern'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_FindMethods: array [0..3] of TDSRestParameterMetaData = ( (Name: 'PackageName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ClassPattern'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'MethodPattern'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_ListClasses: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONArray') ); DSAdmin_DescribeClass: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ClassName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONObject') ); DSAdmin_ListMethods: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ClassName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONArray') ); DSAdmin_DescribeMethod: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ServerMethodName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONObject') ); DSAdmin_GetServerMethods: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_GetServerMethodParameters: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_GetDatabaseConnectionProperties: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 23; TypeName: 'TDBXReader') ); DSAdmin_GetDSServerName: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); DSAdmin_CloseClientChannel: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ChannelId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_UnregisterClientCallback: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ChannelId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_BroadcastToChannel: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ChannelName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Msg'; Direction: 1; DBXType: 37; TypeName: 'TJSONValue'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_BroadcastObjectToChannel: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ChannelName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Msg'; Direction: 1; DBXType: 37; TypeName: 'TObject'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_NotifyCallback: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ClientId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Msg'; Direction: 1; DBXType: 37; TypeName: 'TJSONValue'), (Name: 'Response'; Direction: 2; DBXType: 37; TypeName: 'TJSONValue'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_NotifyObject: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ClientId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Msg'; Direction: 1; DBXType: 37; TypeName: 'TObject'), (Name: 'Response'; Direction: 2; DBXType: 37; TypeName: 'TObject'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_ConsumeClientChannelSecure: array [0..6] of TDSRestParameterMetaData = ( (Name: 'ChannelName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ClientManagerId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ChannelNames'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'SecurityToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ResponseData'; Direction: 1; DBXType: 37; TypeName: 'TJSONValue'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONValue') ); DSAdmin_ConsumeClientChannelTimeoutSecure: array [0..7] of TDSRestParameterMetaData = ( (Name: 'ChannelName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ClientManagerId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ChannelNames'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'SecurityToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Timeout'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'ResponseData'; Direction: 1; DBXType: 37; TypeName: 'TJSONValue'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONValue') ); DSAdmin_CloseClientChannelSecure: array [0..2] of TDSRestParameterMetaData = ( (Name: 'ChannelId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'SecurityToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_RegisterClientCallbackServerSecure: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ChannelId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'ChannelNames'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'SecurityToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); DSAdmin_UnregisterClientCallbackSecure: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ChannelId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'CallbackId'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'SecurityToken'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean') ); implementation uses System.Classes, Data.DBXClientResStrs, Data.DBXCommonTable, System.SysUtils; function GetSecurityToken: string; begin if GDSProxyRestSecurityToken = ' ' then GDSProxyRestSecurityToken := IntToStr(Random(100000)) + '.' + IntToStr(Random(100000)); Result := GDSProxyRestSecurityToken; end; { TDSAdminRestClient } function TDSAdminRestClient.GetPlatformName: string; begin if FGetPlatformNameCommand = nil then begin FGetPlatformNameCommand := FConnection.CreateCommand; FGetPlatformNameCommand.RequestType := 'GET'; FGetPlatformNameCommand.Text := 'DSAdmin.GetPlatformName'; FGetPlatformNameCommand.Prepare(DSAdmin_GetPlatformName); end; FGetPlatformNameCommand.Execute; Result := FGetPlatformNameCommand.Parameters[0].Value.GetWideString; end; function TDSAdminRestClient.ClearResources: Boolean; begin if FClearResourcesCommand = nil then begin FClearResourcesCommand := FConnection.CreateCommand; FClearResourcesCommand.RequestType := 'GET'; FClearResourcesCommand.Text := 'DSAdmin.ClearResources'; FClearResourcesCommand.Prepare(DSAdmin_ClearResources); end; FClearResourcesCommand.Execute; Result := FClearResourcesCommand.Parameters[0].Value.GetBoolean; end; function TDSAdminRestClient.FindPackages: TDBXReader; begin if FFindPackagesCommand = nil then begin FFindPackagesCommand := FConnection.CreateCommand; FFindPackagesCommand.RequestType := 'GET'; FFindPackagesCommand.Text := 'DSAdmin.FindPackages'; FFindPackagesCommand.Prepare(DSAdmin_FindPackages); end; FFindPackagesCommand.Execute; Result := FFindPackagesCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.FindClasses(PackageName: string; ClassPattern: string): TDBXReader; begin if FFindClassesCommand = nil then begin FFindClassesCommand := FConnection.CreateCommand; FFindClassesCommand.RequestType := 'GET'; FFindClassesCommand.Text := 'DSAdmin.FindClasses'; FFindClassesCommand.Prepare(DSAdmin_FindClasses); end; FFindClassesCommand.Parameters[0].Value.SetWideString(PackageName); FFindClassesCommand.Parameters[1].Value.SetWideString(ClassPattern); FFindClassesCommand.Execute; Result := FFindClassesCommand.Parameters[2].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.FindMethods(PackageName: string; ClassPattern: string; MethodPattern: string): TDBXReader; begin if FFindMethodsCommand = nil then begin FFindMethodsCommand := FConnection.CreateCommand; FFindMethodsCommand.RequestType := 'GET'; FFindMethodsCommand.Text := 'DSAdmin.FindMethods'; FFindMethodsCommand.Prepare(DSAdmin_FindMethods); end; FFindMethodsCommand.Parameters[0].Value.SetWideString(PackageName); FFindMethodsCommand.Parameters[1].Value.SetWideString(ClassPattern); FFindMethodsCommand.Parameters[2].Value.SetWideString(MethodPattern); FFindMethodsCommand.Execute; Result := FFindMethodsCommand.Parameters[3].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.ListClasses: TJSONArray; begin if FListClassesCommand = nil then begin FListClassesCommand := FConnection.CreateCommand; FListClassesCommand.RequestType := 'GET'; FListClassesCommand.Text := 'DSAdmin.ListClasses'; FListClassesCommand.Prepare(DSAdmin_ListClasses); end; FListClassesCommand.Execute; Result := TJSONArray(FListClassesCommand.Parameters[0].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.DescribeClass(ClassName: string): TJSONObject; begin if FDescribeClassCommand = nil then begin FDescribeClassCommand := FConnection.CreateCommand; FDescribeClassCommand.RequestType := 'GET'; FDescribeClassCommand.Text := 'DSAdmin.DescribeClass'; FDescribeClassCommand.Prepare(DSAdmin_DescribeClass); end; FDescribeClassCommand.Parameters[0].Value.SetWideString(ClassName); FDescribeClassCommand.Execute; Result := TJSONObject(FDescribeClassCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.ListMethods(ClassName: string): TJSONArray; begin if FListMethodsCommand = nil then begin FListMethodsCommand := FConnection.CreateCommand; FListMethodsCommand.RequestType := 'GET'; FListMethodsCommand.Text := 'DSAdmin.ListMethods'; FListMethodsCommand.Prepare(DSAdmin_ListMethods); end; FListMethodsCommand.Parameters[0].Value.SetWideString(ClassName); FListMethodsCommand.Execute; Result := TJSONArray(FListMethodsCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.DescribeMethod(ServerMethodName: string): TJSONObject; begin if FDescribeMethodCommand = nil then begin FDescribeMethodCommand := FConnection.CreateCommand; FDescribeMethodCommand.RequestType := 'GET'; FDescribeMethodCommand.Text := 'DSAdmin.DescribeMethod'; FDescribeMethodCommand.Prepare(DSAdmin_DescribeMethod); end; FDescribeMethodCommand.Parameters[0].Value.SetWideString(ServerMethodName); FDescribeMethodCommand.Execute; Result := TJSONObject(FDescribeMethodCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.GetServerMethods: TDBXReader; begin if FGetServerMethodsCommand = nil then begin FGetServerMethodsCommand := FConnection.CreateCommand; FGetServerMethodsCommand.RequestType := 'GET'; FGetServerMethodsCommand.Text := 'DSAdmin.GetServerMethods'; FGetServerMethodsCommand.Prepare(DSAdmin_GetServerMethods); end; FGetServerMethodsCommand.Execute; Result := FGetServerMethodsCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.GetServerMethodParameters: TDBXReader; begin if FGetServerMethodParametersCommand = nil then begin FGetServerMethodParametersCommand := FConnection.CreateCommand; FGetServerMethodParametersCommand.RequestType := 'GET'; FGetServerMethodParametersCommand.Text := 'DSAdmin.GetServerMethodParameters'; FGetServerMethodParametersCommand.Prepare(DSAdmin_GetServerMethodParameters); end; FGetServerMethodParametersCommand.Execute; Result := FGetServerMethodParametersCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.GetDatabaseConnectionProperties: TDBXReader; begin if FGetDatabaseConnectionPropertiesCommand = nil then begin FGetDatabaseConnectionPropertiesCommand := FConnection.CreateCommand; FGetDatabaseConnectionPropertiesCommand.RequestType := 'GET'; FGetDatabaseConnectionPropertiesCommand.Text := 'DSAdmin.GetDatabaseConnectionProperties'; FGetDatabaseConnectionPropertiesCommand.Prepare(DSAdmin_GetDatabaseConnectionProperties); end; FGetDatabaseConnectionPropertiesCommand.Execute; Result := FGetDatabaseConnectionPropertiesCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TDSAdminRestClient.ConsumeClientChannel(ChannelName, ClientManagerId, CallbackId, ChannelNames: string; ResponseData: TJSONValue): TJSONValue; begin if FConsumeClientChannelCommand = nil then begin FConsumeClientChannelCommand := FConnection.CreateCommand; FConsumeClientChannelCommand.RequestType := 'POST'; FConsumeClientChannelCommand.Text := 'DSAdmin."ConsumeClientChannel"'; FConsumeClientChannelCommand.Prepare(DSAdmin_ConsumeClientChannelSecure); end; FConsumeClientChannelCommand.Parameters[0].Value.SetWideString(ChannelName); FConsumeClientChannelCommand.Parameters[1].Value.SetWideString(ClientManagerId); FConsumeClientChannelCommand.Parameters[2].Value.SetWideString(CallbackId); FConsumeClientChannelCommand.Parameters[3].Value.SetWideString(ChannelNames); FConsumeClientChannelCommand.Parameters[4].Value.SetWideString(GetSecurityToken); FConsumeClientChannelCommand.Parameters[5].Value.SetJSONValue(ResponseData, FInstanceOwner); FConsumeClientChannelCommand.Execute; Result := TJSONValue(FConsumeClientChannelCommand.Parameters[6].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.ConsumeClientChannelTimeout(ChannelName, ClientManagerId, CallbackId, ChannelNames: string; Timeout: Integer; ResponseData: TJSONValue): TJSONValue; begin if FConsumeClientChannelTimeoutCommand = nil then begin FConsumeClientChannelTimeoutCommand := FConnection.CreateCommand; FConsumeClientChannelTimeoutCommand.RequestType := 'POST'; FConsumeClientChannelTimeoutCommand.Text := 'DSAdmin."ConsumeClientChannelTimeout"'; FConsumeClientChannelTimeoutCommand.Prepare(DSAdmin_ConsumeClientChannelTimeoutSecure); end; FConsumeClientChannelTimeoutCommand.Parameters[0].Value.SetWideString(ChannelName); FConsumeClientChannelTimeoutCommand.Parameters[1].Value.SetWideString(ClientManagerId); FConsumeClientChannelTimeoutCommand.Parameters[2].Value.SetWideString(CallbackId); FConsumeClientChannelTimeoutCommand.Parameters[3].Value.SetWideString(ChannelNames); FConsumeClientChannelTimeoutCommand.Parameters[4].Value.SetWideString(GetSecurityToken); FConsumeClientChannelTimeoutCommand.Parameters[5].Value.SetInt32(Timeout); FConsumeClientChannelTimeoutCommand.Parameters[6].Value.SetJSONValue(ResponseData, FInstanceOwner); FConsumeClientChannelTimeoutCommand.Execute; Result := TJSONValue(FConsumeClientChannelTimeoutCommand.Parameters[7].Value.GetJSONValue(FInstanceOwner)); end; function TDSAdminRestClient.CloseClientChannel(ChannelId: string): Boolean; begin if FCloseClientChannelCommand = nil then begin FCloseClientChannelCommand := FConnection.CreateCommand; FCloseClientChannelCommand.RequestType := 'GET'; FCloseClientChannelCommand.Text := 'DSAdmin.CloseClientChannel'; FCloseClientChannelCommand.Prepare(DSAdmin_CloseClientChannelSecure); end; FCloseClientChannelCommand.Parameters[0].Value.SetWideString(ChannelId); FCloseClientChannelCommand.Parameters[1].Value.SetWideString(GetSecurityToken); FCloseClientChannelCommand.Execute; Result := FCloseClientChannelCommand.Parameters[2].Value.GetBoolean; end; function TDSAdminRestClient.RegisterClientCallbackServer(ChannelId, CallbackId, ChannelNames: string): Boolean; begin if FRegisterClientCallbackServerCommand = nil then begin FRegisterClientCallbackServerCommand := FConnection.CreateCommand; FRegisterClientCallbackServerCommand.RequestType := 'GET'; FRegisterClientCallbackServerCommand.Text := 'DSAdmin.RegisterClientCallbackServer'; FRegisterClientCallbackServerCommand.Prepare(DSAdmin_RegisterClientCallbackServerSecure); end; FRegisterClientCallbackServerCommand.Parameters[0].Value.SetWideString(ChannelId); FRegisterClientCallbackServerCommand.Parameters[1].Value.SetWideString(CallbackId); FRegisterClientCallbackServerCommand.Parameters[2].Value.SetWideString(ChannelNames); FRegisterClientCallbackServerCommand.Parameters[3].Value.SetWideString(GetSecurityToken); FRegisterClientCallbackServerCommand.Execute; Result := FRegisterClientCallbackServerCommand.Parameters[4].Value.GetBoolean; end; function TDSAdminRestClient.UnregisterClientCallback(ChannelId, CallbackId: string): Boolean; begin if FUnregisterClientCallbackCommand = nil then begin FUnregisterClientCallbackCommand := FConnection.CreateCommand; FUnregisterClientCallbackCommand.RequestType := 'GET'; FUnregisterClientCallbackCommand.Text := 'DSAdmin.UnregisterClientCallback'; FUnregisterClientCallbackCommand.Prepare(DSAdmin_UnregisterClientCallbackSecure); end; FUnregisterClientCallbackCommand.Parameters[0].Value.SetWideString(ChannelId); FUnregisterClientCallbackCommand.Parameters[1].Value.SetWideString(CallbackId); FUnregisterClientCallbackCommand.Parameters[2].Value.SetWideString(GetSecurityToken); FUnregisterClientCallbackCommand.Execute; Result := FUnregisterClientCallbackCommand.Parameters[3].Value.GetBoolean; end; function TDSAdminRestClient.BroadcastToChannel(ChannelName: string; Msg: TJSONValue): Boolean; begin if FBroadcastToChannelCommand = nil then begin FBroadcastToChannelCommand := FConnection.CreateCommand; FBroadcastToChannelCommand.RequestType := 'POST'; FBroadcastToChannelCommand.Text := 'DSAdmin."BroadcastToChannel"'; FBroadcastToChannelCommand.Prepare(DSAdmin_BroadcastToChannel); end; FBroadcastToChannelCommand.Parameters[0].Value.SetWideString(ChannelName); FBroadcastToChannelCommand.Parameters[1].Value.SetJSONValue(Msg, FInstanceOwner); FBroadcastToChannelCommand.Execute; Result := FBroadcastToChannelCommand.Parameters[2].Value.GetBoolean; end; function TDSAdminRestClient.BroadcastObjectToChannel(ChannelName: string; Msg: TObject): Boolean; begin if FBroadcastObjectToChannelCommand = nil then begin FBroadcastObjectToChannelCommand := FConnection.CreateCommand; FBroadcastObjectToChannelCommand.RequestType := 'POST'; FBroadcastObjectToChannelCommand.Text := 'DSAdmin."BroadcastObjectToChannel"'; FBroadcastObjectToChannelCommand.Prepare(DSAdmin_BroadcastObjectToChannel); end; FBroadcastObjectToChannelCommand.Parameters[0].Value.SetWideString(ChannelName); if not Assigned(Msg) then FBroadcastObjectToChannelCommand.Parameters[1].Value.SetNull else begin FMarshal := TDSRestCommand(FBroadcastObjectToChannelCommand.Parameters[1].ConnectionHandler).GetJSONMarshaler; try FBroadcastObjectToChannelCommand.Parameters[1].Value.SetJSONValue(FMarshal.Marshal(Msg), True); if FInstanceOwner then Msg.Free finally FreeAndNil(FMarshal) end end; FBroadcastObjectToChannelCommand.Execute; Result := FBroadcastObjectToChannelCommand.Parameters[2].Value.GetBoolean; end; function TDSAdminRestClient.NotifyCallback(ClientId: string; CallbackId: string; Msg: TJSONValue; out Response: TJSONValue): Boolean; begin if FNotifyCallbackCommand = nil then begin FNotifyCallbackCommand := FConnection.CreateCommand; FNotifyCallbackCommand.RequestType := 'POST'; FNotifyCallbackCommand.Text := 'DSAdmin."NotifyCallback"'; FNotifyCallbackCommand.Prepare(DSAdmin_NotifyCallback); end; FNotifyCallbackCommand.Parameters[0].Value.SetWideString(ClientId); FNotifyCallbackCommand.Parameters[1].Value.SetWideString(CallbackId); FNotifyCallbackCommand.Parameters[2].Value.SetJSONValue(Msg, FInstanceOwner); FNotifyCallbackCommand.Execute; Response := TJSONValue(FNotifyCallbackCommand.Parameters[3].Value.GetJSONValue(FInstanceOwner)); Result := FNotifyCallbackCommand.Parameters[4].Value.GetBoolean; end; function TDSAdminRestClient.NotifyObject(ClientId: string; CallbackId: string; Msg: TObject; out Response: TObject): Boolean; begin if FNotifyObjectCommand = nil then begin FNotifyObjectCommand := FConnection.CreateCommand; FNotifyObjectCommand.RequestType := 'POST'; FNotifyObjectCommand.Text := 'DSAdmin."NotifyObject"'; FNotifyObjectCommand.Prepare(DSAdmin_NotifyObject); end; FNotifyObjectCommand.Parameters[0].Value.SetWideString(ClientId); FNotifyObjectCommand.Parameters[1].Value.SetWideString(CallbackId); if not Assigned(Msg) then FNotifyObjectCommand.Parameters[2].Value.SetNull else begin FMarshal := TDSRestCommand(FNotifyObjectCommand.Parameters[2].ConnectionHandler).GetJSONMarshaler; try FNotifyObjectCommand.Parameters[2].Value.SetJSONValue(FMarshal.Marshal(Msg), True); if FInstanceOwner then Msg.Free finally FreeAndNil(FMarshal) end end; FNotifyObjectCommand.Execute; if not FNotifyObjectCommand.Parameters[3].Value.IsNull then begin FUnMarshal := TDSRestCommand(FNotifyObjectCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler; try Response := TObject(FUnMarshal.UnMarshal(FNotifyObjectCommand.Parameters[3].Value.GetJSONValue(True))); finally FreeAndNil(FUnMarshal) end; end else Response := nil; Result := FNotifyObjectCommand.Parameters[4].Value.GetBoolean; end; procedure TDSAdminRestClient.ClearSession; begin if FClearSessionCommand = nil then begin FClearSessionCommand := FConnection.CreateCommand; FClearSessionCommand.RequestType := 'GET'; FClearSessionCommand.Text := 'DSAdmin.ClearSession'; end; FClearSessionCommand.Execute; end; constructor TDSAdminRestClient.Create(AConnection: TDSCustomRestConnection); begin inherited Create(AConnection); end; constructor TDSAdminRestClient.Create(AConnection: TDSCustomRestConnection; AInstanceOwner: Boolean); begin inherited Create(AConnection, AInstanceOwner); end; destructor TDSAdminRestClient.Destroy; begin FreeAndNil(FGetPlatformNameCommand); FreeAndNil(FClearResourcesCommand); FreeAndNil(FFindPackagesCommand); FreeAndNil(FFindClassesCommand); FreeAndNil(FFindMethodsCommand); FreeAndNil(FListClassesCommand); FreeAndNil(FDescribeClassCommand); FreeAndNil(FListMethodsCommand); FreeAndNil(FDescribeMethodCommand); FreeAndNil(FGetServerMethodsCommand); FreeAndNil(FGetServerMethodParametersCommand); FreeAndNil(FGetDatabaseConnectionPropertiesCommand); FreeAndNil(FConsumeClientChannelCommand); FreeAndNil(FConsumeClientChannelTimeoutCommand); FreeAndNil(FCloseClientChannelCommand); FreeAndNil(FRegisterClientCallbackServerCommand); FreeAndNil(FUnregisterClientCallbackCommand); FreeAndNil(FBroadcastToChannelCommand); FreeAndNil(FBroadcastObjectToChannelCommand); FreeAndNil(FNotifyCallbackCommand); FreeAndNil(FNotifyObjectCommand); FreeAndNil(FClearSessionCommand); inherited; end; { TDSRestClient } constructor TDSRestClient.Create(AConnection: TDSCustomRestConnection; AInstanceOwner: Boolean); begin FConnection := AConnection; FInstanceOwner := AInstanceOwner; end; constructor TDSRestClient.Create(AConnection: TDSCustomRestConnection); begin Create(AConnection, True); end; { TDSProxyMetaDataLoader } constructor TDSRestProxyMetaDataLoader.Create(AConnection: TDSCustomRestConnection); begin FConnection := AConnection; end; procedure TDSRestProxyMetaDataLoader.Load(MetaData: TDSProxyMetadata); var LConnection: TDSCustomRestConnection; begin LConnection := FConnection; if LConnection <> nil then LoadFromConnection(LConnection, MetaData); if LConnection = nil then raise TDSProxyException.Create(SNoConnection); end; procedure TDSRestProxyMetaDataLoader.LoadFromConnection(AConnection: TDSCustomRestConnection; AMetaData: TDSProxyMetadata); var LClient: TDSAdminRestClient; LReader: TDBXReader; LTable: TDBXTable; LMethodParameters: TDSMethodParametersEntity; begin LMethodParameters := nil; LClient := TDSAdminRestClient.Create(AConnection, True); try LReader := LClient.GetServerMethodParameters; try LTable := TDBXReaderTable.Create(LReader); LMethodParameters := TDSMethodParametersEntity.Create(LTable, True); AMetaData.LoadMetadata(LMethodParameters); finally //LTable.Free; LMethodParameters.Free; if csDesigning in AConnection.ComponentState then try AConnection.SessionId := ''; AConnection.HTTP.Disconnect; except end; end; finally LClient.Free; end; end; end.
unit TestCaseReturns; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestCaseReturns, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface { AFS 10 Dec 2003 Test block styles and returns in cases } uses TestFrameWork, BaseTestProcess, SettingsTypes; type TTestCaseReturns = class(TBaseTestProcess) private feSaveCaseLabelStyle: TTriOptionStyle; feSaveCaseBeginStyle: TTriOptionStyle; feSaveCaseElseStyle: TTriOptionStyle; feSaveCaseElseBeginStyle: TTriOptionStyle; fbSaveCaseElseIndent: boolean; protected procedure SetUp; override; procedure TearDown; override; published procedure TestCaseStatementLeave1; procedure TestCaseStatementLeave2; procedure TestCaseStatementLeave3; procedure TestCaseStatementNever1; procedure TestCaseStatementNever2; procedure TestCaseStatementNever3; procedure TestCaseStatementAlways1; procedure TestCaseStatementAlways2; procedure TestCaseStatementAlways3; procedure TestCaseStatementJustElse1; procedure TestCaseStatementJustElse2; procedure TestCaseStatementJustElse3; procedure TestCaseStatementElseBegin1; procedure TestCaseStatementElseBegin2; procedure TestCaseStatementElseBegin3; procedure TestCaseStatementElseBegin4; procedure TestCaseStatementElseBegin5; procedure TestCaseStatementElseBegin6; procedure TestCaseBegin1; procedure TestCaseBegin2; procedure TestCaseBegin3; procedure TestCaseBegin4; procedure TestCaseBegin5; procedure TestCaseBegin6; procedure TestCaseStatementElseIndent; procedure TestCaseStatementElseOutdent; end; implementation uses JcfStringUtils, JcfSettings, BlockStyles, Indenter, SetReturns; { TTestCaseReturns } const { test breaking after case labels } UNIT_TEXT_IN_LINE = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1: Bar; ' + ' 2: Fish; ' + ' else Spock; ' + ' end; ' + ' end; ' + UNIT_FOOTER; UNIT_TEXT_NEW_LINE = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1:' + NativeLineBreak + 'Bar; ' + ' 2:' + NativeLineBreak + 'Fish; ' + ' else' + NativeLineBreak + 'Spock; ' + ' end; ' + ' end; ' + UNIT_FOOTER; OUT_UNIT_TEXT_JUST_ELSE_NEWLINE = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1: Bar; ' + ' 2: Fish; ' + ' else' + NativeLineBreak + 'Spock; ' + ' end; ' + ' end; ' + UNIT_FOOTER; { test breaking on else ... begin} UNIT_TEXT_ELSE_BEGIN = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1:' + NativeLineBreak + 'Bar; ' + ' 2:' + NativeLineBreak + 'Fish; ' + ' else begin' + NativeLineBreak + 'Spock; ' + ' end; end; ' + ' end; ' + UNIT_FOOTER; UNIT_TEXT_ELSE_BEGIN_NEWLINE = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1:' + NativeLineBreak + 'Bar; ' + ' 2:' + NativeLineBreak + 'Fish; ' + ' else' + NativeLineBreak + 'begin' + NativeLineBreak + 'Spock; ' + ' end; end; ' + ' end; ' + UNIT_FOOTER; { test breaking on case: begin } UNIT_TEXT_CASE_BEGIN = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1: begin Bar; end ' + ' 2: begin Fish; end ' + ' end; ' + ' end; ' + UNIT_FOOTER; UNIT_TEXT_CASE_BEGIN_NEW_LINE = UNIT_HEADER + ' procedure foo; begin' + ' case x of ' + ' 1:' + NativeLineBreak + 'begin Bar; end ' + ' 2:' + NativeLineBreak + 'begin Fish; end ' + ' end; ' + ' end; ' + UNIT_FOOTER; UNIT_TEXT_INDENTED = UNIT_HEADER + NativeLineBreak + 'procedure foo;' + NativeLineBreak + 'begin' + NativeLineBreak + ' case x of' + NativeLineBreak + ' 1: Bar;' + NativeLineBreak + ' 2: Fish;' + NativeLineBreak + ' else Spock;' + NativeLineBreak + ' end;' + NativeLineBreak + 'end;' + NativeLineBreak + UNIT_FOOTER; UNIT_TEXT_INDENTED_ELSE = UNIT_HEADER + NativeLineBreak + 'procedure foo;' + NativeLineBreak + 'begin' + NativeLineBreak + ' case x of' + NativeLineBreak + ' 1: Bar;' + NativeLineBreak + ' 2: Fish;' + NativeLineBreak + ' else Spock;' + NativeLineBreak + ' end;' + NativeLineBreak + 'end;' + NativeLineBreak + UNIT_FOOTER; procedure TTestCaseReturns.Setup; begin inherited; feSaveCaseLabelStyle := JcfFormatSettings.Returns.CaseLabelStyle; feSaveCaseBeginStyle := JcfFormatSettings.Returns.CaseBeginStyle; feSaveCaseElseStyle := JcfFormatSettings.Returns.CaseElseStyle; feSaveCaseElseBeginStyle := JcfFormatSettings.Returns.CaseElseBeginStyle; fbSaveCaseElseIndent := JcfFormatSettings.Indent.IndentCaseElse; end; procedure TTestCaseReturns.TearDown; begin inherited; JcfFormatSettings.Returns.CaseLabelStyle := feSaveCaseLabelStyle; JcfFormatSettings.Returns.CaseBeginStyle := feSaveCaseBeginStyle; JcfFormatSettings.Returns.CaseElseStyle := feSaveCaseElseStyle; JcfFormatSettings.Returns.CaseElseBeginStyle := feSaveCaseElseBeginStyle; JcfFormatSettings.Indent.IndentCaseElse := fbSaveCaseElseIndent; end; procedure TTestCaseReturns.TestCaseStatementAlways1; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eAlways; TestProcessResult(TBlockStyles, UNIT_TEXT_IN_LINE, UNIT_TEXT_NEW_LINE); end; procedure TTestCaseReturns.TestCaseStatementAlways2; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eAlways; TestProcessResult(TBlockStyles, UNIT_TEXT_NEW_LINE, UNIT_TEXT_NEW_LINE); end; procedure TTestCaseReturns.TestCaseStatementAlways3; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eAlways; TestProcessResult(TBlockStyles, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE, UNIT_TEXT_NEW_LINE); end; procedure TTestCaseReturns.TestCaseStatementJustElse1; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, UNIT_TEXT_IN_LINE, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementJustElse2; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, UNIT_TEXT_NEW_LINE, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementJustElse3; begin JcfFormatSettings.Returns.CaseElseStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementLeave1; begin JcfFormatSettings.Returns.CaseElseStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_NEW_LINE, UNIT_TEXT_NEW_LINE); end; procedure TTestCaseReturns.TestCaseStatementLeave2; begin JcfFormatSettings.Returns.CaseElseStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_IN_LINE, UNIT_TEXT_IN_LINE); end; procedure TTestCaseReturns.TestCaseStatementLeave3; begin JcfFormatSettings.Returns.CaseElseStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementNever1; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, UNIT_TEXT_NEW_LINE, UNIT_TEXT_IN_LINE); end; procedure TTestCaseReturns.TestCaseStatementNever2; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, OUT_UNIT_TEXT_JUST_ELSE_NEWLINE, UNIT_TEXT_IN_LINE); end; procedure TTestCaseReturns.TestCaseStatementNever3; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eNever; TestProcessResult(TBlockStyles, UNIT_TEXT_NEW_LINE, UNIT_TEXT_IN_LINE); end; procedure TTestCaseReturns.TestCaseStatementElseBegin1; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN, UNIT_TEXT_ELSE_BEGIN); end; procedure TTestCaseReturns.TestCaseStatementElseBegin2; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN_NEWLINE, UNIT_TEXT_ELSE_BEGIN); end; procedure TTestCaseReturns.TestCaseStatementElseBegin3; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN, UNIT_TEXT_ELSE_BEGIN); end; procedure TTestCaseReturns.TestCaseStatementElseBegin4; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN_NEWLINE, UNIT_TEXT_ELSE_BEGIN_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementElseBegin5; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN, UNIT_TEXT_ELSE_BEGIN_NEWLINE); end; procedure TTestCaseReturns.TestCaseStatementElseBegin6; begin JcfFormatSettings.Returns.CaseElseStyle := eNever; JcfFormatSettings.Returns.CaseElseBeginStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_ELSE_BEGIN_NEWLINE, UNIT_TEXT_ELSE_BEGIN_NEWLINE); end; procedure TTestCaseReturns.TestCaseBegin1; begin JcfFormatSettings.Returns.CaseBeginStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN, UNIT_TEXT_CASE_BEGIN); end; procedure TTestCaseReturns.TestCaseBegin2; begin JcfFormatSettings.Returns.CaseBeginStyle := eLeave; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN_NEW_LINE, UNIT_TEXT_CASE_BEGIN_NEW_LINE); end; procedure TTestCaseReturns.TestCaseBegin3; begin JcfFormatSettings.Returns.CaseBeginStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN, UNIT_TEXT_CASE_BEGIN_NEW_LINE); end; procedure TTestCaseReturns.TestCaseBegin4; begin JcfFormatSettings.Returns.CaseBeginStyle := eAlways; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN_NEW_LINE, UNIT_TEXT_CASE_BEGIN_NEW_LINE); end; procedure TTestCaseReturns.TestCaseBegin5; begin JcfFormatSettings.Returns.CaseBeginStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN, UNIT_TEXT_CASE_BEGIN); end; procedure TTestCaseReturns.TestCaseBegin6; begin JcfFormatSettings.Returns.CaseBeginStyle := eNever; JcfFormatSettings.Returns.CaseLabelStyle := eLeave; TestProcessResult(TBlockStyles, UNIT_TEXT_CASE_BEGIN_NEW_LINE, UNIT_TEXT_CASE_BEGIN); end; procedure TTestCaseReturns.TestCaseStatementElseIndent; begin JcfFormatSettings.Indent.IndentCaseElse := True; TestProcessResult(TIndenter, UNIT_TEXT_INDENTED, UNIT_TEXT_INDENTED); TestProcessResult(TIndenter, UNIT_TEXT_INDENTED_ELSE, UNIT_TEXT_INDENTED); end; procedure TTestCaseReturns.TestCaseStatementElseOutdent; begin JcfFormatSettings.Indent.IndentCaseElse := False; TestProcessResult(TIndenter, UNIT_TEXT_INDENTED, UNIT_TEXT_INDENTED_ELSE); TestProcessResult(TIndenter, UNIT_TEXT_INDENTED_ELSE, UNIT_TEXT_INDENTED_ELSE); end; initialization TestFramework.RegisterTest('Processes', TTestCaseReturns.Suite); end.
{ Subscribing to all topics and printing out incoming messages Simple test code for the mqttclass unit Copyright (c) 2019 Karoly Balogh <charlie@amigaspirit.hu> See the LICENSE file for licensing details. } {$MODE OBJFPC} program testclass; uses {$IFDEF HASUNIX} cthreads, {$ENDIF} ctypes, mosquitto, mqttclass; type TMyMQTTConnection = class(TMQTTConnection) procedure MyOnMessage(const payload: Pmosquitto_message); end; procedure TMyMQTTConnection.MyOnMessage(const payload: Pmosquitto_message); var msg: ansistring; begin msg:=''; with payload^ do begin { Note that MQTT messages can be binary, but for this test case we just assume they're printable text, as a test } SetLength(msg,payloadlen); Move(payload^,msg[1],payloadlen); writeln('Topic: [',topic,'] - Message: [',msg,']'); end; end; var mqtt: TMyMQTTConnection; config: TMQTTConfig; begin writeln('Press ENTER to quit.'); FillChar(config, sizeof(config), 0); with config do begin port:=1883; hostname:='localhost'; keepalives:=60; end; { use MOSQ_LOG_NODEBUG to disable debug logging } mqtt:=TMyMQTTConnection.Create('TEST',config,MOSQ_LOG_ALL); try { This could also go to a custom constructor of the class, for more complicated setups. } mqtt.OnMessage:=@mqtt.MyOnMessage; mqtt.Connect; mqtt.Subscribe('#',0); { Subscribe to all topics } readln; except end; mqtt.Free; end.
unit fxBroker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DateUtils, ORNet, ORFn, rMisc, ComCtrls, Buttons, ExtCtrls, ORCtrls, ORSystem, fBase508Form, VA508AccessibilityManager, Winapi.RichEdit, Vcl.Menus, fFrame, Vcl.ImgList, Vcl.ToolWin, System.ImageList; const UM_REFRESH_RPC = WM_APP + 1; type TfrmBroker = class(TfrmBase508Form) pnlTop: TORAutoPanel; lblMaxCalls: TLabel; txtMaxCalls: TCaptionEdit; udMax: TUpDown; memData: TRichEdit; lblCallID: TStaticText; pnlMain: TPanel; PnlDebug: TPanel; SplDebug: TSplitter; PnlSearch: TPanel; lblSearch: TLabel; pnlSubSearch: TPanel; SearchTerm: TEdit; btnSearch: TButton; PnlDebugResults: TPanel; lblDebug: TLabel; ResultList: TListView; ScrollBox1: TScrollBox; DbugPageCtrl: TPageControl; SrchPage: TTabSheet; WatchPage: TTabSheet; WatchList: TListView; ToolBar1: TToolBar; c: TImageList; tlAddWatch: TToolButton; tlDelWatch: TToolButton; ToolButton1: TToolButton; tlClrWatch: TToolButton; ProgressBar1: TProgressBar; PopupMenu1: TPopupMenu; AlignLeft1: TMenuItem; AlignRight1: TMenuItem; AlignBottom1: TMenuItem; AlignTop1: TMenuItem; N1: TMenuItem; Undock1: TMenuItem; LivePage: TTabSheet; LiveList: TListView; ToolBar3: TToolBar; ToolButton2: TToolButton; ToolButton6: TToolButton; tlFlag: TToolButton; Panel1: TPanel; cmdNext: TBitBtn; cmdPrev: TBitBtn; btnRLT: TBitBtn; btnAdvTools: TBitBtn; procedure cmdPrevClick(Sender: TObject); procedure cmdNextClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnRLTClick(Sender: TObject); procedure LoadWatchList(); procedure btnSearchClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SearchTermChange(Sender: TObject); procedure SearchTermKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAdvToolsClick(Sender: TObject); procedure tlAddWatchClick(Sender: TObject); procedure tlDelWatchClick(Sender: TObject); procedure tlClrWatchClick(Sender: TObject); procedure ResultListClick(Sender: TObject); procedure FormStartDock(Sender: TObject; var DragObject: TDragDockObject); procedure FillLiveView(Inital: Boolean = False); procedure tlFlagClick(Sender: TObject); procedure LiveListAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure ToolButton2Click(Sender: TObject); procedure AlignClick(Sender: TObject); private { Private declarations } FRetained: Integer; FCurrent: Integer; // RPCArray: Array of TRpcRecord; LiveArray: Array of TRpcRecord; FlagIdent: Integer; // procedure CloneRPCList(); procedure InitalizeCloneArray(); procedure HighlightRichEdit(StartChar, EndChar: Integer; HighLightColor: TColor); procedure OnRefreshRPCRequest(); procedure AlignBroker(AlignStyle: TAlign); Procedure SyncList(index: Integer); public { Public declarations } end; procedure ShowBroker; var frmBroker: TfrmBroker; splLive: TSplitter; implementation {$R *.DFM} procedure ShowBroker; begin if not assigned(frmBroker) then frmBroker := TfrmBroker.Create(Application); // try ResizeAnchoredFormToFont(frmBroker); with frmBroker do begin FRetained := RetainedRPCCount - 1; FCurrent := FRetained; LoadRPCData(memData.Lines, FCurrent); if (Length(fFrame.WatchArray) > 0) then LoadWatchList; memData.SelStart := 0; lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); // ShowModal; Show; end; // finally // frmBroker.Release; // end; end; Procedure TfrmBroker.SyncList(index: Integer); var I: Integer; begin for i := Low(LiveArray) to High(LiveArray) do begin if LiveArray[i].UCallListIndex = Index then begin LiveList.ClearSelection; LiveList.Items[LiveArray[i].ResultListIndex].Selected := true; break; end; end; end; procedure TfrmBroker.cmdPrevClick(Sender: TObject); begin FCurrent := HigherOf(FCurrent - 1, 0); memData.SelStart := 0; LoadRPCData(memData.Lines, FCurrent); lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); if PnlDebug.Visible then SyncList(FCurrent) else begin // LoadRPCData(memData.Lines, FCurrent); // lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); end; end; procedure TfrmBroker.cmdNextClick(Sender: TObject); begin FCurrent := LowerOf(FCurrent + 1, FRetained); memData.SelStart := 0; LoadRPCData(memData.Lines, FCurrent); lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); if PnlDebug.Visible then SyncList(FCurrent) else begin // end; end; procedure TfrmBroker.FormClose(Sender: TObject; var Action: TCloseAction); begin SetRetainedRPCMax(StrToIntDef(txtMaxCalls.Text, 5)); frmBroker.Release; FreeAndNil(splLive); SetAfterRPCEvent(nil); end; procedure TfrmBroker.FormResize(Sender: TObject); begin Refresh; end; procedure TfrmBroker.FormStartDock(Sender: TObject; var DragObject: TDragDockObject); begin inherited; DragObject := TDragDockObjectEx.Create(Self); DragObject.Brush.Color := clAqua; // this will display a red outline end; procedure TfrmBroker.FormCreate(Sender: TObject); begin udMax.Position := GetRPCMax; Width := Width - PnlDebug.Width + SplDebug.Width; FlagIdent := -1; end; procedure TfrmBroker.FormDestroy(Sender: TObject); Var I: Integer; begin { for I := Low(RPCArray) to High(RPCArray) do RPCArray[I].RPCText.Free; SetLength(RPCArray, 0); } for I := Low(LiveArray) to High(LiveArray) do LiveArray[I].RPCText.Free; SetLength(LiveArray, 0); frmBroker := nil; end; procedure TfrmBroker.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; procedure TfrmBroker.HighlightRichEdit(StartChar, EndChar: Integer; HighLightColor: TColor); var Format: CHARFORMAT2; begin memData.SelStart := StartChar; memData.SelLength := EndChar; // Set the background color FillChar(Format, SizeOf(Format), 0); Format.cbSize := SizeOf(Format); Format.dwMask := CFM_BACKCOLOR; Format.crBackColor := HighLightColor; memData.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format)); end; procedure TfrmBroker.LiveListAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); begin if Item.Caption = '1' then begin sender.Canvas.Font.Color := clRed; sender.Canvas.brush.Color := clYellow; sender.Canvas.Font.Style := [fsbold]; end else begin sender.Canvas.Font.Color := clWindowText; sender.Canvas.brush.Color := clWindow; sender.Canvas.Font.Style := []; end; end; procedure TfrmBroker.LoadWatchList(); Var I, ReturnCursor: Integer; ListItem: TListItem; found: Boolean; begin ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try InitalizeCloneArray; if not PnlDebug.Visible then begin PnlDebug.Visible := true; Width := Width + PnlDebug.Width + SplDebug.Width; SplDebug.Visible := true; end; // Clear all WatchList.Clear; found := False; for I := Low(fFrame.WatchArray) to High(fFrame.WatchArray) do begin with fFrame.WatchArray[I] do begin ListItem := WatchList.Items.Add; ListItem.Caption := RpcName; ResultListIndex := ListItem.Index; if not found then begin WatchList.Column[0].Width := -1; found := true; end; end; end; finally Screen.Cursor := ReturnCursor; end; end; procedure TfrmBroker.AlignBroker(AlignStyle: TAlign); begin Self.Align := AlignStyle; if AlignStyle <> alNone then begin Self.Parent := frmFrame; Self.Align := AlignStyle; // create the splitter If not Assigned(splLive) then begin splLive := TSplitter.Create(frmFrame); splLive.parent := frmFrame; splLive.Color := clMedGray; end; splLive.Align := AlignStyle; Self.BorderStyle := bsNone; end else begin Self.Parent := nil; FreeAndNil(splLive); PnlDebug.Align := alLeft; SplDebug.Align := alLeft; SplDebug.Left := Self.Width; pnlMain.Align := alClient; Self.BorderStyle := bsSizeable; end; if AlignStyle = alLeft then begin Self.Left := frmFrame.Left; splLive.Width := 5; splLive.Left := Self.Width; PnlDebug.Align := alTop; SplDebug.Align := alTop; SplDebug.Top := Self.Height; pnlMain.Align := alClient; end else if AlignStyle = alRight then begin Self.Left := frmFrame.Width; splLive.Width := 5; splLive.Left := Self.left; PnlDebug.Align := alTop; SplDebug.Align := alTop; SplDebug.Top := Self.Height; pnlMain.Align := alClient; end else if AlignStyle = alBottom then begin Self.Top := frmFrame.height; splLive.Height := 5; splLive.Left := Self.top; PnlDebug.Align := alLeft; SplDebug.Align := alLeft; SplDebug.Left := Self.Width; pnlMain.Align := alClient; end else if AlignStyle = alTop then begin Self.Top := frmFrame.top; splLive.Height := 5; splLive.Left := Self.height; PnlDebug.Align := alLeft; SplDebug.Align := alLeft; SplDebug.Left := Self.Width; pnlMain.Align := alClient; end; Self.Repaint; end; procedure TfrmBroker.FillLiveView(Inital: Boolean = False); var ListItem: TListItem; I, X, ResetMask, ResetMask2: Integer; procedure DeleteX(const Index: Cardinal); var ALength: Cardinal; Y: integer; begin ALength := Length(LiveArray); Assert(ALength > 0); Assert(Index < ALength); for Y := Index + 1 to ALength - 1 do LiveArray[Y - 1] := LiveArray[Y]; SetLength(LiveArray, ALength - 1); end; function LockForUpdate(CtrlToLock: TWinControl): Integer; begin Result := CtrlToLock.Perform(EM_GETEVENTMASK, 0, 0); CtrlToLock.Perform(EM_SETEVENTMASK, 0, 0); CtrlToLock.Perform(WM_SETREDRAW, Ord(false), 0); end; procedure UnlockForUpdate(Var ReSetVar: Integer; CtrlToLock: TWinControl); begin CtrlToLock.Perform(WM_SETREDRAW, Ord(true), 0); InvalidateRect(CtrlToLock.Handle, NIL, true); CtrlToLock.Perform(EM_SETEVENTMASK, 0, ReSetVar); end; begin // Update the RPC array for the adv tools ResetMask := LockForUpdate(LiveList); ResetMask2 := LockForUpdate(memData); try if Inital then begin InitalizeCloneArray; SetLength(LiveArray, 0); LiveList.Items.BeginUpdate; for I := 0 to RetainedRPCCount - 1 do begin SetLength(LiveArray, Length(LiveArray) + 1); with LiveArray[High(LiveArray)] do begin RPCText := TStringList.Create; try LoadRPCData(RPCText, I); RpcName := RPCText[0]; UCallListIndex := I; for X := 0 to RPCText.Count - 1 do begin if Pos('Run time:', RPCText[X]) > 0 then begin RPCRunTime := Copy(RPCText[X], Pos('Run time:', RPCText[X]), Length(RPCText[X])); break; end; end; LiveList.ClearSelection; ListItem := LiveList.Items.Add; ListItem.Caption := ''; ListItem.SubItems.Add(RpcName); ResultListIndex := ListItem.Index; if (LiveList.Column[0].Width <> 0) or (LiveList.Column[1].Width <> -1) then begin LiveList.Column[0].Width := 0; LiveList.Column[1].Width := -1; end; ListItem.Selected := True; ListItem.MakeVisible(true); SearchIndex := -1; //See if it needs to be added to the search results if Trim(SearchTerm.Text) <> '' then begin if Pos(UpperCase(SearchTerm.Text), UpperCase(LiveArray[I].RPCText.Text)) > 0 then begin ListItem := ResultList.Items.Add; ListItem.Caption := RpcName; SearchIndex := ListItem.Index; end; end; except LiveArray[High(LiveArray)].RPCText.Free; end; end; LiveList.Items.EndUpdate; end; end else begin LiveList.Items.BeginUpdate; // need to add to the array if Length(LiveArray) = GetRPCMax then begin FreeAndNil(LiveArray[0].RPCText); //remove it from the search if LiveArray[0].SearchIndex <> -1 then LiveList.Items[LiveArray[0].SearchIndex].Delete; DeleteX(0); LiveList.Items[0].Delete; // reorder the numbers for I := Low(LiveArray) to High(LiveArray) do begin Dec(LiveArray[I].ResultListIndex); Dec(LiveArray[I].UCallListIndex); end; end; SetLength(LiveArray, Length(LiveArray) + 1); with LiveArray[High(LiveArray)] do begin RPCText := TStringList.Create; try LoadRPCData(RPCText, RetainedRPCCount - 1); RpcName := RPCText[0]; UCallListIndex := RetainedRPCCount - 1; for X := 0 to RPCText.Count - 1 do begin if Pos('Run time:', RPCText[X]) > 0 then begin RPCRunTime := Copy(RPCText[X], Pos('Run time:', RPCText[X]), Length(RPCText[X])); break; end; end; LiveList.ClearSelection; ListItem := LiveList.Items.Add; if (FlagIdent <> -1) and (FlagIdent <= UCallListIndex) then begin ListItem.Caption := '1'; end else ListItem.Caption := ''; if (FlagIdent <> -1) then FlagIdent := HigherOf(0, FlagIdent - 1); ListItem.SubItems.Add(RpcName); ResultListIndex := ListItem.Index; if (LiveList.Column[0].Width <> 0) or (LiveList.Column[1].Width <> -1) then begin LiveList.Column[0].Width := 0; LiveList.Column[1].Width := -1; end; ListItem.Selected := True; ListItem.MakeVisible(true); SearchIndex := -1; //See if it needs to be added to the search results if Trim(SearchTerm.Text) <> '' then begin if Pos(UpperCase(SearchTerm.Text), UpperCase(LiveArray[High(LiveArray)].RPCText.Text)) > 0 then begin ListItem := ResultList.Items.Add; ListItem.Caption := RpcName; SearchIndex := ListItem.Index; end; end; except LiveArray[High(LiveArray)].RPCText.Free; end; LiveList.Items.EndUpdate; end; end; memData.Lines.BeginUpdate; memData.Lines.Clear; memData.Lines.AddStrings(LiveArray[High(LiveArray)].RPCText); memData.Lines.EndUpdate; finally UnlockForUpdate(ResetMask2, memData); UnlockForUpdate(ResetMask, LiveList); end; end; procedure TfrmBroker.btnRLTClick(Sender: TObject); var startTime, endTime: TDateTime; clientVer, serverVer, diffDisplay: string; theDiff: Integer; const TX_OPTION = 'OR CPRS GUI CHART'; disclaimer = 'NOTE: Strictly relative indicator:'; begin clientVer := clientVersion(Application.ExeName); // Obtain before starting. // Check time lapse between a standard RPC call: startTime := now; serverVer := serverVersion(TX_OPTION, clientVer); endTime := now; theDiff := milliSecondsBetween(endTime, startTime); diffDisplay := IntToStr(theDiff); // Show the results: infoBox('Lapsed time (milliseconds) = ' + diffDisplay + '.', disclaimer, MB_OK); end; procedure TfrmBroker.btnSearchClick(Sender: TObject); var I, ReturnCursor: Integer; found: Boolean; ListItem: TListItem; begin ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try // Clear all ResultList.Clear; found := False; for I := Low(LiveArray) to High(LiveArray) do begin LiveArray[I].SearchIndex := -1; if Pos(UpperCase(SearchTerm.Text), UpperCase(LiveArray[I].RPCText.Text)) > 0 then begin ListItem := ResultList.Items.Add; ListItem.Caption := LiveArray[I].RpcName; LiveArray[I].SearchIndex := ListItem.Index; if not found then begin ResultList.Column[0].Width := -1; found := true; end; end; end; if not found then ShowMessage('no matches found'); finally Screen.Cursor := ReturnCursor; end; end; procedure TfrmBroker.AlignClick(Sender: TObject); begin inherited; With (Sender as TMenuItem) do begin if Tag = 1 then AlignBroker(alLeft) else if Tag = 2 then AlignBroker(alRight) else if Tag = 3 then AlignBroker(alBottom) else if Tag = 4 then AlignBroker(alTop) else if Tag = 5 then AlignBroker(alNone); end; end; procedure TfrmBroker.btnAdvToolsClick(Sender: TObject); begin inherited; if not PnlDebug.Visible then begin Width := Width + PnlDebug.Width + SplDebug.Width; PnlDebug.Visible := true; SplDebug.Visible := true; SplDebug.Left := PnlDebug.Width + 10; InitalizeCloneArray; SetAfterRPCEvent(OnRefreshRPCRequest); FillLiveView(True); end; end; procedure TfrmBroker.SearchTermChange(Sender: TObject); begin btnSearch.Enabled := (Trim(SearchTerm.Text) > ''); end; procedure TfrmBroker.SearchTermKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // inherited; if (Key = VK_RETURN) then btnSearchClick(Self); end; procedure TfrmBroker.tlAddWatchClick(Sender: TObject); var I, X: Integer; ListItem: TListItem; begin inherited; // add the entry for I := Low(LiveArray) to High(LiveArray) do begin if LiveArray[I].UCallListIndex = (FCurrent) then begin // Clone the entry SetLength(fFrame.WatchArray, Length(fFrame.WatchArray) + 1); with fFrame.WatchArray[High(fFrame.WatchArray)] do begin RpcName := LiveArray[I].RpcName; UCallListIndex := LiveArray[I].UCallListIndex; RPCText := TStringList.Create; try RPCText.Assign(LiveArray[I].RPCText); for X := 0 to RPCText.Count - 1 do begin if Pos('Run time:', RPCText[X]) > 0 then begin RPCRunTime := Copy(RPCText[X], Pos('Run time:', RPCText[X]), Length(RPCText[X])); break; end; end; Except RPCText.Free; end; ListItem := WatchList.Items.Add; ListItem.Caption := RpcName; ResultListIndex := ListItem.Index; end; if (WatchList.Column[0].Width <> -1) then begin WatchList.Column[0].Width := -1; end; break; end; end; end; procedure TfrmBroker.tlClrWatchClick(Sender: TObject); var I: Integer; begin inherited; for I := Low(fFrame.WatchArray) to High(fFrame.WatchArray) do fFrame.WatchArray[I].RPCText.Free; SetLength(fFrame.WatchArray, 0); WatchList.Clear; end; procedure TfrmBroker.tlDelWatchClick(Sender: TObject); var I: Integer; LS: TListItem; procedure DeleteX(const Index: Cardinal); var ALength: Cardinal; y: Integer; begin ALength := Length(fFrame.WatchArray); Assert(ALength > 0); Assert(Index < ALength); for Y := Index + 1 to ALength - 1 do fFrame.WatchArray[Y - 1] := fFrame.WatchArray[Y]; SetLength(fFrame.WatchArray, ALength - 1); end; begin inherited; LS := WatchList.Selected; // if there at least one item if Assigned(LS) then begin LS := WatchList.GetNextItem(LS, sdAll, [isSelected]); // if there are more than one while Assigned(LS) do begin for I := high(fFrame.WatchArray) downto low(fFrame.WatchArray) do begin if fFrame.WatchArray[I].ResultListIndex = LS.Index then begin fFrame.WatchArray[I].ResultListIndex := -1; fFrame.WatchArray[I].RPCText.Free; DeleteX(I); break; end; end; LS := WatchList.GetNextItem(LS, sdAll, [isSelected]); end; end; WatchList.DeleteSelected; end; procedure TfrmBroker.tlFlagClick(Sender: TObject); begin // flag by date if tlFlag.Down then FlagIdent := FRetained else FlagIdent := -1; end; procedure TfrmBroker.ToolButton2Click(Sender: TObject); begin inherited; AlignBroker(alNone); end; procedure TfrmBroker.InitalizeCloneArray(); begin if Length(LiveArray) = 0 then begin // CloneRPCList; ResultList.Column[0].Width := -2; WatchList.Column[0].Width := -2; LiveList.Column[1].Width := -2; end; end; procedure TfrmBroker.ResultListClick(Sender: TObject); Var TheLstView: TListView; ReturnCursor: Integer; procedure LoadSelected(LookupArray: Array of TRpcRecord); Var I, SelCnt: Integer; SearchString, tmpStr: string; CharPos, CharPos2: Integer; OvTm: TTime; IHour, IMin, ISec, IMilli: Word; LS: TListItem; begin memData.Clear; SelCnt := 0; OvTm := EncodeTime(0, 0, 0, 0); memData.Lines.BeginUpdate; ProgressBar1.Position := 0; ProgressBar1.Max := TheLstView.SelCount + 2; LS := TheLstView.Selected; // if there at least one item if Assigned(LS) then begin while Assigned(LS) do begin Inc(SelCnt); if SelCnt > 1 then begin memData.Lines.Add(''); memData.Lines.Add(''); memData.Lines.Add(StringOfChar('=', 80)); memData.Lines.Add(''); memData.Lines.Add(''); end; for I := Low(LookupArray) to High(LookupArray) do if TheLstView = ResultList then begin if LS.Index = LookupArray[I].SearchIndex then begin memData.Lines.AddStrings(LookupArray[I].RPCText); if TheLstView <> WatchList then lblCallID.Caption := 'Last Call Minus: ' + IntToStr((RetainedRPCCount - LookupArray[I].UCallListIndex) - 1) else lblCallID.Caption := 'Watch List'; FCurrent := LookupArray[I].UCallListIndex; IHour := StrToIntDef(Piece(LookupArray[I].RPCRunTime, ':', 2), 0); IMin := StrToIntDef(Piece(LookupArray[I].RPCRunTime, ':', 3), 0); tmpStr := Piece(LookupArray[I].RPCRunTime, ':', 4); ISec := StrToIntDef(Piece(tmpStr, '.', 1), 0); IMilli := StrToIntDef(Piece(tmpStr, '.', 2), 0); OvTm := IncHour(OvTm, IHour); OvTm := IncMinute(OvTm, IMin); OvTm := IncSecond(OvTm, ISec); OvTm := IncMilliSecond(OvTm, IMilli); break; end; end else begin if LS.Index = LookupArray[I].ResultListIndex then begin memData.Lines.AddStrings(LookupArray[I].RPCText); if TheLstView <> WatchList then lblCallID.Caption := 'Last Call Minus: ' + IntToStr((RetainedRPCCount - LookupArray[I].UCallListIndex) - 1) else lblCallID.Caption := 'Watch List'; FCurrent := LookupArray[I].UCallListIndex; IHour := StrToIntDef(Piece(LookupArray[I].RPCRunTime, ':', 2), 0); IMin := StrToIntDef(Piece(LookupArray[I].RPCRunTime, ':', 3), 0); tmpStr := Piece(LookupArray[I].RPCRunTime, ':', 4); ISec := StrToIntDef(Piece(tmpStr, '.', 1), 0); IMilli := StrToIntDef(Piece(tmpStr, '.', 2), 0); OvTm := IncHour(OvTm, IHour); OvTm := IncMinute(OvTm, IMin); OvTm := IncSecond(OvTm, ISec); OvTm := IncMilliSecond(OvTm, IMilli); break; end; end; LS := TheLstView.GetNextItem(LS, sdAll, [isSelected]); ProgressBar1.Position := ProgressBar1.Position + 1; end; end; memData.SelStart := 0; // Grab the ran time to get an overall if SelCnt > 1 then begin DecodeTime(OvTm, IHour, IMin, ISec, IMilli); tmpStr := ''; if IHour > 0 then tmpStr := tmpStr + IntToStr(IHour) + ' Hours'; if IMin > 0 then begin if tmpStr <> '' then tmpStr := tmpStr + ' '; tmpStr := tmpStr + IntToStr(IMin) + ' Minutes'; end; if ISec > 0 then begin if tmpStr <> '' then tmpStr := tmpStr + ' '; tmpStr := tmpStr + IntToStr(ISec) + ' Seconds'; end; if IMilli > 0 then begin if tmpStr <> '' then tmpStr := tmpStr + ' '; tmpStr := tmpStr + IntToStr(IMilli) + ' Milliseconds'; end; if tmpStr <> '' then tmpStr := 'Total run time of all selected RPCs: ' + tmpStr + CRLF + CRLF + StringOfChar('=', 80) + CRLF + CRLF; memData.Text := tmpStr + memData.Text; ProgressBar1.Position := ProgressBar1.Position + 1; end; if TheLstView = ResultList then begin SearchString := StringReplace(Trim(SearchTerm.Text), #10, '', [rfReplaceAll]); CharPos := 0; repeat // find the text and save the position CharPos2 := memData.FindText(SearchString, CharPos, Length(memData.Text), []); CharPos := CharPos2 + 1; if CharPos = 0 then break; HighlightRichEdit(CharPos2, Length(SearchString), clYellow); until CharPos = 0; ProgressBar1.Position := ProgressBar1.Position + 1; end; memData.Lines.EndUpdate; ProgressBar1.Position := 0; end; begin ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try TheLstView := TListView(Sender); // Setup the lookup array if TheLstView = ResultList then LoadSelected(LiveArray) else if TheLstView = WatchList then LoadSelected(fFrame.WatchArray) else if TheLstView = LiveList then LoadSelected(LiveArray); finally Screen.Cursor := ReturnCursor; end; end; procedure TfrmBroker.OnRefreshRPCRequest(); begin if Assigned(frmBroker) then frmBroker.FillLiveView; end; end.
{*** Program made by Pavel Shlyak. MIEM HSE 2017. All rights reserved. ***} Program Coursera; Var curr: Smallint; a, b, sum, ex, c, diff: Real; Procedure odd(x: Real; n: Integer; Var z: Real); {* Процедура нахождения энного члена ряда *} Begin z := (2*n+1); z := 1/(z*exp(z*ln(x))); End; Procedure exact(x: Real; Var z: Real); {* Процедура для нахождения полной суммы ряда (предела) *} Begin z := 0.5*ln((x+1)/(x-1)); End; Begin Write('Введите x > 1 и точность вычислений: '); Readln(a, b); While ( a<=1 ) Or ( b<=0 ) Do Begin Writeln( 'Юзер, ты тупой. точность вычислений - положительное число! А x должен превышать единицу! Повтори весь ввод' ); Readln(a,b); End; sum := 0; c := 0; curr := 0; Repeat odd(a, curr, c); sum := sum + c; curr := curr + 1; Until (c<=b); {* Найдём полную сумму *} exact(a, ex); diff:= abs(ex - sum); Writeln('Частичная сумма ряда с заданной точностью: ', sum, '. Получена с ', curr, ' итерации.'); Writeln('Полная сумма ряда:', ex); Writeln('Они различаются на: ',diff) End.
unit Comum.StreamUtils; interface uses Classes; type IStreamUTils = interface ['{3695444E-C3DC-4785-A027-4DFA750CD017}'] function textFileCountLines(AStream: TStream; const ABreakLine: Char): IStreamUTils; function textFileReadLine(AStream: TStream; const ABreakLine: Char): IStreamUTils; function textFilePosition(AStream: TFileStream; ANumeroLinha: Integer): IStreamUTils; function toString(): string; function toInteger(): Integer; end; TStreamUtils = class(TInterfacedObject, IStreamUTils) private FString: string; FInteger: Integer; { private declarations} protected { protected declarations} public function textFileCountLines(AStream: TStream; const ABreakLine: Char): IStreamUTils; function textFilePosition(AStream: TFileStream; ANumeroLinha: Integer): IStreamUTils; function textFileReadLine(AStream: TStream; const ABreakLine: Char): IStreamUTils; function toString(): string; function toInteger(): Integer; class function new(): IStreamUtils; { public declarations} end; implementation uses SysUtils; const BufferSize = 1024 * 1024; //1 MB var CharBuffer: array[0..BufferSize - 1] of AnsiChar; { TStreamUtils } function TStreamUtils.textFileCountLines(AStream: TStream; const ABreakLine: Char): IStreamUTils; var I, cutOff: Integer; startPosition: Integer; streamSize: Integer; count: Integer; begin try count := 0; startPosition := 0; streamSize := AStream.Size; cutOff := 0; while AStream.Position < streamSize do begin AStream.Read(CharBuffer[0], BufferSize); startPosition := startPosition + BufferSize; if startPosition > streamSize then cutOff := startPosition - streamSize; for I := 0 to BufferSize - 1 - cutOff do if CharBuffer[I] = ABreakLine then inc(count); end; finally FInteger := count; Result := Self; end; end; function TStreamUtils.textFileReadLine(AStream: TStream; const ABreakLine: Char): IStreamUTils; var ch: AnsiChar; StartPos, lineLength: integer; line: string; begin try StartPos := AStream.Position; ch := #0; while (AStream.Read(ch, 1) = 1) and (ch <> ABreakLine) do ; lineLength := AStream.Position - StartPos; AStream.Position := StartPos; SetString(line, NIL, lineLength); AStream.ReadBuffer(line[1], lineLength); if ch = #13 then begin if (AStream.Read(ch, 1) = 1) and (ch <> ABreakLine) then AStream.Seek(-1, soCurrent) // unread it if not LF character. end finally FString := line; Result := Self; end; end; class function TStreamUtils.new(): IStreamUtils; begin Result := Self.Create; end; function TStreamUtils.toString: string; begin Result := FString; end; function TStreamUtils.textFilePosition(AStream: TFileStream; ANumeroLinha: Integer): IStreamUTils; var position: Integer; stream: TMemoryStream; character: Char; linhaAtual, startPos: Integer; begin try stream := TMemoryStream.Create(); stream.LoadFromStream(AStream); character := #0; startPos := stream.Position; linhaAtual := 2; position := 0; while stream.Position < stream.Size do begin while (stream.Read(character, 1) = 1) and (character <> #10) do ; if linhaAtual = ANumeroLinha then begin position := stream.Position; Break; end; inc(linhaAtual); end; finally FreeAndNil(stream); FInteger := position; Result := Self; end; end; function TStreamUtils.toInteger: Integer; begin Result := FInteger; end; end.
UNIT DoubleLinkedListUnit; INTERFACE type NodePtr = ^Node; Node = Record prev: NodePtr; val: integer; next: NodePtr; end; List = Record first, last: NodePtr; end; PROCEDURE InitList(var l: List); PROCEDURE Prepend(var l: List; n: NodePtr); PROCEDURE Append(var l: List; n: NodePtr); PROCEDURE DeleteAndDisposeNode(var l: List; x: integer); FUNCTION NewNode(x: integer): NodePtr; IMPLEMENTATION PROCEDURE InitList(var l: List); BEGIN l.first := NIL; l.last := NIL; END; FUNCTION IsEmpty(l: List): boolean; BEGIN IsEmpty := (l.first = NIL) AND (l.last = NIL); END; PROCEDURE Prepend(var l: List; n: NodePtr); BEGIN if IsEmpty(l) then begin l.first := n; l.last := n; end else begin n^.prev := NIL; n^.next := l.first; l.first^.prev := n; l.first := n; end; (* IF *) END; PROCEDURE Append(var l: List; n: NodePtr); BEGIN if IsEmpty(l) then begin l.first := n; l.last := n; end else begin n^.next := NIL; n^.prev := l.last; l.last^.next := n; l.last := n; end; END; PROCEDURE DeleteAndDisposeNode(var l: List; x: integer); var toDel: NodePtr; BEGIN if IsEmpty(l) then Exit; toDel := l.first; while (toDel <> NIL) AND (toDel^.val <> x) do toDel := toDel^.next; if toDel <> NIL then begin if toDel^.prev <> NIL then toDel^.prev^.next := toDel^.next else l.first := toDel^.next; if toDel^.next <> NIL then toDel^.next^.prev := toDel^.prev else l.last := toDel^.prev; Dispose(toDel); end; (* IF *) END; FUNCTION NewNode(x: integer): NodePtr; var n: NodePtr; BEGIN New(n); n^.prev := NIL; n^.val := x; n^.next := NIL; NewNode := n; END; BEGIN END.
unit ncaFrmSubject; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls, cxContainer, cxEdit, cxTextEdit, cxLabel, StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, LMDTypes, LMDBaseControl, LMDBaseGraphicControl, LMDGraphicControl, LMDHTMLLabel; type TFrmSubject = class(TForm) LMDSimplePanel3: TLMDSimplePanel; btnOk: TcxButton; btnCancelar: TcxButton; panEmail: TLMDSimplePanel; edAssunto: TcxTextEdit; cxLabel1: TcxLabel; lbBD: TLMDHTMLLabel; procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lbBDLinkClick(Sender: TObject; HRef: TLMDString); private { Private declarations } public { Public declarations } function Editar: Boolean; end; var FrmSubject: TFrmSubject; implementation uses ncaFrmPri, ncClassesBase, ncaDM, ncaFrmAposOrc; resourcestring rsInformarEmail = 'É necessário informar um endereço de e-mail'; rsInformarNome = 'É necessário informar um nome para aparecer no e-mail'; {$R *.dfm} procedure TFrmSubject.btnOkClick(Sender: TObject); begin ModalResult := mrOk; end; function TFrmSubject.Editar: Boolean; begin ShowModal; if (ModalResult=mrOk) and (gConfig.EmailOrc_Subject<>edAssunto.Text) then begin Result := True; gConfig.AtualizaCache; gConfig.EmailOrc_Subject := edAssunto.Text; Dados.CM.SalvaAlteracoesObj(gConfig, False); end else Result := False; end; procedure TFrmSubject.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmSubject.FormCreate(Sender: TObject); begin edAssunto.Text := gConfig.EmailOrc_Subject; if edAssunto.Text='' then edAssunto.Text := ncaFrmAposOrc.rsSubjectDef else if edAssunto.Text='blank' then edAssunto.Text := ''; btnOk.Enabled := Dados.CM.UA.Admin; end; procedure TFrmSubject.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_Esc : Close; end; end; procedure TFrmSubject.lbBDLinkClick(Sender: TObject; HRef: TLMDString); var C: Integer; begin with edAssunto do begin C := CursorPos; Text := Copy(Text, 1, C) + '['+HRef+']' + Copy(Text, C+1, 200); edAssunto.SelStart := C+Length(Text); edAssunto.SelLength := 0; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, //GLS GLCadencer, GLScene, GLObjects, GLParticles, GLWin32Viewer, GLColor, GLMultiProxy, GLTexture, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLVectorGeometry; type TForm1 = class(TForm) GLScene: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera: TGLCamera; DCTarget: TGLDummyCube; DCReferences: TGLDummyCube; GLLightSource1: TGLLightSource; GLParticles: TGLParticles; SPHighRes: TGLSphere; SPMedRes: TGLSphere; SPLowRes: TGLSphere; GLCadencer: TGLCadencer; Timer1: TTimer; MPSphere: TGLMultiProxy; Panel1: TPanel; RBUseLODs: TRadioButton; RBHighRes: TRadioButton; CBColorize: TCheckBox; RBLowRes: TRadioButton; LabelFPS: TLabel; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure MPSphereProgress(Sender: TObject; const deltaTime, newTime: Double); procedure RBUseLODsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i : Integer; begin // adjust settings to their default RBUseLODsClick(Self); // replicate the multiproxy via a TGLParticles object for i:=0 to 35 do GLParticles.CreateParticle.TagFloat:=DegToRad(i*10); end; procedure TForm1.MPSphereProgress(Sender: TObject; const deltaTime, newTime: Double); begin // this is invoked for each of our MultiProxys, it makes them loop an ellipse with (Sender as TGLBaseSceneObject) do begin Position.X:=Sin(newTime+TagFloat)*80-60; Position.Z:=Cos(newTime+TagFloat)*7; end; end; procedure TForm1.RBUseLODsClick(Sender: TObject); begin // adjust LOD on/off (by adjusting base sphere's detail) if RBUseLODs.Checked then begin SPHighRes.Slices:=32; SPHighRes.Stacks:=32; SPMedRes.Slices:=16; SPMedRes.Stacks:=16; SPLowRes.Slices:=8; SPLowRes.Stacks:=8; end else if RBHighRes.Checked then begin SPHighRes.Slices:=32; SPHighRes.Stacks:=32; SPMedRes.Slices:=32; SPMedRes.Stacks:=32; SPLowRes.Slices:=32; SPLowRes.Stacks:=32; end else if RBLowRes.Checked then begin SPHighRes.Slices:=8; SPHighRes.Stacks:=8; SPMedRes.Slices:=8; SPMedRes.Stacks:=8; SPLowRes.Slices:=8; SPLowRes.Stacks:=8; end; // colorize the LODs, to make them clearly visible CBColorize.Enabled:=RBUseLODs.Checked; if CBColorize.Checked and RBUseLODs.Checked then begin SPHighRes.Material.FrontProperties.Diffuse.Color:=clrRed; SPMedRes.Material.FrontProperties.Diffuse.Color:=clrBlue; SPLowRes.Material.FrontProperties.Diffuse.Color:=clrYellow; end else begin SPHighRes.Material.FrontProperties.Diffuse.Color:=clrGray80; SPMedRes.Material.FrontProperties.Diffuse.Color:=clrGray80; SPLowRes.Material.FrontProperties.Diffuse.Color:=clrGray80; end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin LabelFPS.Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
{*********************************************} { TeeChart Delphi Component Library } { Custom Legend Size and Position Demo } { Copyright (c) 1995-1996 by David Berneda } { All rights reserved } {*********************************************} unit Uylegend; interface { This form shows a customized Legend. The Chart.OnGetLegendRect and Chart.OnGetLegendPos events are used to change the default legend size and the default legend text positions. } uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Chart, Series, StdCtrls, Teengine, Buttons, TeeProcs; type TLegendXYForm = class(TForm) Chart1: TChart; PieSeries1: TPieSeries; Panel1: TPanel; RadioGroup1: TRadioGroup; BitBtn3: TBitBtn; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Chart1GetLegendRect(Sender: TCustomChart; var Rect: TRect); procedure Chart1GetLegendPos(Sender: TCustomChart; Index: Longint; var X, Y, XColor: Longint); procedure RadioGroup1Click(Sender: TObject); private { Private declarations } public { Public declarations } DefaultLegend:Boolean; end; var LegendXYForm: TLegendXYForm; implementation {$R *.DFM} procedure TLegendXYForm.FormCreate(Sender: TObject); begin DefaultLegend:=False; { <-- only used in this example } PieSeries1.FillSampleValues(10); { <-- some random pie sectors } end; procedure TLegendXYForm.Chart1GetLegendRect(Sender: TCustomChart; var Rect: TRect); begin if not DefaultLegend then { <-- if we want to customize legend... } Begin { This changes the Legend Rectangle dimensions } Rect.Bottom:=Rect.Top+PieSeries1.Count*15; { <-- Calc Legend Height } Rect.Left:=Rect.Left-120; { <-- Bigger Legend Width } end; end; procedure TLegendXYForm.Chart1GetLegendPos(Sender: TCustomChart; Index: Longint; var X, Y, XColor: Longint); begin if not DefaultLegend then Begin { Calculate the X Y coordinates for each Legend Text } x:=Chart1.Legend.RectLegend.Left; x:=x + (Index div (PieSeries1.Count div 2))*100; y:=Chart1.Legend.RectLegend.Top; y:=y + (Index mod (PieSeries1.Count div 2))*30; if (Index mod 2)=1 then X:=X+20; x:=x+20; XColor:=X-15; end; end; procedure TLegendXYForm.RadioGroup1Click(Sender: TObject); begin { Get the RadioGroup selection and force the chart to repaint } DefaultLegend:=RadioGroup1.ItemIndex=0; Chart1.Repaint; end; end.
unit Model.Entity.Book; interface uses SysUtils; type TBook = class private FID: Integer; FBookName: String; FBookLink: String; FCategoryID: Integer; public property ID: Integer read FID write FID; property BookName: string read FBookName write FBookName; property BookLink: string read FBookLink write FBookLink; property CategoryID: Integer read FCategoryID write FCategoryID; public constructor Create(ABookName: string; ACategoryID: Integer); overload; constructor Create(ABookName: string; ABookLink: string; ACategoryID: Integer); overload; end; implementation { TBook } constructor TBook.Create(ABookName: string; ACategoryID: Integer); begin FBookName := ABookName; FCategoryID := ACategoryID; end; constructor TBook.Create(ABookName, ABookLink: string; ACategoryID: Integer); begin FBookName := ABookName; FBookLink := ABookLink; FCategoryID := ACategoryID; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.EMSConsts; interface resourcestring sFormatEMSError = 'EMS Error: %0:s'; sFormatEMSErrorDescription = 'EMS Error: %0:s. %1:s'; sJSONObjectRequired = 'JSON object required'; sJSONObjectExpected = 'JSON object expected'; sJSONArrayExpected = 'JSON array expected'; sOneUserExpected = 'One user expected'; sOneModuleExpected = 'One module expected'; sUserIDRequired = 'User ID required'; sInstallationIDRequired = 'Installation ID required'; sAuthTokenRequired = 'AuthToken required'; sAppKeyRequired = 'AppKey required'; sAppSecretRequired = 'AppSecret required'; sMasterSecretRequired = 'MasterSecret required'; sUserNameRequired = 'Username required'; sSessionTokenExpected = 'Session token expected'; sGroupNameRequired = 'Group name required'; sChannelNamesExpected = 'Channel names expected'; sDeviceNamesExpected = 'Device names expected'; sMasterKeyRequired = 'MasterKey required'; sBackendCollectionNameRequired = 'BackendCollectionName required'; sSessionIDRequired = 'Session token required'; sAPIKeyRequired = 'APIKey required'; sGroupNotFound = 'Group not found: %s'; sUnsupportedProtocol = 'Unsupported protocol'; sModuleIDRequired = 'Module ID required'; sResourceNameRequired = 'Resource name required'; sURLHostNotBlank = 'URLHost must not be blank'; sURLProtocolNotBlank = 'URLProtocol must not be blank'; implementation end.
unit apiplatforms; {$mode objfpc}{$M+} {$H+} interface uses Classes, SysUtils, Dialogs, Forms, {$IFDEF Windows} Windows, JwaWinUser, JwaTlHelp32, Registry, sqlite3, sqlite3db, {$endif} {$IFDEF unix} sqlite3, sqlite3db, {$endif} {$IFDEF Darwin} {$ifdef ver2_2_0} FPCMacOSAll, {$else} MacOSAll, {$ENDIF} {$ENDIF} configuration, utils, md5, otlog, rules; type TAPIDBR = array of TStringList; TOTSQL = Class private CFG: TOTConfig; public Records: TAPIDBR; constructor Create(mCFG: TOTConfig); function ExecSQL(query: string): boolean; function RecordsSQL(query: string): TAPIDBR; end; TPlatform = Class public constructor Create(mCFG: TOTConfig; lLog: TOTLog; mRules: TList); virtual; abstract; function WindowProcessPassFilters: boolean; virtual; abstract; function SQLExec(query: string): boolean; function SQLRecords(query: string): TAPIDBR; Log: TOTLog; Rules: TList; private CFG: TOTConfig; dbWPId, iteration: integer; {id in db for: window and process register} TimeStart: integer; protected function GetSecondsIdle: integer; virtual; abstract; procedure SetNewWindow; virtual; abstract; procedure SetNewProcess; virtual; abstract; function ChangedWindowProcess:boolean; virtual; abstract; procedure FinishCurrentWindowProcess; virtual; abstract; procedure UpdateCurrentWindowProcess; virtual; abstract; procedure SaveNewWindowProcess; virtual; abstract; procedure RunStartUp(enable: boolean); virtual; abstract; procedure OpenBrowser(url: string); virtual; abstract; function CheckFilters(StrFilters: string; Name: string): boolean; procedure SaveTrack(WName,PName: string); procedure FinishTrack(WName,PName: string); procedure UpdateTrack; function PassFilters(WName,PName: string): boolean; end; {$IFDEF Windows} TWindowsPlatform = Class(TPlatform) private CurrentHWND: HWND; NewHWND: HWND; PID : dword; WindowTitle: array[0..255] of char; ProcessName: array[0..259] of char; RegExprChars: tstringlist; public constructor Create(mCFG: TOTConfig; lLog: TOTLog; mRules: TList); override; function WindowProcessPassFilters: boolean; override; function GetSecondsIdle: integer; override; procedure SetNewWindow; override; procedure SetNewProcess; override; function ChangedWindowProcess: boolean; override; procedure FinishCurrentWindowProcess; override; procedure UpdateCurrentWindowProcess; override; procedure SaveNewWindowProcess; override; procedure RunStartUp(enable: boolean); override; procedure OpenBrowser(url: string); override; end; {$endif} {$IFDEF unix} TUnixPlatform = Class(TPlatform) private CurrentWId: string; NewWId: string; CurrentWindowTitle: array[0..255] of char; CurrentProcessName: array[0..259] of char; NewWindowTitle: array[0..255] of char; NewProcessName: array[0..259] of char; RegExprChars: tstringlist; public constructor Create(mCFG: TOTConfig; lLog: TOTLog; mRules: TList); override; function WindowProcessPassFilters: boolean; override; function GetSecondsIdle: integer; override; procedure SetNewWindow; override; procedure SetNewProcess; override; function ChangedWindowProcess: boolean; override; procedure FinishCurrentWindowProcess; override; procedure UpdateCurrentWindowProcess; override; procedure SaveNewWindowProcess; override; procedure RunStartUp(enable: boolean); override; end; {$endif} function SQLCallback(Sender:pointer; plArgc:longint; argv:PPchar; argcol:PPchar):longint; cdecl; implementation function TPlatform.PassFilters(WName,PName: string): boolean; var AuxResult: boolean; TmpResult: boolean; begin WName := lowercase(trim(WName)); PName := lowercase(trim(PName)); IF strtobool(CFG.Get('PositiveFilters')) THEN BEGIN AuxResult := FALSE; IF Length(CFG.Get('FilterTrackWindows')) > 0 THEN BEGIN AuxResult := CheckFilters(CFG.Get('FilterTrackWindows'), WName); IF auxresult THEN log.add('Positive windows filters result for '+WName+':'+booltostr(auxresult,true)); END; IF Length(CFG.Get('FilterTrackProcesses')) > 0 THEN BEGIN TmpResult := CheckFilters(CFG.Get('FilterTrackProcesses'), PName); IF TmpResult then log.add('Positive process names filters result for '+PName+':'+booltostr(TmpResult,true)); AuxResult := AuxResult OR TmpResult; END END ELSE IF strtobool(CFG.Get('NegativeFilters')) THEN BEGIN IF Length(CFG.Get('FilterNoTrackWindows')) > 0 THEN BEGIN AuxResult := NOT CheckFilters(CFG.Get('FilterNoTrackWindows'), WName); IF NOT AuxResult THEN log.add('Negative windows filters result for '+WName+':'+booltostr(NOT auxresult,true)); END; IF Length(CFG.Get('FilterNoTrackProcesses')) > 0 THEN BEGIN TmpResult := NOT CheckFilters(CFG.Get('FilterNoTrackProcesses'), PName); IF NOT TmpResult THEN log.add('Negative process names filters result for '+PName+':'+booltostr(NOT TmpResult,true)); AuxResult := AuxResult AND TmpResult; END END; result := AuxResult; end; procedure TPlatform.UpdateTrack; begin {Updates each N seconds - performance issue} IF (iteration MOD strtoint(CFG.Get('UpdateFrequency'))) = 0 THEN BEGIN iteration := 0; self.SQLExec('UPDATE wp_track SET timeend = "'+IntToStr(UnixTime())+'", dtimeend = "'+FormatDateTime('yyyy-mm-dd hh:nn:ss', Now)+'", seconds = '+IntToStr(UnixTime())+' - timestart WHERE id = '+IntToStr(dbWPId)); END; iteration := iteration + 1; end; procedure TPlatform.FinishTrack(WName,PName: string); var idt, i: integer; rule: TRule; StopRule: boolean; begin IF UnixTime() - TimeStart >= strtoint(CFG.Get('MinTrackingSeconds')) THEN BEGIN idt := 0; StopRule := false; If Rules.Count > 0 THEN FOR i := 0 TO Rules.Count - 1 DO BEGIN IF NOT StopRule THEN BEGIN rule := TRule(Rules.Items[i]); idt := rule.Check(WName,PName); IF idt <> 0 THEN StopRule := TRUE; END; END; self.SQLExec('UPDATE wp_track SET idt = "'+IntToStr(idt)+'", timeend = "'+IntToStr(UnixTime())+'", dtimeend = "'+FormatDateTime('yyyy-mm-dd hh:nn:ss', Now)+'", seconds = '+IntToStr(UnixTime())+' - timestart WHERE id = '+IntToStr(dbWPId)); Log.add('Current Window Process finished'); END ELSE BEGIN self.SQLExec('DELETE FROM wp_track WHERE id = '+IntToStr(dbWPId)); Log.add('Current Window Process discard: Min tracking seconds: '+CFG.Get('MinTrackingSeconds')); END; end; procedure TPlatform.SaveTrack(WName,PName: string); var idw, idp, wpid: integer; records: TAPIDBR; rt: tstringlist; logstr: string; begin Log.Add('Saving ... '+WName+' '+PName); IF NOT strtobool(CFG.Get('NoSaveWindows')) THEN BEGIN self.SQLExec('INSERT INTO windows (title, md5) VALUES ("'+WName+'", "'+MD5Print(md5.MD5String(WName))+'")'); { Get the window id in the db } records := self.SQLRecords('SELECT id FROM windows WHERE md5 = "'+MD5Print(md5.MD5String(WName))+'"'); IF Length(records) > 0 THEN BEGIN rt := tstringlist(records[0]); idw := strtoint(rt.Values['id']); END ELSE BEGIN idw := 0; END; END; IF NOT strtobool(CFG.Get('NoSaveProcess')) THEN BEGIN self.SQLExec('INSERT INTO processes (name, md5) VALUES ("'+PName+'", "'+MD5Print(md5.MD5String(PName))+'")'); { Get the process id in the db } records := self.SQLRecords('SELECT id FROM processes WHERE md5 = "'+MD5Print(md5.MD5String(PName))+'"'); IF Length(records) > 0 THEN BEGIN rt := tstringlist(records[0]); idp := strtoint(rt.Values['id']); END ELSE BEGIN idp := 0; END; END; IF (idw > 0) OR (idp > 0) THEN BEGIN records := self.SQLRecords('SELECT COUNT(id) as total, MAX(id) as maxvalue FROM wp_track'); rt := tstringlist(records[0]); IF strtoint(rt.Values['total']) = 0 THEN BEGIN wpid := 1; END ELSE BEGIN wpid := strtoint(rt.Values['total']) + 1; END; TimeStart := UnixTime(); self.SQLExec('INSERT INTO wp_track (id,idw,idp,timestart,timeend, dtimestart, dtimeend, seconds) VALUES ("'+Inttostr(wpid)+'", "'+IntToStr(idw)+'", "'+IntToStr(idp)+'", "'+IntToStr(TimeStart)+'", "0", "'+FormatDateTime('yyyy-mm-dd hh:nn:ss',Now)+'", "0", "0")'); logstr:='New Window Process started: '; IF NOT strtobool(CFG.Get('NoSaveWindows')) THEN logstr := logstr+' '+WName; IF NOT strtobool(CFG.Get('NoSaveProcess')) THEN logstr := logstr+' '+PName; Log.Add(logstr); dbWPId := wpid; END end; function TPlatform.CheckFilters(StrFilters: string; Name: string):boolean; var AuxResult, TmpResult: boolean; Filters: TStringList; currentFilter: string; i: integer; begin Filters := TStringList.Create; Split(',',StrFilters,Filters); AuxResult := FALSE; TmpResult := FALSE; IF Filters.Count > 0 THEN BEGIN FOR i:= 0 TO Filters.Count -1 DO BEGIN currentFilter := ''; currentFilter := lowercase(Filters.Strings[i]); IF Pos('*',currentFilter) > 0 THEN BEGIN IF (Pos('*',currentFilter) = 1) AND (LastDelimiter('*',currentFilter) = Length(currentFilter)) THEN BEGIN IF Pos(StringReplace(currentFilter,'*','',[rfReplaceAll, rfIgnoreCase]),Name) > 0 THEN begin log.add('Filter match '+currentfilter+' - '+Name); TmpResult := TRUE; end END ELSE IF (Pos('*',currentFilter) = 1) THEN BEGIN IF Pos(StringReplace(currentFilter,'*','',[rfReplaceAll, rfIgnoreCase]),Name) = (Length(Name) - Length(currentFilter)) + 2 THEN begin log.add('Filter match '+currentfilter+' - '+Name); TmpResult := TRUE; end END; IF (Pos('*',currentFilter) = Length(currentFilter)) THEN BEGIN IF Pos(StringReplace(currentFilter,'*','',[rfReplaceAll, rfIgnoreCase]),Name) = 1 THEN begin log.add('Filter match '+currentfilter+' - '+Name); TmpResult := TRUE; end END END ELSE BEGIN IF CompareText(StringReplace(currentFilter,'*','',[rfReplaceAll, rfIgnoreCase]),Name) = 0 THEN begin log.add('Filter match '+currentfilter+' - '+Name); TmpResult := TRUE; end END; END; AuxResult := TmpResult; END; Filters.Free; result := AuxResult; end; function TPlatform.SQLExec(query: string): boolean; var msql: TOTSQL; begin msql := TOTSQL.Create(self.CFG); result := msql.ExecSQL(query); end; function TPlatform.SQLRecords(query: string): TAPIDBR; var msql: TOTSQL; begin msql := TOTSQL.Create(self.CFG); result := msql.RecordsSQL(query); end; function SQLCallback(Sender:pointer; plArgc:longint; argv:PPchar; argcol:PPchar):longint; cdecl; var i: Integer; PVal, PName: ^PChar; rt: TStringList; begin with TObject(Sender) as TOTSQL do begin SetLength(Records, Length(Records) + 1); rt := TStringList.Create; PVal:=argv; PName:=argcol; for i:=0 to plArgc-1 do begin rt.values[StrPas(PName^)] := StrPas(PVal^); inc(PVal); inc(PName); end; Records[Length(Records) - 1] := rt; Result:=0; end end; {$IFDEF Windows} {Implementation of TWindowsPlatform} constructor TWindowsPlatform.Create(mCFG: TOTConfig; lLog: TOTLog; mRules: TList); begin self.CFG := mCFG; CurrentHWND := 0; NewHWND := 0; dbWPId := 0; iteration := 0; Log := lLog; self.Rules := mRules; RegExprChars := TSTringList.create; Split(',','^,$,.,|,(,),[,],+,*,?,{,}',RegExprChars); end; function TWindowsPlatform.WindowProcessPassFilters: boolean; var REWindowTitle: array[0..255] of char; REProcessName: array[0..259] of char; Snap: Integer; PData :TProcessEntry32; begin GetWindowText(NewHWND, REWindowTitle, 255); Snap:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); try PData.dwSize:=SizeOf(PData); if(Process32First(Snap,PData))then begin repeat if PData.th32ProcessID=PID then begin REProcessName := PData.szExeFile; Break; end; until not(Process32Next(Snap,PData)); end; finally Windows.CloseHandle(Snap); end; result := PassFilters(PStr(REWindowTitle),PStr(REProcessName)); end; function TWindowsPlatform.GetSecondsIdle: integer; var liInfo: TLastInputInfo; begin liInfo.cbSize := SizeOf(TLastInputInfo) ; GetLastInputInfo(liInfo) ; Result := (GetTickCount - liInfo.dwTime) DIV 1000; end; procedure TWindowsPlatform.SetNewWindow; begin NewHWND := GetForegroundWindow; end; procedure TWindowsPlatform.SetNewProcess; begin windows.GetWindowThreadProcessId(NewHWND,PID); end; function TWindowsPlatform.ChangedWindowProcess: boolean; var REWindowTitle: array[0..255] of char; begin IF NewHWND <> CurrentHWND THEN BEGIN result := TRUE; END ELSE BEGIN GetWindowText(NewHWND, REWindowTitle, 255); result := REWindowTitle <> WindowTitle; END end; procedure TWindowsPlatform.FinishCurrentWindowProcess; begin IF CurrentHWND > 0 THEN BEGIN FinishTrack(PStr(WindowTitle),PStr(ProcessName)); CurrentHWND := 0; dbWPId := 0; TimeStart := 0; WindowTitle := ''; ProcessName := ''; END end; procedure TWindowsPlatform.UpdateCurrentWindowProcess; begin UpdateTrack; end; procedure TWindowsPlatform.SaveNewWindowProcess; var Snap: Integer; PData :TProcessEntry32; begin CurrentHWND := NewHWND; GetWindowText(NewHWND, WindowTitle, 255); Snap:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); try PData.dwSize:=SizeOf(PData); if(Process32First(Snap,PData))then begin repeat if PData.th32ProcessID=PID then begin ProcessName := PData.szExeFile; Break; end; until not(Process32Next(Snap,PData)); end; finally Windows.CloseHandle(Snap); end; SaveTrack(Pstr(WindowTitle),PStr(ProcessName)); end; procedure TWindowsPlatform.RunStartUp(enable: boolean); var Registry: TRegistry; Key: string; Values: TStringList; n: integer; RegInfo : TRegDataInfo; begin Key:='Software\Microsoft\Windows\CurrentVersion\Run'; Registry:=TRegistry.Create; IF enable THEN BEGIN try Registry.OpenKey(Key,FALSE); Registry.WriteString('opentempus',Application.EXEName); finally Registry.Free; end END ELSE BEGIN try if Registry.OpenKey(key,FALSE) then begin Values:=TStringList.Create; try Registry.GetValueNames(Values); for n:=0 to Pred(Values.Count) do begin If Registry.GetDataInfo( Values[n], RegInfo) then begin if (RegInfo.RegData = rdString) then begin if Lowercase(Application.ExeName) = LowerCase(Registry.ReadString(Values[n])) then begin Registry.DeleteValue( Values[n] ); end; end; end; end; finally Values.Free; end; end; finally Registry.Free; end; END end; procedure TWindowsPlatform.OpenBrowser(url: string); begin ShellExecute(application.mainform.Handle,nil,PChar(url),'','',SW_SHOWNORMAL); end; {$endif} {Implementation of TUnixPlatform} {$IFDEF unix} constructor TUnixPlatform.Create(mCFG: TOTConfig; lLog: TOTLog; mRules: TList); begin self.CFG := mCFG; CurrentWId := ''; NewWId := ''; CurrentWindowTitle := ''; CurrentProcessName := ''; NewWindowTitle := ''; NewProcessName := ''; iteration := 0; Log := lLog; self.Rules := mRules; RegExprChars := TSTringList.create; Split(',','^,$,.,|,(,),[,],+,*,?,{,}',RegExprChars); end; function TUnixPlatform.WindowProcessPassFilters: boolean; begin result := PassFilters(NewWindowTitle,NewProcessName); end; function TUnixPlatform.GetSecondsIdle: integer; begin result := 0; end; procedure TUnixPlatform.SetNewWindow; begin NewWId := ''; NewWindowTitle := ''; NewProcessName := ''; //Call to script sh end; procedure TUnixPlatform.SetNewProcess; begin NewProcessName := NewProcessName; end; function TUnixPlatform.ChangedWindowProcess: boolean; begin IF NewWId <> CurrentWId THEN BEGIN result := TRUE; END ELSE BEGIN result := NewWindowTitle <> CurrentWindowTitle; END end; procedure TUnixPlatform.FinishCurrentWindowProcess; begin IF CurrentWId <> '' THEN BEGIN FinishTrack(CurrentWindowTitle,CurrentProcessName); CurrentWId := ''; dbWPId := 0; TimeStart := 0; CurrentWindowTitle := ''; CurrentProcessName := ''; END end; procedure TUnixPlatform.UpdateCurrentWindowProcess; begin UpdateTrack; end; procedure TUnixPlatform.SaveNewWindowProcess; begin CurrentWId := NewWId; CurrentWindowTitle := NewWindowTitle; CurrentProcessName := NewProcessName; SaveTrack(CurrentWindowTitle,CurrentProcessName); end; procedure TUnixPlatform.RunStartUp(enable: boolean); begin end; {$endif} constructor TOTSQL.Create(mCFG: TOTConfig); begin self.CFG := mCFG; end; function TOTSQL.ExecSQL(query: string): boolean; var rcc,rcq : Integer; sdb : PPsqlite3; pzErrMsg : PChar; rtmp: boolean; // SL: TSQLite; begin rcc := sqlite3_open(PChar(CFG.DBPath), @sdb); rtmp := TRUE; try if rcc = SQLITE_OK then begin rcq := sqlite3_exec(sdb, PChar(query), nil, nil, @pzErrMsg); if rcq <> SQLITE_OK then begin //Log.Add(pzErrMsg+' '+query); rtmp := FALSE end end else begin rtmp:= false; //Log.Add(pzErrMsg+' '+query); end finally sqlite3_close(sdb); end; result := rtmp; end; function TOTSQL.RecordsSQL(query: string): TAPIDBR; var rc : Integer; sdb : PPsqlite3; pzErrMsg : PChar; begin rc := sqlite3_open(PChar(CFG.DBPath), @sdb); try if rc = SQLITE_OK then begin SetLength(Records,0); rc := sqlite3_exec(sdb, PChar(query), @SQLCallback, Self, @pzErrMsg); if rc <> SQLITE_OK then begin //Log.Add(pzErrMsg+' '+query); end end else begin //Log.Add(pzErrMsg+' '+query); end finally sqlite3_close(sdb); end; result := Records; end; end.
unit UProdutoOS; interface uses UProduto; type ProdutoOS = class(Produto) protected largura : Real; altura : Real; valorUnitario : Real; quantidade : Real; desconto : Real; TotalProdAux : Real; public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setLargura (vLargura : Real); Procedure setAltura (vAltura : Real); Procedure setValorUnitario (vValorUnitario : Real); Procedure setQtdProduto (vQuantidade : Real); Procedure setDesconto (vDesconto : Real); Procedure setTotalProdAux (vTotalProdAux : Real); Function getLargura : Real; Function getAltura : Real; Function getValorUnitario : Real; Function getQtdProduto : Real; Function getDesconto : Real; Function getTotalProdAux : Real; end; implementation { ProdutoOS } constructor ProdutoOS.CrieObjeto; begin inherited; largura := 0; altura := 0; valorUnitario := 0; quantidade := 0; desconto := 0; TotalProdAux := 0; end; destructor ProdutoOS.Destrua_Se; begin end; function ProdutoOS.getAltura: Real; begin Result := altura; end; function ProdutoOS.getDesconto: Real; begin Result := desconto; end; function ProdutoOS.getLargura: Real; begin Result := largura; end; function ProdutoOS.getQtdProduto: Real; begin Result := quantidade; end; function ProdutoOS.getTotalProdAux: Real; begin Result := TotalProdAux; end; function ProdutoOS.getValorUnitario: Real; begin Result := valorUnitario; end; procedure ProdutoOS.setAltura(vAltura: Real); begin altura := vAltura; end; procedure ProdutoOS.setDesconto(vDesconto: Real); begin desconto := vDesconto; end; procedure ProdutoOS.setLargura(vLargura: Real); begin largura := vLargura; end; procedure ProdutoOS.setQtdProduto(vQuantidade: Real); begin quantidade := vQuantidade; end; procedure ProdutoOS.setTotalProdAux(vTotalProdAux: Real); begin TotalProdAux := vTotalProdAux; end; procedure ProdutoOS.setValorUnitario(vValorUnitario: Real); begin valorUnitario := vValorUnitario; end; end.
{ Sort edges of a planar graph Quick Sort O(E.LgN) Input: N: Number of vertices G[I]: List of vertices adjacent to I D[I]: Degree of vertex I P[I]: Position of Vertex P Output: G[I]: List of vertices adjacent to I in counter-clockwise order Notes: G should be planar with representation P By Ali } program Faces; type Point = record x, y: Integer; end; const MaxN = 100 + 1; var N: Integer; G: array [1 .. MaxN, 0 .. MaxN] of Integer; D: array [1 .. MaxN] of Integer; P: array [1 .. MaxN] of Point; Tab: Array[1..MaxN] of Extended; Pair: Array[1..MaxN] of Integer; function Comp(a, b: Extended): Integer; begin if abs(a - b) < 1e-8 then Comp := 0 else if a > b then Comp := 1 else Comp := -1; end; function Angle(P, Q: Point): Extended; var a: Extended; begin Q.x := Q.x - P.x; Q.y := Q.y - P.y; if Comp(Q.x, 0) = 0 then if Q.y > 0 then Angle := Pi / 2 else Angle := 3 * Pi / 2 else begin a := ArcTan(Q.y / Q.x); if Q.x < 0 then a := a + Pi; if a < 0 then a := a + 2 * Pi; Angle := a; end; end; procedure Swap(var a, b: Integer); var c: Integer; begin c := a; a := b; b := c; end; procedure Sort(l, r: Integer); var i, j: integer; x, y: Extended; begin i := l; j := r; x := Tab[(l+r) DIV 2]; repeat while Tab[i] < x do i := i + 1; while x < Tab[j] do j := j - 1; if i <= j then begin y := Tab[i]; Tab[i] := Tab[j]; Tab[j] := y; Swap(Pair[i], Pair[j]); i := i + 1; j := j - 1; end; until i > j; if l < j then Sort(l, j); if i < r then Sort(i, r); end; procedure SortEdges; var i, j: Integer; begin for i := 1 to N do begin for j := 1 to D[i] do begin Pair[j] := G[i, j]; Tab[j] := Angle(P[i], P[Pair[j]]); end; if D[i] > 1 then Sort(1, D[i]); for j := 1 to D[i] do G[i, j] := Pair[j]; end; end; begin SortEdges; end.
unit uSession; interface uses Redis.Client, REST.Json, uRedisConfig; type TSession = class private Fempresa: Integer; public property empresa: Integer read Fempresa write Fempresa; end; TSessionManager = class public class function GetInstance(Auth: string): TSession; end; implementation uses Redis.Values; { TSessionManager } class function TSessionManager.GetInstance(Auth: string): TSession; var ARedis: TRedisClient; ARedisConfig: TRedisConfig; AValue: TRedisString; begin Result := nil; ARedisConfig := TRedisConfig.Create; try ARedis := TRedisClient.Create(ARedisConfig.Host, ARedisConfig.Port); try ARedis.Connect; AValue := ARedis.GET(Auth); if not AValue.IsNull then begin Result := TJson.JsonToObject<TSession>(AValue.Value); end; finally ARedis.Free; end; finally ARedisConfig.Free; end; end; end.
unit uConsultaCNPJ; interface uses uPessoa, U_Principal, Controls; type IConsultaCNPJ = Interface(IInterface) ['{F91C0F7B-47C1-4A48-B7FA-55281E049439}'] function CNPJ(const Value: String): IConsultaCNPJ; overload; function CNPJ: string; overload; function Consulta : TPessoa; End; TConsultaCNPJ = class(TInterfacedObject, IConsultaCNPJ) strict private FCNPJ : String; public class function New: IConsultaCNPJ; function CNPJ(const Value: string): IConsultaCNPJ; overload; function CNPJ: string; overload; function Consulta : TPessoa; end; implementation uses System.SysUtils; { TConsultaCNPJ } var Pessoa: TPessoa; function TConsultaCNPJ.CNPJ(const Value: string): IConsultaCNPJ; begin Result := Self; FCNPJ := Value; end; function TConsultaCNPJ.CNPJ: string; begin Result := FCNPJ; end; function TConsultaCNPJ.Consulta: TPessoa; var u_Principal : TF_Principal; begin u_Principal := TF_Principal.Create(nil); try u_Principal.EditCNPJ.Text := FCNPJ; u_Principal.ShowModal; if u_Principal.ModalResult = mrOk then begin with u_Principal do begin Pessoa.RazaoSocial := ACBrConsultaCNPJ1.RazaoSocial; Pessoa.Endereco := ACBrConsultaCNPJ1.Endereco; Pessoa.Cidade := ACBrConsultaCNPJ1.Cidade; Pessoa.UF := ACBrConsultaCNPJ1.UF; Pessoa.Bairro := ACBrConsultaCNPJ1.Bairro; Pessoa.CEP := ACBrConsultaCNPJ1.CEP; Pessoa.Numero := ACBrConsultaCNPJ1.Numero; Pessoa.Fantasia := ACBrConsultaCNPJ1.Fantasia; Pessoa.CNPJ := ACBrConsultaCNPJ1.CNPJ; Pessoa.Telefone := ACBrConsultaCNPJ1.Telefone; if Pessoa.Telefone <> EmptyStr then begin Pessoa.Telefone := StringReplace(Pessoa.Telefone,'(','', [rfReplaceAll]); Pessoa.Telefone := StringReplace(Pessoa.Telefone,')','', [rfReplaceAll]); Pessoa.Telefone := StringReplace(Pessoa.Telefone,'-','', [rfReplaceAll]); Pessoa.Telefone := StringReplace(Pessoa.Telefone,' ','', [rfReplaceAll]); end; end; end; Result := Pessoa; finally u_Principal.Free; end; end; class function TConsultaCNPJ.New: IConsultaCNPJ; begin Result := Self.Create; Pessoa := TPessoa.create; end; end.
{ ***************************************************************************** This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. A copy of this licence is found in the root directory of this project in the file LICENCE.txt or alternatively at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: Renate Schaaf (original code and extensions) Markus Humm (made it compile and run under Android) HuichanKIM (routine for faster adding of bitmaps) ***************************************************************************** } unit UBitmaps2VideoM; interface uses System.SysUtils, FFMPEG, FMX.Graphics, System.types, UFormatsM, System.Classes, UToolsM; type /// <summary> Libav-Scaling used if bitmapsize<>videosize </summary> TVideoScaling = (vsFastBilinear, vsBilinear, vsBiCubic, vsLanczos); /// <summary> Zoom algorithms, the higher the better and slower not yet implemented /// zoAAx2: Antialising factor 2 /// zoAAx4: Antialising factor 4 /// zoAAx6: Antialising factor 6 /// zoResample: "Bicubic" resampling, almost perfect but slow.</summary> TZoomOption = (zoAAx2, zoAAx4, zoAAx6, zoResample); const ScaleFunction: array [TVideoScaling] of integer = (SWS_FAST_BILINEAR, SWS_BILINEAR, SWS_BICUBIC, SWS_LANCZOS); FilterName: array [TVideoScaling] of string = ('Fast Bilinear', 'Bilinear', 'Bicubic', 'Lanczos'); type TVideoProgressEvent = procedure(Videotime: int64) of object; // Compatible with windows TRGBTriple TBGR = record Blue: Byte; Green: Byte; Red: Byte; end; PBGR = ^TBGR; TBitmapEncoderM = class private fWidth, fHeight, fRate: integer; fQuality: Byte; fFilename: string; fFrameCount: integer; fVideoTime: int64; fVideoScaling: TVideoScaling; fCodecId: TAVCodecId; fInputVideoTimebase: TAVRational; fVideoFrameCount: integer; fVideoFrameStart: integer; fBackground: Byte; fRGB_pix_fmt: TAVPixelFormat; VideoPts, VideoDts: int64; fmt: PAVOutputFormat; oc: PAVFormatContext; stream: PAVStream; codec: PAVCodec; c: PAVCodecContext; yuvpic: PAVFrame; pkt: PAVPacket; CodecSetup: TBaseCodecSetup; fOnProgress: TVideoProgressEvent; function encode(frame: PAVFrame; FromVideo: boolean): boolean; procedure BitmapToFrame(const bm: TBitmap); procedure ColorToFrame(Color: TBGR); procedure BitmapToRGBFrame(const bm: TBitmap; const rgbFrame: PAVFrame); procedure ExpandToAspectRatio(const FrameSrc, FrameDst: PAVFrame; AR: TAVRational; Background: Byte); procedure ExpandToVideoSize(const FrameSrc, FrameDst: PAVFrame); procedure RGBFrameToFrame(const aFrame: PAVFrame); procedure Alphablend(fSrc1, fSrc2, fDst: PAVFrame; alpha: Byte); procedure ZoomDeleteScans(const Src, Dest: PAVFrame; rs: TRectF); procedure ZoomResampleTripleOnly(const Source, Target: PAVFrame; SourceRect: TRectF; Radius: single); public DroppedFrames: integer; /// <param name="filename"> Output filename. Extension picks the container format (.mp4 .avi .mkv ..) /// </param> /// <param name="Width"> Video size in pixels (multiples of 2)</param> /// <param name="Height"> Video size in pixels (multiples of 2)</param> /// <param name="FrameRate"> Frames per second (can be slightly off in the resulting file)</param> /// <param name="Quality"> Encoding quality, scale from 0 to 100. 0 gives marginally acceptable quality </param> /// <param name="CodecId"> (TAVCodecID see UFormats.pas) Identifier of the codec to use. AV_CODEC_ID_NONE picks the default codec for the file extension. </param> /// <param name="VideoScaling">Resample algo used if video size differs from bitmap size </param> constructor Create(const filename: string; Width, Height: integer; FrameRate: integer; Quality: Byte; CodecId: TAVCodecId = AV_CODEC_ID_NONE; VideoScaling: TVideoScaling = vsFastBilinear; Background: Byte = 0); /// <summary> Turn a Bitmap into a movie frame. If its aspect ratio does not match the /// one of the movie, a grayscale background will be added (see Background in Create)</summary> /// <param name="bm"> Bitmap(TBitmap) to be fed to the video. </param> procedure AddFrame(const bm: TBitmap); /// <summary>Add a uniformly colored Frame to the Video</summary> procedure AddColorFrame(Color: TBGR); /// <summary> Hold the last frame </summary> /// <param name="EffectTime"> Displaytime(integer) in ms </param> procedure Freeze(EffectTime: integer); /// <summary> Add a picture which is displayed for a certain time </summary> /// <param name="bm"> Bitmap(TBitmap) of the picture to be displayed </param> /// <param name="ShowTime"> Time(integer) in ms for the display </param> procedure AddStillImage(const bm: TBitmap; ShowTime: integer); /// <summary> Add an existing video to the video stream. It will be resized and reencoded with the current settings. /// The format of the video can be anything that VLC-player plays. /// If its aspect ratio does not match the /// one of the movie, a grayscale background will be added (see Background in Create)</summary> procedure AddVideo(const VideoInput: string); /// <summary> Make a smooth transition between 2 zoom rects within EffectTime.</summary> /// <param name="bm"> The Bitmap(TBitmap) to be animated </param> /// <param name="zSrc"> Beginning zoom into rect(0,0,bm.width,bm.height) (see TZoom) </param> /// <param name="zDst"> End zoom into rect(0,0,bm.width,bm.height) </param> /// <param name="EffectTime"> Duration(integer) of the animation in ms </param> /// <param name="ZoomOption"> Quality of the zoom (zoAAx2, zoAAx4, zoAAx6, zoResample). </param> /// <param name="SpeedEnvelope"> Modifies the speed during EffectTime. (zeFastSlow, zeSlowFast, zeSlowSlow, zeLinear) </param> procedure ZoomPan(const bm: TBitmap; zSrc, zDst: TZoom; EffectTime: integer; ZoomOption: TZoomOption; SpeedEnvelope: TZoomSpeedEnvelope = zeLinear); procedure CrossFade(const am, bm: TBitmap; EffectTime: integer); /// <summary> Close the file and make the output file usable. </summary> function CloseFile: boolean; destructor Destroy; override; /// <summary> how many frames have been added to the movie so far </summary> property FrameCount: integer read fFrameCount; /// <summary> Videotime so far in ms, more accurate if the frame rate varies slightly </summary> property Videotime: int64 read fVideoTime; /// <summary> Frame count of the last video clip added, use for grabbing thumbnails or timing </summary> property LastVideoFrameCount: integer read fVideoFrameCount; /// <summary> Event which fires every second of video time while writing. Use it to update a progressbar etc.. </summary> property OnProgress: TVideoProgressEvent read fOnProgress write fOnProgress; end; /// <summary> Estimates the size of the output video in MB for the given settings </summary> function VideoSizeInMB(Videotime: int64; CodecId: TAVCodecId; Width, Height, Rate: integer; Quality: Byte): double; /// <summary> Combine the 1st video stream from VideoFile with 1st audio stream from Audiofile. The streams will just be copied, not encoded. /// Audio is clipped to video length. Raises exception if the format of the audio file is not supported.</summary> /// <param name="VideoFile"> (string) File which contains a video stream. Any audio stream present will be ignored. </param> /// <param name="AudioFile"> (string) Genuine audio file (.wav .mp3 .aac) or any file containing an audio stream. This will be added to the video in VideoFile. </param> /// <param name="OutputFile"> (string) Name of the file containing the newly combined video and audio. </param> procedure MuxStreams2(const VideoFile, AudioFile: string; const OutputFile: string); implementation uses System.UITypes, math; { TBitmapEncoder } function VideoSizeInMB(Videotime: int64; CodecId: TAVCodecId; Width, Height, Rate: integer; Quality: Byte): double; var Setup: TBaseCodecSetup; TimeSec: integer; begin TimeSec := Videotime div 1000; if CodecSetupClass(CodecId) = nil then begin Raise Exception.Create('Codec-Id is not supported'); exit; end; Setup := CodecSetupClass(CodecId).Create(CodecId); try result := 0.001 * 1 / 8 * 1 / 1024 * Setup.QualityToBitrate(Quality, Width, Height, Rate) * TimeSec; finally Setup.Free; end; end; function TBitmapEncoderM.encode(frame: PAVFrame; FromVideo: boolean): boolean; var ret: integer; pkt: TAvPacket; begin result := true; if fFrameCount mod fRate = 0 then // update once per second begin if assigned(fOnProgress) then fOnProgress(fVideoTime); end; av_init_packet(@pkt); pkt.data := nil; pkt.size := 0; // leave frame.pts at default, otherwise mpeg-1 and mpeg-2 aren't happy ret := avcodec_send_frame(c, frame); if ret >= 0 then while true do begin ret := avcodec_receive_packet(c, @pkt); // Could there be a bug in ffmpeg.pas mixing up AVERROR_EAGAIN and AVERROR_EDEADLK for Android? if (ret = AVERROR_EOF) or (ret = AVERROR_EAGAIN) or (ret = AVERROR_EDEADLK) then begin av_packet_unref(@pkt); exit; end else if ret < 0 then begin Raise Exception.Create('Package read error'); exit; end; // Adjust the frame rate, now works if FromVideo then begin pkt.dts := VideoDts; pkt.pts := VideoPts; av_packet_rescale_ts(@pkt, fInputVideoTimebase, c.time_base); pkt.pts := fVideoFrameStart + pkt.pts; pkt.dts := fVideoFrameStart + pkt.dts; fFrameCount := pkt.dts; end else begin pkt.pts := fFrameCount; pkt.dts := fFrameCount; inc(fFrameCount); end; pkt.duration := 1; av_packet_rescale_ts(@pkt, c.time_base, stream.time_base); pkt.stream_index := stream.index; // Write the encoded frame to the video file. // Does not seem to fail anymore, ret<0 should maybe throw an exception ret := av_interleaved_write_frame(oc, @pkt); result := (ret >= 0); av_packet_unref(@pkt); fVideoTime := av_rescale_q(av_stream_get_end_pts(stream), stream.time_base, av_make_q(1, 1000)); end else result := false; if not result then inc(DroppedFrames); end; procedure TBitmapEncoderM.Freeze(EffectTime: integer); var frametime: double; time: double; begin frametime := 1000 / fRate; time := 0; while time < EffectTime do begin encode(yuvpic, false); time := time + frametime; end; end; // we need to make the direct pixel access of the bitmap as short as possible, so // we copy the bm to an RGBFrame first thing // fast pixel access as suggested by HuichanKIM procedure TBitmapEncoderM.BitmapToRGBFrame(const bm: TBitmap; const rgbFrame: PAVFrame); var w, h, y: integer; stride, bps, jump: integer; ret: integer; BitData: TBitmapData; rowB, rowF: PByte; const Epsilon = 0.05; begin Assert((bm.Width > 0) and (bm.Height > 0)); w := bm.Width; h := bm.Height; rgbFrame.Width := w; rgbFrame.Height := h; rgbFrame.format := Ord(fRGB_pix_fmt); ret := av_frame_get_buffer(rgbFrame, 0); Assert(ret >= 0); Assert(bm.Map(TMapAccess.Read, BitData)); try // Pitch is more reliable than BytesPerLine stride := BitData.Pitch; bps := 4 * w; jump := rgbFrame.linesize[0]; ret := av_frame_make_writable(rgbFrame); Assert(ret >= 0); // This is more reliable than a convertCtx rowB := BitData.GetScanline(0); rowF := rgbFrame.data[0]; for y := 0 to h - 1 do begin Move(rowB^, rowF^, bps); inc(rowB, stride); inc(rowF, jump); end; finally bm.Unmap(BitData); end; end; procedure TBitmapEncoderM.RGBFrameToFrame(const aFrame: PAVFrame); var convertCtx: PSwsContext; ret: integer; AspectDiffers: boolean; rgbFrame2, rgbFrameSource: PAVFrame; const Epsilon = 0.05; begin Assert((aFrame.Width > 0) and (aFrame.Height > 0)); AspectDiffers := Abs(aFrame.Width / aFrame.Height - fWidth / fHeight) > Epsilon; rgbFrame2 := nil; if AspectDiffers then begin rgbFrame2 := av_frame_alloc; ExpandToAspectRatio(aFrame, rgbFrame2, av_make_q(fWidth, fHeight), fBackground); convertCtx := sws_getContext(rgbFrame2.Width, rgbFrame2.Height, fRGB_pix_fmt, fWidth, fHeight, CodecSetup.OutputPixelFormat, ScaleFunction[fVideoScaling], nil, nil, nil); Assert(convertCtx <> nil); rgbFrameSource := rgbFrame2; end else begin convertCtx := sws_getContext(aFrame.Width, aFrame.Height, fRGB_pix_fmt, fWidth, fHeight, CodecSetup.OutputPixelFormat, ScaleFunction[fVideoScaling], nil, nil, nil); Assert(convertCtx <> nil); rgbFrameSource := aFrame; end; try ret := av_frame_make_writable(yuvpic); Assert(ret >= 0); ret := sws_scale(convertCtx, @rgbFrameSource.data, @rgbFrameSource.linesize, 0, rgbFrameSource.Height, @yuvpic.data, @yuvpic.linesize); Assert(ret >= 0); finally sws_freeContext(convertCtx); if assigned(rgbFrame2) then av_frame_free(@rgbFrame2); end; end; procedure TBitmapEncoderM.BitmapToFrame(const bm: TBitmap); var rgbFrame1: PAVFrame; begin rgbFrame1 := av_frame_alloc; try BitmapToRGBFrame(bm, rgbFrame1); RGBFrameToFrame(rgbFrame1); finally av_frame_free(@rgbFrame1); end; end; procedure TBitmapEncoderM.AddColorFrame(Color: TBGR); begin ColorToFrame(Color); encode(yuvpic, false); end; procedure TBitmapEncoderM.AddFrame(const bm: TBitmap); begin // Store the Bitmap in the yuv-frame BitmapToFrame(bm); // Encode the yuv-frame encode(yuvpic, false); end; procedure TBitmapEncoderM.AddStillImage(const bm: TBitmap; ShowTime: integer); begin BitmapToFrame(bm); // Encode the yuv-frame repeatedly Freeze(ShowTime); end; function TBitmapEncoderM.CloseFile: boolean; begin // flush the encoder av_write_frame(oc,nil); av_write_trailer(oc); // Writing the end of the file. if ((fmt.flags and AVFMT_NOFILE) = 0) then avio_closep(@oc.pb); // Closing the file. result := (avcodec_close(stream.codec) >= 0); end; procedure TBitmapEncoderM.ColorToFrame(Color: TBGR); var rgbpic: PAVFrame; convertCtx: PSwsContext; x, y: integer; px, py: PByte; jump: integer; ret: integer; begin // Set up conversion to YUV convertCtx := sws_getContext(fWidth, fHeight, AV_PIX_FMT_BGR24, fWidth, fHeight, CodecSetup.OutputPixelFormat, ScaleFunction[fVideoScaling], nil, nil, nil); // Video ignores the alpha-channel. Size will be scaled if necessary, // proportionality might not be preserved Assert(convertCtx <> nil); // Allocate storage for the rgb-frame rgbpic := av_frame_alloc(); Assert(rgbpic <> nil); try rgbpic.format := Ord(AV_PIX_FMT_BGR24); rgbpic.Width := fWidth; rgbpic.Height := fHeight; av_frame_get_buffer(rgbpic, 0); // Store the color in the frame ret := av_frame_make_writable(rgbpic); Assert(ret >= 0); py := @PByte(rgbpic.data[0])[0]; jump := rgbpic.linesize[0]; for y := 0 to fHeight - 1 do begin px := py; for x := 0 to fWidth - 1 do begin PBGR(px)^ := Color; inc(px, 3); end; inc(py, jump); end; // Convert the rgb-frame to yuv-frame ret := av_frame_make_writable(yuvpic); Assert(ret >= 0); ret := sws_scale(convertCtx, @rgbpic.data, @rgbpic.linesize, 0, fHeight, @yuvpic.data, @yuvpic.linesize); Assert(ret >= 0); finally sws_freeContext(convertCtx); av_frame_free(@rgbpic); end; end; constructor TBitmapEncoderM.Create(const filename: string; Width, Height, FrameRate: integer; Quality: Byte; CodecId: TAVCodecId = AV_CODEC_ID_NONE; VideoScaling: TVideoScaling = vsFastBilinear; Background: Byte = 0); var ret: integer; begin fFilename := filename; fWidth := Width; fHeight := Height; fRate := FrameRate; fQuality := Quality; fVideoScaling := VideoScaling; fFrameCount := 0; DroppedFrames := 0; fBackground := Background; // the pixel-format of all rgb-frames matches the one of the operating system {$IFDEF ANDROID} fRGB_pix_fmt := AV_PIX_FMT_RGBA; {$ELSE} fRGB_pix_fmt := AV_PIX_FMT_BGRA; {$ENDIF} if CodecId = AV_CODEC_ID_NONE then fCodecId := PreferredCodec(ExtractFileExt(fFilename)) else fCodecId := CodecId; CodecSetup := CodecSetupClass(fCodecId).Create(fCodecId); fmt := GetOutputFormat(ExtractFileExt(fFilename)); Assert(fmt <> nil, 'No matching format'); oc := nil; ret := avformat_alloc_output_context2(@oc, nil, nil, MarshaledAString(UTF8String(filename))); Assert(ret >= 0, 'avformat_alloc.. error' + inttostr(ret)); stream := avformat_new_stream(oc, nil); Assert(stream <> nil, 'avformat_new_stream failed'); codec := CodecSetup.codec; Assert(codec <> nil, 'codec not found'); c := avcodec_alloc_context3(codec); c.Width := fWidth; c.Height := fHeight; c.time_base.num := 1; c.time_base.den := fRate; c.FrameRate.num := fRate; c.FrameRate.den := 1; c.pix_fmt := CodecSetup.OutputPixelFormat; CodecSetup.CodecContextProps(c); c.bit_rate := CodecSetup.QualityToBitrate(fQuality, fWidth, fHeight, fRate); // c.bit_rate_tolerance := 0; Left at defaults. More research needed :) if (oc.oformat.flags and AVFMT_GLOBALHEADER) <> 0 then c.flags := c.flags or AV_CODEC_FLAG_GLOBAL_HEADER; ret := avcodec_open2(c, codec, @CodecSetup.OptionsDictionary); Assert(ret >= 0); stream.time_base := c.time_base; ret := avcodec_parameters_from_context(stream.codecpar, c); // replaces avcodec_get_context_defaults3 Assert(ret >= 0); ret := avio_open(@oc.pb, MarshaledAString(UTF8String(filename)), AVIO_FLAG_WRITE); Assert(ret >= 0); ret := avformat_write_header(oc, @CodecSetup.OptionsDictionary); Assert(ret >= 0); // Allocating memory for conversion output YUV frame: yuvpic := av_frame_alloc(); Assert(yuvpic <> nil); yuvpic.format := Ord(CodecSetup.OutputPixelFormat); yuvpic.Width := fWidth; yuvpic.Height := fHeight; ret := av_frame_get_buffer(yuvpic, 0); Assert(ret >= 0); // Allocating memory for packet pkt := av_packet_alloc(); Assert(pkt <> nil); end; procedure TBitmapEncoderM.CrossFade(const am, bm: TBitmap; EffectTime: integer); var fSrc1, fSrc2, temp: PAVFrame; frametime, time, fact: double; begin fSrc1 := av_frame_alloc; try temp := av_frame_alloc; try BitmapToRGBFrame(am, temp); ExpandToVideoSize(temp, fSrc1); finally av_frame_free(@temp); end; fSrc2 := av_frame_alloc; try temp := av_frame_alloc; try BitmapToRGBFrame(bm, temp); ExpandToVideoSize(temp, fSrc2); finally av_frame_free(@temp); end; frametime := 1000 / fRate; time := 0; fact := 1 / EffectTime; temp := av_frame_alloc; try temp.Width := fWidth; temp.Height := fHeight; temp.format := Ord(fRGB_pix_fmt); av_frame_get_buffer(temp, 0); while time < EffectTime do begin Alphablend(fSrc1, fSrc2, temp, trunc(time * fact * 255)); RGBFrameToFrame(temp); encode(yuvpic, false); time := time + frametime; end; finally av_frame_free(@temp); end; finally av_frame_free(@fSrc2); end; finally av_frame_free(@fSrc1); end; end; procedure TBitmapEncoderM.AddVideo(const VideoInput: string); var fmt_ctx: PAVFormatContext; video_dec_ctx: PAVCodecContext; Width, Height: integer; pix_fmt, rgb_fmt: TAVPixelFormat; video_stream_idx: integer; frame: PAVFrame; pkt: TAvPacket; ret, i: integer; got_frame: integer; video_dst_data: array [0 .. 3] of PByte; video_dst_linesize: array [0 .. 3] of integer; video_stream: PAVStream; convertCtx: PSwsContext; p: PPAVStream; sar: TAVRational; TrueHeight: integer; AspectDiffers: boolean; // args: array [0 .. 512 - 1] of AnsiChar; // buffersink_ctx: PAVFilterContext; // buffersrc_ctx: PAVFilterContext; // filter_graph: PAVFilterGraph; // f: PAVFrame; // inputs, outputs: PAVFilterInOut; // FilterInitialized: boolean; QuitLoop: boolean; // Filterstring: UTF8String; const Epsilon = 0.05; function AddVideoFrame(aFrame: PAVFrame): boolean; var bm: TBitmap; BitmapData: TBitmapData; row: PByte; bps: integer; begin if AspectDiffers then begin bm := TBitmap.Create; try bm.SetSize(aFrame.Width, TrueHeight); bm.Map(TMapAccess.Write, BitmapData); try row := BitmapData.data; bps := BitmapData.Pitch; ret := sws_scale(convertCtx, @aFrame.data, @aFrame.linesize, 0, aFrame.Height, @row, @bps); Assert(ret >= 0); finally bm.Unmap(BitmapData); end; BitmapToFrame(bm); finally bm.Free; end; end else begin // scale the frame and change the pixel format, if necessary ret := av_frame_make_writable(yuvpic); Assert(ret >= 0); ret := sws_scale(convertCtx, @aFrame.data, @aFrame.linesize, 0, Height, @yuvpic.data, @yuvpic.linesize); Assert(ret >= 0); end; result := encode(yuvpic, true); av_packet_unref(@pkt); end; begin Assert(UpperCase(fFilename) <> UpperCase(VideoInput), 'Output file name must be different from input file name'); // FilterInitialized := False; // filter_graph := nil; // inputs := nil; // outputs := nil; fmt_ctx := nil; video_dec_ctx := nil; // buffersrc_ctx := nil; // buffersink_ctx := nil; frame := nil; fVideoFrameCount := 0; for i := 0 to 3 do video_dst_data[i] := nil; (* open input file, and allocate format context *) ret := avformat_open_input(@fmt_ctx, MarshaledAString(UTF8String(VideoInput)), nil, nil); Assert(ret >= 0); (* retrieve stream information *) ret := avformat_find_stream_info(fmt_ctx, nil); Assert(ret >= 0); open_decoder_context(@video_stream_idx, @video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO); p := fmt_ctx.streams; inc(p, video_stream_idx); video_stream := p^; fInputVideoTimebase := video_stream.time_base; (* allocate image where the decoded image will be put *) Width := video_dec_ctx.Width; Height := video_dec_ctx.Height; pix_fmt := video_dec_ctx.pix_fmt; ret := av_image_alloc(@video_dst_data[0], @video_dst_linesize[0], Width, Height, pix_fmt, 1); Assert(ret >= 0); // calculate the true aspect ratio based on sample aspect ratio (ar of one pixel in the source) sar := video_dec_ctx.sample_aspect_ratio; if (sar.num > 0) and (sar.den > 0) then TrueHeight := round(Height * sar.den / sar.num) else TrueHeight := Height; AspectDiffers := Abs(fWidth / fHeight - Width / TrueHeight) > Epsilon; if AspectDiffers then begin {$IFDEF ANDROID} rgb_fmt := AV_PIX_FMT_RGBA; {$ELSE} rgb_fmt := AV_PIX_FMT_BGRA; {$ENDIF} // We convert the frames to bitmaps and then encode the bitmaps convertCtx := sws_getContext(Width, Height, pix_fmt, Width, TrueHeight, rgb_fmt, ScaleFunction[fVideoScaling], nil, nil, nil); end else begin // If the aspect is OK just resize and change the pix-format convertCtx := sws_getContext(Width, Height, pix_fmt, fWidth, fHeight, c.pix_fmt, ScaleFunction[fVideoScaling], nil, nil, nil); end; frame := av_frame_alloc(); Assert(frame <> nil); try (* initialize packet, set data to nil, let the demuxer fill it *) av_init_packet(@pkt); pkt.data := nil; pkt.size := 0; (* read frames from the file *) fVideoFrameStart := fFrameCount + 1; fVideoFrameCount := 0; QuitLoop := false; while true do begin ret := av_read_frame(fmt_ctx, @pkt); if ret < 0 then break; if pkt.stream_index <> video_stream_idx then begin av_packet_unref(@pkt); Continue; end; (* decode video frame *) // !avcodec_decode_video2 is deprecated, but I couldn't get // the replacement avcode_send_packet and avcodec_receive_frame to work got_frame := 0; ret := avcodec_decode_video2(video_dec_ctx, frame, @got_frame, @pkt); Assert(ret >= 0); if (got_frame <> 0) then begin inc(fVideoFrameCount); // This is needed to give the frames the right decoding- and presentation- timestamps // see encode for FromVideo = true VideoPts := pkt.pts; VideoDts := pkt.dts; if VideoPts < VideoDts then VideoPts := VideoDts; // Deinterlace the frame if necessary /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Couldn't get deinterlacing to work under Android // if frame.interlaced_frame = 0 then QuitLoop := QuitLoop or (not AddVideoFrame(frame)); { else begin If not FilterInitialized then begin // Configure the de-interlace filter (yadif) FillChar(args[0], length(args) * sizeof(AnsiChar), #0); Filterstring := UTF8String('buffer=video_size=' + inttostr(video_dec_ctx.Width) + 'x' + inttostr(video_dec_ctx.Height) + ':pix_fmt=' + inttostr(Ord(video_dec_ctx.pix_fmt)) + ':time_base=1/1:pixel_aspect=0/1[in];[in]yadif[out];[out]buffersink'); Move(Filterstring[1], args[0], length(Filterstring) * sizeof(AnsiChar)); filter_graph := avfilter_graph_alloc(); inputs := nil; outputs := nil; ret := avfilter_graph_parse2(filter_graph, MarshaledAString(@args[0]), @inputs, @outputs); Assert(ret >= 0,'Error= '+IntToStr(ret)); ret := avfilter_graph_config(filter_graph, nil); Assert(ret >= 0); buffersrc_ctx := avfilter_graph_get_filter(filter_graph, 'Parsed_buffer_0'); buffersink_ctx := avfilter_graph_get_filter(filter_graph, 'Parsed_buffersink_2'); Assert(buffersrc_ctx <> nil); Assert(buffersink_ctx <> nil); FilterInitialized := true; end; f := nil; f := av_frame_alloc(); try av_frame_ref(f, frame); av_buffersrc_add_frame(buffersrc_ctx, f); while true do begin ret := av_buffersink_get_frame(buffersink_ctx, f); // AVError_EAgain means that more data are needed to fill the frame if (ret = AVERROR_EAGAIN) or (ret = AVERROR_EOF) or (ret = AVERROR_EDEADLK) then break; Assert(ret >= 0); QuitLoop := QuitLoop or (not AddVideoFrame(f)); end; finally av_frame_free(@f); end; end; } end; // if got_frame end; // while true Assert(not QuitLoop, 'Some video frames could not be added'); finally { if assigned(inputs) then avfilter_inout_free(@inputs); if assigned(outputs) then avfilter_inout_free(@outputs); if assigned(filter_graph) then avfilter_graph_free(@filter_graph); } av_freep(@video_dst_data[0]); av_frame_free(@frame); avcodec_free_context(@video_dec_ctx); sws_freeContext(convertCtx); avformat_close_input(@fmt_ctx); end; end; destructor TBitmapEncoderM.Destroy; begin CodecSetup.Free; av_frame_free(@yuvpic); avformat_free_context(oc); avcodec_free_context(@c); av_packet_free(@pkt); inherited; end; procedure TBitmapEncoderM.ExpandToAspectRatio(const FrameSrc, FrameDst: PAVFrame; AR: TAVRational; Background: Byte); var xstart, ystart: integer; ret: integer; bmRow, FrameRow, FrameStart: PByte; y, bps, jumpB, jumpF: integer; begin Assert((FrameSrc.Width > 0) and (FrameSrc.Height > 0)); if FrameSrc.Width / FrameSrc.Height < AR.num / AR.den then // Add background right and left begin FrameDst.Height := FrameSrc.Height; FrameDst.Width := round(FrameSrc.Height / AR.den * AR.num); xstart := (FrameDst.Width - FrameSrc.Width) div 2; ystart := 0; end else begin FrameDst.Width := FrameSrc.Width; FrameDst.Height := round(FrameSrc.Width / AR.num * AR.den); xstart := 0; ystart := (FrameDst.Height - FrameSrc.Height) div 2; end; // Set up the Frame with the right pixelformat FrameDst.format := Ord(fRGB_pix_fmt); ret := av_frame_get_buffer(FrameDst, 0); Assert(ret >= 0); av_frame_make_writable(FrameDst); // Fill the frame with gray 0:black 255:white FillChar(FrameDst.data[0]^, FrameDst.Height * FrameDst.linesize[0], Background); // Copy FrameSrc to FrameDst bmRow := FrameSrc.data[0]; FrameRow := FrameDst.data[0]; bps := 4 * FrameSrc.Width; jumpF := FrameDst.linesize[0]; jumpB := FrameSrc.linesize[0]; inc(FrameRow, ystart * jumpF); xstart := 4 * xstart; for y := 0 to FrameSrc.Height - 1 do begin FrameStart := FrameRow; inc(FrameStart, xstart); Move(bmRow^, FrameStart^, bps); inc(bmRow, jumpB); inc(FrameRow, jumpF); end; end; procedure TBitmapEncoderM.ExpandToVideoSize(const FrameSrc, FrameDst: PAVFrame); var temp: PAVFrame; convertCtx: PSwsContext; begin temp := av_frame_alloc; try ExpandToAspectRatio(FrameSrc, temp, av_make_q(fWidth, fHeight), fBackground); convertCtx := sws_getContext(temp.Width, temp.Height, fRGB_pix_fmt, fWidth, fHeight, fRGB_pix_fmt, ScaleFunction[fVideoScaling], nil, nil, nil); try FrameDst.Width := fWidth; FrameDst.Height := fHeight; FrameDst.format := Ord(fRGB_pix_fmt); av_frame_get_buffer(FrameDst, 0); av_frame_make_writable(FrameDst); sws_scale(convertCtx, @temp.data, @temp.linesize, 0, temp.Height, @FrameDst.data, @FrameDst.linesize); finally sws_freeContext(convertCtx); end; finally av_frame_free(@temp); end; end; procedure TBitmapEncoderM.ZoomPan(const bm: TBitmap; zSrc, zDst: TZoom; EffectTime: integer; ZoomOption: TZoomOption; SpeedEnvelope: TZoomSpeedEnvelope = zeLinear); var asp: double; aw, ah: integer; // antialiased width height elapsed: integer; Src, trg, mid: TRectF; targetTime: integer; frametime, t: double; evf: TEnvelopeFunction; bw, bh: integer; frRGB, frSrc, frDst: PAVFrame; ret: integer; begin evf := EnvelopeFunction[SpeedEnvelope]; bw := bm.Width; bh := bm.Height; frSrc := av_frame_alloc; // Antialias frame try frRGB := av_frame_alloc; try BitmapToRGBFrame(bm, frRGB); ah := frRGB.Height; // suppress compiler warning case ZoomOption of zoAAx2: ah := 2 * fHeight; zoAAx4: ah := 4 * fHeight; zoAAx6: ah := 6 * fHeight; // 6*fHeight might give an EOutOfResources if there is no // suffiently large memory block available, less likely for 64-bit zoResample: ah := fHeight + 100; end; asp := bw / bh; aw := round(ah * asp); frSrc.Width := aw; frSrc.Height := ah; frSrc.format := Ord(fRGB_pix_fmt); ret := av_frame_get_buffer(frSrc, 0); Assert(ret >= 0); // start with a nice upscale ZoomResampleTripleOnly(frRGB, frSrc, Rect(0, 0, bw, bh), 1.8) finally av_frame_free(@frRGB); end; Src := zSrc.ToRect(aw, ah); trg := zDst.ToRect(aw, ah); // scale zooms to rects for antialias-size frametime := 1000 / fRate; elapsed := 0; targetTime := round(EffectTime - 0.5 * frametime); frDst := av_frame_alloc; try frDst.Height := fHeight; frDst.Width := round(fHeight * bw / bh); frDst.format := Ord(fRGB_pix_fmt); ret := av_frame_get_buffer(frDst, 0); Assert(ret >= 0); while elapsed < targetTime do begin t := elapsed / EffectTime; mid := Interpolate(Src, trg, evf(t)); case ZoomOption of zoAAx2, zoAAx4, zoAAx6: ZoomDeleteScans(frSrc, frDst, mid); zoResample: ZoomResampleTripleOnly(frSrc, frDst, mid, 1.5); // radius 1.5 is good enough end; // feed frDst to the encoder RGBFrameToFrame(frDst); encode(yuvpic, false); elapsed := round(elapsed + frametime); end; finally av_frame_free(@frDst); end; finally av_frame_free(@frSrc); end; end; // Alphablend rgb-frames // Must be of the same size // fDst = alpha*(fSrc2-fSrc1)/255 + fSrc1 procedure TBitmapEncoderM.Alphablend(fSrc1, fSrc2, fDst: PAVFrame; alpha: Byte); var x, y, jump: integer; rowSrc1, rowSrc2, rowDst: PByte; bSrc1, bSrc2, bDst: PByte; begin av_frame_make_writable(fDst); rowSrc1 := fSrc1.data[0]; rowSrc2 := fSrc2.data[0]; rowDst := fDst.data[0]; jump := fDst.linesize[0]; for y := 0 to fDst.Height - 1 do begin bSrc1 := rowSrc1; bSrc2 := rowSrc2; bDst := rowDst; for x := 0 to fDst.linesize[0] - 1 do begin bDst^ := (alpha * (bSrc2^ - bSrc1^)) shr 8 + bSrc1^; inc(bSrc1); inc(bSrc2); inc(bDst); end; inc(rowSrc1, jump); inc(rowSrc2, jump); inc(rowDst, jump); end; end; type TContributor = record Min, High: integer; // Min: start source pixel // High+1: number of source pixels to contribute to the result Weights: array of integer; // doubles scaled by $800 end; TContribArray = array of TContributor; TIntArray = array of integer; {$IFDEF ANDROID} TQuad = record r, g, b, a: Byte; end; {$ELSE} TQuad = record b, g, r, a: Byte; end; {$ENDIF} PQuad = ^TQuad; const beta = 0.54; // f(beta)=0 beta2 = beta * beta; alpha = 105 / (16 - 112 * beta2); aa = 1 / 7 * alpha; bb = -1 / 5 * alpha * (2 + beta2); cc = 1 / 3 * alpha * (1 + 2 * beta2); dd = -alpha * beta2; // constants computed with maple for polynomial fit function AntiMyFilter(x: double): double; inline; // Antiderivative of a filter function similar to bicubic, but I like it better begin if x < -1 then result := -0.5 else if x < 1 then result := aa * x * x * x * x * x * x * x + bb * x * x * x * x * x + cc * x * x * x + dd * x else result := 0.5; end; procedure MakeContributors(r: single; SourceSize, TargetSize: integer; SourceStart, SourceFloatwidth: double; var Contribs: TContribArray); // r: Filterradius var xCenter, scale, rr: double; x, j: integer; x1, x2, delta: double; TrueMin, TrueMax, Mx: integer; begin if SourceFloatwidth = 0 then SourceFloatwidth := SourceSize; scale := SourceFloatwidth / TargetSize; SetLength(Contribs, TargetSize); if scale > 1 then // downsampling rr := r * scale else rr := r; delta := 1 / rr; for x := 0 to TargetSize - 1 do begin xCenter := (x + 0.5) * scale; TrueMin := Ceil(xCenter - rr + SourceStart - 1); TrueMax := Floor(xCenter + rr + SourceStart); Contribs[x].Min := Min(Max(TrueMin, 0), SourceSize - 1); // make sure not to read in negative pixel locations Mx := Max(Min(TrueMax, SourceSize - 1), 0); // make sure not to read past w1-1 in the source Contribs[x].High := Mx - Contribs[x].Min; Assert(Contribs[x].High >= 0); // hasn't failed lately:) // High=Number of contributing pixels minus 1 SetLength(Contribs[x].Weights, Contribs[x].High + 1); with Contribs[x] do begin x1 := delta * (Min - SourceStart - xCenter); for j := 0 to High do begin x2 := x1 + delta; Weights[j] := round($800 * (AntiMyFilter(x2) - AntiMyFilter(x1))); x1 := x2; end; for j := TrueMin - Min to -1 do begin // assume the first pixel to be repeated x1 := delta * (Min + j - SourceStart - xCenter); x2 := x1 + delta; Weights[0] := Weights[0] + round($800 * (AntiMyFilter(x2) - AntiMyFilter(x1))); end; for j := High + 1 to TrueMax - Min do begin // assume the last pixel to be repeated x1 := delta * (Min + j - SourceStart - xCenter); x2 := x1 + delta; Weights[High] := Weights[High] + round($800 * (AntiMyFilter(x2) - AntiMyFilter(x1))); end; end; { with Contribs[x] } end; { for x } end; // Source and Target must have been allocated, the right size and format and memory must have been allocated procedure TBitmapEncoderM.ZoomResampleTripleOnly(const Source, Target: PAVFrame; SourceRect: TRectF; Radius: single); var ContribsX, ContribsY: TContribArray; OldWidth, OldHeight: integer; NewWidth, NewHeight: integer; // Target needs to be set to correct size Sbps, Tbps: integer; tr, tg, tb: integer; // total red etc. dr, dg, db: integer; // For Subsum ps, pT: PQuad; rs, rT, rStart, rTStart: PByte; // Row start in Source, Target weightx, weighty, weightxStart: PInteger; rx, gx, bx: TIntArray; x, y, xs, ys, ymin, ymax: integer; highx, highy, minx, miny: integer; runr, rung, runb: PInteger; runrstart, rungstart, runbstart: PInteger; begin NewWidth := Target.Width; NewHeight := Target.Height; OldWidth := Source.Width; OldHeight := Source.Height; Tbps := Target.linesize[0]; // BytesPerScanline Target Sbps := Source.linesize[0]; // BytesPerScanline Source MakeContributors(Radius, OldWidth, NewWidth, SourceRect.Left, SourceRect.Right - SourceRect.Left, ContribsX); MakeContributors(Radius, OldHeight, NewHeight, SourceRect.Top, SourceRect.Bottom - SourceRect.Top, ContribsY); ymin := ContribsY[0].Min; ymax := ContribsY[NewHeight - 1].High + ContribsY[NewHeight - 1].Min; SetLength(rx, ymax - ymin + 1); SetLength(gx, ymax - ymin + 1); SetLength(bx, ymax - ymin + 1); // cache arrays av_frame_make_writable(Target); rStart := Source.data[0]; inc(rStart, ymin * Source.linesize[0]); rTStart := Target.data[0]; // Compute color at each target pixel (x,y) runrstart := @rx[0]; rungstart := @gx[0]; runbstart := @bx[0]; for x := 0 to NewWidth - 1 do begin rs := rStart; highx := ContribsX[x].High; minx := ContribsX[x].Min; weightxStart := @ContribsX[x].Weights[0]; runr := runrstart; rung := rungstart; runb := runbstart; for y := ymin to ymax do begin // For each source line y // Sum up weighted color values at source pixels ContribsX[x].Min+xs // 0<=xs<=ContribsX[x].High // and store the results in rx[y-ymin], gx[y-ymin] etc. ps := PQuad(rs); inc(ps, minx); weightx := weightxStart; db := weightx^ * ps.b; dg := weightx^ * ps.g; dr := weightx^ * ps.r; for xs := 1 to highx do begin inc(weightx); inc(ps); db := db + weightx^ * ps.b; dg := dg + weightx^ * ps.g; dr := dr + weightx^ * ps.r; end; // store results in rx,gx,bx runr^ := dr; rung^ := dg; runb^ := db; inc(runr); inc(rung); inc(runb); inc(rs, Sbps); end; // Average in y-direction: // For each target line y sum up weighted colors // rx[ys+ContribsY[y].Min-ymin], 0<=ys<=ContribsY[y].High, (same for gx, bx) // Store result in tr,tg,tb ("total red" etc.) // round and assign to TargetPixel[x,y] rT := rTStart; for y := 0 to NewHeight - 1 do begin pT := PQuad(rT); inc(pT, x); highy := ContribsY[y].High; miny := ContribsY[y].Min - ymin; weighty := @ContribsY[y].Weights[0]; runr := runrstart; rung := rungstart; runb := runbstart; inc(runr, miny); inc(rung, miny); inc(runb, miny); tr := weighty^ * runr^; tb := weighty^ * runb^; tg := weighty^ * rung^; for ys := 1 to highy do begin inc(weighty); inc(runr); inc(rung); inc(runb); tr := tr + weighty^ * runr^; tb := tb + weighty^ * runb^; tg := tg + weighty^ * rung^; end; tr := Max(tr, 0); tg := Max(tg, 0); tb := Max(tb, 0); // results could be negative, filter has negative values tr := (tr + $1FFFFF) shr 22; // "round" the result tg := (tg + $1FFFFF) shr 22; tb := (tb + $1FFFFF) shr 22; pT.b := Min(tb, 255); pT.g := Min(tg, 255); pT.r := Min(tr, 255); inc(rT, Tbps); end; // for y end; // for x end; procedure MakeSteps(DestSize, SourceSize: integer; SourceLeft, SourceWidth: double; var steps: TIntArray; fact: integer); inline; var shift, delta: double; x1, x2, i: integer; xx2: double; begin SetLength(steps, DestSize); delta := SourceWidth / DestSize; shift := SourceLeft + 0.5 * delta; x1 := 0; xx2 := shift; x2 := Floor(xx2); if x2 > SourceSize - 1 then x2 := SourceSize - 1; steps[0] := (x2 - x1) * fact; x1 := x2; for i := 1 to DestSize - 1 do begin xx2 := xx2 + delta; x2 := Floor(xx2); if x2 > SourceSize - 1 then x2 := SourceSize - 1; steps[i] := (x2 - x1) * fact; x1 := x2; end; end; procedure TBitmapEncoderM.ZoomDeleteScans(const Src, Dest: PAVFrame; rs: TRectF); var iwd, ihd, iws, ihs, bs, bd: integer; x, y: integer; xsteps, ysteps: TIntArray; Rows, rowd: PByte; Stepsx, Stepsy: PInteger; ts, td: PQuad; begin iwd := Dest.Width; ihd := Dest.Height; Assert((iwd > 1) and (ihd > 1), 'Dest Frame too small'); iws := Src.Width; ihs := Src.Height; av_frame_make_writable(Dest); bs := Src.linesize[0]; // BytesPerScanline Source bd := Dest.linesize[0]; // BytesPerScanline Dest MakeSteps(iwd, iws, rs.Left, rs.Right - rs.Left, xsteps, 1); MakeSteps(ihd, ihs, rs.Top, rs.Bottom - rs.Top, ysteps, bs); Rows := Src.data[0]; rowd := Dest.data[0]; Stepsy := @ysteps[0]; for y := 0 to ihd - 1 do begin inc(Rows, Stepsy^); ts := PQuad(Rows); td := PQuad(rowd); Stepsx := @xsteps[0]; for x := 0 to iwd - 1 do begin inc(ts, Stepsx^); td^ := ts^; inc(td); inc(Stepsx) end; inc(rowd, bd); inc(Stepsy); end; end; procedure MuxStreams2(const VideoFile, AudioFile: string; const OutputFile: string); var ofmt: PAVOutputFormat; ifmt_ctx1, ifmt_ctx2, ofmt_ctx: PAVFormatContext; pkt: TAvPacket; in_filename1, in_filename2, out_filename: PAnsiChar; ret: integer; out_streamV, out_streamA: PAVStream; in_streamV, in_streamA: PAVStream; in_codecpar: PAVCodecParameters; Videotime, AudioTime: int64; p: PPAVStream; sn: cardinal; VideoStreamIndex, AudioStreamIndex: integer; begin ifmt_ctx1 := nil; ifmt_ctx2 := nil; ofmt_ctx := nil; in_filename1 := MarshaledAString(UTF8String(VideoFile)); in_filename2 := MarshaledAString(UTF8String(AudioFile)); out_filename := MarshaledAString(UTF8String(OutputFile)); ret := avformat_open_input(@ifmt_ctx1, in_filename1, nil, nil); Assert(ret = 0, format('Could not open input file ''%s''', [in_filename1])); ret := avformat_open_input(@ifmt_ctx2, in_filename2, nil, nil); Assert(ret = 0, format('Could not open input file ''%s''', [in_filename2])); ret := avformat_find_stream_info(ifmt_ctx1, nil); Assert(ret = 0, 'Failed to retrieve input stream information'); ret := avformat_find_stream_info(ifmt_ctx2, nil); Assert(ret = 0, 'Failed to retrieve input stream information'); avformat_alloc_output_context2(@ofmt_ctx, nil, nil, out_filename); Assert(assigned(ofmt_ctx), 'Could not create output context'); ofmt := ofmt_ctx.oformat; // look for the 1st video stream p := ifmt_ctx1.streams; sn := 0; while (p^.codec.codec_type <> AVMEDIA_TYPE_VIDEO) and (sn < ifmt_ctx1.nb_streams) do begin inc(p); inc(sn); end; Assert((sn < ifmt_ctx1.nb_streams) and (p^.codec.codec_type = AVMEDIA_TYPE_VIDEO), 'No video stream found in ' + VideoFile); VideoStreamIndex := sn; in_streamV := p^; in_codecpar := in_streamV.codecpar; out_streamV := avformat_new_stream(ofmt_ctx, nil); Assert(assigned(out_streamV)); ret := avcodec_parameters_copy(out_streamV.codecpar, in_codecpar); Assert(ret = 0, 'Failed to copy codec parameters'); out_streamV.codecpar^.codec_tag.tag := 0; out_streamV.time_base.num := in_streamV.time_base.num; out_streamV.time_base.den := in_streamV.time_base.den; // Handle the audio stream from file 2 // Locate the 1st audio stream p := ifmt_ctx2.streams; sn := 0; while (p^.codec.codec_type <> AVMEDIA_TYPE_AUDIO) and (sn < ifmt_ctx2.nb_streams) do begin inc(p); inc(sn); end; Assert((sn < ifmt_ctx2.nb_streams) and (p^.codec.codec_type = AVMEDIA_TYPE_AUDIO), 'No audio stream found in ' + AudioFile); AudioStreamIndex := sn; in_streamA := p^; in_codecpar := in_streamA.codecpar; out_streamA := avformat_new_stream(ofmt_ctx, nil); Assert(assigned(out_streamA)); ret := avcodec_parameters_copy(out_streamA.codecpar, in_codecpar); Assert(ret = 0, 'Failed to copy codec parameters'); out_streamA.codecpar^.codec_tag.tag := 0; if (ofmt.flags and AVFMT_NOFILE) = 0 then begin ret := avio_open(@ofmt_ctx.pb, out_filename, AVIO_FLAG_WRITE); Assert(ret = 0, format('Could not open output file ''%s''', [out_filename])); end; ret := avformat_write_header(ofmt_ctx, nil); Assert(ret = 0, 'Error occurred when opening output file'); p := ofmt_ctx.streams; out_streamV := p^; inc(p, 1); out_streamA := p^; AudioTime := 0; while true do begin ret := av_read_frame(ifmt_ctx1, @pkt); if ret < 0 then break; if (pkt.stream_index <> VideoStreamIndex) then begin av_packet_unref(@pkt); Continue; end; pkt.stream_index := 0; // PPtrIdx(stream_mapping, pkt.stream_index); (* copy packet *) pkt.pts := av_rescale_q_rnd(pkt.pts, in_streamV.time_base, out_streamV.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.dts := av_rescale_q_rnd(pkt.dts, in_streamV.time_base, out_streamV.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.duration := av_rescale_q(pkt.duration, in_streamV.time_base, out_streamV.time_base); pkt.pos := -1; ret := av_interleaved_write_frame(ofmt_ctx, @pkt); if ret < 0 then break; Videotime := av_stream_get_end_pts(out_streamV); while (AudioTime < Videotime) and (ret >= 0) do begin ret := av_read_frame(ifmt_ctx2, @pkt); if ret < 0 then break; if (pkt.stream_index <> AudioStreamIndex) then begin av_packet_unref(@pkt); Continue; end; pkt.stream_index := 1; (* copy packet *) pkt.pts := av_rescale_q_rnd(pkt.pts, in_streamA.time_base, out_streamA.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.dts := av_rescale_q_rnd(pkt.dts, in_streamA.time_base, out_streamA.time_base, Ord(AV_ROUND_NEAR_INF) or Ord(AV_ROUND_PASS_MINMAX)); pkt.duration := av_rescale_q(pkt.duration, in_streamA.time_base, out_streamA.time_base); pkt.pos := -1; ret := av_interleaved_write_frame(ofmt_ctx, @pkt); // assert(ret >= 0); av_packet_unref(@pkt); AudioTime := av_rescale_q(av_stream_get_end_pts(out_streamA), out_streamA.time_base, out_streamV.time_base); end; end; av_write_trailer(ofmt_ctx); avformat_close_input(@ifmt_ctx1); avformat_close_input(@ifmt_ctx2); (* close output *) if assigned(ofmt_ctx) and ((ofmt.flags and AVFMT_NOFILE) = 0) then avio_closep(@ofmt_ctx.pb); avformat_free_context(ofmt_ctx); Assert((ret >= 0) or (ret = AVERROR_EOF)); end; end.
{ ******************************************************************************************************************* SpiderTable: Contains TSpiderTable component which can be used to generate HTML tables, manually or from date set Author: Motaz Abdel Azeem email: motaz@code.sd Home page: http://code.sd License: LGPL Last modifie: 23.Dec.2012 Jul/2010 - Modified by Luiz Américo * Remove LCL dependency ******************************************************************************************************************* } unit SpiderTable; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db; type THeaderEvent = procedure(Sender: TObject; DataSet: TDataSet; ColCount: Integer; var CellData, BgColor, ExtraParams: string) of object; TRowEvent = procedure(Sender: TObject; DataSet: TDataSet; RowCount: Integer; var BgColor, ExtraParams: string) of object; TCellEvent = procedure(Sender: TObject; DataSet: TDataSet; ColCount, RowCount: Integer; var CellData, BgColor, ExtraParams: string) of object; { TSpiderTable } TSpiderTable = class(TComponent) private fBorder: Byte; fTableExtraParams: string; fColumnCount: SmallInt; fHeader: array of string; fRows: array of array of string; fHeaderColor: string; fHeaderExtraParams: string; fDefaultRowColor: string; fRowsColor: array of string; fRowsExtraParams: array of string; fDataSet: TDataSet; fOnDrawHeader : THeaderEvent; fOnDrawCell: TCellEvent; fOnDrawRow: TRowEvent; { Private declarations } protected { Protected declarations } public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure SetColumnCount(ACount: SmallInt); procedure SetHeader(Cols: array of string); overload; procedure SetHeader(Cols: TStringList); overload; procedure AddRow(RowColor, RowExtraParams: string; Cells: array of string); overload; procedure AddRow(RowColor: string; Cells: array of string); overload; procedure AddRow(Cells: array of string); overload; procedure AddRow(Cells: TStringList; BgColor: string = ''); overload; function GetContent: string; procedure Clear; property Contents: string read GetContent; { Public declarations } published property Border: Byte read fBorder write fBorder; property TableExtraParams: string read fTableExtraParams write fTableExtraParams; property HeaderExtraParams: string read fHeaderExtraParams write fHeaderExtraParams; property ColumnCount: SmallInt read fColumnCount write SetColumnCount default 2; property HeaderColor: string read fHeaderColor write fHeaderColor; property DataSet: TDataSet read fDataSet write fDataSet; property RowColor: string read fDefaultRowColor write fDefaultRowColor; property OnDrawHeader: THeaderEvent read fOnDrawHeader write fOnDrawHeader; property OnDrawRow: TRowEvent read FOnDrawRow write FOnDrawRow; property OnDrawDataCell: TCellEvent read fOnDrawCell write fOnDrawCell; { Published declarations } end; implementation { TSpiderTable } constructor TSpiderTable.Create(TheOwner: TComponent); begin inherited Create(TheOwner); fDataSet:= nil; end; destructor TSpiderTable.Destroy; begin SetLength(fRows, 0); setLength(fHeader, 0); SetLength(fRowsColor, 0); inherited Destroy; end; procedure TSpiderTable.SetColumnCount(ACount: SmallInt); begin fColumnCount:= ACount; end; procedure TSpiderTable.SetHeader(Cols: array of string); var i: Integer; begin fColumnCount:= Length(Cols); SetLength(fHeader, fColumnCount); for i:= 0 to fColumnCount - 1 do fHeader[i]:= Cols[i]; SetLength(fRows, 0); SetLength(fRowsColor, 0); SetLength(fRowsExtraParams, 0); end; procedure TSpiderTable.SetHeader(Cols: TStringList); var i: Integer; begin fColumnCount:= Cols.Count; SetLength(fHeader, fColumnCount); for i:= 0 to fColumnCount - 1 do fHeader[i]:= Cols[i]; SetLength(fRows, 0); SetLength(fRowsColor, 0); SetLength(fRowsExtraParams, 0); end; procedure TSpiderTable.AddRow(RowColor, RowExtraParams: string; Cells: array of string); var i: Integer; begin SetLength(fRows, Length(fRows) + 1); // Add new row SetLength(fRows[High(fRows)], fColumnCount); // add new columns array SetLength(fRowsColor, Length(fRowsColor) + 1); SetLength(fRowsExtraParams, Length(fRowsExtraParams) + 1); if Trim(RowColor) <> '' then fRowsColor[High(fRowsColor)]:= Trim(RowColor) else fRowsColor[High(fRowsColor)]:= Trim(fDefaultRowColor); fRowsExtraParams[High(fRowsExtraParams)]:= RowExtraParams; for i:= 0 to fColumnCount - 1 do fRows[High(fRows), i]:= Cells[i]; end; procedure TSpiderTable.AddRow(RowColor: string; Cells: array of string); begin AddRow(RowColor, '', Cells); end; procedure TSpiderTable.AddRow(Cells: array of string); begin AddRow('', '', Cells); end; procedure TSpiderTable.AddRow(Cells: TStringList; BgColor: string = ''); var CellsStr: array of string; i: Integer; begin SetLength(CellsStr, fColumnCount); for i:= 0 to Cells.Count -1 do if i < fColumnCount then CellsStr[i]:= Cells[i]; AddRow(BgColor, CellsStr); CellsStr:= nil; end; function TSpiderTable.GetContent: string; var x, y: Integer; BgColor: string; CellData: string; ExtraParams: string; aRowColor, aRowExtraParams: string; begin try // Header Result:= '<table border = ' + IntToStr(fBorder) + ' ' + fTableExtraParams + '><tr ' + fHeaderExtraParams + ' '; if fHeaderColor <> '' then Result:= Result + ' bgcolor="' + fHeaderColor + '"'; Result:= Result + '>'; // DataSet if fDataSet <> nil then begin if not fDataSet.Active then fDataSet.Open; // Header for x:= 0 to fDataSet.FieldCount - 1 do if fDataSet.Fields[x].Visible then begin Result:= Result + '<th '; CellData:= fDataSet.Fields[x].DisplayLabel; BgColor:= ''; ExtraParams:= ''; if Assigned(fOnDrawHeader) then begin fOnDrawHeader(Self, fDataSet, x, CellData, BgColor, ExtraParams); if Trim(BgColor) <> '' then Result:= Result + 'BgColor="' + BgColor + '" ' + ExtraParams + ' '; end; Result:= Result + '>' + CellData + '</th>'; end; Result:= Result + '</tr>' + #10; // Rows fDataSet.First; while not fDataSet.EOF do begin aRowColor:= fDefaultRowColor; // Row event aRowExtraParams:= ''; if Assigned(fOnDrawRow) then begin fOnDrawRow(self, fDataSet, fDataSet.RecNo - 1, aRowColor, aRowExtraParams); end; Result:= Result + '<tr '; if aRowColor <> '' then Result:= Result + 'bgcolor="' + aRowColor + '" '; Result:= Result + aRowExtraParams + ' >'; for x:= 0 to fDataSet.FieldCount -1 do if fDataSet.Fields[x].Visible then begin BgColor:= ''; ExtraParams:= ''; CellData:= fDataSet.Fields[x].AsString; Result:= Result + '<td '; if Assigned(fOnDrawCell) then begin fOnDrawCell(self, fDataSet, x, fDataSet.RecNo - 1, CellData, BgColor, ExtraParams); if BgColor <> '' then Result:= Result + 'BgColor="' + BgColor + '" ' + ExtraParams + ' '; end; Result:= Result + '>' + CellData + '</td>'; end; Result:= Result + '</tr>' + #10; fDataSet.Next; end; end else // Manual table begin // put header if fHeader <> nil then begin for x:= 0 to fColumnCount - 1 do begin Result:= Result + '<th ' ; BgColor:= ''; ExtraParams:= ''; CellData:= fHeader[x]; if Assigned(fOnDrawHeader) then begin fOnDrawHeader(Self, nil, x, CellData, BgColor, ExtraParams); if Trim(BgColor) <> '' then Result:= Result + 'BgColor="' + BgColor + '" ' + ExtraParams + ' '; end; Result:= Result + '>' + CellData + '</th>'; end; Result:= Result + '</tr>' + #10; end; // Rows if fRows <> nil then begin for y:= 0 to High(fRows) do begin Result:= Result + '<tr bgcolor="' + fRowsColor[y] + '" ' + fRowsExtraParams[y] + ' >'; for x:= 0 to High(fRows[y]) do begin BgColor:= ''; ExtraParams:= ''; Result:= Result + '<td '; CellData:= fRows[y, x]; if Assigned(fOnDrawCell) then begin fOnDrawCell(self, nil, x, y, CellData, BgColor, ExtraParams); if BgColor <> '' then Result:= Result + 'BgColor="' + BgColor + '" ' + ExtraParams + ' '; end; Result:= Result + '>' + CellData + '</td>'; end; Result:= Result + '</tr>' + #10; end; end; end; Result:= Result + '</table>' + #10; except on e: exception do Result:= e.Message; end; end; procedure TSpiderTable.Clear; begin SetLength(fHeader, 0); SetLength(fRows, 0); SetLength(fRowsColor, 0); end; end.
unit ptr_arith_pchar_2; interface implementation var S: string = 'ASDF'; procedure Test; var P: ^Char; begin P := @S[Low(s)]; for var i := Low(S) to High(S) do begin P^ := 'a'; Inc(P); end; end; initialization Test(); finalization Assert(S = 'aaaa'); end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.DateTimeCtrls, {$IF DEFINED(ANDROID) AND (RTLVersion >= 33)} Androidapi.Helpers, Androidapi.JNI.Os, System.Permissions, {$ENDIF} UI.Base, UI.Standard, UI.Toast, UI.ListView, UI.Dialog, UI.VKhelper; type TForm1 = class(TForm) ToastManager1: TToastManager; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } {$IF DEFINED(ANDROID) AND (RTLVersion >= 33)} procedure PermissionsCheck; procedure PermissionsResultHandler(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); {$ENDIF} public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses {$IF DEFINED(ANDROID) AND (RTLVersion >= 33)} Androidapi.JNI.JavaTypes, {$ENDIF} UI.Async, UI.Frame, uFrame1, uFrame2; procedure TForm1.FormCreate(Sender: TObject); begin // use android transparent statusbar new method TFrameView.SetStatusTransparentNewMethod(True); TFrameView.SetDefaultStatusLight(False); TFrameView.SetDefaultStatusTransparent(True); TFrameView.SetDefaultStatusColor($ff800080); //TFrameView.SetDefaultBackColor($fff1f2f3); end; procedure TForm1.FormShow(Sender: TObject); begin TFrame1.ShowFrame(Self, 'FMXUI Demo'); {$IF DEFINED(ANDROID) AND (RTLVersion >= 33)} PermissionsCheck; {$ENDIF} end; {$IF DEFINED(ANDROID) AND (RTLVersion >= 33)} procedure TForm1.PermissionsCheck; begin if TJBuild_VERSION.JavaClass.SDK_INT >= 23 then PermissionsService.RequestPermissions([JStringToString(TJManifest_permission.JavaClass.CAMERA), JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE), JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE)], PermissionsResultHandler); end; procedure TForm1.PermissionsResultHandler(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); begin if PermissionsService.IsEveryPermissionGranted( [JStringToString(TJManifest_permission.JavaClass.CAMERA), JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE), JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE)]) then Toast('Permission granted') else Toast('Permission not granted'); end; {$ENDIF} end.
unit MapProximitySelectUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TMapProximitySelectDialog = class(TForm) ProximityTypeRadioGroup: TRadioGroup; LocateButton: TBitBtn; OKButton: TBitBtn; CancelButton: TBitBtn; PrintLabelsCheckBox: TCheckBox; Label2: TLabel; ProximityRadiusEdit: TEdit; Label1: TLabel; UseAlreadySelectedParcelsCheckBox: TCheckBox; procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure LocateButtonClick(Sender: TObject); private { Private declarations } OriginalSwisSBLKey : String; public { Public declarations } SwisSBLKey : String; ProximityRadius : Double; ProximityType : Integer; PrintLabels : Boolean; UseAlreadySelectedParcels : Boolean; Procedure SetCaption; end; var MapProximitySelectDialog: TMapProximitySelectDialog; implementation {$R *.DFM} uses PASUtils, Prclocat, Utilitys; {====================================================================} Procedure TMapProximitySelectDialog.SetCaption; begin If (SwisSBLKey = '') then Caption := 'Highlight proximate parcels' else Caption := 'Proximate parcels from ' + ConvertSwisSBLToDashDot(SwisSBLKey); end; {SetCaption} {====================================================================} Procedure TMapProximitySelectDialog.FormShow(Sender: TObject); begin OriginalSwisSBLKey := SwisSBLKey; SetCaption; end; {FormShow} {====================================================================} Procedure TMapProximitySelectDialog.LocateButtonClick(Sender: TObject); begin LocateParcelForm.WindowState := wsNormal; If ExecuteParcelLocateDialog(SwisSBLKey, True, False, 'Locate a Parcel', False, nil) then SetCaption; end; {LocateButtonClick} {====================================================================} Procedure TMapProximitySelectDialog.OKButtonClick(Sender: TObject); var Continue : Boolean; begin Continue := True; ProximityType := ProximityTypeRadioGroup.ItemIndex; PrintLabels := PrintLabelsCheckBox.Checked; UseAlreadySelectedParcels := UseAlreadySelectedParcelsCheckBox.Checked; try ProximityRadius := StrToFloat(ProximityRadiusEdit.Text); except Continue := False; MessageDlg('Please enter a valid number of feet for the proximity.', mtError, [mbOK], 0); end; If (Deblank(SwisSBLKey) = '') then begin Continue := False; MessageDlg('Please select a parcel to find the distance from.', mtError, [mbOK], 0); LocateButton.SetFocus; end; {If (Deblank(SwisSBLKey) = '')} If Continue then ModalResult := mrOK; end; {OKButtonClick} {====================================================================} Procedure TMapProximitySelectDialog.CancelButtonClick(Sender: TObject); begin SwisSBLKey := OriginalSwisSBLKey; ModalResult := mrCancel; end; end.
{ ****************************************************************** Unit TPMATH - Interface for TPMATH.DLL ****************************************************************** } {$DEFINE DELPHI} unit tpmath; interface {$IFDEF DELPHI} uses Graphics; {$ENDIF} { ------------------------------------------------------------------ Types and constants ------------------------------------------------------------------ } {$i types.inc} { ------------------------------------------------------------------ Error handling ------------------------------------------------------------------ } procedure SetErrCode(ErrCode : Integer); external 'tpmath'; { Sets the error code } function DefaultVal(ErrCode : Integer; DefVal : Float) : Float; external 'tpmath'; { Sets error code and default function value } function MathErr : Integer; external 'tpmath'; { Returns the error code } { ------------------------------------------------------------------ Dynamic arrays ------------------------------------------------------------------ } procedure SetAutoInit(AutoInit : Boolean); external 'tpmath'; { Sets the auto-initialization of arrays } procedure DimVector(var V : PVector; Ub : Integer); external 'tpmath'; { Creates floating point vector V[0..Ub] } procedure DimIntVector(var V : PIntVector; Ub : Integer); external 'tpmath'; { Creates integer vector V[0..Ub] } procedure DimCompVector(var V : PCompVector; Ub : Integer); external 'tpmath'; { Creates complex vector V[0..Ub] } procedure DimBoolVector(var V : PBoolVector; Ub : Integer); external 'tpmath'; { Creates boolean vector V[0..Ub] } procedure DimStrVector(var V : PStrVector; Ub : Integer); external 'tpmath'; { Creates string vector V[0..Ub] } procedure DimMatrix(var A : PMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Creates floating point matrix A[0..Ub1, 0..Ub2] } procedure DimIntMatrix(var A : PIntMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Creates integer matrix A[0..Ub1, 0..Ub2] } procedure DimCompMatrix(var A : PCompMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Creates complex matrix A[0..Ub1, 0..Ub2] } procedure DimBoolMatrix(var A : PBoolMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Creates boolean matrix A[0..Ub1, 0..Ub2] } procedure DimStrMatrix(var A : PStrMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Creates string matrix A[0..Ub1, 0..Ub2] } procedure DelVector(var V : PVector; Ub : Integer); external 'tpmath'; { Deletes floating point vector V[0..Ub] } procedure DelIntVector(var V : PIntVector; Ub : Integer); external 'tpmath'; { Deletes integer vector V[0..Ub] } procedure DelCompVector(var V : PCompVector; Ub : Integer); external 'tpmath'; { Deletes complex vector V[0..Ub] } procedure DelBoolVector(var V : PBoolVector; Ub : Integer); external 'tpmath'; { Deletes boolean vector V[0..Ub] } procedure DelStrVector(var V : PStrVector; Ub : Integer); external 'tpmath'; { Deletes string vector V[0..Ub] } procedure DelMatrix(var A : PMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Deletes floating point matrix A[0..Ub1, 0..Ub2] } procedure DelIntMatrix(var A : PIntMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Deletes integer matrix A[0..Ub1, 0..Ub2] } procedure DelCompMatrix(var A : PCompMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Deletes complex matrix A[0..Ub1, 0..Ub2] } procedure DelBoolMatrix(var A : PBoolMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Deletes boolean matrix A[0..Ub1, 0..Ub2] } procedure DelStrMatrix(var A : PStrMatrix; Ub1, Ub2 : Integer); external 'tpmath'; { Deletes string matrix A[0..Ub1, 0..Ub2] } { ------------------------------------------------------------------ Minimum, maximum, sign and exchange ------------------------------------------------------------------ } function FMin(X, Y : Float) : Float; external 'tpmath'; { Minimum of 2 reals } function FMax(X, Y : Float) : Float; external 'tpmath'; { Maximum of 2 reals } function IMin(X, Y : Integer) : Integer; external 'tpmath'; { Minimum of 2 integers } function IMax(X, Y : Integer) : Integer; external 'tpmath'; { Maximum of 2 integers } function Sgn(X : Float) : Integer; external 'tpmath'; { Sign (returns 1 if X = 0) } function Sgn0(X : Float) : Integer; external 'tpmath'; { Sign (returns 0 if X = 0) } function DSgn(A, B : Float) : Float; external 'tpmath'; { Sgn(B) * |A| } procedure FSwap(var X, Y : Float); external 'tpmath'; { Exchange 2 reals } procedure ISwap(var X, Y : Integer); external 'tpmath'; { Exchange 2 integers } { ------------------------------------------------------------------ Rounding functions ------------------------------------------------------------------ } function RoundN(X : Float; N : Integer) : Float; external 'tpmath'; { Rounds X to N decimal places } function Ceil(X : Float) : Integer; external 'tpmath'; { Ceiling function } function Floor(X : Float) : Integer; external 'tpmath'; { Floor function } { ------------------------------------------------------------------ Logarithms, exponentials and power ------------------------------------------------------------------ } function Expo(X : Float) : Float; external 'tpmath'; { Exponential } function Exp2(X : Float) : Float; external 'tpmath'; { 2^X } function Exp10(X : Float) : Float; external 'tpmath'; { 10^X } function Log(X : Float) : Float; external 'tpmath'; { Natural log } function Log2(X : Float) : Float; external 'tpmath'; { Log, base 2 } function Log10(X : Float) : Float; external 'tpmath'; { Decimal log } function LogA(X, A : Float) : Float; external 'tpmath'; { Log, base A } function IntPower(X : Float; N : Integer) : Float; external 'tpmath'; { X^N } function Power(X, Y : Float) : Float; external 'tpmath'; { X^Y, X >= 0 } { ------------------------------------------------------------------ Trigonometric functions ------------------------------------------------------------------ } function Pythag(X, Y : Float) : Float; external 'tpmath'; { Sqrt(X^2 + Y^2) } function FixAngle(Theta : Float) : Float; external 'tpmath'; { Set Theta in -Pi..Pi } function Tan(X : Float) : Float; external 'tpmath'; { Tangent } function ArcSin(X : Float) : Float; external 'tpmath'; { Arc sinus } function ArcCos(X : Float) : Float; external 'tpmath'; { Arc cosinus } function ArcTan2(Y, X : Float) : Float; external 'tpmath'; { Angle (Ox, OM) with M(X,Y) } { ------------------------------------------------------------------ Hyperbolic functions ------------------------------------------------------------------ } function Sinh(X : Float) : Float; external 'tpmath'; { Hyperbolic sine } function Cosh(X : Float) : Float; external 'tpmath'; { Hyperbolic cosine } function Tanh(X : Float) : Float; external 'tpmath'; { Hyperbolic tangent } function ArcSinh(X : Float) : Float; external 'tpmath'; { Inverse hyperbolic sine } function ArcCosh(X : Float) : Float; external 'tpmath'; { Inverse hyperbolic cosine } function ArcTanh(X : Float) : Float; external 'tpmath'; { Inverse hyperbolic tangent } procedure SinhCosh(X : Float; var SinhX, CoshX : Float); external 'tpmath'; { Sinh & Cosh } { ------------------------------------------------------------------ Gamma function and related functions ------------------------------------------------------------------ } function Fact(N : Integer) : Float; external 'tpmath'; { Factorial } function SgnGamma(X : Float) : Integer; external 'tpmath'; { Sign of Gamma function } function Gamma(X : Float) : Float; external 'tpmath'; { Gamma function } function LnGamma(X : Float) : Float; external 'tpmath'; { Logarithm of Gamma function } function Stirling(X : Float) : Float; external 'tpmath'; { Stirling's formula for the Gamma function } function StirLog(X : Float) : Float; external 'tpmath'; { Approximate Ln(Gamma) by Stirling's formula, for X >= 13 } function DiGamma(X : Float ) : Float; external 'tpmath'; { Digamma function } function TriGamma(X : Float ) : Float; external 'tpmath'; { Trigamma function } function IGamma(A, X : Float) : Float; external 'tpmath'; { Incomplete Gamma function} function JGamma(A, X : Float) : Float; external 'tpmath'; { Complement of incomplete Gamma function } function InvGamma(A, P : Float) : Float; external 'tpmath'; { Inverse of incomplete Gamma function } function Erf(X : Float) : Float; external 'tpmath'; { Error function } function Erfc(X : Float) : Float; external 'tpmath'; { Complement of error function } { ------------------------------------------------------------------ Beta function and related functions ------------------------------------------------------------------ } function Beta(X, Y : Float) : Float; external 'tpmath'; { Beta function } function IBeta(A, B, X : Float) : Float; external 'tpmath'; { Incomplete Beta function } function InvBeta(A, B, Y : Float) : Float; external 'tpmath'; { Inverse of incomplete Beta function } { ------------------------------------------------------------------ Lambert's function ------------------------------------------------------------------ } function LambertW(X : Float; UBranch, Offset : Boolean) : Float; external 'tpmath'; { ------------------------------------------------------------------ Binomial distribution ------------------------------------------------------------------ } function Binomial(N, K : Integer) : Float; external 'tpmath'; { Binomial coefficient C(N,K) } function PBinom(N : Integer; P : Float; K : Integer) : Float; external 'tpmath'; { Probability of binomial distribution } function FBinom(N : Integer; P : Float; K : Integer) : Float; external 'tpmath'; { Cumulative probability for binomial distrib. } { ------------------------------------------------------------------ Poisson distribution ------------------------------------------------------------------ } function PPoisson(Mu : Float; K : Integer) : Float; external 'tpmath'; { Probability of Poisson distribution } function FPoisson(Mu : Float; K : Integer) : Float; external 'tpmath'; { Cumulative probability for Poisson distrib. } { ------------------------------------------------------------------ Exponential distribution ------------------------------------------------------------------ } function DExpo(A, X : Float) : Float; external 'tpmath'; { Density of exponential distribution with parameter A } function FExpo(A, X : Float) : Float; external 'tpmath'; { Cumulative probability function for exponential dist. with parameter A } { ------------------------------------------------------------------ Standard normal distribution ------------------------------------------------------------------ } function DNorm(X : Float) : Float; external 'tpmath'; { Density of standard normal distribution } function FNorm(X : Float) : Float; external 'tpmath'; { Cumulative probability for standard normal distrib. } function PNorm(X : Float) : Float; external 'tpmath'; { Prob(|U| > X) for standard normal distrib. } function InvNorm(P : Float) : Float; external 'tpmath'; { Inverse of standard normal distribution } { ------------------------------------------------------------------ Student's distribution ------------------------------------------------------------------ } function DStudent(Nu : Integer; X : Float) : Float; external 'tpmath'; { Density of Student distribution with Nu d.o.f. } function FStudent(Nu : Integer; X : Float) : Float; external 'tpmath'; { Cumulative probability for Student distrib. with Nu d.o.f. } function PStudent(Nu : Integer; X : Float) : Float; external 'tpmath'; { Prob(|t| > X) for Student distrib. with Nu d.o.f. } function InvStudent(Nu : Integer; P : Float) : Float; external 'tpmath'; { Inverse of Student's t-distribution function } { ------------------------------------------------------------------ Khi-2 distribution ------------------------------------------------------------------ } function DKhi2(Nu : Integer; X : Float) : Float; external 'tpmath'; { Density of Khi-2 distribution with Nu d.o.f. } function FKhi2(Nu : Integer; X : Float) : Float; external 'tpmath'; { Cumulative prob. for Khi-2 distrib. with Nu d.o.f. } function PKhi2(Nu : Integer; X : Float) : Float; external 'tpmath'; { Prob(Khi2 > X) for Khi-2 distrib. with Nu d.o.f. } function InvKhi2(Nu : Integer; P : Float) : Float; external 'tpmath'; { Inverse of Khi-2 distribution function } { ------------------------------------------------------------------ Fisher-Snedecor distribution ------------------------------------------------------------------ } function DSnedecor(Nu1, Nu2 : Integer; X : Float) : Float; external 'tpmath'; { Density of Fisher-Snedecor distribution with Nu1 and Nu2 d.o.f. } function FSnedecor(Nu1, Nu2 : Integer; X : Float) : Float; external 'tpmath'; { Cumulative prob. for Fisher-Snedecor distrib. with Nu1 and Nu2 d.o.f. } function PSnedecor(Nu1, Nu2 : Integer; X : Float) : Float; external 'tpmath'; { Prob(F > X) for Fisher-Snedecor distrib. with Nu1 and Nu2 d.o.f. } function InvSnedecor(Nu1, Nu2 : Integer; P : Float) : Float; external 'tpmath'; { Inverse of Snedecor's F-distribution function } { ------------------------------------------------------------------ Beta distribution ------------------------------------------------------------------ } function DBeta(A, B, X : Float) : Float; external 'tpmath'; { Density of Beta distribution with parameters A and B } function FBeta(A, B, X : Float) : Float; external 'tpmath'; { Cumulative probability for Beta distrib. with param. A and B } { ------------------------------------------------------------------ Gamma distribution ------------------------------------------------------------------ } function DGamma(A, B, X : Float) : Float; external 'tpmath'; { Density of Gamma distribution with parameters A and B } function FGamma(A, B, X : Float) : Float; external 'tpmath'; { Cumulative probability for Gamma distrib. with param. A and B } { ------------------------------------------------------------------ Matrices and linear equations ------------------------------------------------------------------ } procedure GaussJordan(A : PMatrix; Lb, Ub1, Ub2 : Integer; var Det : Float); external 'tpmath'; { Transforms a matrix according to the Gauss-Jordan method } procedure LinEq(A : PMatrix; B : PVector; Lb, Ub : Integer; var Det : Float); external 'tpmath'; { Solves a linear system according to the Gauss-Jordan method } procedure Cholesky(A, L : PMatrix; Lb, Ub : Integer); external 'tpmath'; { Cholesky factorization of a positive definite symmetric matrix } procedure LU_Decomp(A : PMatrix; Lb, Ub : Integer); external 'tpmath'; { LU decomposition } procedure LU_Solve(A : PMatrix; B : PVector; Lb, Ub : Integer; X : PVector); external 'tpmath'; { Solution of linear system from LU decomposition } procedure QR_Decomp(A : PMatrix; Lb, Ub1, Ub2 : Integer; R : PMatrix); external 'tpmath'; { QR decomposition } procedure QR_Solve(Q, R : PMatrix; B : PVector; Lb, Ub1, Ub2 : Integer; X : PVector); external 'tpmath'; { Solution of linear system from QR decomposition } procedure SV_Decomp(A : PMatrix; Lb, Ub1, Ub2 : Integer; S : PVector; V : PMatrix); external 'tpmath'; { Singular value decomposition } procedure SV_SetZero(S : PVector; Lb, Ub : Integer; Tol : Float); external 'tpmath'; { Set lowest singular values to zero } procedure SV_Solve(U : PMatrix; S : PVector; V : PMatrix; B : PVector; Lb, Ub1, Ub2 : Integer; X : PVector); external 'tpmath'; { Solution of linear system from SVD } procedure SV_Approx(U : PMatrix; S : PVector; V : PMatrix; Lb, Ub1, Ub2 : Integer; A : PMatrix); external 'tpmath'; { Matrix approximation from SVD } procedure EigenVals(A : PMatrix; Lb, Ub : Integer; Lambda : PCompVector); external 'tpmath'; { Eigenvalues of a general square matrix } procedure EigenVect(A : PMatrix; Lb, Ub : Integer; Lambda : PCompVector; V : PMatrix); external 'tpmath'; { Eigenvalues and eigenvectors of a general square matrix } procedure Jacobi(A : PMatrix; Lb, Ub, MaxIter : Integer; Tol : Float; Lambda : PVector; V : PMatrix); external 'tpmath'; { Eigenvalues and eigenvectors of a symmetric matrix } { ------------------------------------------------------------------ Optimization ------------------------------------------------------------------ } procedure MinBrack(Func : TFunc; var A, B, C, Fa, Fb, Fc : Float); external 'tpmath'; { Brackets a minimum of a function } procedure GoldSearch(Func : TFunc; A, B : Float; MaxIter : Integer; Tol : Float; var Xmin, Ymin : Float); external 'tpmath'; { Minimization of a function of one variable (golden search) } procedure LinMin(Func : TFuncNVar; X, DeltaX : PVector; Lb, Ub : Integer; var R : Float; MaxIter : Integer; Tol : Float; var F_min : Float); external 'tpmath'; { Minimization of a function of several variables along a line } procedure Newton(Func : TFuncNVar; HessGrad : THessGrad; X : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; var F_min : Float; G : PVector; H_inv : PMatrix; var Det : Float); external 'tpmath'; { Minimization of a function of several variables (Newton's method) } procedure SaveNewton(FileName : string); external 'tpmath'; { Save Newton iterations in a file } procedure Marquardt(Func : TFuncNVar; HessGrad : THessGrad; X : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; var F_min : Float; G : PVector; H_inv : PMatrix; var Det : Float); external 'tpmath'; { Minimization of a function of several variables (Marquardt's method) } procedure SaveMarquardt(FileName : string); external 'tpmath'; { Save Marquardt iterations in a file } procedure BFGS(Func : TFuncNVar; Gradient : TGradient; X : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; var F_min : Float; G : PVector; H_inv : PMatrix); external 'tpmath'; { Minimization of a function of several variables (BFGS method) } procedure SaveBFGS(FileName : string); external 'tpmath'; { Save BFGS iterations in a file } procedure Simplex(Func : TFuncNVar; X : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; var F_min : Float); external 'tpmath'; { Minimization of a function of several variables (Simplex) } procedure SaveSimplex(FileName : string); external 'tpmath'; { Save Simplex iterations in a file } { ------------------------------------------------------------------ Nonlinear equations ------------------------------------------------------------------ } procedure RootBrack(Func : TFunc; var X, Y, FX, FY : Float); external 'tpmath'; { Brackets a root of function Func between X and Y } procedure Bisect(Func : TFunc; var X, Y : Float; MaxIter : Integer; Tol : Float; var F : Float); external 'tpmath'; { Bisection method } procedure Secant(Func : TFunc; var X, Y : Float; MaxIter : Integer; Tol : Float; var F : Float); external 'tpmath'; { Secant method } procedure NewtEq(Func, Deriv : TFunc; var X : Float; MaxIter : Integer; Tol : Float; var F : Float); external 'tpmath'; { Newton-Raphson method for a single nonlinear equation } procedure NewtEqs(Equations : TEquations; Jacobian : TJacobian; X, F : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float); external 'tpmath'; { Newton-Raphson method for a system of nonlinear equations } procedure Broyden(Equations : TEquations; X, F : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float); external 'tpmath'; { Broyden's method for a system of nonlinear equations } { ------------------------------------------------------------------ Polynomials and rational fractions ------------------------------------------------------------------ } function Poly(X : Float; Coef : PVector; Deg : Integer) : Float; external 'tpmath'; { Evaluates a polynomial } function RFrac(X : Float; Coef : PVector; Deg1, Deg2 : Integer) : Float; external 'tpmath'; { Evaluates a rational fraction } function RootPol1(A, B : Float; var X : Float) : Integer; external 'tpmath'; { Solves the linear equation A + B * X = 0 } function RootPol2(Coef : PVector; Z : PCompVector) : Integer; external 'tpmath'; { Solves a quadratic equation } function RootPol3(Coef : PVector; Z : PCompVector) : Integer; external 'tpmath'; { Solves a cubic equation } function RootPol4(Coef : PVector; Z : PCompVector) : Integer; external 'tpmath'; { Solves a quartic equation } function RootPol(Coef : PVector; Deg : Integer; Z : PCompVector) : Integer; external 'tpmath'; { Solves a polynomial equation } function SetRealRoots(Deg : Integer; Z : PCompVector; Tol : Float) : Integer; external 'tpmath'; { Set the imaginary part of a root to zero } procedure SortRoots(Deg : Integer; Z : PCompVector); external 'tpmath'; { Sorts the roots of a polynomial } { ------------------------------------------------------------------ Numerical integration and differential equations ------------------------------------------------------------------ } function TrapInt(X, Y : PVector; N : Integer) : Float; external 'tpmath'; { Integration by trapezoidal rule } function GausLeg(Func : TFunc; A, B : Float) : Float; external 'tpmath'; { Integral from A to B } function GausLeg0(Func : TFunc; B : Float) : Float; external 'tpmath'; { Integral from 0 to B } function Convol(Func1, Func2 : TFunc; T : Float) : Float; external 'tpmath'; { Convolution product at time T } procedure RKF45(F : TDiffEqs; Neqn : Integer; Y, Yp : PVector; var T : Float; Tout, RelErr, AbsErr : Float; var Flag : Integer); external 'tpmath'; { Integration of a system of differential equations } { ------------------------------------------------------------------ Fast Fourier Transform ------------------------------------------------------------------ } procedure FFT(NumSamples : Integer; InArray, OutArray : PCompVector); external 'tpmath'; { Fast Fourier Transform } procedure IFFT(NumSamples : Integer; InArray, OutArray : PCompVector); external 'tpmath'; { Inverse Fast Fourier Transform } procedure FFT_Integer(NumSamples : Integer; RealIn, ImagIn : PIntVector; OutArray : PCompVector); external 'tpmath'; { Fast Fourier Transform for integer data } procedure FFT_Integer_Cleanup; external 'tpmath'; { Clear memory after a call to FFT_Integer } procedure CalcFrequency(NumSamples, FrequencyIndex : Integer; InArray : PCompVector; var FFT : Complex); external 'tpmath'; { Direct computation of Fourier transform } { ------------------------------------------------------------------ Random numbers ------------------------------------------------------------------ } procedure SetRNG(RNG : RNG_Type); external 'tpmath'; { Select generator } procedure InitGen(Seed : RNG_IntType); external 'tpmath'; { Initialize generator } function IRanGen : RNG_IntType; external 'tpmath'; { 32-bit random integer in [-2^31 .. 2^31 - 1] } function IRanGen31 : RNG_IntType; external 'tpmath'; { 31-bit random integer in [0 .. 2^31 - 1] } function RanGen1 : Float; external 'tpmath'; { 32-bit random real in [0,1] } function RanGen2 : Float; external 'tpmath'; { 32-bit random real in [0,1) } function RanGen3 : Float; external 'tpmath'; { 32-bit random real in (0,1) } function RanGen53 : Float; external 'tpmath'; { 53-bit random real in [0,1) } procedure InitMWC(Seed : RNG_IntType); external 'tpmath'; { Initializes the 'Multiply with carry' random number generator } function IRanMWC : RNG_IntType; external 'tpmath'; { Returns a 32 bit random number in [-2^31 ; 2^31-1] } procedure InitMT(Seed : RNG_IntType); external 'tpmath'; { Initializes Mersenne Twister generator with a seed } procedure InitMTbyArray(InitKey : array of RNG_LongType; KeyLength : Word); external 'tpmath'; { Initialize MT generator with an array InitKey[0..(KeyLength - 1)] } function IRanMT : RNG_IntType; external 'tpmath'; { Random integer from MT generator } procedure InitUVAGbyString(KeyPhrase : string); external 'tpmath'; { Initializes the UVAG generator with a string } procedure InitUVAG(Seed : RNG_IntType); external 'tpmath'; { Initializes the UVAG generator with an integer } function IRanUVAG : RNG_IntType; external 'tpmath'; { Random integer from UVAG generator } function RanGaussStd : Float; external 'tpmath'; { Random number from standard normal distribution } function RanGauss(Mu, Sigma : Float) : Float; external 'tpmath'; { Random number from normal distrib. with mean Mu and S. D. Sigma } procedure RanMult(M : PVector; L : PMatrix; Lb, Ub : Integer; X : PVector); external 'tpmath'; { Random vector from multinormal distribution (correlated) } procedure RanMultIndep(M, S : PVector; Lb, Ub : Integer; X : PVector); external 'tpmath'; { Random vector from multinormal distribution (uncorrelated) } procedure InitMHParams(NCycles, MaxSim, SavedSim : Integer); external 'tpmath'; { Initializes Metropolis-Hastings parameters } procedure GetMHParams(var NCycles, MaxSim, SavedSim : Integer); external 'tpmath'; { Returns Metropolis-Hastings parameters } procedure Hastings(Func : TFuncNVar; T : Float; X : PVector; V : PMatrix; Lb, Ub : Integer; Xmat : PMatrix; X_min : PVector; var F_min : Float); external 'tpmath'; { Simulation of a probability density function by Metropolis-Hastings } procedure InitSAParams(NT, NS, NCycles : Integer; RT : Float); external 'tpmath'; { Initializes Simulated Annealing parameters } procedure SA_CreateLogFile(FileName : String); external 'tpmath'; { Initializes log file } procedure SimAnn(Func : TFuncNVar; X, Xmin, Xmax : PVector; Lb, Ub : Integer; var F_min : Float); external 'tpmath'; { Minimization of a function of several var. by simulated annealing } procedure InitGAParams(NP, NG : Integer; SR, MR, HR : Float); external 'tpmath'; { Initializes Genetic Algorithm parameters } procedure GA_CreateLogFile(FileName : String); external 'tpmath'; { Initializes log file } procedure GenAlg(Func : TFuncNVar; X, Xmin, Xmax : PVector; Lb, Ub : Integer; var F_min : Float); external 'tpmath'; { Minimization of a function of several var. by genetic algorithm } { ------------------------------------------------------------------ Statistics ------------------------------------------------------------------ } function Mean(X : PVector; Lb, Ub : Integer) : Float; external 'tpmath'; { Mean of sample X } function Min(X : PVector; Lb, Ub : Integer) : Float; external 'tpmath'; { Minimum of sample X } function Max(X : PVector; Lb, Ub : Integer) : Float; external 'tpmath'; { Maximum of sample X } function Median(X : PVector; Lb, Ub : Integer; Sorted : Boolean) : Float; external 'tpmath'; { Median of sample X } function StDev(X : PVector; Lb, Ub : Integer; M : Float) : Float; external 'tpmath'; { Standard deviation estimated from sample X } function StDevP(X : PVector; Lb, Ub : Integer; M : Float) : Float; external 'tpmath'; { Standard deviation of population } function Correl(X, Y : PVector; Lb, Ub : Integer) : Float; external 'tpmath'; { Correlation coefficient } function Skewness(X : PVector; Lb, Ub : Integer; M, Sigma : Float) : Float; external 'tpmath'; { Skewness of sample X } function Kurtosis(X : PVector; Lb, Ub : Integer; M, Sigma : Float) : Float; external 'tpmath'; { Kurtosis of sample X } procedure QSort(X : PVector; Lb, Ub : Integer); external 'tpmath'; { Quick sort (ascending order) } procedure DQSort(X : PVector; Lb, Ub : Integer); external 'tpmath'; { Quick sort (descending order) } procedure Interval(X1, X2 : Float; MinDiv, MaxDiv : Integer; var Min, Max, Step : Float); external 'tpmath'; { Determines an interval for a set of values } procedure AutoScale(X : PVector; Lb, Ub : Integer; Scale : TScale; var XMin, XMax, XStep : Float); external 'tpmath'; { Finds an appropriate scale for plotting the data in X[Lb..Ub] } procedure StudIndep(N1, N2 : Integer; M1, M2, S1, S2 : Float; var T : Float; var DoF : Integer); external 'tpmath'; { Student t-test for independent samples } procedure StudPaired(X, Y : PVector; Lb, Ub : Integer; var T : Float; var DoF : Integer); external 'tpmath'; { Student t-test for paired samples } procedure AnOVa1(Ns : Integer; N : PIntVector; M, S : PVector; var V_f, V_r, F : Float; var DoF_f, DoF_r : Integer); external 'tpmath'; { One-way analysis of variance } procedure AnOVa2(NA, NB, Nobs : Integer; M, S : PMatrix; V, F : PVector; DoF : PIntVector); external 'tpmath'; { Two-way analysis of variance } procedure Snedecor(N1, N2 : Integer; S1, S2 : Float; var F : Float; var DoF1, DoF2 : Integer); external 'tpmath'; { Snedecor's F-test (comparison of two variances) } procedure Bartlett(Ns : Integer; N : PIntVector; S : PVector; var Khi2 : Float; var DoF : Integer); external 'tpmath'; { Bartlett's test (comparison of several variances) } procedure Mann_Whitney(N1, N2 : Integer; X1, X2 : PVector; var U, Eps : Float); external 'tpmath'; { Mann-Whitney test} procedure Wilcoxon(X, Y : PVector; Lb, Ub : Integer; var Ndiff : Integer; var T, Eps : Float); external 'tpmath'; { Wilcoxon test } procedure Kruskal_Wallis(Ns : Integer; N : PIntVector; X : PMatrix; var H : Float; var DoF : Integer); external 'tpmath'; { Kruskal-Wallis test } procedure Khi2_Conform(N_cls : Integer; N_estim : Integer; Obs : PIntVector; Calc : PVector; var Khi2 : Float; var DoF : Integer); external 'tpmath'; { Khi-2 test for conformity } procedure Khi2_Indep(N_lin : Integer; N_col : Integer; Obs : PIntMatrix; var Khi2 : Float; var DoF : Integer); external 'tpmath'; { Khi-2 test for independence } procedure Woolf_Conform(N_cls : Integer; N_estim : Integer; Obs : PIntVector; Calc : PVector; var G : Float; var DoF : Integer); external 'tpmath'; { Woolf's test for conformity } procedure Woolf_Indep(N_lin : Integer; N_col : Integer; Obs : PIntMatrix; var G : Float; var DoF : Integer); external 'tpmath'; { Woolf's test for independence } procedure DimStatClassVector(var C : PStatClassVector; Ub : Integer); external 'tpmath'; { Allocates an array of statistical classes: C[0..Ub] } procedure DelStatClassVector(var C : PStatClassVector; Ub : Integer); external 'tpmath'; { Deallocates an array of statistical classes: C[0..Ub] } procedure Distrib(X : PVector; Lb, Ub : Integer; A, B, H : Float; C : PStatClassVector); external 'tpmath'; { Distributes an array X[Lb..Ub] into statistical classes } { ------------------------------------------------------------------ Linear / polynomial regression ------------------------------------------------------------------ } procedure LinFit(X, Y : PVector; Lb, Ub : Integer; B : PVector; V : PMatrix); external 'tpmath'; { Linear regression : Y = B(0) + B(1) * X } procedure WLinFit(X, Y, S : PVector; Lb, Ub : Integer; B : PVector; V : PMatrix); external 'tpmath'; { Weighted linear regression : Y = B(0) + B(1) * X } procedure MulFit(X : PMatrix; Y : PVector; Lb, Ub, Nvar : Integer; ConsTerm : Boolean; B : PVector; V : PMatrix); external 'tpmath'; { Multiple linear regression by Gauss-Jordan method } procedure WMulFit(X : PMatrix; Y, S : PVector; Lb, Ub, Nvar : Integer; ConsTerm : Boolean; B : PVector; V : PMatrix); external 'tpmath'; { Weighted multiple linear regression by Gauss-Jordan method } procedure SVDFit(X : PMatrix; Y : PVector; Lb, Ub, Nvar : Integer; ConsTerm : Boolean; SVDTol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Multiple linear regression by singular value decomposition } procedure WSVDFit(X : PMatrix; Y, S : PVector; Lb, Ub, Nvar : Integer; ConsTerm : Boolean; SVDTol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted multiple linear regression by singular value decomposition } procedure PolFit(X, Y : PVector; Lb, Ub, Deg : Integer; B : PVector; V : PMatrix); external 'tpmath'; { Polynomial regression by Gauss-Jordan method } procedure WPolFit(X, Y, S : PVector; Lb, Ub, Deg : Integer; B : PVector; V : PMatrix); external 'tpmath'; { Weighted polynomial regression by Gauss-Jordan method } procedure SVDPolFit(X, Y : PVector; Lb, Ub, Deg : Integer; SVDTol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted polynomial regression by singular value decomposition } procedure WSVDPolFit(X, Y, S : PVector; Lb, Ub, Deg : Integer; SVDTol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted polynomial regression by singular value decomposition } procedure RegTest(Y, Ycalc : PVector; LbY, UbY : Integer; V : PMatrix; LbV, UbV : Integer; var Test : TRegTest); external 'tpmath'; { Test of unweighted regression } procedure WRegTest(Y, Ycalc, S : PVector; LbY, UbY : Integer; V : PMatrix; LbV, UbV : Integer; var Test : TRegTest); external 'tpmath'; { Test of weighted regression } { ------------------------------------------------------------------ Nonlinear regression ------------------------------------------------------------------ } procedure SetOptAlgo(Algo : TOptAlgo); external 'tpmath'; { Sets the optimization algorithm for nonlinear regression } function GetOptAlgo : TOptAlgo; external 'tpmath'; { Returns the optimization algorithm } procedure SetMaxParam(N : Byte); external 'tpmath'; { Sets the maximum number of regression parameters for nonlinear regression } procedure SetParamBounds(I : Byte; ParamMin, ParamMax : Float); external 'tpmath'; { Sets the bounds on the I-th regression parameter } procedure NLFit(RegFunc : TRegFunc; DerivProc : TDerivProc; X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; FirstPar, LastPar : Integer; V : PMatrix); external 'tpmath'; { Unweighted nonlinear regression } procedure WNLFit(RegFunc : TRegFunc; DerivProc : TDerivProc; X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; FirstPar, LastPar : Integer; V : PMatrix); external 'tpmath'; { Weighted nonlinear regression } procedure SetMCFile(FileName : String); external 'tpmath'; { Set file for saving MCMC simulations } procedure SimFit(RegFunc : TRegFunc; X, Y : PVector; Lb, Ub : Integer; B : PVector; FirstPar, LastPar : Integer; V : PMatrix); external 'tpmath'; { Simulation of unweighted nonlinear regression by MCMC } procedure WSimFit(RegFunc : TRegFunc; X, Y, S : PVector; Lb, Ub : Integer; B : PVector; FirstPar, LastPar : Integer; V : PMatrix); external 'tpmath'; { Simulation of weighted nonlinear regression by MCMC } { ------------------------------------------------------------------ Nonlinear regression models ------------------------------------------------------------------ } procedure FracFit(X, Y : PVector; Lb, Ub : Integer; Deg1, Deg2 : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of rational fraction } procedure WFracFit(X, Y, S : PVector; Lb, Ub : Integer; Deg1, Deg2 : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of rational fraction } function FracFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the rational fraction at point X } procedure ExpFit(X, Y : PVector; Lb, Ub, Nexp : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of sum of exponentials } procedure WExpFit(X, Y, S : PVector; Lb, Ub, Nexp : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of sum of exponentials } function ExpFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the regression function at point X } procedure IncExpFit(X, Y : PVector; Lb, Ub : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of model of increasing exponential } procedure WIncExpFit(X, Y, S : PVector; Lb, Ub : Integer; ConsTerm : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of increasing exponential } function IncExpFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the regression function at point X } procedure ExpLinFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of the "exponential + linear" model } procedure WExpLinFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of the "exponential + linear" model } function ExpLinFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the regression function at point X } procedure MichFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of Michaelis equation } procedure WMichFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of Michaelis equation } function MichFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the Michaelis equation at point X } procedure MintFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of the integrated Michaelis equation } procedure WMintFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of the integrated Michaelis equation } function MintFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the integrated Michaelis equation at point X } procedure HillFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of Hill equation } procedure WHillFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of Hill equation } function HillFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the Hill equation at point X } procedure LogiFit(X, Y : PVector; Lb, Ub : Integer; ConsTerm : Boolean; General : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of logistic function } procedure WLogiFit(X, Y, S : PVector; Lb, Ub : Integer; ConsTerm : Boolean; General : Boolean; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of logistic function } function LogiFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the logistic function at point X } procedure PKFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of the acid-base titration curve } procedure WPKFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of the acid-base titration curve } function PKFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the acid-base titration function at point X } procedure PowFit(X, Y : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Unweighted fit of power function } procedure WPowFit(X, Y, S : PVector; Lb, Ub : Integer; MaxIter : Integer; Tol : Float; B : PVector; V : PMatrix); external 'tpmath'; { Weighted fit of power function } function PowFit_Func(X : Float; B : PVector) : Float; external 'tpmath'; { Returns the value of the power function at point X } { ------------------------------------------------------------------ Principal component analysis ------------------------------------------------------------------ } procedure VecMean(X : PMatrix; Lb, Ub, Nvar : Integer; M : PVector); external 'tpmath'; { Computes the mean vector M from matrix X } procedure VecSD(X : PMatrix; Lb, Ub, Nvar : Integer; M, S : PVector); external 'tpmath'; { Computes the vector of standard deviations S from matrix X } procedure MatVarCov(X : PMatrix; Lb, Ub, Nvar : Integer; M : PVector; V : PMatrix); external 'tpmath'; { Computes the variance-covariance matrix V from matrix X } procedure MatCorrel(V : PMatrix; Nvar : Integer; R : PMatrix); external 'tpmath'; { Computes the correlation matrix R from the var-cov matrix V } procedure PCA(R : PMatrix; Nvar : Integer; MaxIter : Integer; Tol : Float; Lambda : PVector; C, Rc : PMatrix); external 'tpmath'; { Performs a principal component analysis of the correlation matrix R } procedure ScaleVar(X : PMatrix; Lb, Ub, Nvar : Integer; M, S : PVector; Z : PMatrix); external 'tpmath'; { Scales a set of variables by subtracting means and dividing by SD's } procedure PrinFac(Z : PMatrix; Lb, Ub, Nvar : Integer; C, F : PMatrix); external 'tpmath'; { Computes principal factors } { ------------------------------------------------------------------ Strings ------------------------------------------------------------------ } function LTrim(S : String) : String; external 'tpmath'; { Removes leading blanks } function RTrim(S : String) : String; external 'tpmath'; { Removes trailing blanks } function Trim(S : String) : String; external 'tpmath'; { Removes leading and trailing blanks } function StrChar(N : Byte; C : Char) : String; external 'tpmath'; { Returns a string made of character C repeated N times } function RFill(S : String; L : Byte) : String; external 'tpmath'; { Completes string S with trailing blanks for a total length L } function LFill(S : String; L : Byte) : String; external 'tpmath'; { Completes string S with leading blanks for a total length L } function CFill(S : String; L : Byte) : String; external 'tpmath'; { Centers string S on a total length L } function Replace(S : String; C1, C2 : Char) : String; external 'tpmath'; { Replaces in string S all the occurences of C1 by C2 } function Extract(S : String; var Index : Byte; Delim : Char) : String; external 'tpmath'; { Extracts a field from a string } procedure Parse(S : String; Delim : Char; Field : PStrVector; var N : Byte); external 'tpmath'; { Parses a string into its constitutive fields } procedure SetFormat(NumLength, MaxDec : Integer; FloatPoint, NSZero : Boolean); external 'tpmath'; { Sets the numeric format } function FloatStr(X : Float) : String; external 'tpmath'; { Converts a real to a string according to the numeric format } function IntStr(N : LongInt) : String; external 'tpmath'; { Converts an integer to a string } function CompStr(Z : Complex) : String; external 'tpmath'; { Converts a complex number to a string } { ------------------------------------------------------------------ BGI / Delphi graphics ------------------------------------------------------------------ } function InitGraphics {$IFDEF DELPHI} (Width, Height : Integer) : Boolean; {$ELSE} (Pilot, Mode : Integer; BGIPath : String) : Boolean; {$ENDIF} external 'tpmath'; { Enters graphic mode } procedure SetWindow({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} X1, X2, Y1, Y2 : Integer; GraphBorder : Boolean); external 'tpmath'; { Sets the graphic window } procedure SetOxScale(Scale : TScale; OxMin, OxMax, OxStep : Float); external 'tpmath'; { Sets the scale on the Ox axis } procedure SetOyScale(Scale : TScale; OyMin, OyMax, OyStep : Float); external 'tpmath'; { Sets the scale on the Oy axis } procedure SetGraphTitle(Title : String); external 'tpmath'; { Sets the title for the graph } procedure SetOxTitle(Title : String); external 'tpmath'; { Sets the title for the Ox axis } procedure SetOyTitle(Title : String); external 'tpmath'; { Sets the title for the Oy axis } {$IFNDEF DELPHI} procedure SetTitleFont(FontIndex, Width, Height : Integer); external 'tpmath'; { Sets the font for the main graph title } procedure SetOxFont(FontIndex, Width, Height : Integer); external 'tpmath'; { Sets the font for the Ox axis (title and labels) } procedure SetOyFont(FontIndex, Width, Height : Integer); external 'tpmath'; { Sets the font for the Oy axis (title and labels) } procedure SetLgdFont(FontIndex, Width, Height : Integer); external 'tpmath'; { Sets the font for the legends } procedure SetClipping(Clip : Boolean); external 'tpmath'; { Determines whether drawings are clipped at the current viewport boundaries, according to the value of the Boolean parameter Clip } {$ENDIF} procedure PlotOxAxis{$IFDEF DELPHI}(Canvas : TCanvas){$ENDIF}; external 'tpmath'; { Plots the horizontal axis } procedure PlotOyAxis{$IFDEF DELPHI}(Canvas : TCanvas){$ENDIF}; external 'tpmath'; { Plots the vertical axis } procedure PlotGrid({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} Grid : TGrid); external 'tpmath'; { Plots a grid on the graph } procedure WriteGraphTitle{$IFDEF DELPHI}(Canvas : TCanvas){$ENDIF}; external 'tpmath'; { Writes the title of the graph } procedure SetMaxCurv(NCurv : Byte); external 'tpmath'; { Sets the maximum number of curves and re-initializes their parameters } procedure SetPointParam {$IFDEF DELPHI} (CurvIndex, Symbol, Size : Integer; Color : TColor); {$ELSE} (CurvIndex, Symbol, Size, Color : Integer); {$ENDIF} external 'tpmath'; { Sets the point parameters for curve # CurvIndex } procedure SetLineParam {$IFDEF DELPHI} (CurvIndex : Integer; Style : TPenStyle; Width : Integer; Color : TColor); {$ELSE} (CurvIndex, Style, Width, Color : Integer); {$ENDIF} external 'tpmath'; { Sets the line parameters for curve # CurvIndex } procedure SetCurvLegend(CurvIndex : Integer; Legend : String); external 'tpmath'; { Sets the legend for curve # CurvIndex } procedure SetCurvStep(CurvIndex, Step : Integer); external 'tpmath'; { Sets the step for curve # CurvIndex } {$IFDEF DELPHI} procedure PlotPoint(Canvas : TCanvas; X, Y : Float; CurvIndex : Integer); external 'tpmath'; {$ELSE} procedure PlotPoint(Xp, Yp, CurvIndex : Integer); external 'tpmath'; {$ENDIF} { Plots a point on the screen } procedure PlotCurve({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} X, Y : PVector; Lb, Ub, CurvIndex : Integer); external 'tpmath'; { Plots a curve } procedure PlotCurveWithErrorBars({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} X, Y, S : PVector; Ns, Lb, Ub, CurvIndex : Integer); external 'tpmath'; { Plots a curve with error bars } procedure PlotFunc({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} Func : TFunc; Xmin, Xmax : Float; {$IFDEF DELPHI}Npt : Integer;{$ENDIF} CurvIndex : Integer); external 'tpmath'; { Plots a function } procedure WriteLegend({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} NCurv : Integer; ShowPoints, ShowLines : Boolean); external 'tpmath'; { Writes the legends for the plotted curves } procedure ConRec({$IFDEF DELPHI}Canvas : TCanvas;{$ENDIF} Nx, Ny, Nc : Integer; X, Y, Z : PVector; F : PMatrix); external 'tpmath'; { Contour plot } function Xpixel(X : Float) : Integer; external 'tpmath'; { Converts user abscissa X to screen coordinate } function Ypixel(Y : Float) : Integer; external 'tpmath'; { Converts user ordinate Y to screen coordinate } function Xuser(X : Integer) : Float; external 'tpmath'; { Converts screen coordinate X to user abscissa } function Yuser(Y : Integer) : Float; external 'tpmath'; { Converts screen coordinate Y to user ordinate } procedure LeaveGraphics; external 'tpmath'; { Quits graphic mode } { ------------------------------------------------------------------ LaTeX graphics ------------------------------------------------------------------ } function TeX_InitGraphics(FileName : String; PgWidth, PgHeight : Integer; Header : Boolean) : Boolean; external 'tpmath'; { Initializes the LaTeX file } procedure TeX_SetWindow(X1, X2, Y1, Y2 : Integer; GraphBorder : Boolean); external 'tpmath'; { Sets the graphic window } procedure TeX_LeaveGraphics(Footer : Boolean); external 'tpmath'; { Close the LaTeX file } procedure TeX_SetOxScale(Scale : TScale; OxMin, OxMax, OxStep : Float); external 'tpmath'; { Sets the scale on the Ox axis } procedure TeX_SetOyScale(Scale : TScale; OyMin, OyMax, OyStep : Float); external 'tpmath'; { Sets the scale on the Oy axis } procedure TeX_SetGraphTitle(Title : String); external 'tpmath'; { Sets the title for the graph } procedure TeX_SetOxTitle(Title : String); external 'tpmath'; { Sets the title for the Ox axis } procedure TeX_SetOyTitle(Title : String); external 'tpmath'; { Sets the title for the Oy axis } procedure TeX_PlotOxAxis; external 'tpmath'; { Plots the horizontal axis } procedure TeX_PlotOyAxis; external 'tpmath'; { Plots the vertical axis } procedure TeX_PlotGrid(Grid : TGrid); external 'tpmath'; { Plots a grid on the graph } procedure TeX_WriteGraphTitle; external 'tpmath'; { Writes the title of the graph } procedure TeX_SetMaxCurv(NCurv : Byte); external 'tpmath'; { Sets the maximum number of curves and re-initializes their parameters } procedure TeX_SetPointParam(CurvIndex, Symbol, Size : Integer); external 'tpmath'; { Sets the point parameters for curve # CurvIndex } procedure TeX_SetLineParam(CurvIndex, Style : Integer; Width : Float; Smooth : Boolean); external 'tpmath'; { Sets the line parameters for curve # CurvIndex } procedure TeX_SetCurvLegend(CurvIndex : Integer; Legend : String); external 'tpmath'; { Sets the legend for curve # CurvIndex } procedure TeX_SetCurvStep(CurvIndex, Step : Integer); external 'tpmath'; { Sets the step for curve # CurvIndex } procedure TeX_PlotCurve(X, Y : PVector; Lb, Ub, CurvIndex : Integer); external 'tpmath'; { Plots a curve } procedure TeX_PlotCurveWithErrorBars(X, Y, S : PVector; Ns, Lb, Ub, CurvIndex : Integer); external 'tpmath'; { Plots a curve with error bars } procedure TeX_PlotFunc(Func : TFunc; X1, X2 : Float; Npt : Integer; CurvIndex : Integer); external 'tpmath'; { Plots a function } procedure TeX_WriteLegend(NCurv : Integer; ShowPoints, ShowLines : Boolean); external 'tpmath'; { Writes the legends for the plotted curves } procedure TeX_ConRec(Nx, Ny, Nc : Integer; X, Y, Z : PVector; F : PMatrix); external 'tpmath'; { Contour plot } function Xcm(X : Float) : Float; external 'tpmath'; { Converts user coordinate X to cm } function Ycm(Y : Float) : Float; external 'tpmath'; { Converts user coordinate Y to cm } implementation end.
{(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is frObfuscateSettings.pas, released April 2000. 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 ------------------------------------------------------------------------------*) {*)} unit frObfuscateSettings; {$I JcfGlobal.inc} interface uses { delphi } Classes, Controls, Forms, StdCtrls, ExtCtrls, { local } frmBaseSettingsFrame; type TfObfuscateSettings = class(TfrSettingsFrame) cbRemoveWhiteSpace: TCheckBox; cbRemoveComments: TCheckBox; rgObfuscateCaps: TRadioGroup; cbRebreak: TCheckBox; cbRemoveIndent: TCheckBox; cbEnabled: TCheckBox; private public constructor Create(AOwner: TComponent); override; procedure Read; override; procedure Write; override; end; implementation {$ifdef FPC} {$R *.lfm} {$else} {$R *.dfm} {$endif} uses JcfSettings, SettingsTypes, JcfHelp, SetObfuscate; { TfObfuscateSettings } constructor TfObfuscateSettings.Create(AOwner: TComponent); begin inherited; fiHelpContext := HELP_OBFUSCATE_SETTINGS; end; procedure TfObfuscateSettings.Read; begin with JcfFormatSettings.Obfuscate do begin cbEnabled.Checked := Enabled; rgObfuscateCaps.ItemIndex := Ord(Caps); cbRemoveWhiteSpace.Checked := RemoveWhiteSpace; cbRemoveComments.Checked := RemoveComments; cbRemoveIndent.Checked := RemoveIndent; cbRebreak.Checked := RebreakLines; end; end; procedure TfObfuscateSettings.Write; begin with JcfFormatSettings.Obfuscate do begin Enabled := cbEnabled.Checked; Caps := TCapitalisationType(rgObfuscateCaps.ItemIndex); RemoveWhiteSpace := cbRemoveWhiteSpace.Checked; RemoveComments := cbRemoveComments.Checked; RemoveIndent := CbRemoveIndent.Checked; RebreakLines := cbRebreak.Checked; end; end; end.
unit USerialize; interface uses Classes, Variants; { 序列化TComponent } procedure SerializeComponent(obj: TComponent; Stream: TStream); { 反序列化TComponent } procedure UnSerializeComponent(obj: TComponent; Stream: TStream); { Component、Stream互转,转换前后均会置Stream.Position := 0 } procedure Component2Stream(obj: TComponent; Stream: TStream); overload; function Component2Stream(obj: TComponent): TStream; overload; procedure Stream2Component(Stream: TStream; obj: TComponent); overload; function Stream2Component(Stream: TStream): TComponent; overload; { Component、OleVariant互转,使用Stream作中介 } procedure Component2Ole(obj: TComponent; out aOleValue: OleVariant); overload; function Component2Ole(obj: TComponent): OleVariant; overload; procedure Ole2Component(aOleValue: OleVariant; obj: TComponent); overload; function Ole2Component(aOleValue: OleVariant): TComponent; overload; { OleVariant、Stream互转,转换前后均会置Stream.Position := 0 } procedure Ole2Stream(aOleValue: OleVariant; Stream: TStream); overload; function Ole2Stream(aOleValue: OleVariant): TStream; overload; procedure Stream2Ole(Stream: TStream; out aOleValue: OleVariant); overload; function Stream2Ole(Stream: TStream): OleVariant; overload; { Stream、Buffer互转,功能简单,主要是封装ReadBuffer、WriteBuffer } procedure Stream2Buffer(Stream: TStream; Buffer: PChar); overload; function Stream2Buffer(Stream: TStream): PChar; overload; procedure Stream2Buffer(Stream: TStream; out Buffer: PChar; out BufferLen: Integer); overload; procedure Buffer2Stream(Buffer: PChar; BufferLen: Integer; Stream: TStream); overload; function Buffer2Stream(Buffer: PChar; BufferLen: Integer): TStream; overload; { Component、Buffer互转,使用Stream作中介 } procedure Component2Buffer(obj: TComponent; out Buffer: PChar; out BufferLen: Integer); procedure Buffer2Component(Buffer: PChar; BufferLen: Integer; obj: TComponent); overload; function Buffer2Component(Buffer: PChar; BufferLen: Integer): TComponent; overload; function VarArrayFromStrings(Strings: TStrings): Variant; implementation procedure SerializeComponent(obj: TComponent; Stream: TStream); begin Component2Stream(obj, Stream); end; procedure UnSerializeComponent(obj: TComponent; Stream: TStream); begin Stream2Component(Stream, obj); end; procedure Component2Stream(obj: TComponent; Stream: TStream); begin Stream.Position := 0; Stream.WriteComponent(obj); Stream.Position := 0; end; function Component2Stream(obj: TComponent): TStream; begin Result := TMemoryStream.Create; Component2Stream(obj, Result); end; procedure Stream2Component(Stream: TStream; obj: TComponent); var objTmp: TComponent; objClass: TComponentClass; begin objClass := TComponentClass(obj.ClassType); objTmp := objClass.Create(nil); try Stream.Position := 0; try Stream.ReadComponent(objTmp); obj.Assign(objTmp); except raise ; end; Stream.Position := 0; finally objTmp.Free; end; end; function Stream2Component(Stream: TStream): TComponent; begin Stream.Position := 0; Result := TComponent(Stream.ReadComponent(nil)); Stream.Position := 0; end; procedure Component2Ole(obj: TComponent; out aOleValue: OleVariant); var msTmp: TMemoryStream; begin msTmp := TMemoryStream.Create; try Component2Stream(obj, msTmp); Stream2Ole(msTmp, aOleValue); finally msTmp.Free; end; end; function Component2Ole(obj: TComponent): OleVariant; begin Component2Ole(obj, Result); end; procedure Ole2Component(aOleValue: OleVariant; obj: TComponent); var objTmp: TComponent; begin objTmp := Ole2Component(aOleValue); try obj.Assign(objTmp); finally objTmp.Free; end; end; function Ole2Component(aOleValue: OleVariant): TComponent; var Stream: TStream; begin Stream := Ole2Stream(aOleValue); try Result := Stream2Component(Stream); finally Stream.Free; end; end; procedure Ole2Stream(aOleValue: OleVariant; Stream: TStream); var MyBuffer: Pointer; Size: Integer; begin if Stream is TMemoryStream then TMemoryStream(Stream).Clear; Stream.Position := 0; Size := VarArrayHighBound(aOleValue, 1) - VarArrayLowBound(aOleValue, 1) + 1; MyBuffer := VarArrayLock(aOleValue); Stream.WriteBuffer(MyBuffer^, Size); VarArrayUnlock(aOleValue); Stream.Position := 0; end; function Ole2Stream(aOleValue: OleVariant): TStream; begin Result := TMemoryStream.Create; Ole2Stream(aOleValue, Result); end; procedure Stream2Ole(Stream: TStream; out aOleValue: OleVariant); var MyBuffer: Pointer; begin Stream.Position := 0; aOleValue := VarArrayCreate([0, Stream.Size - 1], VarByte); MyBuffer := VarArrayLock(aOleValue); Stream.ReadBuffer(MyBuffer^, Stream.Size); VarArrayUnlock(aOleValue); Stream.Position := 0; end; function Stream2Ole(Stream: TStream): OleVariant; begin Stream2Ole(Stream, Result); end; procedure Stream2Buffer(Stream: TStream; Buffer: PChar); begin Stream.ReadBuffer(Buffer^, Stream.Size); Stream.Position := 0; end; function Stream2Buffer(Stream: TStream): PChar; begin Result := AllocMem(Stream.Size); Stream2Buffer(Stream, Result); end; procedure Stream2Buffer(Stream: TStream; out Buffer: PChar; out BufferLen: Integer); begin BufferLen := Stream.Size; Buffer := AllocMem(BufferLen); Stream2Buffer(Stream, Buffer); end; procedure Buffer2Stream(Buffer: PChar; BufferLen: Integer; Stream: TStream); begin Stream.WriteBuffer(Buffer^, BufferLen); Stream.Position := 0; end; function Buffer2Stream(Buffer: PChar; BufferLen: Integer): TStream; begin Result := TMemoryStream.Create; Buffer2Stream(Buffer, BufferLen, Result); end; procedure Component2Buffer(obj: TComponent; out Buffer: PChar; out BufferLen: Integer); var Stream: TStream; begin Stream := Component2Stream(obj); try Stream2Buffer(Stream, Buffer, BufferLen); finally Stream.Free; end; end; procedure Buffer2Component(Buffer: PChar; BufferLen: Integer; obj: TComponent); var objTmp: TComponent; begin objTmp := Buffer2Component(Buffer, BufferLen); try obj.Assign(objTmp); finally objTmp.Free; end; end; function Buffer2Component(Buffer: PChar; BufferLen: Integer): TComponent; var Stream: TStream; begin Stream := Buffer2Stream(Buffer, BufferLen); try Result := Stream2Component(Stream); finally Stream.Free; end; end; function VarArrayFromStrings(Strings: TStrings): Variant; var I: Integer; begin Result := Null; if Strings.Count > 0 then begin Result := VarArrayCreate([0, Strings.Count - 1], varOleStr); for I := 0 to Strings.Count - 1 do Result[I] := WideString(Strings[I]); end; end; end.
unit UI.ConsoleUI; interface uses System.SysUtils, System.Classes, App.Types, App.Abstractions, App.Meta, App.IHandlerCore, UI.Abstractions, UI.ParserCommand, UI.GUI, UI.Types; type TConsoleUI = class(TBaseUI) private {Fields} fversion: string; isTerminate: boolean; {Instances} parser: TCommandsParser; public procedure DoRun; procedure DoTerminate; procedure RunCommand(Data: TCommandData); constructor Create; destructor Destroy; override; end; implementation {$REGION 'TConsoleUI'} constructor TConsoleUI.Create; begin isTerminate := False; parser := TCommandsParser.Create; end; destructor TConsoleUI.Destroy; begin Parser.Free; inherited; end; procedure TConsoleUI.RunCommand(Data: TCommandData); begin case Data.CommandName of TCommandsNames.help: begin try case TCommandsNames.AsCommand(Data.Parametrs[0].Name) of TCommandsNames.node: begin ShowMessage('INFO: Node - command for work with node app.'); end; end; except ShowMessage('INFO: Incorrect parametrs.'); end; end; TCommandsNames.node: begin end; TCommandsNames.check: begin ShowMessage('ECHO: check'); end; TCommandsNames.update: begin //need updatecore end; TCommandsNames.quit: begin isTerminate := True; end; TCommandsNames.createwallet: begin handler.HandleCommand(CMD_CREATE_WALLET, data.Parametrs.AsStringArray); end; TCommandsNames.openwallet: begin handler.HandleCommand(CMD_OPEN_WALLET,data.Parametrs.AsStringArray) end; TCommandsNames.getwalletlist: begin handler.HandleCommand(CMD_GET_WALLETS,data.Parametrs.AsStringArray); end; end; end; procedure TConsoleUI.DoRun; var inputString: string; args: strings; begin TThread.CreateAnonymousThread(procedure begin Writeln(GetTextGreeting(English)); Writeln(Carriage); Writeln(GetTextRequestForInput(English)); while not isTerminate do begin readln(inputString); if length(trim(inputString)) = 0 then Continue; args.SetStrings(inputString); RunCommand(parser.TryParse(args)); end; end).Start; Handler.HandleCommand(255,[]); while not isTerminate do begin CheckSynchronize(100); end; end; procedure TConsoleUI.DoTerminate; begin isTerminate := True; end; {$ENDREGION} end.
{ Some text file tricks. Copyright (C) 2002-2005 Free Software Foundation, Inc. Author: Frank Heckenbach <frank@pascal.gnu.de> This file is part of GNU Pascal. GNU Pascal 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, or (at your option) any later version. GNU Pascal is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Pascal; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, if you link this file with files compiled with a GNU compiler to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. } {$gnu-pascal,I-} {$if __GPC_RELEASE__ < 20030412} {$error This unit requires GPC release 20030412 or newer.} {$endif} unit TFDD; interface uses GPC; { Write to multiple files. Everything written to Dest after calling this procedure will be written to both File1 and File2. Can be chained. } procedure MultiFileWrite (var Dest, File1, File2: AnyFile); implementation type TMultiFileWritePrivateData = record f1, f2: ^AnyFile; end; function MultiFileWriteWrite (var PrivateData; const Buffer; Size: SizeType): SizeType; var Data: TMultiFileWritePrivateData absolute PrivateData; CharBuf: array [1 .. Size] of Char absolute Buffer; begin BlockWrite (Data.f1^, CharBuf, Size); BlockWrite (Data.f2^, CharBuf, Size); MultiFileWriteWrite := Size end; procedure MultiFileWriteFlush (var PrivateData); var Data: TMultiFileWritePrivateData absolute PrivateData; begin Flush (Data.f1^); Flush (Data.f2^) end; procedure MultiFileWriteDone (var PrivateData); begin Dispose (@PrivateData) end; procedure MultiFileWrite (var Dest, File1, File2: AnyFile); var Data: ^TMultiFileWritePrivateData; begin SetReturnAddress (ReturnAddress (0)); New (Data); Data^.f1 := @File1; Data^.f2 := @File2; AssignTFDD (Dest, nil, nil, nil, nil, MultiFileWriteWrite, MultiFileWriteFlush, nil, MultiFileWriteDone, Data); Rewrite (Dest); RestoreReturnAddress end; end.
unit AAbertura; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ExtCtrls, StdCtrls, Componentes1, LabelCorMove; type TFAbertura = class(TFormularioPermissao) Image1: TImage; Label3D1: TLabel3D; ESerie: TEditColor; Label3D2: TLabel3D; ESenha: TEditColor; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } VprTentativas : Integer; function RetornaSerie : String; function ValidaSenha : Boolean; function RetornaSenha(VpaSerie : String) :String; public { Public declarations } VplCancelado : Boolean; end; var FAbertura: TFAbertura; implementation {$R *.DFM} Uses FunValida, FunHardware, ConstMsg, FunString,FunData; { ****************** Na criação do Formulário ******************************** } procedure TFAbertura.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } Brush.Style:=bsClear; BorderStyle:=bsNone; VplCancelado := True; VprTentativas := 0; ESerie.Text := RetornaSerie; end; { ******************* Quando o formulario e fechado ************************** } procedure TFAbertura.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos diversos )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************* rentorna o numero de serie *******************************} function TFAbertura.RetornaSerie : String; var VprDataBios, VprData, VprHora : String; begin VprData := FormatDateTime('DD/MM/YYYY',(Date)); VprHora := FormatDateTime('hh:mm:ss',Time); VprDataBios := DataBios; Result := Copy(VprData,1,1)+ Copy(VprDataBios,2,1)+ Copy(VprHora,7,1)+ Copy(VprData,2,1)+ Copy(VprHora,8,1)+ Copy(VprHora,4,1)+Copy(VprHora,5,1); end; {************************ valida a senha **************************************} function TFAbertura.ValidaSenha : Boolean; var VpfStringAux : String; begin VpfStringAux := RetornaSenha(ESerie.Text); if ESenha.Text = VpfStringAux Then result := true else begin Result := false; inc(VprTentativas); erro('Senha Inválida....'); end; if Vprtentativas >= 3 Then Close; end; {************ retorna a senha da serie passada como parametro *****************} function TFAbertura.RetornaSenha(VpaSerie : String) :String; begin result := IntTostr(StrToInt(copy(VpaSerie,length(VpaSerie),1))+1)+ IntTostr(StrToInt(copy(VpaSerie,1,1))+1)+ AdicionaCharE('0',IntToStr(Mes(Date)),2) + IntTostr(StrToInt(copy(VpaSerie,length(VpaSerie)-1,1))+2)+ IntTostr(StrToInt(copy(VpaSerie,2,1))+2) ; end; {******************** verifica as teclas pressionadas *************************} procedure TFAbertura.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Case key of 27 : Close; 13 : if ValidaSenha then begin VplCancelado := false; close; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFAbertura]); end.
{ CTU Open Contest 2002 ===================== Sample solution for the problem: battle Martin Kacer, Oct 2002 } Program Battle; Const MAXSIZE = 10000; chShip = '#'; chWater = '.'; Type TRow = Array [0..MAXSIZE+1] of Char; Var Row1, Row2 : TRow; SizeX, SizeY : Integer; IsValid : Boolean; ShipCnt : Integer; {compare two successive rows} Procedure CompareRows; Var I: Integer; Begin I := 1; While (I <= SizeY) do Begin If (Row1[I] <> Row2[I]) then Begin If (Row1[I-1] = chShip) or (Row2[I-1] = chShip) then IsValid := false; If (Row1[I] = chShip) then Begin Repeat Inc (I); If (Row2[I] = chShip) then IsValid := false; until (Row1[I] <> chShip) End else Begin Inc (ShipCnt); Repeat Inc (I); If (Row1[I] = chShip) then IsValid := false; until (Row2[I] <> chShip); End; End; Inc (I); End; End; {read the whole field and compare every two rows} Procedure ReadAll; Var X, Y: Integer; Begin For Y := 0 to SizeY+1 do Row1[Y] := chWater; Row2[0] := chWater; Row2[SizeY+1] := chWater; For X := 1 to SizeX do Begin For Y := 1 to SizeY do Read (Row2[Y]); ReadLn; CompareRows; Row1 := Row2; End; End; Begin Repeat ReadLn (SizeX, SizeY); If (SizeX > 0) then Begin ShipCnt := 0; IsValid := true; ReadAll; If IsValid then WriteLn ('There are ', ShipCnt, ' ships.') else WriteLn ('Bad placement.'); End; until (SizeX = 0); End.
unit TravelAgents; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr; type TTravelAgents = class public Id: string; Login: string; Password: string; Procedure AddAgent(Id, Login, Password: string); function ConnectToDb: TSQLConnection; procedure SelectUserTravel(Password: string); function LogInCheck(name, Password: string): Boolean; procedure UserRegistration(Item: TTravelAgents); function CheckUser(name: string): Boolean; procedure AddUserInDb; end; implementation { TTravelAgents } procedure TTravelAgents.AddAgent(Id, Login, Password: string); var Item: TTravelAgents; begin Item.Id := Id; Item.Login := Login; Item.Password := Password; end; procedure TTravelAgents.AddUserInDb; var query: String; querity: TSQLQuery; connect: TSQLConnection; Guid: TGUID; begin connect := ConnectToDb; querity := TSQLQuery.Create(nil); try querity.SQLConnection := connect; query := 'INSERT INTO TravelAgents (Id,Login,Password) VALUES (:Id,:Login,:Password)'; CreateGUID(Guid); querity.Params.CreateParam(TFieldType.ftString, 'Id', ptInput); querity.Params.ParamByName('Id').AsString := GUIDToString(Guid); querity.Params.CreateParam(TFieldType.ftString, 'Login', ptInput); querity.Params.ParamByName('Login').AsString := self.Login; querity.Params.CreateParam(TFieldType.ftString, 'Password', ptInput); querity.Params.ParamByName('Password').AsString := self.Password; querity.SQL.Text := query; querity.ExecSQL(); finally FreeAndNil(querity); end; FreeAndNil(connect); end; function TTravelAgents.CheckUser(name: string): Boolean; var connect: TSQLConnection; query: TSQLQuery; begin connect := ConnectToDb; query := TSQLQuery.Create(nil); try query.SQLConnection := connect; query.SQL.Text := 'select Login from TravelAgents where Login = "' + Name + '"'; query.Open; if query.Eof then begin result := false; connect.Close; end else begin result := true; connect.Close; end; finally FreeAndNil(query); end; FreeAndNil(connect); end; function TTravelAgents.ConnectToDb: TSQLConnection; var ASQLConnection: TSQLConnection; Path: string; begin ASQLConnection := TSQLConnection.Create(nil); ASQLConnection.ConnectionName := 'SQLITECONNECTION'; ASQLConnection.DriverName := 'Sqlite'; ASQLConnection.LoginPrompt := false; ASQLConnection.Params.Values['Host'] := 'localhost'; ASQLConnection.Params.Values['FailIfMissing'] := 'False'; ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False'; Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb')); Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db'; ASQLConnection.Params.Values['Database'] := Path; ASQLConnection.Execute('CREATE TABLE if not exists TravelAgents(' + 'Id TEXT,' + 'Login TEXT,' + 'Password TEXT' + ');', nil); ASQLConnection.Open; result := ASQLConnection; end; function TTravelAgents.LogInCheck(name, Password: string): Boolean; var ASQLConnection: TSQLConnection; connect: TSQLQuery; query: string; i, j: integer; begin i := 0; j := 0; ASQLConnection := ConnectToDb; connect := TSQLQuery.Create(nil); try connect.SQLConnection := ASQLConnection; connect.SQL.Text := 'select Login from TravelAgents where Login = "' + name + '"'; connect.Open; if not connect.Eof then i := 1; connect.Close; connect.SQL.Text := 'select Password from TravelAgents where Password = "' + Password + '"'; connect.Open; if not connect.Eof then j := 1; connect.Close; if (i + j) = 2 then result := true else result := false; finally FreeAndNil(connect); end; FreeAndNil(ASQLConnection); end; procedure TTravelAgents.SelectUserTravel(Password: string); begin end; procedure TTravelAgents.UserRegistration(Item: TTravelAgents); var DB: TSQLConnection; Params: TParams; query: string; begin query := 'INSERT INTO TravelAgents (Id,Login,Password) VALUES (:Id,:Login,:Password)'; DB := ConnectToDb; try Params := TParams.Create; Params.CreateParam(TFieldType.ftString, 'id', ptInput); Params.ParamByName('id').AsString := Item.Id; Params.CreateParam(TFieldType.ftString, 'Login', ptInput); Params.ParamByName('Login').AsString := Item.Login; Params.CreateParam(TFieldType.ftString, 'Password', ptInput); Params.ParamByName('Password').AsString := Item.Password; DB.Execute(query, Params); FreeAndNil(Params); finally FreeAndNil(DB); end; end; end.