text
stringlengths
14
6.51M
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Соединение, использующее для источника данных историю котировок (IStockDataStorage) History: -----------------------------------------------------------------------------} unit FC.StockData.HC.StockDataConnection; {$I Compiler.inc} interface uses SysUtils,Classes,DB, Controls, Serialization, FC.Definitions, FC.StockData.StockDataSource,StockChart.Definitions,FC.Singletons; type //--------------------------------------------------------------------------- //Соединение с History Center TStockDataSourceConnection_HistoryCenter = class (TPersistentObjectRefCounted,IStockDataSourceConnection) private FSymbol: string; FInterval: TStockTimeInterval; FStartLoadingFrom: TDateTime; public //from IStockDataSourceConnection function CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; function ConnectionString: string; //TPersistentObject procedure ReadData(const aReader: IDataReader); override; procedure WriteData(const aWriter: IDataWriter); override; constructor Create(const aSymbol: string; aInterval: TStockTimeInterval; const aStartLoadingFrom: TDateTime); end; implementation uses SystemService,FC.StockData.HC.StockDataSource,FC.StockData.StockDataSourceRegistry; { TStockDataSourceConnection_HistoryCenter } function TStockDataSourceConnection_HistoryCenter.ConnectionString: string; begin result:='HistoryCenter: '+FSymbol+IntToStr(StockTimeIntervalValues[FInterval]); end; constructor TStockDataSourceConnection_HistoryCenter.Create(const aSymbol: string; aInterval: TStockTimeInterval; const aStartLoadingFrom: TDateTime); begin FSymbol:=aSymbol; FInterval:=aInterval; FStartLoadingFrom:=aStartLoadingFrom; end; function TStockDataSourceConnection_HistoryCenter.CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; var aObj: TObject; begin result:=nil; if aUseCacheIfPossible then begin aObj:=StockLoadedDataSourceRegistry.FindDataSourceObject(self.ConnectionString,TStockDataSource_HistoryCenter,FSymbol,FInterval,FloatToStr(FStartLoadingFrom)); if aObj<>nil then result:=aObj as TStockDataSource_HistoryCenter end; if result=nil then result:=TStockDataSource_HistoryCenter.Create(self,FSymbol,FInterval,StockDataStorage,FStartLoadingFrom); end; procedure TStockDataSourceConnection_HistoryCenter.ReadData(const aReader: IDataReader); begin inherited; aReader.ReadString(FSymbol); aReader.Read(FInterval,sizeof(FInterval)); aReader.ReadDateTime(FStartLoadingFrom); end; procedure TStockDataSourceConnection_HistoryCenter.WriteData(const aWriter: IDataWriter); begin inherited; aWriter.WriteString(FSymbol); aWriter.Write(FInterval,sizeof(FInterval)); aWriter.WriteDateTime(FStartLoadingFrom); end; initialization Serialization.TClassFactory.RegisterClass(TStockDataSourceConnection_HistoryCenter); end.
{$i deltics.interfacedobjects.inc} unit Deltics.InterfacedObjects.InterfacedObject; interface uses Deltics.Multicast, Deltics.InterfacedObjects.Interfaces.IInterfacedObject, Deltics.InterfacedObjects.ObjectLifecycle; type // @TInterfacedObjectBase // // Provides a base class for objects that implement interfaces but with // explicit lifetime management (must be Free'd and are NOT reference // counted). // // Reference counting is still taking place (the calls are generated by // the compiler and are unavoidable) but the implementation does not // track the reference count and does not free itself when there are // no references left. // TInterfacedObject = class(TObject, IUnknown, IInterfacedObject, IOn_Destroy) private fIsBeingDestroyed: Boolean; fOn_Destroy: IOn_Destroy; protected property IsBeingDestroyed: Boolean read fIsBeingDestroyed; public procedure BeforeDestruction; override; // IUnknown protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; virtual; stdcall; function _Release: Integer; virtual; stdcall; // IInterfacedObject protected function get_IsReferenceCounted: Boolean; virtual; function get_Lifecycle: TObjectLifecycle; virtual; function get_Object: TObject; function get_ReferenceCount: Integer; virtual; property Lifecycle: TObjectLifecycle read get_Lifecycle; property ReferenceCount: Integer read get_ReferenceCount; // IOn_Destroy protected function get_On_Destroy: IOn_Destroy; public property On_Destroy: IOn_Destroy read get_On_Destroy implements IOn_Destroy; end; implementation { TInterfacedObjectBase -------------------------------------------------------------------------- } { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject._AddRef: Integer; begin result := 1; { NO-OP } end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject._Release: Integer; begin result := 1; { NO-OP } end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } procedure TInterfacedObject.BeforeDestruction; begin fIsBeingDestroyed := TRUE; inherited; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.get_IsReferenceCounted: Boolean; begin result := FALSE; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.get_Lifecycle: TObjectLifecycle; begin result := olExplicit; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.get_Object: TObject; begin result := self; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.get_On_Destroy: IOn_Destroy; // Create the multi-cast event on demand, since we cannot // guarantee any particular constructor call order and there // may be dependencies created during construction (e.g. if // multi-cast event handlers are added before/after any call // to a particular inherited constructor etc etc) begin if NOT fIsBeingDestroyed and NOT Assigned(fOn_Destroy) then fOn_Destroy := TOnDestroy.Create(self); result := fOn_Destroy; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TInterfacedObject.get_ReferenceCount: Integer; begin result := 1; end; end.
unit Expense; interface type TExpense = class private FLocation: string; FCash: currency; FExpenseDate: TDate; FAmount: currency; FTitleCode: string; FTitleName: string; FExpenseId: string; FCheck: currency; public property ExpenseId: string read FExpenseId write FExpenseId; property ExpenseDate: TDate read FExpenseDate write FExpenseDate; property TitleCode: string read FTitleCode write FTitleCode; property TitleName: string read FTitleName write FTitleName; property Location: string read FLocation write FLocation; property Amount: currency read FAmount write FAmount; property Cash: currency read FCash write FCash; property Check: currency read FCheck write FCheck; end; implementation end.
unit IdMappedPortTCP; interface { 2001-12-xx - Andrew P.Rybin -new architecture 2002-02-02 - Andrew P.Rybin -DoDisconnect fix } uses Classes, IdGlobal, IdTCPConnection, IdTCPServer, IdAssignedNumbers, SysUtils; type TIdMappedPortThread = class (TIdPeerThread) protected FOutboundClient: TIdTCPConnection;//was TIdTCPClient FReadList: TList; FNetData: String; //data buf FConnectTimeOut: Integer; // procedure Cleanup; override; //Free OutboundClient procedure OutboundConnect; virtual; public constructor Create(ACreateSuspended: Boolean = True); override; destructor Destroy; override; // property ConnectTimeOut: Integer read FConnectTimeOut write FConnectTimeOut default IdTimeoutDefault; property NetData: String read FNetData write FNetData; property OutboundClient: TIdTCPConnection read FOutboundClient write FOutboundClient; property ReadList: TList read FReadList; End;//TIdMappedPortThread TIdMappedPortThreadEvent = procedure(AThread: TIdMappedPortThread) of object; TIdMappedPortOutboundConnectEvent = procedure(AThread: TIdMappedPortThread; AException: Exception) of object;//E=NIL-OK TIdMappedPortTCP = class(TIdTCPServer) protected FMappedHost: String; FMappedPort: Integer; //AThread.Connection.Server & AThread.OutboundClient FOnOutboundConnect: TIdMappedPortOutboundConnectEvent; FOnOutboundData: TIdMappedPortThreadEvent; FOnOutboundDisConnect: TIdMappedPortThreadEvent; // procedure DoConnect(AThread: TIdPeerThread); override; function DoExecute(AThread: TIdPeerThread): boolean; override; procedure DoDisconnect(AThread: TIdPeerThread); override; //DoLocalClientDisconnect procedure DoLocalClientConnect(AThread: TIdMappedPortThread); virtual; procedure DoLocalClientData(AThread: TIdMappedPortThread); virtual;//APR: bServer procedure DoOutboundClientConnect(AThread: TIdMappedPortThread; const AException: Exception=NIL); virtual; procedure DoOutboundClientData(AThread: TIdMappedPortThread); virtual; procedure DoOutboundDisconnect(AThread: TIdMappedPortThread); virtual; function GetOnConnect: TIdMappedPortThreadEvent; function GetOnExecute: TIdMappedPortThreadEvent; procedure SetOnConnect(const Value: TIdMappedPortThreadEvent); procedure SetOnExecute(const Value: TIdMappedPortThreadEvent); function GetOnDisconnect: TIdMappedPortThreadEvent; procedure SetOnDisconnect(const Value: TIdMappedPortThreadEvent); // try to hide property OnBeforeCommandHandler;// NOT USED property OnAfterCommandHandler;// NOT USED property OnNoCommandHandler;// NOT USED public constructor Create(AOwner: TComponent); override; published property MappedHost: String read FMappedHost write FMappedHost; property MappedPort: Integer read FMappedPort write FMappedPort; // property OnConnect: TIdMappedPortThreadEvent read GetOnConnect write SetOnConnect; //OnLocalClientConnect property OnOutboundConnect: TIdMappedPortOutboundConnectEvent read FOnOutboundConnect write FOnOutboundConnect; property OnExecute: TIdMappedPortThreadEvent read GetOnExecute write SetOnExecute;//OnLocalClientData property OnOutboundData: TIdMappedPortThreadEvent read FOnOutboundData write FOnOutboundData; property OnDisconnect: TIdMappedPortThreadEvent read GetOnDisconnect write SetOnDisconnect;//OnLocalClientDisconnect property OnOutboundDisconnect: TIdMappedPortThreadEvent read FOnOutboundDisconnect write FOnOutboundDisconnect; End;//TIdMappedPortTCP //============================================================================= // * Telnet * //============================================================================= TIdMappedTelnetThread = class (TIdMappedPortThread) protected FAllowedConnectAttempts: Integer; // procedure OutboundConnect; override; public property AllowedConnectAttempts: Integer read FAllowedConnectAttempts; End;//TIdMappedTelnetThread TIdMappedTelnetCheckHostPort = procedure (AThread: TIdMappedPortThread; const AHostPort: String; var VHost,VPort: String) of object; TIdCustomMappedTelnet = class (TIdMappedPortTCP) protected FAllowedConnectAttempts: Integer; FOnCheckHostPort: TIdMappedTelnetCheckHostPort; procedure DoCheckHostPort (AThread: TIdMappedPortThread; const AHostPort: String; var VHost,VPort: String); virtual; procedure SetAllowedConnectAttempts(const Value: Integer); procedure ExtractHostAndPortFromLine(AThread: TIdMappedPortThread; const AHostPort: String); public constructor Create(AOwner: TComponent); override; // property AllowedConnectAttempts: Integer read FAllowedConnectAttempts write SetAllowedConnectAttempts default -1; // property OnCheckHostPort: TIdMappedTelnetCheckHostPort read FOnCheckHostPort write FOnCheckHostPort; published property DefaultPort default IdPORT_TELNET; property MappedPort default IdPORT_TELNET; End;//TIdCustomMappedTelnet TIdMappedTelnet = class (TIdCustomMappedTelnet) published property AllowedConnectAttempts: Integer read FAllowedConnectAttempts write SetAllowedConnectAttempts default -1; // property OnCheckHostPort: TIdMappedTelnetCheckHostPort read FOnCheckHostPort write FOnCheckHostPort; End;//TIdMappedTelnet //============================================================================= // * P O P 3 * // USER username#host:port //============================================================================= TIdMappedPop3Thread = class (TIdMappedTelnetThread) protected procedure OutboundConnect; override; public End;//TIdMappedPop3Thread TIdMappedPop3 = class (TIdMappedTelnet) protected FUserHostDelimiter: String; public constructor Create(AOwner: TComponent); override; published property DefaultPort default IdPORT_POP3; property MappedPort default IdPORT_POP3; property UserHostDelimiter: String read FUserHostDelimiter write FUserHostDelimiter; End;//TIdMappedPop3 Implementation uses IdStack, IdIOHandlerSocket, IdException, IdResourceStrings, IdTCPClient; resourcestring RSEmptyHost = 'Host is empty'; {Do not Localize} RSPop3ProxyGreeting = 'POP3 proxy ready'; {Do not Localize} RSPop3UnknownCommand = 'command must be either USER or QUIT'; {Do not Localize} RSPop3QuitMsg = 'POP3 proxy signing off'; {Do not Localize} constructor TIdMappedPortTCP.Create(AOwner: TComponent); Begin inherited Create(AOwner); ThreadClass := TIdMappedPortThread; End;// procedure TIdMappedPortTCP.DoLocalClientConnect(AThread: TIdMappedPortThread); Begin if Assigned(FOnConnect) then FOnConnect(AThread); End;// procedure TIdMappedPortTCP.DoOutboundClientConnect(AThread: TIdMappedPortThread; const AException: Exception=NIL); Begin if Assigned(FOnOutboundConnect) then FOnOutboundConnect(AThread,AException); End;// procedure TIdMappedPortTCP.DoLocalClientData(AThread: TIdMappedPortThread); Begin if Assigned(FOnExecute) then FOnExecute(AThread); End;// procedure TIdMappedPortTCP.DoOutboundClientData(AThread: TIdMappedPortThread); Begin if Assigned(FOnOutboundData) then FOnOutboundData(AThread); End;// procedure TIdMappedPortTCP.DoDisconnect(AThread: TIdPeerThread); Begin inherited DoDisconnect(AThread); if Assigned(TIdMappedPortThread(AThread).FOutboundClient) and TIdMappedPortThread(AThread).FOutboundClient.Connected then begin//check for loop TIdMappedPortThread(AThread).FOutboundClient.Disconnect; end; End;//DoDisconnect procedure TIdMappedPortTCP.DoOutboundDisconnect(AThread: TIdMappedPortThread); Begin if Assigned(FOnOutboundDisconnect) then begin FOnOutboundDisconnect(AThread); end; AThread.Connection.Disconnect; //disconnect local End;// procedure TIdMappedPortTCP.DoConnect(AThread: TIdPeerThread); begin //WARNING: Check TIdTCPServer.DoConnect and synchronize code. Don't call inherited!=> OnConnect in OutboundConnect {Do not Localize} AThread.Connection.WriteRFCReply(Greeting); //was: inherited DoConnect(AThread); TIdMappedPortThread(AThread).OutboundConnect; End; function TIdMappedPortTCP.DoExecute(AThread: TIdPeerThread): boolean; var LConnectionHandle: TObject; LOutBoundHandle: TObject; begin Result:= TRUE; try LConnectionHandle:= TObject( (AThread.Connection.IOHandler as TIdIOHandlerSocket).Binding.Handle); LOutBoundHandle:= TObject( (TIdMappedPortThread(AThread).FOutboundClient.IOHandler as TIdIOHandlerSocket).Binding.Handle); with TIdMappedPortThread(AThread).FReadList do begin Clear; Add(LConnectionHandle); Add(LOutBoundHandle); if GStack.WSSelect(TIdMappedPortThread(AThread).FReadList, nil, nil, IdTimeoutInfinite) > 0 then begin //TODO: Make a select list that also has a function to check of handles if IndexOf(LConnectionHandle) > -1 then begin // TODO: WSAECONNRESET (Exception [EIdSocketError] Socket Error # 10054 Connection reset by peer) TIdMappedPortThread(AThread).FNetData := AThread.Connection.CurrentReadBuffer; if Length(TIdMappedPortThread(AThread).FNetData)>0 then begin DoLocalClientData(TIdMappedPortThread(AThread));//bServer TIdMappedPortThread(AThread).FOutboundClient.Write(TIdMappedPortThread(AThread).FNetData); end;//if end; if IndexOf(LOutBoundHandle) > -1 then begin TIdMappedPortThread(AThread).FNetData := TIdMappedPortThread(AThread).FOutboundClient.CurrentReadBuffer; if Length(TIdMappedPortThread(AThread).FNetData)>0 then begin DoOutboundClientData(TIdMappedPortThread(AThread)); AThread.Connection.Write(TIdMappedPortThread(AThread).FNetData); end;//if end; end;//if select end;//with finally if NOT TIdMappedPortThread(AThread).FOutboundClient.Connected then begin DoOutboundDisconnect(TIdMappedPortThread(AThread)); //&Connection.Disconnect end;//if end;//tryf End;//TIdMappedPortTCP.DoExecute function TIdMappedPortTCP.GetOnConnect: TIdMappedPortThreadEvent; Begin Result:=TIdMappedPortThreadEvent(FOnConnect); End;// function TIdMappedPortTCP.GetOnExecute: TIdMappedPortThreadEvent; Begin Result:=TIdMappedPortThreadEvent(FOnExecute); End;// function TIdMappedPortTCP.GetOnDisconnect: TIdMappedPortThreadEvent; Begin Result:=TIdMappedPortThreadEvent(FOnDisconnect); End;//OnDisconnect procedure TIdMappedPortTCP.SetOnConnect(const Value: TIdMappedPortThreadEvent); Begin TIdMappedPortThreadEvent(FOnConnect):=Value; End;// procedure TIdMappedPortTCP.SetOnExecute(const Value: TIdMappedPortThreadEvent); Begin TIdMappedPortThreadEvent(FOnExecute):=Value; End;// procedure TIdMappedPortTCP.SetOnDisconnect(const Value: TIdMappedPortThreadEvent); Begin TIdMappedPortThreadEvent(FOnDisconnect):=Value; End;//OnDisconnect { TIdMappedPortThread } constructor TIdMappedPortThread.Create; Begin inherited Create(ACreateSuspended); FReadList:= TList.Create; FConnectTimeOut := IdTimeoutDefault; End; procedure TIdMappedPortThread.Cleanup; Begin FreeAndNil(FOutboundClient); inherited Cleanup; End; destructor TIdMappedPortThread.Destroy; begin //^FreeAndNil(FOutboundClient); FreeAndNil(FReadList); inherited Destroy; End; procedure TIdMappedPortThread.OutboundConnect; Begin FOutboundClient := TIdTCPClient.Create(NIL); with TIdMappedPortTCP(Connection.Server) do begin try with TIdTcpClient(FOutboundClient) do begin Port := MappedPort; Host := MappedHost; end;//with DoLocalClientConnect(SELF); TIdTcpClient(FOutboundClient).Connect(FConnectTimeOut); DoOutboundClientConnect(SELF); except on E: Exception do begin DoOutboundClientConnect(SELF,E); // DONE: Handle connect failures Connection.Disconnect; //req IdTcpServer with "Stop this thread if we were disconnected" end; end;//trye end;//with End;//for easy inheritance //============================================================================= { TIdCustomMappedTelnet } constructor TIdCustomMappedTelnet.Create(AOwner: TComponent); Begin inherited Create(AOwner); FAllowedConnectAttempts := -1; ThreadClass := TIdMappedTelnetThread; DefaultPort := IdPORT_TELNET; MappedPort := IdPORT_TELNET; End;//TIdMappedTelnet.Create procedure TIdCustomMappedTelnet.DoCheckHostPort(AThread: TIdMappedPortThread; const AHostPort: String; var VHost,VPort: String); Begin if Assigned(FOnCheckHostPort) then FOnCheckHostPort(AThread,AHostPort,VHost,VPort); End;// procedure TIdCustomMappedTelnet.ExtractHostAndPortFromLine(AThread: TIdMappedPortThread; const AHostPort: String); var LHost,LPort: String; P,L: PChar; Begin if Length(AHostPort)>0 then begin P := Pointer(AHostPort); L := P + Length(AHostPort); while (P<L) and NOT(P^ in [#0,#9,' ',':']) do begin {Do not Localize} inc(P); end; SetString(LHost, PChar(Pointer(AHostPort)), P-Pointer(AHostPort)); while (P<L) and (P^ in [#9,' ',':']) do begin {Do not Localize} inc(P); end; SetString(LPort, P, L-P); LHost := TrimRight(LHost); LPort := TrimLeft(LPort); end else begin LHost := ''; {Do not Localize} LPort := ''; {Do not Localize} end;//if DoCheckHostPort(AThread, AHostPort,LHost,LPort); TIdTcpClient(AThread.OutboundClient).Host := LHost; TIdTcpClient(AThread.OutboundClient).Port := StrToIntDef(LPort,TIdTcpClient(AThread.OutboundClient).Port); End;//ExtractHostAndPortFromLine procedure TIdMappedTelnetThread.OutboundConnect; var LHostPort: String; Begin //don`t call inherited, NEW behavior FOutboundClient := TIdTCPClient.Create(NIL); with TIdCustomMappedTelnet(Connection.Server) do begin with TIdTcpClient(FOutboundClient) do begin Port := MappedPort; Host := MappedHost; end;//with FAllowedConnectAttempts := TIdCustomMappedTelnet(Connection.Server).AllowedConnectAttempts; DoLocalClientConnect(SELF); repeat if FAllowedConnectAttempts>0 then begin dec(FAllowedConnectAttempts); end; try LHostPort := Trim(Connection.InputLn); //~telnet input ExtractHostAndPortFromLine(SELF,LHostPort); if Length(TIdTcpClient(FOutboundClient).Host)<1 then begin raise EIdException.Create(RSEmptyHost); end; TIdTcpClient(FOutboundClient).Connect(FConnectTimeOut); except on E: Exception do begin // DONE: Handle connect failures FNetData := 'ERROR: ['+E.ClassName+'] ' + E.Message; {Do not Localize} DoOutboundClientConnect(SELF,E);//?DoException(AThread,E); Connection.WriteLn(FNetData); end; end;//trye until FOutboundClient.Connected or (FAllowedConnectAttempts=0); if FOutboundClient.Connected then begin DoOutboundClientConnect(SELF) end else begin Connection.Disconnect; //prevent all next work end; end;//with End;//TIdMappedTelnet.OutboundConnect procedure TIdCustomMappedTelnet.SetAllowedConnectAttempts(const Value: Integer); Begin if Value >= 0 then begin FAllowedConnectAttempts:= Value end else begin FAllowedConnectAttempts:=-1; //unlimited end; End;// { TIdMappedPop3 } constructor TIdMappedPop3.Create(AOwner: TComponent); Begin inherited Create(AOwner); FUserHostDelimiter := '#';//standard {Do not Localize} Greeting.NumericCode := 0;//same as POP3 Greeting.Text.Text := '+OK '+RSPop3ProxyGreeting; {Do not Localize} ReplyUnknownCommand.NumericCode := 0; ReplyUnknownCommand.Text.Text := '-ERR '+RSPop3UnknownCommand; {Do not Localize} DefaultPort := IdPORT_POP3; MappedPort := IdPORT_POP3; ThreadClass := TIdMappedPop3Thread; End;//TIdMappedPop3.Create { TIdMappedPop3Thread } procedure TIdMappedPop3Thread.OutboundConnect; var LHostPort,LUserName,LPop3Cmd: String; Begin //don`t call inherited, NEW behavior with TIdMappedPop3(Connection.Server) do begin FOutboundClient := TIdTCPClient.Create(NIL); with TIdTcpClient(FOutboundClient) do begin Port := MappedPort; Host := MappedHost; end;//with FAllowedConnectAttempts := TIdMappedPop3(Connection.Server).AllowedConnectAttempts; DoLocalClientConnect(SELF); repeat if FAllowedConnectAttempts>0 then begin dec(FAllowedConnectAttempts); end; try // Greeting LHostPort := Trim(Connection.ReadLn);//USER username#host OR QUIT LPop3Cmd := UpperCase(Fetch(LHostPort,' ',TRUE)); {Do not Localize} if LPop3Cmd = 'QUIT' then begin {Do not Localize} Connection.WriteLn('+OK '+RSPop3QuitMsg); {Do not Localize} Connection.Disconnect; BREAK; end else if LPop3Cmd = 'USER' then begin {Do not Localize} LUserName := Fetch(LHostPort,FUserHostDelimiter,TRUE,FALSE);//?:CaseSensetive FNetData := LUserName; //save for OnCheckHostPort LHostPort := TrimLeft(LHostPort); //trimRight above ExtractHostAndPortFromLine(SELF,LHostPort); LUserName := FNetData; //allow username substitution end else begin Connection.WriteRFCReply(ReplyUnknownCommand); Continue; end;//if if Length(TIdTcpClient(FOutboundClient).Host)<1 then begin raise EIdException.Create(RSEmptyHost); end; TIdTcpClient(FOutboundClient).Connect(FConnectTimeOut); FNetData := FOutboundClient.ReadLn;//Read Pop3 Banner for OnOutboundClientConnect FOutboundClient.WriteLn('USER '+LUserName); {Do not Localize} except on E: Exception do begin // DONE: Handle connect failures FNetData :='-ERR ['+E.ClassName+'] '+E.Message; {Do not Localize} DoOutboundClientConnect(SELF,E);//?DoException(AThread,E); Connection.WriteLn(FNetData); end; end;//trye until FOutboundClient.Connected or (FAllowedConnectAttempts=0); if FOutboundClient.Connected then begin DoOutboundClientConnect(SELF) end else begin Connection.Disconnect; //prevent all next work end; end;//with End;//TIdMappedPop3.OutboundConnect END.
unit Mock.DeviceTrimmer; interface uses SysUtils, Generics.Collections, Windows, OSFile; type TPendingTrimOperation = record IsUnusedSpaceFound: Boolean; StartLBA: UInt64; LengthInLBA: UInt64; end; TTrimOperationList = TList<TPendingTrimOperation>; TDeviceTrimmer = class(TOSFile) private PendingTrimOperation: TPendingTrimOperation; class var TrimOperationList: TTrimOperationList; public constructor Create(const FileToGetAccess: String); override; procedure Flush; procedure SetStartPoint(StartLBA, LengthInLBA: UInt64); procedure IncreaseLength(LengthInLBA: UInt64); function IsUnusedSpaceFound: Boolean; function IsLBACountOverLimit: Boolean; class procedure CreateTrimOperationLogger; class procedure FreeTrimOperationLogger; class function GetTrimOperationLogger: TTrimOperationList; end; implementation { TDeviceTrimmer } constructor TDeviceTrimmer.Create(const FileToGetAccess: String); begin inherited; ZeroMemory(@PendingTrimOperation, SizeOf(PendingTrimOperation)); end; class procedure TDeviceTrimmer.CreateTrimOperationLogger; begin TrimOperationList := TTrimOperationList.Create; end; class procedure TDeviceTrimmer.FreeTrimOperationLogger; begin FreeAndNil(TrimOperationList); end; procedure TDeviceTrimmer.SetStartPoint(StartLBA, LengthInLBA: UInt64); begin PendingTrimOperation.IsUnusedSpaceFound := true; PendingTrimOperation.StartLBA := StartLBA; PendingTrimOperation.LengthInLBA := LengthInLBA; end; procedure TDeviceTrimmer.IncreaseLength(LengthInLBA: UInt64); begin PendingTrimOperation.LengthInLBA := PendingTrimOperation.LengthInLBA + LengthInLBA; end; procedure TDeviceTrimmer.Flush; begin TrimOperationList.Add(PendingTrimOperation); ZeroMemory(@PendingTrimOperation, SizeOf(PendingTrimOperation)); end; function TDeviceTrimmer.IsLBACountOverLimit: Boolean; const LimitLengthInLBA = 65500; begin result := PendingTrimOperation.LengthInLBA > LimitLengthInLBA; end; function TDeviceTrimmer.IsUnusedSpaceFound: Boolean; begin result := PendingTrimOperation.IsUnusedSpaceFound; end; class function TDeviceTrimmer.GetTrimOperationLogger: TTrimOperationList; begin result := TrimOperationList end; end.
{ Radius NT Directory Watcher Based on FnugryDirWatch Component Copyright (C) 1998 Gleb Yourchenko } {$A-,B-,I-,R-,X+} {.$define PlatformCheck} // Check platform before allocating // DirWatch instance. unit RadDW_NT; interface uses Windows, SysUtils, Classes, Messages, xbase{, syncobjs}; const FILE_ACTION_ADDED = $00000001; FILE_ACTION_REMOVED = $00000002; FILE_ACTION_MODIFIED = $00000003; FILE_ACTION_RENAMED_OLD_NAME = $00000004; FILE_ACTION_RENAMED_NEW_NAME = $00000005; type EDirWatchError = class(Exception); TDirWatchOption = ( dw_file_name, dw_dir_name, dw_file_attr, dw_file_size, dw_file_write_date, dw_file_access_date, dw_file_creation_date, dw_file_security ); TDirWatchOptions = set of TDirWatchOption; TFileChangeNotifyEvent = procedure(Sender :TObject; Action :Integer; const FileName :string) of object; TRadiusNTDirWatch = class(TComponent) private FWatchThread :TThread; FOptions :TDirWatchOptions; FWndHandle :HWND; FErrorMsg :String; FWatchSubtree :Boolean; FDirectory :String; FOnChange :TNotifyEvent; FOnNotify :TFileChangeNotifyEvent; function GetEnabled :Boolean; procedure SetEnabled(const Value :Boolean); procedure SetOptions(const Value :TDirWatchOptions); procedure WatchWndProc(var M :TMessage); function MakeFilter :Cardinal; procedure SetWatchSubTree(const Value :Boolean); function GetDirectory :String; procedure SetDirectory(const Value :String); procedure EvWatchNotify(Sender :TObject); procedure EvWatchError(Sender :TObject); protected procedure AllocWatchThread; procedure ReleaseWatchThread; procedure RestartWatchThread; procedure CHange; virtual; procedure Notify(Action :Integer; const FileName :String); virtual; public constructor Create(AOwner :TComponent); override; destructor Destroy; override; function ActionName(Action :Integer):String; property ErrorMsg :String read FErrorMsg; published property Enabled :Boolean read GetEnabled write SetEnabled; property Options :TDirWatchOptions read FOptions write SetOptions; property WatchSubTree :Boolean read FWatchSubTree write SetWatchSubTree; property Directory :String read GetDirectory write SetDirectory; property OnChange :TNotifyEvent read FOnChange write FOnChange; property OnNotify :TFileChangeNotifyEvent read FOnNotify write FOnNotify; end; procedure Register; implementation uses forms; procedure Register; begin RegisterComponents('Argus', [TRadiusNTDirWatch]); end; { Types & constants from winnt.h not included in windows.pas: } type LPOVERLAPPED_COMPLETION_ROUTINE = procedure ( dwErrorCode :Longint; dwNumberOfBytesTransfered :Longint; lpOverlapped :POverlapped); stdcall; TReadDirectoryChangesWProc = function( hDirectory :THandle; lpBuffer :Pointer; nBufferLength :Longint; bWatchSubtree :Bool; dwNotifyFilter :Longint; var lpBytesReturned :Longint; lpOverlapped :POVERLAPPED; lpCompletionRoutine :LPOVERLAPPED_COMPLETION_ROUTINE):Bool; stdcall; PFILE_NOTIFY_INFORMATION = ^TFILE_NOTIFY_INFORMATION; TFILE_NOTIFY_INFORMATION = record NextEntryOffset :Longint; Action :Longint; FileNameLength :Longint; FileName :array[0..MAX_PATH-1] of WideChar; end; const WM_DIRWATCH_ERROR = WM_USER + 137; WM_DIRWATCH_NOTIFY = WM_USER + 138; FILE_NOTIFY_CHANGE_FILE_NAME = $00000001; FILE_NOTIFY_CHANGE_DIR_NAME = $00000002; FILE_NOTIFY_CHANGE_ATTRIBUTES = $00000004; FILE_NOTIFY_CHANGE_SIZE = $00000008; FILE_NOTIFY_CHANGE_LAST_WRITE = $00000010; FILE_NOTIFY_CHANGE_LAST_ACCESS = $00000020; FILE_NOTIFY_CHANGE_CREATION = $00000040; FILE_NOTIFY_CHANGE_SECURITY = $00000100; FILE_LIST_DIRECTORY = $0001; { Error messages: } const m_err_platform = 'TRadiusNTDirWatch requires MS Windows NT Version 4 or higher'; m_err_opendir = 'Could not open directory "%s"'#13#10'Error code: %d'; m_err_link = 'Could not find procedure "%s" in module "%s"'; m_err_readchanges = 'ReadDirectoryChanges call failed.'; m_err_getresult = 'GetOverlappedResult call failed'; { TDirWatchThread } const szKernel32 = 'kernel32'; szReadDirectoryChangesW = 'ReadDirectoryChangesW'; const IO_BUFFER_LEN = 32*sizeof(TFILE_NOTIFY_INFORMATION); type CException = class of Exception; TDirWatchThread = class(TThread) private FWatchSubTree :Bool; FIOResult :Pointer; FIOResultLen :cardinal; FDirHandle :THandle; FDirectory :String; FFilter :Cardinal; FErrorClass :TClass; FErrorMsg :String; FOnError :TNotifyEvent; FOnNotify :TNotifyEvent; FCompletionEvent : THandle; FKernelHandle :Thandle; FReadDirectoryChangesProc :TReadDirectoryChangesWProc; protected procedure Execute; override; procedure DoError; procedure DoNotify; public constructor Create(const aDir :String; aFilter :Cardinal; aWatchSubTree :Bool; aNotifyProc, aErrorProc :TNotifyEvent); destructor Destroy; override; procedure ClearError; property ErrorClass :TClass read FErrorClass; property ErrorMsg :String read FErrorMsg; property OnError :TNotifyEvent read FOnError write FOnError; property OnNotify :TNotifyEvent read FOnNotify write FOnNotify; property IOResult :Pointer read FIOResult; end; procedure TDirWatchThread.ClearError; begin FErrorMsg := ''; FErrorClass := Nil; end; procedure TDirWatchThread.DoError; begin if assigned(FOnError) then FOnError(Self); end; procedure TDirWatchThread.DoNotify; begin if assigned(FOnNotify) then FOnNotify(Self); end; procedure TDirWatchThread.Execute; var Overlapped :TOVERLAPPED; WaitResult :DWORD; begin while not terminated do try // // Do nothing if an error occured. // (Waiting for owner to release the // thread or clear error state) // if assigned(FErrorClass) then begin sleep(0); continue; end; // // fillchar(overlapped, sizeof(overlapped), 0); FCompletionEvent := CreateEvent(nil, False, False, PCHAR('RadiusComplitionEvent')); ResetEvent(FCompletionEvent); overlapped.hEvent := FCompletionEvent; if not FReadDirectoryChangesProc(FDirHandle, FIOResult, IO_BUFFER_LEN, FWatchSubtree, FFilter, integer(FIOResultLen), @Overlapped, nil) then raise EDirWatchError.Create(m_err_readchanges); repeat WaitResult := WaitForSingleObject(FCompletionEvent, 100); if WaitResult = WAIT_OBJECT_0 then begin // // retrieve overlapped result // and generate Notify event // if not GetOverlappedResult(FDirHandle, Overlapped, FIOResultLen, true) then raise EDirWatchError.Create(m_err_getresult); DoNotify; end; until terminated or (WaitResult <> WAIT_TIMEOUT); except on E :Exception do begin FErrorClass := E.ClassType; FErrorMsg := E.Message; DoError; end else raise; end; end; constructor TDirWatchThread.Create(const aDir :String; aFilter :Cardinal; aWatchSubTree :Bool; aNotifyProc, aErrorProc :TNotifyEvent); begin // // Retrieve proc pointer, open directory to // watch and allocate buffer for notification data. // (note, it is done before calling inherited // create (that calls BeginThread) so any exception // will be still raised in caller's thread) // FKernelHandle := LoadLibrary(szKernel32); assert(FKernelHandle <> 0); FReadDirectoryChangesProc := GetProcAddress( FKernelHandle, szReadDirectoryChangesW); if not assigned(FReadDirectoryChangesProc) then raise EDirWatchError.CreateFmt(m_err_link, [szReadDirectoryChangesW, szKernel32]); FDirHandle := CreateFile( PChar(aDir), FILE_LIST_DIRECTORY, FILE_SHARE_READ OR FILE_SHARE_DELETE OR FILE_SHARE_WRITE, Nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS OR FILE_FLAG_OVERLAPPED, 0 ); if FDirHandle = INVALID_HANDLE_VALUE then raise EDirWatchError.CreateFmt( m_err_opendir, [aDir, GetLastError]); GetMem(FIOResult, IO_BUFFER_LEN); inherited Create(true); FOnError := aErrorProc; FOnNotify := aNotifyProc; FFilter := aFilter; FWatchSubTree := aWatchSubtree; FDirectory := aDir; FreeOnTerminate := false; FCompletionEvent := OpenEvent(EVENT_MODIFY_STATE, False, PCHAR('RadiusComplitionEvent')); // // Start the thread // Resume; end; destructor TDirWatchThread.Destroy; begin Terminate; WaitFor; if FCompletionEvent <> INVALID_HANDLE_VALUE then CloseHandle(FCompletionEvent); if FDirHandle <> INVALID_HANDLE_VALUE then CloseHandle(FDirHandle); if assigned(FIOResult) then FreeMem(FIOResult); if FKernelHandle <> 0 then FreeLibrary(FKernelHandle); inherited Destroy; end; { TRadiusNTDirWatch } procedure TRadiusNTDirWatch.AllocWatchThread; begin assert(FWatchThread = Nil); FWatchThread := TDirWatchThread.Create(Directory, MakeFilter, WatchSubtree, EvWatchNotify, EvWatchError); end; procedure TRadiusNTDirWatch.ReleaseWatchThread; begin assert(assigned(FWatchThread)); FWatchThread.Free; FWatchThread := Nil; end; procedure TRadiusNTDirWatch.RestartWatchThread; begin Enabled := false; Enabled := true; end; function TRadiusNTDirWatch.GetEnabled :Boolean; begin result := assigned(FWatchThread); end; procedure TRadiusNTDirWatch.SetEnabled(const Value :Boolean); begin if Value <> Enabled then begin if Value then AllocWatchThread else ReleaseWatchThread; Change; end; end; destructor TRadiusNTDirWatch.Destroy; begin Enabled := false; if FWndHandle <> 0 then DeallocateHWnd(FWndHandle); inherited Destroy; end; constructor TRadiusNTDirWatch.Create(AOwner :TComponent); begin {$ifdef PlatformCheck} if (Win32Platform <> VER_PLATFORM_WIN32_NT) then raise EDirWatchError.Create(m_err_platform); {$endif} inherited Create(AOwner); FWndHandle := AllocateHWnd(WatchWndProc); FOptions := [dw_file_name, dw_dir_name, dw_file_size, dw_file_attr, dw_file_creation_date, dw_file_access_date, dw_file_write_date, dw_file_security]; FWatchSubtree := true; end; procedure TRadiusNTDirWatch.SetOptions(const Value :TDirWatchOptions); begin if FOptions <> Value then begin FOptions := Value; if Enabled then RestartWatchThread; Change; end; end; procedure TRadiusNTDirWatch.WatchWndProc(var M :TMessage); var ErrorClass :CException; begin case m.msg of WM_DIRWATCH_NOTIFY : // // Retrieve notify data and forward // the event to TRadiusNTDirWatch's notify // handler. Free filename string (allocated // in WatchThread's notify handler.) // begin try Notify(m.wParam, WideCharToString(PWideChar(m.lParam))); finally if m.lParam <> 0 then FreeMem(Pointer(m.lParam)); end; end; WM_DIRWATCH_ERROR : // // Disable dir watch and re-raise // exception on error // begin ErrorClass := CException(m.lParam); assert(assigned(ErrorClass)); Enabled := false; raise ErrorClass.Create(ErrorMsg); end; end; end; function TRadiusNTDirWatch.MakeFilter :Cardinal; const FilterFlags :array[TDirWatchOption] of Integer = ( FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_LAST_ACCESS, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_SECURITY); var f :TDirWatchOption; begin result := 0; for f := low(TDirWatchOption) to high(TDirWatchOption) do if f in FOptions then result := result or dword(FilterFlags[f]); end; procedure TRadiusNTDirWatch.EvWatchNotify(Sender :TObject); var NotifyData :PFILE_NOTIFY_INFORMATION; FileName :PWideChar; NextEntry :Integer; begin assert(Sender is TDirWatchThread); NotifyData := TDirWatchThread(Sender).IOResult; repeat FileName := nil; if NotifyData^.FileNameLength > 0 then begin GetMem(FileName, NotifyData^.FileNameLength + 2); move(NotifyData^.FileName, Pointer(FileName)^, NotifyData^.FileNameLength); PWord(Integer(FileName)+NotifyData^.FileNameLength)^ := 0; end; PostMessage(FWndHandle, WM_DIRWATCH_NOTIFY, NotifyData^.Action, LPARAM(FileName)); NextEntry := NotifyData^.NextEntryOffset; inc(longint(NotifyData), NextEntry); until (NextEntry = 0); end; procedure TRadiusNTDirWatch.EvWatchError(Sender :TObject); begin assert(Sender is TDirWatchThread); FErrorMsg := TDirWatchThread(Sender).ErrorMsg; PostMessage(FWndHandle, WM_DIRWATCH_ERROR, 0, LPARAM(TDirWatchThread(Sender).ErrorClass)); end; procedure TRadiusNTDirWatch.SetWatchSubTree(const Value :Boolean); begin if Value <> FWatchSubtree then begin FWatchSubtree := Value; if Enabled then RestartWatchThread; Change; end; end; function TRadiusNTDirWatch.GetDirectory :String; begin result := FDirectory; if result = '' then result := '.\'; end; procedure TRadiusNTDirWatch.SetDirectory(const Value :String); begin if stricomp(PChar(trim(Value)), PChar(FDirectory)) <> 0 then begin FDirectory := trim(Value); if Enabled then RestartWatchThread; Change; end; end; procedure TRadiusNTDirWatch.CHange; begin if assigned(FOnChange) then FOnChange(Self); end; procedure TRadiusNTDirWatch.Notify( Action :Integer; const FileName :String); begin if assigned(FOnNotify) then FOnNotify(Self, Action, FileName); end; function TRadiusNTDirWatch.ActionName(Action :Integer):String; const ActionNames :array[FILE_ACTION_ADDED..FILE_ACTION_RENAMED_NEW_NAME] of string = ( 'FILE_ACTION_ADDED', 'FILE_ACTION_REMOVED', 'FILE_ACTION_MODIFIED', 'FILE_ACTION_RENAMED_OLD_NAME', 'FILE_ACTION_RENAMED_NEW_NAME'); begin if Action in [FILE_ACTION_ADDED..FILE_ACTION_RENAMED_NEW_NAME] then result := ActionNames[Action] else result := 'FILE_ACTION_UNKNOWN'; end; end.
unit daemon_printer_server; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, DaemonApp, server_thread, fphttpserver, printers, fpjson, jsonparser; type { TPrinterServer } TPrinterServer = class(TDaemon) procedure DataModuleContinue(Sender: TCustomDaemon; var OK: Boolean); procedure DataModulePause(Sender: TCustomDaemon; var OK: Boolean); procedure DataModuleStart(Sender: TCustomDaemon; var OK: Boolean); procedure DataModuleStop(Sender: TCustomDaemon; var OK: Boolean); private FServer : THTTPServerThread; procedure ReceiveRequest(Sender: TObject; Var ARequest: TFPHTTPConnectionRequest; Var AResponse : TFPHTTPConnectionResponse); procedure listPrinters(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); procedure print(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); procedure status(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); function translateCodes(str : string) : string; public { public declarations } end; var PrinterServer: TPrinterServer; implementation procedure RegisterDaemon; begin RegisterDaemonClass(TPrinterServer); end; {$R *.lfm} { TPrinterServer } procedure TPrinterServer.DataModuleContinue(Sender: TCustomDaemon; var OK: Boolean); begin FServer.Start; OK := true; end; procedure TPrinterServer.DataModulePause(Sender: TCustomDaemon; var OK: Boolean); begin FServer.Suspend; OK := true; end; procedure TPrinterServer.DataModuleStart(Sender: TCustomDaemon; var OK: Boolean); begin Logger.Info('Start service ...'); FServer := THTTPServerThread.Create(9123, @ReceiveRequest, false); // FThread.OnTerminate:=@ThreadStopped; FServer.FreeOnTerminate := true; FServer.Start; OK := true; end; procedure TPrinterServer.DataModuleStop(Sender: TCustomDaemon; var OK: Boolean); begin Logger.Info('Stop service ...'); FServer.Terminate; OK := true; end; procedure TPrinterServer.ReceiveRequest(Sender: TObject; var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); begin AResponse.Code := 404; AResponse.ContentType := 'application/json'; AResponse.SetCustomHeader('X-Powered-By', 'LivePDV Server'); AResponse.SetCustomHeader('X-Server-Version', '0'); AResponse.SetCustomHeader('Access-Control-Allow-Credentials', 'true'); AResponse.SetCustomHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS'); AResponse.SetCustomHeader('Access-Control-Allow-Origin', '*'); AResponse.SetCustomHeader('Access-Control-Allow-Headers', 'origin, content-type, Content-Type, accept, Access-Control-Allow-Headers'); AResponse.SetCustomHeader('Connection', 'keep-alive'); if (ARequest.Method = 'GET') and (ARequest.URI = '/printers') then self.listPrinters(ARequest, AResponse); if (ARequest.Method = 'POST') and (ARequest.URI = '/print') then self.print(ARequest, AResponse); if (ARequest.Method = 'GET') and (ARequest.URI = '/status') then self.status(ARequest, AResponse); if (ARequest.Method = 'OPTIONS') then AResponse.Code := 200; if (AResponse.Code <> 200) and (AResponse.Code <> 202) then Logger.Error('URI: '+ARequest.URI+' errorcode: '+IntToStr(AResponse.Code)); end; procedure TPrinterServer.listPrinters(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); var i : integer; data : string; begin status(ARequest, AResponse); if (AResponse.Code = 500) then exit; try data := '['; for i := 0 to Printer.Printers.Count-1 do data := data + '"'+Printer.Printers[i]+'"' +', '; data := copy(data, 1, length(data)-2) + ']'; AResponse.Code := 202; AResponse.Content := '{"data": '+data+'}'; except on e : Exception do begin AResponse.Code := 500; AResponse.Content := '{"message":"'+ e.Message+'", "code":"005"}'; end; end; end; procedure TPrinterServer.print(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); var data : TJSONObject; printerContent : AnsiString; begin status(ARequest, AResponse); if (AResponse.Code <> 200) then exit; try data := TJSONObject(GetJSON(ARequest.Content)); Printer.Title := 'Impressao de cupons'; Printer.RawMode := True; Printer.SetPrinter(String(data.Get('printer'))); printerContent := data.Get('content'); //+ LineEnding + String(data.Get('content')) + LineEnding + data.Get('content'); Printer.BeginDoc; Printer.Write(translateCodes(printerContent)); Printer.Write(LineEnding); Printer.Write(LineEnding); Printer.EndDoc; AResponse.Code := 202; //AResponse.Content:='{"res":"'+translateCodes(printerContent)+'"}'; except on e: Exception do begin AResponse.Code := 500; AResponse.Content := '{"message":"'+ e.Message+'", "code":"004"}'; end; end; end; procedure TPrinterServer.status(var ARequest: TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse); begin if not Assigned(Printer) then begin AResponse.Code := 500; AResponse.Content := '{"message":"Impressoras não iniciadas", "code":"001"}'; exit; end; try Printer.Printers; except on e: Exception do begin AResponse.Code := 500; AResponse.Content := '{"message":"Erro na instanciação das impressoras", "code":"003"}'; exit; end; end; if not Assigned(Printer.Printers) then begin Logger.Info('TPrinterServer.status 4'); AResponse.Code := 500; AResponse.Content := '{"message":"Lista de impressoras não iniciadas", "code":"002"}'; exit; end; Logger.Info('TPrinterServer.status 5'); AResponse.Code := 200; end; function TPrinterServer.translateCodes(str: string): string; var i : integer; begin result := str; for i := 0 to 256 do result := StringReplace(result, '['+FormatFloat('00', i)+']', Char(i), [rfReplaceAll]); end; initialization RegisterDaemon; end.
{******************************************} { Base types and Procedures } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeProcs; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} {$IFDEF TEEVCL} {$IFDEF CLX} Qt, QClipbrd, QGraphics, QStdCtrls, QExtCtrls, QControls, QForms, QPrinters, {$ELSE} Printers, Clipbrd, ExtCtrls, Controls, Graphics, Forms, {$IFNDEF D6} {$IFNDEF D5} Buttons, {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF D6} Types, {$ENDIF} Classes, SysUtils, TeCanvas; {$IFDEF CLX} type TMetafile=class(TBitmap) private FEnhanced: Boolean; published property Enhanced:Boolean read FEnhanced write FEnhanced; end; {$ENDIF} Const TeeDefVerticalMargin = 4; TeeDefHorizMargin = 3; crTeeHand = TCursor(2020); { Hand cursor } TeeMsg_TeeHand = 'crTeeHand'; { string cursor name (dont translate) } TeeNormalPrintDetail = 0; TeeHighPrintDetail = -100; TeeDefault_PrintMargin = 15; MaxDefaultColors=19; // Length of DefaultPalette (+1) TeeTabDelimiter = #9; { separator used in TeExport.pas } Var TeeCheckPenWidth : Boolean=True; { for HP Laserjet printers... } TeeClipWhenPrinting : Boolean=True; { Apply clipping when printing } TeeClipWhenMetafiling : Boolean=True; { Apply clipping when creating metafiles } TeeEraseBack : Boolean=False; { erase background before repainting panel } { Should Panel background to be printed ? Default: False } PrintTeePanel : Boolean=False; type TDateTimeStep=( dtOneMicroSecond, dtOneMillisecond, dtOneSecond, dtFiveSeconds, dtTenSeconds, dtFifteenSeconds, dtThirtySeconds, dtOneMinute, dtFiveMinutes, dtTenMinutes, dtFifteenMinutes, dtThirtyMinutes, dtOneHour, dtTwoHours, dtSixHours, dtTwelveHours, dtOneDay, dtTwoDays, dtThreeDays, dtOneWeek, dtHalfMonth, dtOneMonth, dtTwoMonths, dtThreeMonths, dtFourMonths, dtSixMonths, dtOneYear, dtNone ); Const DateTimeStep:Array[TDateTimeStep] of Double= ( 1.0/(1000000.0*86400.0), 1.0/(1000.0*86400.0), 1.0/86400.0, 5.0/86400.0, 10.0/86400.0, 0.25/1440.0, 0.5/1440.0, 1.0/1440.0, 5.0/1440.0, 10.0/1440.0, 0.25/24.0, 0.5/24.0 , 1.0/24.0 , 2.0/24.0 , 6.0/24.0 , 12.0/24.0, 1, 2, 3, 7, 15, 30, 60, 90, 120, 182, 365, {none:} 1 ); type TCustomPanelNoCaption=class(TCustomPanel) public Constructor Create(AOwner: TComponent); override; end; TCustomTeePanel=class; TZoomPanning={$IFNDEF BCB}packed{$ENDIF} class(TPersistent) private FActive : Boolean; public X0,Y0,X1,Y1 : Integer; Procedure Check; Procedure Activate(x,y:Integer); property Active:Boolean read FActive write FActive; end; TTeeEvent=class public Sender : TCustomTeePanel; {$IFDEF CLR} Constructor Create; virtual; {$ENDIF} end; ITeeEventListener=interface procedure TeeEvent(Event:TTeeEvent); end; TTeeEventListeners=class {$IFDEF CLR}sealed{$ENDIF} (TList) private Function Get(Index:Integer):ITeeEventListener; public function Add(Const Item: ITeeEventListener): Integer; function Remove(Item: ITeeEventListener): Integer; property Items[Index:Integer]:ITeeEventListener read Get; default; end; TTeeMouseEventKind=(meDown,meUp,meMove); TTeeMouseEvent=class {$IFDEF CLR}sealed{$ENDIF} (TTeeEvent) public Event : TTeeMouseEventKind; Button : TMouseButton; Shift : TShiftState; X : Integer; Y : Integer; end; TTeeView3DEvent=class {$IFDEF CLR}sealed{$ENDIF}(TTeeEvent); TTeeUnits=(muPercent,muPixels); TCustomTeePanel=class(TCustomPanelNoCaption) private FApplyZOrder : Boolean; FAutoRepaint : Boolean; { when False, it does not refresh } FBorder : TChartHiddenPen; FBorderRound : Integer; FCancelMouse : Boolean; { when True, it does not finish mouse events } FChartBounds : TRect; FChartWidth : Integer; FChartHeight : Integer; FChartXCenter : Integer; FChartYCenter : Integer; FDelphiCanvas : TCanvas; FHeight3D : Integer; FMargins : TRect; FMarginUnits : TTeeUnits; FOriginalCursor : TCursor; FPanning : TZoomPanning; FPrinting : Boolean; FPrintMargins : TRect; FPrintProportional: Boolean; FPrintResolution : Integer; FShadow : TTeeShadow; FView3D : Boolean; FView3DOptions : TView3DOptions; FWidth3D : Integer; FGLComponent : TComponent; { internal } IEventListeners : TTeeEventListeners; {$IFNDEF CLX} IRounding : Boolean; {$ENDIF} Procedure BroadcastMouseEvent(Kind:TTeeMouseEventKind; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Function GetBorderStyle:TBorderStyle; Function GetBufferedDisplay:Boolean; Function GetMargin(Index:Integer):Integer; Function GetMonochrome:Boolean; Procedure NonBufferDraw(ACanvas:TCanvas; Const R:TRect); procedure ReadBorderStyle(Reader: TReader); // obsolete Procedure SetBorder(const Value:TChartHiddenPen); Procedure SetBorderRound(Value:Integer); Procedure SetBorderStyle(Value:TBorderStyle); Procedure SetBufferedDisplay(Value:Boolean); procedure SetControlRounded; Procedure SetMargin(Index,Value:Integer); Procedure SetMarginUnits(const Value:TTeeUnits); Procedure SetMonochrome(Value:Boolean); Procedure SetShadow(Value:TTeeShadow); procedure SetView3D(Value:Boolean); procedure SetView3DOptions(Value:TView3DOptions); protected InternalCanvas : TCanvas3D; procedure AssignTo(Dest: TPersistent); override; Function BroadcastTeeEvent(Event:TTeeEvent):TTeeEvent; {$IFNDEF CLX} procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE; procedure CreateParams(var Params: TCreateParams); override; {$ELSE} procedure BoundsChanged; override; procedure MouseLeave(AControl: TControl); override; {$ENDIF} Procedure DefineProperties(Filer:TFiler); override; // obsolete procedure DblClick; override; // 7.0 Function GetBackColor:TColor; virtual; Procedure InternalDraw(Const UserRectangle:TRect); virtual; // abstract; {$IFNDEF CLR} property Listeners:TTeeEventListeners read IEventListeners; {$ENDIF} Procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; {$IFNDEF CLR} procedure RemoveListener(Sender:ITeeEventListener); {$ENDIF} procedure Resize; override; Procedure SetBooleanProperty(Var Variable:Boolean; Value:Boolean); Procedure SetColorProperty(Var Variable:TColor; Value:TColor); Procedure SetDoubleProperty(Var Variable:Double; Const Value:Double); Procedure SetIntegerProperty(Var Variable:Integer; Value:Integer); Procedure SetStringProperty(Var Variable:String; Const Value:String); {$IFDEF CLX} function WidgetFlags: Integer; override; {$ELSE} procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; {$ENDIF} {$IFDEF CLR} public {$ENDIF} property GLComponent:TComponent read FGLComponent write FGLComponent; { internal } public ChartRect : TRect; { the rectangle bounded by axes in pixels } Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure CalcMetaBounds( Var R:TRect; Const AChartRect:TRect; Var WinWidth,WinHeight,ViewWidth,ViewHeight:Integer); Function CalcProportionalMargins:TRect; Function CanClip:Boolean; Procedure CanvasChanged(Sender:TObject); virtual; Function ChartPrintRect:TRect; Procedure CheckPenWidth(APen:TPen); Procedure CopyToClipboardBitmap; overload; Procedure CopyToClipboardBitmap(Const R:TRect); overload; Procedure CopyToClipboardMetafile(Enhanced:Boolean); overload; Procedure CopyToClipboardMetafile(Enhanced:Boolean; Const R:TRect); overload; Function TeeCreateBitmap(ABackColor:TColor; Const Rect:TRect; APixelFormat:TPixelFormat= {$IFDEF CLX}TeePixelFormat{$ELSE}pfDevice{$ENDIF} ):TBitmap; Procedure Draw(UserCanvas:TCanvas; Const UserRect:TRect); overload; virtual; Procedure Draw; overload; Procedure DrawPanelBevels(Rect:TRect); dynamic; Procedure DrawToMetaCanvas(ACanvas:TCanvas; Const Rect:TRect); Function GetCursorPos:TPoint; Function GetRectangle:TRect; virtual; procedure Invalidate; override; Function IsScreenHighColor:Boolean; Procedure Print; Procedure PrintLandscape; Procedure PrintOrientation(AOrientation:TPrinterOrientation); Procedure PrintPartial(Const PrinterRect:TRect); Procedure PrintPartialCanvas( PrintCanvas:TCanvas; Const PrinterRect:TRect); Procedure PrintPortrait; Procedure PrintRect(Const R:TRect); {$IFDEF CLR} procedure RemoveListener(Sender:ITeeEventListener); {$ENDIF} Procedure SaveToBitmapFile(Const FileName:String); overload; Procedure SaveToBitmapFile(Const FileName:String; Const R:TRect); overload; Procedure SaveToMetafile(Const FileName:String); Procedure SaveToMetafileEnh(Const FileName:String); Procedure SaveToMetafileRect( Enhanced:Boolean; Const FileName:String; Const Rect:TRect ); Procedure SetBrushCanvas( AColor:TColor; ABrush:TChartBrush; ABackColor:TColor); Procedure SetInternalCanvas(NewCanvas:TCanvas3D); Procedure ReCalcWidthHeight; Function TeeCreateMetafile(Enhanced:Boolean; Const Rect:TRect):TMetafile; { public properties } property ApplyZOrder:Boolean read FApplyZOrder write FApplyZOrder; property AutoRepaint:Boolean read FAutoRepaint write FAutoRepaint; { when False, it does not refresh } property Border:TChartHiddenPen read FBorder write SetBorder; property BorderRound:Integer read FBorderRound write SetBorderRound default 0; property BorderStyle:TBorderStyle read GetBorderStyle write SetBorderStyle; // obsolete property BufferedDisplay:Boolean read GetBufferedDisplay write SetBufferedDisplay; property CancelMouse:Boolean read FCancelMouse write FCancelMouse; { when True, it does not finish mouse events } property Canvas:TCanvas3D read InternalCanvas write SetInternalCanvas; property ChartBounds:TRect read FChartBounds; property ChartHeight:Integer read FChartHeight; property ChartWidth:Integer read FChartWidth; property ChartXCenter:Integer read FChartXCenter; property ChartYCenter:Integer read FChartYCenter; property DelphiCanvas:TCanvas read FDelphiCanvas; property Height3D:Integer read FHeight3D write FHeight3D; property IPanning:TZoomPanning read FPanning; {$IFDEF CLR} property Listeners:TTeeEventListeners read IEventListeners; {$ENDIF} property OriginalCursor:TCursor read FOriginalCursor write FOriginalCursor; property Printing:Boolean read FPrinting write FPrinting; property Width3D:Integer read FWidth3D write FWidth3D; property PrintResolution:Integer read FPrintResolution write FPrintResolution default TeeNormalPrintDetail; { to be published properties } property MarginLeft:Integer index 0 read GetMargin write SetMargin default TeeDefHorizMargin; property MarginTop:Integer index 1 read GetMargin write SetMargin default TeeDefVerticalMargin; property MarginRight:Integer index 2 read GetMargin write SetMargin default TeeDefHorizMargin; property MarginBottom:Integer index 3 read GetMargin write SetMargin default TeeDefVerticalMargin; property MarginUnits:TTeeUnits read FMarginUnits write SetMarginUnits default muPercent; property Monochrome:Boolean read GetMonochrome write SetMonochrome default False; property PrintMargins:TRect read FPrintMargins write FPrintMargins; { the percent of paper printer margins } property PrintProportional:Boolean read FPrintProportional write FPrintProportional default True; property Shadow:TTeeShadow read FShadow write SetShadow; property View3D:Boolean read FView3D write SetView3D default True; property View3DOptions:TView3DOptions read FView3DOptions write SetView3DOptions; { TPanel properties } property Align; property Anchors; property BevelInner; property BevelOuter; property BevelWidth; {$IFDEF CLX} property Bitmap; {$ENDIF} property BorderWidth; property Color {$IFDEF CLX}default clBackground{$ENDIF}; {$IFNDEF CLX} property DragCursor; {$ENDIF} property DragMode; property Enabled; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnMouseDown; property OnMouseMove; property OnMouseUp; {$IFDEF K3} property OnMouseEnter; property OnMouseLeave; {$ENDIF} published end; TChartGradient=TTeeGradient; TChartGradientClass=class of TChartGradient; TPanningMode=(pmNone,pmHorizontal,pmVertical,pmBoth); TTeeZoomPen=class(TChartPen) // do not seal (TeeTree) private Function IsColorStored:Boolean; {$IFNDEF CLR} protected {$ELSE} public {$ENDIF} DefaultColor : TColor; published property Color stored IsColorStored nodefault; // 5.03 end; TTeeZoomBrush=class {$IFDEF CLR}sealed{$ENDIF}(TChartBrush) published property Color default clWhite; property Style default bsClear; end; TTeeZoomDirection=(tzdHorizontal, tzdVertical, tzdBoth); TTeeZoom=class {$IFDEF CLR}sealed{$ENDIF} (TZoomPanning) private FAllow : Boolean; FAnimated : Boolean; FAnimatedSteps : Integer; FBrush : TTeeZoomBrush; FDirection : TTeeZoomDirection; FKeyShift : TShiftState; FMinimumPixels : Integer; FMouseButton : TMouseButton; FPen : TTeeZoomPen; FUpLeftZooms : Boolean; Function GetBrush:TTeeZoomBrush; Function GetPen:TTeeZoomPen; Procedure SetBrush(Value:TTeeZoomBrush); Procedure SetPen(Value:TTeeZoomPen); public Constructor Create; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; published property Allow:Boolean read FAllow write FAllow default True; property Animated:Boolean read FAnimated write FAnimated default False; property AnimatedSteps:Integer read FAnimatedSteps write FAnimatedSteps default 8; property Brush:TTeeZoomBrush read GetBrush write SetBrush; property Direction:TTeeZoomDirection read FDirection write FDirection default tzdBoth; property KeyShift:TShiftState read FKeyShift write FKeyShift default []; property MinimumPixels:Integer read FMinimumPixels write FMinimumPixels default 16; property MouseButton:TMouseButton read FMouseButton write FMouseButton default mbLeft; property Pen:TTeeZoomPen read GetPen write SetPen; property UpLeftZooms:Boolean read FUpLeftZooms write FUpLeftZooms default False; end; TTeeBackImageMode=(pbmStretch,pbmTile,pbmCenter,pbmCustom); // 7.0 TBackImage=class(TPicture) // 7.0 private FInside : Boolean; FLeft : Integer; FMode : TTeeBackImageMode; FTop : Integer; procedure SetInside(Const Value:Boolean); procedure SetLeft(Value:Integer); procedure SetMode(Const Value:TTeeBackImageMode); procedure SetTop(Value:Integer); public constructor Create; procedure Assign(Source:TPersistent); override; published property Inside:Boolean read FInside write SetInside default False; property Left:Integer read FLeft write SetLeft default 0; property Mode:TTeeBackImageMode read FMode write SetMode default pbmStretch; property Top:Integer read FTop write SetTop default 0; end; TCustomTeePanelExtended=class(TCustomTeePanel) private FAllowPanning : TPanningMode; FGradient : TChartGradient; FZoom : TTeeZoom; FZoomed : Boolean; { for compatibility with Tee4 } Function GetAllowZoom:Boolean; Function GetAnimatedZoom:Boolean; Function GetAnimatedZoomSteps:Integer; Function GetBackImage:TBackImage; Function GetBackImageInside:Boolean; Function GetBackImageMode:TTeeBackImageMode; Function GetBackImageTransp:Boolean; Function GetGradient:TChartGradient; procedure ReadAnimatedZoomSteps(Reader: TReader); procedure ReadAnimatedZoom(Reader: TReader); procedure ReadAllowZoom(Reader: TReader); procedure ReadPrintMargins(Reader: TReader); procedure SavePrintMargins(Writer: TWriter); Procedure SetAllowZoom(Value:Boolean); Procedure SetAnimatedZoom(Value:Boolean); Procedure SetAnimatedZoomSteps(Value:Integer); procedure SetBackImage(const Value:TBackImage); procedure SetBackImageInside(Const Value:Boolean); procedure SetBackImageMode(Const Value:TTeeBackImageMode); procedure SetBackImageTransp(Const Value:Boolean); Procedure SetGradient(Value:TChartGradient); Procedure SetZoom(Value:TTeeZoom); protected FBackImage : TBackImage; FOnAfterDraw : TNotifyEvent; FOnScroll : TNotifyEvent; FOnUndoZoom : TNotifyEvent; FOnZoom : TNotifyEvent; Procedure DefineProperties(Filer:TFiler); override; procedure DrawBitmap(Rect:TRect; Z:Integer); procedure FillPanelRect(Const Rect:TRect); virtual; {$IFNDEF CLR} {$IFNDEF CLX} function GetPalette: HPALETTE; override; { override the method } {$ENDIF} {$ENDIF} procedure PanelPaint(Const UserRect:TRect); virtual; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure DrawZoomRectangle; function HasBackImage:Boolean; // Returns True when has BackImage.Graphic procedure UndoZoom; dynamic; property Zoomed:Boolean read FZoomed write FZoomed; property AllowPanning:TPanningMode read FAllowPanning write FAllowPanning default pmBoth; { for compatibility with Tee4 } property AllowZoom:Boolean read GetAllowZoom write SetAllowZoom default True; property AnimatedZoom:Boolean read GetAnimatedZoom write SetAnimatedZoom default False; property AnimatedZoomSteps:Integer read GetAnimatedZoomSteps write SetAnimatedZoomSteps default 8; {} property BackImage:TBackImage read GetBackImage write SetBackImage; property BackImageInside:Boolean read GetBackImageInside write SetBackImageInside default False; property BackImageMode:TTeeBackImageMode read GetBackImageMode write SetBackImageMode default pbmStretch; property BackImageTransp:Boolean read GetBackImageTransp write SetBackImageTransp default False; property Gradient:TChartGradient read GetGradient write SetGradient; property Zoom:TTeeZoom read FZoom write SetZoom; { events } property OnAfterDraw:TNotifyEvent read FOnAfterDraw write FOnAfterDraw; property OnScroll:TNotifyEvent read FOnScroll write FOnScroll; property OnUndoZoom:TNotifyEvent read FOnUndoZoom write FOnUndoZoom; property OnZoom:TNotifyEvent read FOnZoom write FOnZoom; end; TChartBrushClass=class of TChartBrush; TTeeCustomShapeBrushPen=class(TPersistent) private FBrush : TChartBrush; FParent : TCustomTeePanel; FPen : TChartPen; FVisible : Boolean; Procedure SetBrush(Value:TChartBrush); Procedure SetPen(Value:TChartPen); Procedure SetVisible(Value:Boolean); protected Procedure CanvasChanged(Sender:TObject); Function GetBrushClass:TChartBrushClass; dynamic; Procedure SetParent(Value:TCustomTeePanel); virtual; public Constructor Create; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure Show; Procedure Hide; Procedure Repaint; property Brush:TChartBrush read FBrush write SetBrush; property Frame:TChartPen read FPen write SetPen; // alias obsolete property ParentChart:TCustomTeePanel read FParent write SetParent; property Pen:TChartPen read FPen write SetPen; property Visible:Boolean read FVisible write SetVisible; end; TChartObjectShapeStyle=(fosRectangle,fosRoundRectangle); TTeeCustomShape=class(TTeeCustomShapeBrushPen) private FBevel : TPanelBevel; FBevelWidth : TBevelWidth; FColor : TColor; FFont : TTeeFont; FShadow : TTeeShadow; FShapeStyle : TChartObjectShapeStyle; FTransparent : Boolean; Function GetGradient:TChartGradient; Function GetHeight:Integer; Function GetWidth:Integer; Function GetShadow:TTeeShadow; Function GetShadowColor:TColor; // obsolete Function GetShadowSize:Integer; // obsolete Function IsTranspStored:Boolean; procedure ReadShadowColor(Reader: TReader); // obsolete procedure ReadShadowSize(Reader: TReader); // obsolete Procedure SetBevel(Value:TPanelBevel); procedure SetBevelWidth(Value: TBevelWidth); Procedure SetColor(Value:TColor); Procedure SetFont(Value:TTeeFont); procedure SetGradient(Value:TChartGradient); procedure SetHeight(Value:Integer); Procedure SetShadow(Value:TTeeShadow); Procedure SetShadowColor(Value:TColor); // obsolete Procedure SetShadowSize(Value:Integer); // obsolete Procedure SetShapeStyle(Value:TChartObjectShapeStyle); procedure SetTransparency(Value:TTeeTransparency); procedure SetTransparent(Value:Boolean); procedure SetWidth(Value:Integer); protected FDefaultTransparent : Boolean; FGradient : TChartGradient; FTransparency : TTeeTransparency; Procedure DefineProperties(Filer:TFiler); override; Function GetGradientClass:TChartGradientClass; dynamic; Procedure InitShadow(AShadow:TTeeShadow); dynamic; property Transparency:TTeeTransparency read FTransparency write SetTransparency default 0; public ShapeBounds : TRect; Constructor Create(AOwner: TCustomTeePanel); overload; virtual; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure Draw; Procedure DrawRectRotated(Const Rect:TRect; Angle:Integer=0; AZ:Integer=0); // compatibility with v5 (obsolete) property ShadowColor:TColor read GetShadowColor write SetShadowColor default clBlack; property ShadowSize:Integer read GetShadowSize write SetShadowSize default 3; // public properties property Height: Integer read GetHeight write SetHeight; property Width: Integer read GetWidth write SetWidth; { to be published } property Bevel:TPanelBevel read FBevel write SetBevel default bvNone; property BevelWidth:TBevelWidth read FBevelWidth write SetBevelWidth default 2; property Color:TColor read FColor write SetColor default clWhite; property Font:TTeeFont read FFont write SetFont; property Gradient:TChartGradient read GetGradient write SetGradient; property Shadow:TTeeShadow read GetShadow write SetShadow; property ShapeStyle:TChartObjectShapeStyle read FShapeStyle write SetShapeStyle default fosRectangle; property Transparent:Boolean read FTransparent write SetTransparent stored IsTranspStored; end; TTeeShape=class(TTeeCustomShape) public property Transparency; published property Bevel; property BevelWidth; property Color; property Font; property Gradient; property Shadow; property ShapeStyle; property Transparent; end; TeeString256=Array[0..255] of Char; // Used at TeExport, TeeStore and TeeTree export dialog. TTeeExportData=class public Function AsString:String; virtual; // abstract; Procedure CopyToClipboard; dynamic; Procedure SaveToFile(Const FileName:String); dynamic; Procedure SaveToStream(AStream:TStream); dynamic; end; Function TeeStr(Num:Integer):String; // same as IntToStr but a bit faster { returns the appropiate string date or time format according to "step" } Function DateTimeDefaultFormat(Const AStep:Double):String; { returns the number of days of month-year } Function DaysInMonth(Year,Month:Word):Word; { Given a "step", return the corresponding set element } Function FindDateTimeStep(Const StepValue:Double):TDateTimeStep; { Returns the next "step" in ascending order. (eg: TwoDays follows OneDay } Function NextDateTimeStep(Const AStep:Double):Double; { Returns True if point T is over line: P --> Q } Function PointInLine(Const P:TPoint; px,py,qx,qy:Integer):Boolean; overload; Function PointInLine(Const P,FromPoint,ToPoint:TPoint):Boolean; overload; { Returns True if point T is over (more or less "Tolerance" pixels) line: P --> Q } Function PointInLine(Const P,FromPoint,ToPoint:TPoint; TolerancePixels:Integer):Boolean; overload; // obsolete; Function PointInLine(Const P:TPoint; px,py,qx,qy,TolerancePixels:Integer):Boolean; overload; Function PointInLineTolerance(Const P:TPoint; px,py,qx,qy,TolerancePixels:Integer):Boolean; // obsolete; { Returns True if point P is inside Poly polygon } Function PointInPolygon(Const P:TPoint; Const Poly:Array of TPoint):Boolean; { Returns True if point P is inside the vert triangle of x0y0, midxY1, x1y0 } Function PointInTriangle(Const P:TPoint; X0,X1,Y0,Y1:Integer):Boolean; { Returns True if point P is inside the horiz triangle of x0y0, x1midY, x0y0 } Function PointInHorizTriangle(Const P:TPoint; Y0,Y1,X0,X1:Integer):Boolean; { Returns True if point P is inside the ellipse bounded by Rect } Function PointInEllipse(Const P:TPoint; Const Rect:TRect):Boolean; overload; Function PointInEllipse(Const P:TPoint; Left,Top,Right,Bottom:Integer):Boolean; overload; { This functions try to solve locale problems with formatting numbers } Function DelphiToLocalFormat(Const Format:String):String; Function LocalToDelphiFormat(Const Format:String):String; { For all controls in the array, set the Enabled property } Procedure EnableControls(Enable:Boolean; Const ControlArray:Array of TControl); { Round "ADate" to the nearest "AStep" value } Function TeeRoundDate(Const ADate:TDateTime; AStep:TDateTimeStep):TDateTime; { Increment or Decrement "Value", for DateTime and not-DateTime } Procedure TeeDateTimeIncrement( IsDateTime:Boolean; Increment:Boolean; Var Value:Double; Const AnIncrement:Double; tmpWhichDateTime:TDateTimeStep); { Generic "QuickSort" sorting algorithm } type TTeeSortCompare=Function(a,b:Integer):Integer of object; TTeeSortSwap=Procedure(a,b:Integer) of object; Procedure TeeSort( StartIndex,EndIndex:Integer; CompareFunc:TTeeSortCompare; SwapFunc:TTeeSortSwap); { Returns a valid component name } Function TeeGetUniqueName(AOwner:TComponent; Const AStartName:String):TComponentName; { Delimited field routines } Var TeeFieldsSeparator:String=';'; { Returns the "index" item in string, using "TeeFieldsSeparator" character } Function TeeExtractField(St:String; Index:Integer):String; overload; { Returns the "index" item in string, using "Separator" parameter } Function TeeExtractField(St:String; Index:Integer; const Separator:String):String; overload; { Returns the number of fields in string, using "TeeFieldsSeparator" character } Function TeeNumFields(St:String):Integer; overload; { Returns the number of fields in string, using "Separator" parameter } Function TeeNumFields(const St,Separator:String):Integer; overload; { Try to find a resource bitmap and load it } Procedure TeeGetBitmapEditor(AObject:TObject; Var Bitmap:TBitmap); Procedure TeeLoadBitmap(Bitmap:TBitmap; Const Name1,Name2:String); type TColorArray=Array of TColor; { returns one of the sample colors in default ColorPalette constant array } Function GetDefaultColor(Const Index:Integer):TColor; // Resets ColorPalette to default one. Procedure SetDefaultColorPalette; overload; Procedure SetDefaultColorPalette(const Palette:Array of TColor); overload; var ColorPalette:TColorArray; const TeeBorderStyle={$IFDEF CLX}fbsDialog{$ELSE}bsDialog{$ENDIF}; TeeCheckBoxSize=11; { for TChart Legend } { Keyboard codes } TeeKey_Escape = {$IFDEF CLX}Key_Escape {$ELSE}VK_ESCAPE{$ENDIF}; TeeKey_Up = {$IFDEF CLX}Key_Up {$ELSE}VK_UP{$ENDIF}; TeeKey_Down = {$IFDEF CLX}Key_Down {$ELSE}VK_DOWN{$ENDIF}; TeeKey_Insert = {$IFDEF CLX}Key_Insert {$ELSE}VK_INSERT{$ENDIF}; TeeKey_Delete = {$IFDEF CLX}Key_Delete {$ELSE}VK_DELETE{$ENDIF}; TeeKey_Left = {$IFDEF CLX}Key_Left {$ELSE}VK_LEFT{$ENDIF}; TeeKey_Right = {$IFDEF CLX}Key_Right {$ELSE}VK_RIGHT{$ENDIF}; TeeKey_Return = {$IFDEF CLX}Key_Return {$ELSE}VK_RETURN{$ENDIF}; TeeKey_Space = {$IFDEF CLX}Key_Space {$ELSE}VK_SPACE{$ENDIF}; TeeKey_Back = {$IFDEF CLX}Key_BackSpace {$ELSE}VK_BACK{$ENDIF}; TeeKey_F1 = {$IFDEF CLX}Key_F1 {$ELSE}VK_F1{$ENDIF}; TeeKey_F2 = {$IFDEF CLX}Key_F2 {$ELSE}VK_F2{$ENDIF}; TeeKey_F3 = {$IFDEF CLX}Key_F3 {$ELSE}VK_F3{$ENDIF}; TeeKey_F4 = {$IFDEF CLX}Key_F4 {$ELSE}VK_F4{$ENDIF}; TeeKey_F5 = {$IFDEF CLX}Key_F5 {$ELSE}VK_F5{$ENDIF}; TeeKey_F6 = {$IFDEF CLX}Key_F6 {$ELSE}VK_F6{$ENDIF}; TeeKey_F7 = {$IFDEF CLX}Key_F7 {$ELSE}VK_F7{$ENDIF}; TeeKey_F8 = {$IFDEF CLX}Key_F8 {$ELSE}VK_F8{$ENDIF}; TeeKey_F9 = {$IFDEF CLX}Key_F9 {$ELSE}VK_F9{$ENDIF}; TeeKey_F10 = {$IFDEF CLX}Key_F10 {$ELSE}VK_F10{$ENDIF}; TeeKey_F11 = {$IFDEF CLX}Key_F11 {$ELSE}VK_F11{$ENDIF}; TeeKey_F12 = {$IFDEF CLX}Key_F12 {$ELSE}VK_F12{$ENDIF}; Procedure TeeDrawCheckBox( x,y:Integer; Canvas:TCanvas; Checked:Boolean; ABackColor:TColor; CheckBox:Boolean=True); {$IFNDEF D6} function StrToFloatDef(const S: string; const Default: Extended): Extended; {$ENDIF} { Returns True if line1 and line2 cross each other. xy is returned with crossing point. } function CrossingLines(const X1,Y1,X2,Y2,X3,Y3,X4,Y4:Double; var x,y:Double):Boolean; // TRANSLATIONS type TTeeTranslateHook=procedure(AControl:TControl); var TeeTranslateHook:TTeeTranslateHook=nil; // Main procedure to translate a control (or Form) Procedure TeeTranslateControl(AControl:TControl); // Replaces "Search" char with "Replace" char // in all occurrences in AString parameter. // Returns "AString" with replace characters. Function ReplaceChar(AString:String; Search:{$IFDEF NET}String{$ELSE}Char{$ENDIF}; Replace:Char=#0):String; // Returns "P" calculating 4 rotated corners using Angle parameter // Note: Due to a C++ Builder v5 bug, this procedure is not a function. Procedure RectToFourPoints(Const ARect:TRect; const Angle:Double; var P:TFourPoints); Function TeeAntiAlias(Panel:TCustomTeePanel):TBitmap; Procedure DrawBevel(Canvas:TTeeCanvas; Bevel:TPanelBevel; var R:TRect; Width:Integer; Round:Integer=0); // Internal use. Reads and saves a boolean from / to TRegistry / Inifile // Used by TGalleryPanel, TChartEditor and TeeDesignOptions function TeeReadBoolOption(const AKey:String; DefaultValue:Boolean):Boolean; procedure TeeSaveBoolOption(const AKey:String; Value:Boolean); Function TeeReadIntegerOption(const AKey:String; DefaultValue:Integer):Integer; procedure TeeSaveIntegerOption(const AKey:String; Value:Integer); {$IFDEF CLR} var HInstance : THandle=0; // WORKAROUND..pending. {$ENDIF} implementation Uses {$IFDEF CLR} System.Runtime.InteropServices, System.Reflection, System.IO, System.Drawing, {$ENDIF} {$IFNDEF D5} DsgnIntf, {$ENDIF} Math, TypInfo, {$IFDEF LINUX} IniFiles, {$ELSE} Registry, {$ENDIF} TeeConst; {.$DEFINE MONITOR_REDRAWS} {$IFDEF MONITOR_REDRAWS} var RedrawCount:Integer=0; {$ENDIF} {$IFNDEF CLR} {$R TeeResou.res} {$ENDIF} {$IFDEF CLX} Const LOGPIXELSX = 0; LOGPIXELSY = 1; {$ENDIF} var Tee19000101:TDateTime=0; { Optimization for TeeRoundDate function, 5.02 } { Same as IntToStr but faster } Function TeeStr(Num:Integer):String; begin Str(Num,Result); end; // Returns one of the sample colors in default ColorPalette constant array Function GetDefaultColor(Const Index:Integer):TColor; Begin result:=ColorPalette[Low(ColorPalette)+(Index mod Succ(High(ColorPalette)))]; // 6.02 end; {$IFDEF D5} Function DaysInMonth(Year,Month:Word):Word; begin result:=MonthDays[IsLeapYear(Year),Month] end; {$ELSE} Function DaysInMonth(Year,Month:Word):Word; Const DaysMonths:Array[1..12] of Byte=(31,28,31,30,31,30,31,31,30,31,30,31); Begin result:=DaysMonths[Month]; if (Month=2) and IsLeapYear(Year) then Inc(result); End; {$ENDIF} Function DateTimeDefaultFormat(Const AStep:Double):String; Begin if AStep<=1 then result:=ShortTimeFormat else result:=ShortDateFormat; end; Function NextDateTimeStep(Const AStep:Double):Double; var t : TDateTimeStep; Begin for t:=Pred(dtOneYear) downto Low(DateTimeStep) do if AStep>=DateTimeStep[t] then Begin result:=DateTimeStep[Succ(t)]; exit; end; result:=DateTimeStep[dtOneYear]; end; Function FindDateTimeStep(Const StepValue:Double):TDateTimeStep; begin for result:=Pred(High(DateTimeStep)) downto Low(DateTimeStep) do if Abs(DateTimeStep[result]-StepValue)<DateTimeStep[Low(DateTimeStep)] then Exit; result:=dtNone; end; { draw a simulated checkbox on Canvas } Procedure TeeDrawCheckBox( x,y:Integer; Canvas:TCanvas; Checked:Boolean; ABackColor:TColor; CheckBox:Boolean=True); {$IFDEF CLX} Procedure DoHorizLine(x1,x2,y:Integer); begin with Canvas do begin MoveTo(x1,y); LineTo(x2,y); end; end; Procedure DoVertLine(x,y1,y2:Integer); begin with Canvas do begin MoveTo(x,y1); LineTo(x,y2); end; end; {$ENDIF} var t : Integer; begin {$IFNDEF CLX} if CheckBox then t:=DFCS_BUTTONCHECK else t:=DFCS_BUTTONRADIO; if Checked then t:=t or DFCS_CHECKED; DrawFrameControl(Canvas.Handle,Bounds(x,y,13,13),DFC_BUTTON,t); {$ELSE} With Canvas do begin // RadioButton ???? Pen.Style:=psSolid; Pen.Width:=1; Pen.Color:=clGray; DoHorizLine(x+TeeCheckBoxSize,x,y); LineTo(x,y+TeeCheckBoxSize+1); ABackColor:=ColorToRGB(ABackColor); if (ABackColor=clWhite) {$IFDEF CLX}or (ABackColor=1){$ENDIF} then Pen.Color:=clSilver else Pen.Color:=clWhite; DoHorizLine(x,x+TeeCheckBoxSize+1,y+TeeCheckBoxSize+1); LineTo(x+TeeCheckBoxSize+1,y-1); Pen.Color:=clBlack; DoHorizLine(x+TeeCheckBoxSize-1,x+1,y+1); LineTo(x+1,y+TeeCheckBoxSize); Brush.Style:=bsSolid; Brush.Color:=clWindow; Pen.Style:=psClear; Rectangle(x+2,y+2,x+TeeCheckBoxSize+1,y+TeeCheckBoxSize+1); if Checked then begin Pen.Style:=psSolid; Pen.Color:=clWindowText; for t:=1 to 3 do DoVertLine(x+2+t,y+4+t,y+7+t); for t:=1 to 4 do DoVertLine(x+5+t,y+7-t,y+10-t); end; end; {$ENDIF} end; { TCustomPanelNoCaption } Constructor TCustomPanelNoCaption.Create(AOwner: TComponent); begin inherited; ControlStyle:=ControlStyle-[csSetCaption {$IFDEF CLX},csNoFocus{$ENDIF} ]; end; type TChartPenAccess=class {$IFDEF CLR}sealed{$ENDIF} (TChartPen); { TCustomTeePanel } Constructor TCustomTeePanel.Create(AOwner: TComponent); begin inherited; IEventListeners:=TTeeEventListeners.Create; Width := 400; Height:= 250; FApplyZOrder :=True; FDelphiCanvas:=inherited Canvas; FView3D :=True; FView3DOptions:=TView3DOptions.Create({$IFDEF TEEVCL}Self{$ENDIF}); InternalCanvas:=TTeeCanvas3D.Create; InternalCanvas.ReferenceCanvas:=FDelphiCanvas; FMargins:= TeeRect( TeeDefHorizMargin,TeeDefVerticalMargin, TeeDefHorizMargin,TeeDefVerticalMargin); FPrintProportional:=True; FPrintResolution:=TeeNormalPrintDetail; PrintMargins:=TeeRect( TeeDefault_PrintMargin,TeeDefault_PrintMargin, TeeDefault_PrintMargin,TeeDefault_PrintMargin); FOriginalCursor:=Cursor; FPanning:=TZoomPanning.Create; FShadow:=TTeeShadow.Create(CanvasChanged); FBorder:=TChartHiddenPen.Create(CanvasChanged); FBorder.EndStyle:=esFlat; TChartPenAccess(FBorder).DefaultEnd:=esFlat; if TeeEraseBack then TeeEraseBack:=not (csDesigning in ComponentState); AutoRepaint:=True; {$IFDEF CLX} QWidget_setBackgroundMode(Handle,QWidgetBackgroundMode_NoBackground); {$ENDIF} end; Destructor TCustomTeePanel.Destroy; Begin FreeAndNil(InternalCanvas); FBorder.Free; FShadow.Free; FView3DOptions.Free; FPanning.Free; FreeAndNil(IEventListeners); inherited; end; Procedure TCustomTeePanel.CanvasChanged(Sender:TObject); Begin Invalidate; end; {$IFNDEF CLX} procedure TCustomTeePanel.CreateParams(var Params: TCreateParams); begin inherited; // OpenGL: // Params.WindowClass.Style:=Params.WindowClass.Style or CS_OWNDC; if Color=clNone then Params.ExStyle:=Params.ExStyle or WS_EX_TRANSPARENT; { 5.02 } InternalCanvas.View3DOptions:=nil; end; {$ENDIF} Procedure TCustomTeePanel.SetShadow(Value:TTeeShadow); begin FShadow.Assign(Value); end; Procedure TCustomTeePanel.InternalDraw(Const UserRectangle:TRect); // virtual; abstract; begin end; procedure TCustomTeePanel.SetView3DOptions(Value:TView3DOptions); begin FView3DOptions.Assign(Value); end; procedure TCustomTeePanel.SetView3D(Value:Boolean); Begin if FView3D<>Value then // 6.0 begin SetBooleanProperty(FView3D,Value); BroadcastTeeEvent(TTeeView3DEvent.Create).Free; end; end; Procedure TCustomTeePanel.Draw; begin Draw(FDelphiCanvas,GetClientRect); end; type TCanvasAccess=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCanvas3D); Procedure TCustomTeePanel.Draw(UserCanvas:TCanvas; Const UserRect:TRect); Procedure AdjustChartBounds; Function GetMargin(Value,Range:Integer):Integer; begin if MarginUnits=muPercent then result:=Value*Range div 100 else result:=Value; end; Var tmpW : Integer; tmpH : Integer; tmpBorder : Integer; begin RectSize(FChartBounds,tmpW,tmpH); // Calculate amount of pixels for border and bevels... tmpBorder:=BorderWidth; if BevelInner<>bvNone then Inc(tmpBorder,BevelWidth); if BevelOuter<>bvNone then Inc(tmpBorder,BevelWidth); if Border.Visible then Inc(tmpBorder,Border.Width); // Apply margins With FChartBounds do ChartRect:=TeeRect( Left + tmpBorder + GetMargin(MarginLeft,tmpW), Top + tmpBorder + GetMargin(MarginTop,tmpH), Right - tmpBorder - GetMargin(MarginRight,tmpW), Bottom- tmpBorder - GetMargin(MarginBottom,tmpH) ); end; Begin {$IFDEF CLX} UserCanvas.Start; try {$ENDIF} FChartBounds:=InternalCanvas.InitWindow(UserCanvas,FView3DOptions,Color,FView3D,UserRect); AdjustChartBounds; RecalcWidthHeight; InternalDraw(FChartBounds); {$IFDEF MONITOR_REDRAWS} Inc(RedrawCount); InternalCanvas.TextAlign:=TA_LEFT; InternalCanvas.Font.Size:=8; TCanvasAccess(InternalCanvas).IFont:=nil; InternalCanvas.TextOut(0,0,TeeStr(RedrawCount)); {$ENDIF} InternalCanvas.ShowImage(UserCanvas,FDelphiCanvas,UserRect); {$IFDEF CLX} finally UserCanvas.Stop; end; {$ENDIF} end; procedure TCustomTeePanel.Paint; {$IFDEF TEEOCX} procedure TeeFpuInit; asm FNINIT FWAIT FLDCW Default8087CW end; {$ENDIF} begin {$IFDEF TEEOCX} TeeFPUInit; {$ENDIF} {$IFDEF CLX} if csDestroying in ComponentState then Exit; {$ENDIF} if (not FPrinting) and (not InternalCanvas.ReDrawBitmap) then Draw; end; {$IFDEF CLX} type TMetafileCanvas=class(TCanvas) public Constructor Create(Meta:TMetafile; Ref:Integer); end; { TMetafileCanvas } Constructor TMetafileCanvas.Create(Meta: TMetafile; Ref: Integer); begin inherited Create; end; {$ENDIF} Function TCustomTeePanel.TeeCreateMetafile( Enhanced:Boolean; Const Rect:TRect ):TMetafile; var tmpCanvas : TMetafileCanvas; begin result:=TMetafile.Create; { bug in Delphi 3.02 : graphics.pas metafile reduces width/height. Fixed in Delphi 4.0x and BCB4. } result.Width :=Max(1,Rect.Right-Rect.Left); result.Height:=Max(1,Rect.Bottom-Rect.Top); result.Enhanced:=Enhanced; tmpCanvas:=TMetafileCanvas.Create(result,0); try DrawToMetaCanvas(tmpCanvas,Rect); finally tmpCanvas.Free; end; end; Procedure TCustomTeePanel.SetBrushCanvas( AColor:TColor; ABrush:TChartBrush; ABackColor:TColor); begin if (ABrush.Style<>bsSolid) and (AColor=ABackColor) then if ABackColor=clBlack then AColor:=clWhite else AColor:=clBlack; Canvas.AssignBrushColor(ABrush,AColor,ABackColor); end; Function TeeGetDeviceCaps(Handle:{$IFDEF CLX}QPaintDeviceH {$ELSE}TTeeCanvasHandle {$ENDIF}; Cap:Integer):Integer; begin {$IFDEF CLX} result:=1; {$ELSE} result:=GetDeviceCaps(Handle,Cap); {$ENDIF} end; Function TCustomTeePanel.IsScreenHighColor:Boolean; Begin {$IFNDEF CLX} With InternalCanvas do result:= SupportsFullRotation or (TeeGetDeviceCaps(Handle,BITSPIXEL)* TeeGetDeviceCaps(Handle,PLANES)>=15); {$ELSE} result:=True; {$ENDIF} End; Function TCustomTeePanel.CanClip:Boolean; begin result:= (not Canvas.SupportsFullrotation) and ( ((not Printing) and (not Canvas.Metafiling)) or (Printing and TeeClipWhenPrinting) or (Canvas.Metafiling and TeeClipWhenMetafiling) ) end; Procedure TCustomTeePanel.SetStringProperty(Var Variable:String; Const Value:String); Begin if Variable<>Value then begin Variable:=Value; Invalidate; end; end; Procedure TCustomTeePanel.SetDoubleProperty(Var Variable:Double; Const Value:Double); begin if Variable<>Value then begin Variable:=Value; Invalidate; end; end; Procedure TCustomTeePanel.SetColorProperty(Var Variable:TColor; Value:TColor); Begin if Variable<>Value then begin Variable:=Value; Invalidate; end; end; Procedure TCustomTeePanel.SetBooleanProperty(Var Variable:Boolean; Value:Boolean); Begin if Variable<>Value then begin Variable:=Value; Invalidate; end; end; Procedure TCustomTeePanel.SetIntegerProperty(Var Variable:Integer; Value:Integer); Begin if Variable<>Value then begin Variable:=Value; Invalidate; end; end; procedure TCustomTeePanel.ReadBorderStyle(Reader: TReader); // obsolete begin Border.Visible:=Reader.ReadIdent='bsSingle'; end; Procedure TCustomTeePanel.DefineProperties(Filer:TFiler); // obsolete begin inherited; Filer.DefineProperty('BorderStyle',ReadBorderStyle,nil,False); end; Function TCustomTeePanel.GetBackColor:TColor; begin result:=Color; end; Procedure TCustomTeePanel.Loaded; begin inherited; FOriginalCursor:=Cursor; { save cursor } if BorderRound>0 then // 6.01 SetControlRounded; end; {$IFDEF CLX} procedure TCustomTeePanel.BoundsChanged; begin inherited; Invalidate; end; {$ENDIF} {$IFDEF CLX} procedure TCustomTeePanel.MouseLeave(AControl: TControl); {$ELSE} procedure TCustomTeePanel.CMMouseLeave(var Message: TMessage); {$ENDIF} begin Cursor:=FOriginalCursor; FPanning.Active:=False; inherited; end; {$IFNDEF CLX} procedure TCustomTeePanel.CMSysColorChange(var Message: TMessage); begin inherited; Invalidate; end; procedure TCustomTeePanel.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; Message.Result:=Message.Result or DLGC_WANTARROWS; end; procedure TCustomTeePanel.WMEraseBkgnd(var Message: TWmEraseBkgnd); Begin if TeeEraseBack then Inherited; Message.Result:=1; End; {$ENDIF} procedure TCustomTeePanel.Invalidate; begin if AutoRepaint then begin if Assigned(InternalCanvas) then InternalCanvas.Invalidate; inherited; end; end; procedure TCustomTeePanel.AssignTo(Dest: TPersistent); var tmp : TBitmap; begin if (Dest is TGraphic) or (Dest is TPicture) then begin tmp:=TeeCreateBitmap(Color,GetRectangle); try Dest.Assign(tmp); finally tmp.Free; end; end else inherited; end; procedure TCustomTeePanel.RemoveListener(Sender:ITeeEventListener); begin if Assigned(IEventListeners) then IEventListeners.Remove(Sender); end; procedure TCustomTeePanel.Resize; begin if (not (csLoading in ComponentState)) and (BorderRound>0) then SetControlRounded; inherited; end; Function TCustomTeePanel.BroadcastTeeEvent(Event:TTeeEvent):TTeeEvent; var t : Integer; tmp : ITeeEventListener; begin result:=Event; if not (csDestroying in ComponentState) then begin Event.Sender:=Self; t:=0; while t<Listeners.Count do begin tmp:=Listeners[t]; tmp.TeeEvent(Event); if (Event is TTeeMouseEvent) and CancelMouse then break; { 5.01 } Inc(t); end; end; end; procedure TCustomTeePanel.BroadcastMouseEvent(Kind:TTeeMouseEventKind; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var tmp : TTeeMouseEvent; begin if Listeners.Count>0 then begin tmp:=TTeeMouseEvent.Create; try tmp.Event:=Kind; tmp.Button:=Button; tmp.Shift:=Shift; tmp.X:=X; tmp.Y:=Y; BroadcastTeeEvent(tmp); finally tmp.Free; end; end; end; procedure TCustomTeePanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin CancelMouse:=False; inherited; BroadcastMouseEvent(meDown,Button,Shift,X,Y); end; procedure TCustomTeePanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; BroadcastMouseEvent(meUp,Button,Shift,X,Y); end; procedure TCustomTeePanel.MouseMove(Shift: TShiftState; X, Y: Integer); begin CancelMouse:=False; inherited; if (Listeners.Count>0) and (not (csDesigning in ComponentState)) then BroadcastMouseEvent(meMove,mbLeft,Shift,X,Y); end; procedure TCustomTeePanel.DblClick; begin CancelMouse:=False; inherited; if CancelMouse then Abort; end; {$IFNDEF CLR} type TRectArray=array[0..3] of Integer; {$ENDIF} Function TCustomTeePanel.GetMargin(Index:Integer):Integer; begin {$IFDEF CLR} case Index of 0: result:=FMargins.Left; 1: result:=FMargins.Top; 2: result:=FMargins.Right; else result:=FMargins.Bottom; end; {$ELSE} result:=TRectArray(FMargins)[Index]; {$ENDIF} end; Procedure TCustomTeePanel.SetMargin(Index,Value:Integer); begin {$IFDEF CLR} case Index of 0: SetIntegerProperty(FMargins.Left,Value); 1: SetIntegerProperty(FMargins.Top,Value); 2: SetIntegerProperty(FMargins.Right,Value); 3: SetIntegerProperty(FMargins.Bottom,Value); end; {$ELSE} SetIntegerProperty(TRectArray(FMargins)[Index],Value); {$ENDIF} end; Function TCustomTeePanel.GetBufferedDisplay:Boolean; begin result:=InternalCanvas.UseBuffer; end; Procedure TCustomTeePanel.SetBorder(const Value:TChartHiddenPen); begin Border.Assign(Value); end; procedure TCustomTeePanel.SetControlRounded; {$IFDEF CLX} begin end; {$ELSE} var Region : HRGN; begin if not IRounding then // re-entrance protection (from Resize method) if Assigned(Parent) then // <-- needs Parent to obtain Handle below begin IRounding:=True; try if BorderRound>0 then Region:=CreateRoundRectRgn(0,0,Width,Height,BorderRound,BorderRound) else Region:=0; SetWindowRgn(Handle,Region,True); finally IRounding:=False; end; end; end; {$ENDIF} Procedure TCustomTeePanel.SetBorderRound(Value:Integer); begin if FBorderRound<>Value then begin FBorderRound:=Value; if not (csLoading in ComponentState) then SetControlRounded; end; end; Function TCustomTeePanel.GetBorderStyle:TBorderStyle; begin if FBorder.Visible then result:=bsSingle else result:=bsNone; end; Procedure TCustomTeePanel.SetBorderStyle(Value:TBorderStyle); begin FBorder.Visible:=Value=bsSingle; end; Procedure TCustomTeePanel.SetBufferedDisplay(Value:Boolean); begin InternalCanvas.UseBuffer:=Value; end; Procedure TCustomTeePanel.SetInternalCanvas(NewCanvas:TCanvas3D); var Old : Boolean; begin if Assigned(NewCanvas) then begin NewCanvas.ReferenceCanvas:=FDelphiCanvas; if Assigned(InternalCanvas) then begin Old:=AutoRepaint; { 5.02 } AutoRepaint:=False; NewCanvas.Assign(InternalCanvas); AutoRepaint:=Old; { 5.02 } InternalCanvas.Free; end; InternalCanvas:=NewCanvas; if AutoRepaint then Repaint; { 5.02 } end; end; procedure TCustomTeePanel.RecalcWidthHeight; Begin With ChartRect do begin if Left<FChartBounds.Left then Left:=FChartBounds.Left; if Top<FChartBounds.Top then Top:=FChartBounds.Top; if Right<Left then Right:=Left+1 else if Right=Left then Right:=Left+Width; if Bottom<Top then Bottom:=Top+1 else if Bottom=Top then Bottom:=Top+Height; FChartWidth :=Right-Left; FChartHeight :=Bottom-Top; end; RectCenter(ChartRect,FChartXCenter,FChartYCenter); end; Function TCustomTeePanel.GetCursorPos:TPoint; Begin result:=ScreenToClient(Mouse.CursorPos); end; Function TCustomTeePanel.GetRectangle:TRect; begin if Assigned(Parent) then result:=GetClientRect else result:=TeeRect(0,0,Width,Height); // 5.02 end; Procedure TCustomTeePanel.DrawToMetaCanvas(ACanvas:TCanvas; Const Rect:TRect); begin { assume the acanvas is in MM_ANISOTROPIC mode } InternalCanvas.Metafiling:=True; try NonBufferDraw(ACanvas,Rect); finally InternalCanvas.Metafiling:=False; end; end; Function TCustomTeePanel.GetMonochrome:Boolean; Begin result:=InternalCanvas.Monochrome; end; Procedure TCustomTeePanel.SetMarginUnits(const Value:TTeeUnits); begin if FMarginUnits<>Value then begin FMarginUnits:=Value; Invalidate; end; end; Procedure TCustomTeePanel.SetMonochrome(Value:Boolean); Begin InternalCanvas.Monochrome:=Value; end; Procedure TCustomTeePanel.Assign(Source:TPersistent); begin if Source is TCustomTeePanel then With TCustomTeePanel(Source) do begin Self.Border := Border; Self.BorderRound := BorderRound; Self.BufferedDisplay := BufferedDisplay; Self.PrintMargins := PrintMargins; Self.FPrintProportional := FPrintProportional; Self.FPrintResolution := FPrintResolution; Self.FMargins := FMargins; Self.FMarginUnits := FMarginUnits; // 6.01.1 Self.Monochrome := Monochrome; Self.Shadow := Shadow; Self.FView3D := FView3D; Self.View3DOptions := FView3DOptions; Self.Color := Color; end else inherited; end; Procedure TCustomTeePanel.SaveToMetafile(Const FileName:String); begin SaveToMetaFileRect(False,FileName,GetRectangle); end; Procedure TCustomTeePanel.SaveToMetafileEnh(Const FileName:String); begin SaveToMetaFileRect(True,FileName,GetRectangle); end; { Enhanced:Boolean } Procedure TCustomTeePanel.SaveToMetafileRect( Enhanced:Boolean; Const FileName:String; Const Rect:TRect); Var tmpStream : TFileStream; Begin With TeeCreateMetafile(Enhanced,Rect) do try tmpStream:=TFileStream.Create(FileName,fmCreate); try SaveToStream(tmpStream); finally tmpStream.Free; end; finally Free; end; End; Procedure TCustomTeePanel.NonBufferDraw(ACanvas:TCanvas; Const R:TRect); var Old : Boolean; begin Old:=BufferedDisplay; try BufferedDisplay:=False; Draw(ACanvas,R); finally BufferedDisplay:=Old; end; end; Function TCustomTeePanel.TeeCreateBitmap(ABackColor:TColor; Const Rect:TRect; APixelFormat:{$IFNDEF CLX}Graphics.{$ENDIF}TPixelFormat= {$IFDEF CLX}TeePixelFormat{$ELSE}pfDevice{$ENDIF} ):TBitmap; begin result:=TBitmap.Create; With result do begin {$IFNDEF CLX} IgnorePalette:=PixelFormat=TeePixelFormat; {$ENDIF} if InternalCanvas.SupportsFullRotation then PixelFormat:=TeePixelFormat else PixelFormat:=APixelFormat; Width:=Rect.Right-Rect.Left; Height:=Rect.Bottom-Rect.Top; if ABackColor<>clWhite then begin Canvas.Brush.Color:=ABackColor; Canvas.FillRect(Rect); end; NonBufferDraw(Canvas,Rect); end; end; Procedure TCustomTeePanel.SaveToBitmapFile(Const FileName:String); Begin SaveToBitmapFile(FileName,GetRectangle); End; Procedure TCustomTeePanel.SaveToBitmapFile(Const FileName:String; Const R:TRect); begin With TeeCreateBitmap(clWhite,R) do try SaveToFile(FileName); finally Free; end; end; Procedure TCustomTeePanel.PrintPortrait; Begin PrintOrientation(poPortrait); end; Procedure TCustomTeePanel.PrintLandscape; Begin PrintOrientation(poLandscape); end; Procedure TCustomTeePanel.PrintOrientation(AOrientation:TPrinterOrientation); Var OldOrientation : TPrinterOrientation; Begin OldOrientation:=Printer.Orientation; Printer.Orientation:=AOrientation; try Print; finally Printer.Orientation:=OldOrientation; end; end; Procedure TCustomTeePanel.CopyToClipboardBitmap(Const R:TRect); var tmpBitmap : TBitmap; begin tmpBitmap:=TeeCreateBitmap(clWhite,R); try ClipBoard.Assign(tmpBitmap); finally tmpBitmap.Free; end; end; Procedure TCustomTeePanel.CopyToClipboardBitmap; begin CopyToClipboardBitmap(GetRectangle); end; Procedure TCustomTeePanel.CopyToClipboardMetafile( Enhanced:Boolean; Const R:TRect); Var tmpMeta : TMetaFile; begin tmpMeta:=TeeCreateMetafile(Enhanced,R); try ClipBoard.Assign(tmpMeta); finally tmpMeta.Free; end; end; Procedure TCustomTeePanel.CopyToClipboardMetafile(Enhanced:Boolean); begin CopyToClipboardMetafile(Enhanced,GetRectangle); end; Procedure TCustomTeePanel.CalcMetaBounds( Var R:TRect; Const AChartRect:TRect; Var WinWidth,WinHeight, ViewWidth,ViewHeight:Integer); Var tmpRectWidth : Integer; tmpRectHeight : Integer; begin { apply PrintResolution to the desired rectangle coordinates } RectSize(R,ViewWidth,ViewHeight); RectSize(AChartRect,tmpRectWidth,tmpRectHeight); WinWidth :=tmpRectWidth -MulDiv(tmpRectWidth, PrintResolution,100); WinHeight:=tmpRectHeight-MulDiv(tmpRectHeight,PrintResolution,100); With R do begin Left :=MulDiv(Left ,WinWidth,ViewWidth); Right :=MulDiv(Right ,WinWidth,ViewWidth); Top :=MulDiv(Top ,WinHeight,ViewHeight); Bottom:=MulDiv(Bottom,WinHeight,ViewHeight); end; end; Procedure TCustomTeePanel.PrintPartialCanvas( PrintCanvas:TCanvas; Const PrinterRect:TRect); Var ViewWidth : Integer; ViewHeight : Integer; WinWidth : Integer; WinHeight : Integer; tmpR : TRect; {$IFNDEF CLX} OldMapMode : Integer; {$ENDIF} Procedure SetAnisotropic; { change canvas/windows metafile mode } {$IFNDEF CLX} Var DC : HDC; {$ENDIF} begin {$IFNDEF CLX} DC:=PrintCanvas.Handle; OldMapMode:=GetMapMode(DC); SetMapMode(DC, MM_ANISOTROPIC); SetWindowOrgEx( DC, 0, 0, nil); SetWindowExtEx( DC, WinWidth, WinHeight, nil); SetViewportExtEx(DC, ViewWidth,ViewHeight, nil); SetViewportOrgEx(DC, 0, 0, nil); {$ENDIF} end; Begin { check if margins inverted } tmpR:=OrientRectangle(PrinterRect); { apply PrintResolution to dimensions } CalcMetaBounds(tmpR,GetRectangle,WinWidth,WinHeight,ViewWidth,ViewHeight); {//SaveDC} SetAnisotropic; FPrinting:=True; try if CanClip then ClipCanvas(PrintCanvas,tmpR); DrawToMetaCanvas(PrintCanvas,tmpR); UnClipCanvas(PrintCanvas); finally FPrinting:=False; end; {$IFNDEF CLX} SetMapMode(PrintCanvas.Handle,OldMapMode); {$ENDIF} {//RestoreDC} end; Procedure TCustomTeePanel.PrintPartial(Const PrinterRect:TRect); Begin PrintPartialCanvas(Printer.Canvas,PrinterRect); End; Procedure TCustomTeePanel.PrintRect(Const R:TRect); Begin if Name<>'' then Printer.Title:=Name; Printer.BeginDoc; try PrintPartial(R); Printer.EndDoc; except on Exception do begin Printer.Abort; if Printer.Printing then Printer.EndDoc; Raise; end; end; end; Function TCustomTeePanel.CalcProportionalMargins:TRect; var tmpPrinterOk : Boolean; Function CalcMargin(Size1,Size2:Integer; Const ARatio:Double):Integer; Var tmpPrinterRatio : Double; tmpDefaultMargin : Double; begin if tmpPrinterOk then tmpPrinterRatio:= TeeGetDeviceCaps(Printer.Handle,LOGPIXELSX)/ TeeGetDeviceCaps(Printer.Handle,LOGPIXELSY) else tmpPrinterRatio:= 1; tmpDefaultMargin:=(2.0*TeeDefault_PrintMargin)*Size1*0.01; // 7.0 result:=Round(100.0*(Size2-((Size1-tmpDefaultMargin)*ARatio*tmpPrinterRatio))/Size2) div 2; end; Var tmp : Integer; tmpWidth : Integer; tmpHeight : Integer; tmpPrinterW : Integer; { 5.03 } tmpPrinterH : Integer; begin With GetRectangle do begin tmpWidth:=Right-Left; tmpHeight:=Bottom-Top; end; tmpPrinterOk:=True; try tmpPrinterW:=Printer.PageWidth; tmpPrinterH:=Printer.PageHeight; except on EPrinter do begin tmpPrinterOk:=False; tmpPrinterW:=Screen.Width; tmpPrinterH:=Screen.Height; end; end; if tmpWidth > tmpHeight then begin tmp:=CalcMargin(tmpPrinterW,tmpPrinterH,tmpHeight/tmpWidth); Result:=TeeRect(TeeDefault_PrintMargin,tmp,TeeDefault_PrintMargin,tmp); end else begin tmp:=CalcMargin(tmpPrinterH,tmpPrinterW,tmpWidth/tmpHeight); Result:=TeeRect(tmp,TeeDefault_PrintMargin,tmp,TeeDefault_PrintMargin); end; end; Function TCustomTeePanel.ChartPrintRect:TRect; Var tmpLog : Array[Boolean] of Integer; Function InchToPixel(Horizontal:Boolean; Const Inch:Double):Integer; begin result:=Round(Inch*tmpLog[Horizontal]); end; Var tmp : Double; Begin if FPrintProportional then PrintMargins:=CalcProportionalMargins; { calculate margins in pixels and calculate the remaining rectangle in pixels } tmpLog[True] :=TeeGetDeviceCaps(Printer.Handle,LOGPIXELSX); tmpLog[False]:=TeeGetDeviceCaps(Printer.Handle,LOGPIXELSY); With result do Begin tmp :=0.01*Printer.PageWidth/(1.0*tmpLog[True]); Left :=InchToPixel(True,1.0*PrintMargins.Left*tmp); Right :=Printer.PageWidth-InchToPixel(True,1.0*PrintMargins.Right*tmp); tmp :=0.01*Printer.PageHeight/(1.0*tmpLog[False]); Top :=InchToPixel(False,1.0*PrintMargins.Top*tmp); Bottom:=Printer.PageHeight-InchToPixel(False,1.0*PrintMargins.Bottom*tmp); end; end; Procedure TCustomTeePanel.Print; Begin PrintRect(ChartPrintRect); end; Procedure TCustomTeePanel.CheckPenWidth(APen:TPen); begin if Printing and TeeCheckPenWidth and (APen.Style<>psSolid) and (APen.Width=1) then APen.Width:=0; { <-- fixes some printer's bug (HP Laserjets?) } end; Procedure DrawBevel(Canvas:TTeeCanvas; Bevel:TPanelBevel; var R:TRect; Width:Integer; Round:Integer=0); Const Colors:Array[Boolean] of TColor=(clBtnHighlight,clBtnShadow); begin if Bevel<>bvNone then if Round>0 then begin Canvas.Pen.Color:=Colors[Bevel=bvLowered]; Canvas.RoundRect(R,Round,Round); InflateRect(R,-Width,-Width); end else Canvas.Frame3D(R,Colors[Bevel=bvLowered],Colors[Bevel=bvRaised],Width); end; Procedure TCustomTeePanel.DrawPanelBevels(Rect:TRect); var tmp : Integer; tmpHoriz : Integer; begin Canvas.FrontPlaneBegin; Canvas.Brush.Style:=bsClear; if Border.Visible then begin Canvas.AssignVisiblePen(Border); if Border.SmallDots then tmp:=1 else begin // Fix big pen width tmp:=Border.Width-1; if tmp>0 then begin tmpHoriz:=tmp div 2; if tmp mod 2=1 then Inc(tmpHoriz); tmp:=tmp div 2; if tmp mod 2=1 then Dec(tmp); Inc(Rect.Left,tmpHoriz); Inc(Rect.Top,tmpHoriz); Dec(Rect.Right,tmp); Dec(Rect.Bottom,tmp); end; end; if BorderRound>0 then begin Dec(Rect.Right); Dec(Rect.Bottom); Canvas.RoundRect(Rect,BorderRound,BorderRound) end else begin Canvas.Rectangle(Rect); if not Border.SmallDots then Inc(tmp); end; InflateRect(Rect,-tmp,-tmp); end; if (not Printing) or PrintTeePanel then begin With Canvas.Pen do begin Style:=psSolid; Width:=1; Mode:=pmCopy; end; DrawBevel(Canvas,BevelOuter,Rect,BevelWidth,BorderRound); if BorderWidth>0 then Canvas.Frame3D(Rect, Color, Color, BorderWidth); DrawBevel(Canvas,BevelInner,Rect,BevelWidth,BorderRound); end; Canvas.FrontPlaneEnd; end; {$IFDEF CLX} function TCustomTeePanel.WidgetFlags: Integer; begin result:=inherited WidgetFlags or Integer(WidgetFlags_WRepaintNoErase) or Integer(WidgetFlags_WResizeNoErase); end; {$ENDIF} Function TTeeZoomPen.IsColorStored:Boolean; begin result:=Color<>DefaultColor; end; { TTeeZoom } Constructor TTeeZoom.Create; begin inherited; FAnimatedSteps:=8; FAllow:=True; FDirection:=tzdBoth; FMinimumPixels:=16; FMouseButton:=mbLeft; end; Destructor TTeeZoom.Destroy; Begin FPen.Free; FBrush.Free; inherited; end; Procedure TTeeZoom.Assign(Source:TPersistent); begin if Source is TTeeZoom then With TTeeZoom(Source) do begin Self.FAllow := FAllow; Self.FAnimated := FAnimated; Self.FAnimatedSteps:= FAnimatedSteps; Self.Brush := FBrush; Self.FDirection := FDirection; Self.FKeyShift := FKeyShift; Self.FMouseButton := FMouseButton; Self.Pen := FPen; end; end; procedure TTeeZoom.SetBrush(Value:TTeeZoomBrush); begin if Assigned(Value) then Brush.Assign(Value) else FreeAndNil(FBrush); end; procedure TTeeZoom.SetPen(Value:TTeeZoomPen); begin if Assigned(Value) then Pen.Assign(Value) else FreeAndNil(FPen); end; Function TTeeZoom.GetBrush:TTeeZoomBrush; begin if not Assigned(FBrush) then begin FBrush:=TTeeZoomBrush.Create(nil); FBrush.Color:=clWhite; FBrush.Style:=bsClear; end; result:=FBrush; end; Function TTeeZoom.GetPen:TTeeZoomPen; begin if not Assigned(FPen) then begin FPen:=TTeeZoomPen.Create(nil); FPen.Color:=clWhite; FPen.DefaultColor:=clWhite; end; result:=FPen; end; // TBackImage constructor TBackImage.Create; begin inherited; FMode:=pbmStretch; end; procedure TBackImage.Assign(Source:TPersistent); begin if Source is TBackImage then with TBackImage(Source) do begin Self.FInside:=FInside; Self.FLeft:=FLeft; Self.FMode:=FMode; Self.FTop:=FTop; end; inherited; end; procedure TBackImage.SetInside(Const Value:Boolean); begin if Inside<>Value then begin FInside:=Value; Changed(Self); end; end; procedure TBackImage.SetMode(Const Value:TTeeBackImageMode); begin if Mode<>Value then begin FMode:=Value; Changed(Self); end; end; procedure TBackImage.SetLeft(Value:Integer); begin if Left<>Value then begin FLeft:=Value; Changed(Self); end; end; procedure TBackImage.SetTop(Value:Integer); begin if Top<>Value then begin FTop:=Value; Changed(Self); end; end; { TCustomTeePanelExtended } Constructor TCustomTeePanelExtended.Create(AOwner: TComponent); begin inherited; FAllowPanning:=pmBoth; FZoom:=TTeeZoom.Create; end; Destructor TCustomTeePanelExtended.Destroy; Begin FZoom.Free; FGradient.Free; FBackImage.Free; inherited; end; Procedure TCustomTeePanelExtended.SetAnimatedZoom(Value:Boolean); Begin FZoom.Animated:=Value; end; Procedure TCustomTeePanelExtended.SetAnimatedZoomSteps(Value:Integer); Begin FZoom.AnimatedSteps:=Value; end; Function TCustomTeePanelExtended.GetBackImage:TBackImage; begin if not Assigned(FBackImage) then begin FBackImage:=TBackImage.Create; FBackImage.OnChange:=CanvasChanged; end; result:=FBackImage; end; procedure TCustomTeePanelExtended.SetBackImage(const Value:TBackImage); begin if Assigned(Value) then BackImage.Assign(Value) else FreeAndNil(FBackImage); end; procedure TCustomTeePanelExtended.SetBackImageInside(Const Value:Boolean); begin BackImage.Inside:=Value; end; procedure TCustomTeePanelExtended.SetBackImageMode(Const Value:TTeeBackImageMode); Begin BackImage.Mode:=Value; End; function TCustomTeePanelExtended.HasBackImage:Boolean; begin result:=Assigned(FBackImage) and Assigned(FBackImage.Graphic); end; procedure TCustomTeePanelExtended.SetBackImageTransp(Const Value:Boolean); begin if HasBackImage then { 5.03 } FBackImage.Graphic.Transparent:=Value; { 5.02 } end; procedure TCustomTeePanelExtended.UndoZoom; begin if Assigned(FOnUndoZoom) then FOnUndoZoom(Self); Invalidate; FZoomed:=False; end; Function TCustomTeePanelExtended.GetGradient:TChartGradient; begin if not Assigned(FGradient) then FGradient:=TChartGradient.Create(CanvasChanged); result:=FGradient; end; procedure TCustomTeePanelExtended.SetGradient(Value:TChartGradient); begin if Assigned(Value) then Gradient.Assign(Value) else FreeAndNil(FGradient); end; Procedure TCustomTeePanelExtended.Assign(Source:TPersistent); begin if Source is TCustomTeePanelExtended then With TCustomTeePanelExtended(Source) do begin Self.BackImage := FBackImage; Self.Gradient := FGradient; Self.FAllowPanning:= FAllowPanning; Self.Zoom := Zoom; end; inherited; end; {$IFNDEF CLR} {$IFNDEF CLX} function TCustomTeePanelExtended.GetPalette: HPALETTE; begin Result:=0; { default result is no palette } if HasBackImage and (FBackImage.Graphic is TBitmap) then { only bitmaps have palettes } Result := TBitmap(FBackImage.Graphic).Palette; { use it if available } end; {$ENDIF} {$ENDIF} procedure TCustomTeePanelExtended.DrawBitmap(Rect:TRect; Z:Integer); var RectH : Integer; RectW : Integer; Procedure TileBitmap; Var tmpWidth : Integer; tmpHeight : Integer; tmpX : Integer; tmpY : Integer; tmpIs3D : Boolean; begin tmpWidth :=FBackImage.Width; tmpHeight:=FBackImage.Height; { keep "painting" the wall with tiled small images... } if (tmpWidth>0) and (tmpHeight>0) then begin tmpY:=0; tmpIs3D:=(Z>0) and (not View3DOptions.Orthogonal); while tmpY<RectH do begin tmpX:=0; while tmpX<RectW do begin if tmpIs3D then Canvas.StretchDraw(TeeRect(Rect.Left+tmpX,Rect.Top+tmpY, Rect.Left+tmpX+tmpWidth, Rect.Top+tmpY+tmpHeight), FBackImage.Graphic,Z) else Canvas.Draw(Rect.Left+tmpX,Rect.Top+tmpY,FBackImage.Graphic); Inc(tmpX,tmpWidth); end; Inc(tmpY,tmpHeight); end; end; end; Procedure Calc3DRect; begin Rect:=Canvas.CalcRect3D(Rect,Z); if not View3D then Inc(Rect.Top); end; var ShouldClip : Boolean; Begin if HasBackImage then begin if BackImage.Mode=pbmStretch then begin if Z>0 then if View3DOptions.Orthogonal then begin Calc3DRect; Canvas.StretchDraw(Rect,FBackImage.Graphic); end else Canvas.StretchDraw(Rect,FBackImage.Graphic,Z) else Canvas.StretchDraw(Rect,FBackImage.Graphic); end else begin ShouldClip:=CanClip; if ShouldClip then if Z=0 then Canvas.ClipRectangle(Rect) else Canvas.ClipCube(Rect,0,Width3D); if (Z>0) and View3DOptions.Orthogonal then Calc3DRect; RectSize(Rect,RectW,RectH); if BackImage.Mode=pbmTile then TileBitmap else { draw centered } begin FillPanelRect(Rect); if BackImage.Mode=pbmCustom then begin Rect.Left:=Rect.Left+BackImage.Left; Rect.Top:=Rect.Top+BackImage.Top; Rect.Right:=Rect.Left+BackImage.Width; Rect.Bottom:=Rect.Top+BackImage.Height; end else InflateRect(Rect,-(RectW-FBackImage.Width) div 2, -(RectH-FBackImage.Height) div 2); if (Z>0) and (not View3DOptions.Orthogonal) then Canvas.StretchDraw(Rect,FBackImage.Graphic,Z) else Canvas.Draw(Rect.Left,Rect.Top,FBackImage.Graphic); end; if ShouldClip then Canvas.UnClipRectangle; end; end; end; procedure TCustomTeePanelExtended.PanelPaint(Const UserRect:TRect); Var Rect : TRect; Procedure DrawShadow; var tmpColor : TColor; begin if Assigned(Parent) then tmpColor:=Parent.Brush.Color else tmpColor:=Color; With Canvas do begin Brush.Color:=tmpColor; Brush.Style:=bsSolid; EraseBackground(Rect); end; Dec(Rect.Right,Shadow.HorizSize); Dec(Rect.Bottom,Shadow.VertSize); Shadow.Draw(Canvas,Rect); end; begin Canvas.FrontPlaneBegin; Rect:=UserRect; if Shadow.Size>0 then DrawShadow; FillPanelRect(Rect); if HasBackImage and (not BackImage.Inside) then DrawBitmap(Rect,0); DrawPanelBevels(Rect); Canvas.FrontPlaneEnd; end; procedure TCustomTeePanelExtended.FillPanelRect(Const Rect:TRect); Begin Canvas.FrontPlaneBegin; if Assigned(FGradient) and FGradient.Visible then FGradient.Draw(Canvas,Rect) else { PrintTeePanel is a "trick" to paint Chart background also when printing } if ((not Printing) or PrintTeePanel) and (Self.Color<>clNone) then With Canvas do begin Brush.Color:=Self.Color; Brush.Style:=bsSolid; EraseBackground(Rect); end; Canvas.FrontPlaneEnd; end; procedure TCustomTeePanelExtended.DrawZoomRectangle; var tmp:TColor; Begin tmp:=ColorToRGB(GetBackColor); if Assigned(Zoom.FBrush) then SetBrushCanvas((clWhite-tmp) xor Zoom.Brush.Color,Zoom.Brush,tmp) else InternalCanvas.Brush.Style:=bsClear; Zoom.Pen.Mode:=pmNotXor; With InternalCanvas do Begin AssignVisiblePenColor(Zoom.Pen,(clWhite-tmp) xor Zoom.Pen.Color); if (not Assigned(Zoom.FBrush)) or (Zoom.FBrush.Style=bsClear) then BackMode:=cbmTransparent; With Zoom do Rectangle(X0,Y0,X1,Y1); end; end; function TCustomTeePanelExtended.GetAllowZoom: Boolean; begin result:=Zoom.Allow; end; function TCustomTeePanelExtended.GetAnimatedZoom: Boolean; begin result:=Zoom.Animated; end; function TCustomTeePanelExtended.GetAnimatedZoomSteps: Integer; begin result:=Zoom.AnimatedSteps; end; Function TCustomTeePanelExtended.GetBackImageTransp:Boolean; begin result:=HasBackImage and FBackImage.Graphic.Transparent; end; Function TCustomTeePanelExtended.GetBackImageInside:Boolean; begin result:=HasBackImage and BackImage.Inside; end; Function TCustomTeePanelExtended.GetBackImageMode:TTeeBackImageMode; begin result:=BackImage.Mode; end; procedure TCustomTeePanelExtended.SetAllowZoom(Value: Boolean); begin Zoom.Allow:=Value; end; procedure TCustomTeePanelExtended.SetZoom(Value: TTeeZoom); begin FZoom.Assign(Value); end; procedure TCustomTeePanelExtended.ReadAllowZoom(Reader: TReader); begin Zoom.Allow:=Reader.ReadBoolean; end; procedure TCustomTeePanelExtended.ReadAnimatedZoom(Reader: TReader); begin Zoom.Animated:=Reader.ReadBoolean; end; procedure TCustomTeePanelExtended.ReadAnimatedZoomSteps(Reader: TReader); begin Zoom.AnimatedSteps:=Reader.ReadInteger; end; procedure TCustomTeePanelExtended.ReadPrintMargins(Reader: TReader); begin Reader.ReadListBegin; with FPrintMargins do begin Left :=Reader.ReadInteger; Top :=Reader.ReadInteger; Right :=Reader.ReadInteger; Bottom:=Reader.ReadInteger; end; Reader.ReadListEnd; end; procedure TCustomTeePanelExtended.SavePrintMargins(Writer: TWriter); begin Writer.WriteListBegin; with PrintMargins do begin Writer.WriteInteger(Left); Writer.WriteInteger(Top); Writer.WriteInteger(Right); Writer.WriteInteger(Bottom); end; Writer.WriteListEnd; end; procedure TCustomTeePanelExtended.DefineProperties(Filer:TFiler); Function NotDefaultPrintMargins:Boolean; begin With PrintMargins do result:= (Left<>TeeDefault_PrintMargin) or (Top<>TeeDefault_PrintMargin) or (Right<>TeeDefault_PrintMargin) or (Bottom<>TeeDefault_PrintMargin); end; begin inherited; Filer.DefineProperty('AllowZoom',ReadAllowZoom,nil,False); Filer.DefineProperty('AnimatedZoom',ReadAnimatedZoom,nil,False); Filer.DefineProperty('AnimatedZoomSteps',ReadAnimatedZoomSteps,nil,False); Filer.DefineProperty('PrintMargins',ReadPrintMargins,SavePrintMargins,NotDefaultPrintMargins); end; { TTeeCustomShapeBrushPen } Constructor TTeeCustomShapeBrushPen.Create; Begin inherited Create; FBrush:=GetBrushClass.Create(CanvasChanged); FPen:=TChartPen.Create(CanvasChanged); FVisible:=True; end; Destructor TTeeCustomShapeBrushPen.Destroy; begin FBrush.Free; FPen.Free; inherited; end; Procedure TTeeCustomShapeBrushPen.Assign(Source:TPersistent); Begin if Source is TTeeCustomShapeBrushPen then With TTeeCustomShapeBrushPen(Source) do begin Self.Brush :=FBrush; Self.Pen :=FPen; Self.FVisible:=FVisible; end else inherited; end; function TTeeCustomShapeBrushPen.GetBrushClass: TChartBrushClass; begin result:=TChartBrush; end; Procedure TTeeCustomShapeBrushPen.SetBrush(Value:TChartBrush); begin FBrush.Assign(Value); end; Procedure TTeeCustomShapeBrushPen.SetPen(Value:TChartPen); Begin FPen.Assign(Value); end; Procedure TTeeCustomShapeBrushPen.Show; begin Visible:=True; end; Procedure TTeeCustomShapeBrushPen.Hide; begin Visible:=False; end; Procedure TTeeCustomShapeBrushPen.Repaint; begin if Assigned(ParentChart) then ParentChart.Invalidate; end; Procedure TTeeCustomShapeBrushPen.CanvasChanged(Sender:TObject); begin Repaint; end; Procedure TTeeCustomShapeBrushPen.SetParent(Value:TCustomTeePanel); begin FParent:=Value; end; procedure TTeeCustomShapeBrushPen.SetVisible(Value:Boolean); begin if Assigned(ParentChart) then ParentChart.SetBooleanProperty(FVisible,Value) else FVisible:=Value; end; type TShadowAccess=class {$IFDEF CLR}sealed{$ENDIF} (TTeeShadow); { TTeeCustomShape } Constructor TTeeCustomShape.Create(AOwner: TCustomTeePanel); Begin {$IFDEF CLR} inherited Create; ParentChart:=AOwner; {$ELSE} ParentChart:=AOwner; inherited Create; {$ENDIF} FBevel:=bvNone; FBevelWidth:=2; FColor:=clWhite; FFont:=TTeeFont.Create(CanvasChanged); FShapeStyle:=fosRectangle; end; Destructor TTeeCustomShape.Destroy; begin FShadow.Free; FFont.Free; FGradient.Free; inherited; end; Procedure TTeeCustomShape.InitShadow(AShadow:TTeeShadow); begin {$IFDEF CLR} with AShadow do {$ELSE} with TShadowAccess(AShadow) do {$ENDIF} begin Color:=clBlack; Size:=3; DefaultColor:=clBlack; DefaultSize:=3; end; end; Function TTeeCustomShape.GetShadow:TTeeShadow; begin if not Assigned(FShadow) then begin FShadow:=TTeeShadow.Create(CanvasChanged); InitShadow(FShadow); end; result:=FShadow; end; Procedure TTeeCustomShape.Assign(Source:TPersistent); Begin if Source is TTeeCustomShape then With TTeeCustomShape(Source) do begin Self.FBevel :=FBevel; Self.FBevelWidth :=FBevelWidth; Self.FColor :=FColor; Self.Font :=FFont; Self.Gradient :=FGradient; Self.FShapeStyle :=FShapeStyle; Self.Shadow :=FShadow; Self.FTransparent :=FTransparent; Self.FTransparency:=FTransparency; // 6.02 end; inherited; end; Procedure TTeeCustomShape.Draw; begin DrawRectRotated(ShapeBounds); end; Procedure RectToFourPoints(Const ARect:TRect; const Angle:Double; var P:TFourPoints); Var tmpSin : Extended; tmpCos : Extended; tmpCenter : TPoint; Procedure RotatePoint(Var P:TPoint; AX,AY:Integer); begin P.X:=tmpCenter.x+Round( AX*tmpCos + AY*tmpSin ); P.Y:=tmpCenter.y+Round( -AX*tmpSin + AY*tmpCos ); end; Var tmp : Double; tmpRect : TRect; begin RectCenter(ARect,tmpCenter.X,tmpCenter.Y); tmp:=Angle*TeePiStep; SinCos(tmp,tmpSin,tmpCos); tmpRect:=ARect; With tmpRect do begin Dec(Left,tmpCenter.X); Dec(Right,tmpCenter.X); Dec(Top,tmpCenter.Y); Dec(Bottom,tmpCenter.Y); RotatePoint(P[0],Left,Top); RotatePoint(P[1],Right,Top); RotatePoint(P[2],Right,Bottom); RotatePoint(P[3],Left,Bottom); end; end; Procedure TTeeCustomShape.DrawRectRotated(Const Rect:TRect; Angle:Integer=0; AZ:Integer=0); Const TeeDefaultRoundSize=16; Procedure InternalDrawShape(Const ARect:TRect); var P : TFourPoints; begin if Angle>0 then begin RectToFourPoints(ARect,Angle,P); ParentChart.Canvas.Polygon(P); end else With ParentChart.Canvas do if SupportsFullRotation then RectangleWithZ(ARect,AZ) else Case FShapeStyle of fosRectangle: Rectangle(ARect); else With ARect do RoundRect(Left,Top,Right,Bottom,TeeDefaultRoundSize,TeeDefaultRoundSize) end; end; Procedure DrawShadow; var tmpH : Integer; tmpV : Integer; tmpR : TRect; tmpBlend : TTeeBlend; begin if (Angle=0) and (FShapeStyle=fosRectangle) then if ParentChart.Canvas.SupportsFullRotation then FShadow.Draw(ParentChart.Canvas,Rect,AZ) else begin ParentChart.Canvas.FrontPlaneBegin; FShadow.Draw(ParentChart.Canvas,Rect,AZ); ParentChart.Canvas.FrontPlaneEnd; end; if Transparency>0 then // Trick. v7. If we have transparency, draw back. begin tmpH:=FShadow.HorizSize; tmpV:=FShadow.VertSize; if (Max(tmpH,tmpV)>0) and Pen.Visible then begin Inc(tmpH,Pen.Width); Inc(tmpV,Pen.Width); end; With ParentChart.Canvas do begin Pen.Style:=psClear; Brush.Style:=bsSolid; Brush.Color:=FShadow.Color; if FShadow.Transparency>0 then begin with Rect do tmpR:=TeeRect(Left+tmpH,Top+tmpV,Right+tmpH,Bottom+tmpV); tmpBlend:=ParentChart.Canvas.BeginBlending(tmpR,FShadow.Transparency); end else tmpBlend:=nil; With Rect do InternalDrawShape(TeeRect(Left+tmpH,Top+tmpV,Right+tmpH,Bottom+tmpV)); if FShadow.Transparency>0 then ParentChart.Canvas.EndBlending(tmpBlend); end; end; end; var tmp : Integer; tmpR : TRect; P : TFourPoints; tmpBlend : TTeeBlend; begin if not Transparent then begin if Transparency>0 then begin if Angle<>0 then begin RectToFourPoints(Rect,Angle,P); tmpR:=RectFromPolygon(P,4); end else tmpR:=Rect; tmpBlend:=ParentChart.Canvas.BeginBlending(tmpR,Transparency); end else tmpBlend:=nil; if Assigned(FShadow) and (FShadow.Size<>0) and (FBrush.Style<>bsClear) then DrawShadow; With ParentChart.Canvas do begin if Assigned(FGradient) and FGradient.Visible then begin if Angle>0 then begin RectToFourPoints(Rect,Angle,P); if SupportsFullRotation then FGradient.Draw(ParentChart.Canvas,P,AZ) else FGradient.Draw(ParentChart.Canvas,P); end else begin if Self.FShapeStyle=fosRoundRectangle then tmp:=TeeDefaultRoundSize else tmp:=0; if SupportsFullRotation then begin TCanvasAccess(ParentChart.Canvas).GradientZ:=AZ; FGradient.Draw(ParentChart.Canvas,Rect); TCanvasAccess(ParentChart.Canvas).GradientZ:=0; end else FGradient.Draw(ParentChart.Canvas,Rect,tmp); end; Brush.Style:=bsClear; end else AssignBrush(Self.Brush,Self.Color); AssignVisiblePen(Self.Pen); InternalDrawShape(Rect); end; if Angle=0 then begin tmpR:=Rect; DrawBevel(ParentChart.Canvas,FBevel,tmpR,BevelWidth); end; if Transparency>0 then ParentChart.Canvas.EndBlending(tmpBlend); end; end; Function TTeeCustomShape.IsTranspStored:Boolean; begin result:=FTransparent<>FDefaultTransparent; end; procedure TTeeCustomShape.ReadShadowColor(Reader: TReader); // obsolete begin if Reader.NextValue=vaIdent then Shadow.Color:=StringToColor(Reader.ReadIdent) else Shadow.Color:=Reader.ReadInteger; end; procedure TTeeCustomShape.ReadShadowSize(Reader: TReader); // obsolete begin Shadow.Size:=Reader.ReadInteger; end; Procedure TTeeCustomShape.DefineProperties(Filer:TFiler); begin inherited; Filer.DefineProperty('ShadowColor',ReadShadowColor,nil,False); Filer.DefineProperty('ShadowSize',ReadShadowSize,nil,False); end; function TTeeCustomShape.GetGradientClass: TChartGradientClass; begin result:=TChartGradient; end; Function TTeeCustomShape.GetHeight:Integer; begin result:=ShapeBounds.Bottom-ShapeBounds.Top; end; Function TTeeCustomShape.GetWidth:Integer; begin result:=ShapeBounds.Right-ShapeBounds.Left; end; Function TTeeCustomShape.GetShadowColor:TColor; // obsolete begin result:=Shadow.Color; end; Function TTeeCustomShape.GetShadowSize:Integer; // obsolete begin result:=Shadow.Size; end; procedure TTeeCustomShape.SetBevel(Value: TPanelBevel); begin if FBevel<>Value then begin FBevel:=Value; Repaint; end; end; procedure TTeeCustomShape.SetBevelWidth(Value: TBevelWidth); begin if FBevelWidth<>Value then begin FBevelWidth:=Value; Repaint; end; end; Procedure TTeeCustomShape.SetColor(Value:TColor); begin if Assigned(ParentChart) then ParentChart.SetColorProperty(FColor,Value) else FColor:=Value; end; Procedure TTeeCustomShape.SetFont(Value:TTeeFont); begin FFont.Assign(Value); end; Function TTeeCustomShape.GetGradient:TChartGradient; begin if not Assigned(FGradient) then FGradient:=GetGradientClass.Create(CanvasChanged); result:=FGradient; end; procedure TTeeCustomShape.SetGradient(Value:TChartGradient); begin if Assigned(Value) then Gradient.Assign(Value) else FreeAndNil(FGradient); end; procedure TTeeCustomShape.SetHeight(Value:Integer); begin ShapeBounds.Bottom:=ShapeBounds.Top+Value; end; procedure TTeeCustomShape.SetWidth(Value:Integer); begin ShapeBounds.Right:=ShapeBounds.Left+Value; end; procedure TTeeCustomShape.SetShadow(Value:TTeeShadow); begin if Assigned(Value) then Shadow.Assign(Value) else FreeAndNil(FShadow); end; Procedure TTeeCustomShape.SetShadowColor(Value:TColor); // obsolete begin Shadow.Color:=Value; end; Procedure TTeeCustomShape.SetShadowSize(Value:Integer); // obsolete begin Shadow.Size:=Value; end; Procedure TTeeCustomShape.SetShapeStyle(Value:TChartObjectShapeStyle); Begin if FShapeStyle<>Value then begin FShapeStyle:=Value; Repaint; end; end; procedure TTeeCustomShape.SetTransparency(Value: TTeeTransparency); begin if FTransparency<>Value then begin FTransparency:=Value; Repaint; end; end; procedure TTeeCustomShape.SetTransparent(Value:Boolean); begin if Assigned(ParentChart) then ParentChart.SetBooleanProperty(FTransparent,Value) else FTransparent:=Value; end; { Zoom & Scroll (Panning) } Procedure TZoomPanning.Check; begin if X0>X1 Then SwapInteger(X0,X1); if Y0>Y1 Then SwapInteger(Y0,Y1); end; Procedure TZoomPanning.Activate(x,y:Integer); Begin X0:=x; Y0:=y; X1:=x; Y1:=y; Active:=True; End; { TTeeMouseEventListeners } // Adds Item to the list. If duplicated, do not add again. function TTeeEventListeners.Add(Const Item: ITeeEventListener): Integer; begin {$IFDEF CLR} result:=IndexOf(Item); // prevent duplicating... 6.0 {$ELSE} result:=IndexOf(Pointer(Item)); // prevent duplicating... 6.0 {$ENDIF} if result=-1 then begin result:=inherited Add(nil); inherited Items[result]:={$IFNDEF CLR}Pointer{$ENDIF}(Item); end; end; function TTeeEventListeners.Get(Index: Integer): ITeeEventListener; begin {$IFDEF CLR} result:=({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]) as ITeeEventListener; {$ELSE} result:=ITeeEventListener({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]); {$ENDIF} end; function TTeeEventListeners.Remove(Item: ITeeEventListener): Integer; begin result:=IndexOf({$IFNDEF CLR}Pointer{$ENDIF}(Item)); if result>-1 then begin inherited Items[result]:=nil; Delete(result); end; end; { TTeeExportData } Procedure TTeeExportData.CopyToClipboard; begin Clipboard.AsText:=AsString; end; Function TTeeExportData.AsString:String; // virtual; abstract; begin result:=''; end; Procedure TTeeExportData.SaveToStream(AStream:TStream); var tmpSt : String; {$IFDEF CLR} Bytes : TBytes; {$ENDIF} begin tmpSt:=AsString; {$IFDEF CLR} Bytes := BytesOf(tmpSt); AStream.Write(Bytes, Length(Bytes)); {$ELSE} AStream.Write(PChar(tmpSt)^,Length(tmpSt)); {$ENDIF} end; Procedure TTeeExportData.SaveToFile(Const FileName:String); var tmp : TFileStream; begin tmp:=TFileStream.Create(FileName,fmCreate); try SaveToStream(tmp); finally tmp.Free; end; end; { Returns True if point T is over (more or less "Tolerance" pixels) line: P --> Q } Function PointInLine(Const P:TPoint; px,py,qx,qy,TolerancePixels:Integer):Boolean; Function Dif(a,b:Integer):Boolean; begin result:=(a+TolerancePixels)<b; end; begin if ( Abs(1.0*(qy-py)*(P.x-px)-1.0*(P.y-py)*(qx-px)) >= (Math.Max(Abs(qx-px),Abs(qy-py)))) then result:=False else if ((Dif(qx,px) and Dif(px,P.x)) or (Dif(qy,py) and Dif(py,P.y))) then result:=False else if ((Dif(P.x,px) and Dif(px,qx)) or (Dif(P.y,py) and Dif(py,qy))) then result:=False else if ((Dif(px,qx) and Dif(qx,P.x)) or (Dif(py,qy) and Dif(qy,P.y))) then result:=False else if ((Dif(P.x,qx) and Dif(qx,px)) or (Dif(P.y,qy) and Dif(qy,py))) then result:=False else result:=True; end; Function PointInLineTolerance(Const P:TPoint; px,py,qx,qy,TolerancePixels:Integer):Boolean; // obsolete begin result:=PointInLine(P,px,py,qx,qy,TolerancePixels); end; Function PointInLine(Const P,FromPoint,ToPoint:TPoint; TolerancePixels:Integer):Boolean; overload; begin result:=PointInLine(P,FromPoint.X,FromPoint.Y,ToPoint.X,ToPoint.Y,TolerancePixels); end; Function PointInLine(Const P:TPoint; px,py,qx,qy:Integer):Boolean; Begin result:=PointInLine(P,px,py,qx,qy,0); end; Function PointInLine(Const P,FromPoint,ToPoint:TPoint):Boolean; overload; begin result:=PointInLine(P,FromPoint.X,FromPoint.Y,ToPoint.X,ToPoint.Y,0); end; Function PointInPolygon(Const P:TPoint; Const Poly:Array of TPoint):Boolean; { this is slow... Var Region:HRGN; begin Region:=CreatePolygonRgn(Poly,1+High(Poly),0); result:=(Region>0) and PtInRegion(Region,p.x,p.y); DeleteObject(Region); end; } Var i,j : Integer; begin result:=False; j:=High(Poly); for i:=0 to High(Poly) do begin if (((( Poly[i].Y <= P.Y ) and ( P.Y < Poly[j].Y ) ) or (( Poly[j].Y <= P.Y ) and ( P.Y < Poly[i].Y ) )) and ( P.X < (1.0* (( Poly[j].X - Poly[i].X ) * ( P.Y - Poly[i].Y ))) / (1.0*( Poly[j].Y - Poly[i].Y )) + Poly[i].X )) then result:=not result; j:=i; end; end; Function PointInTriangle(Const P:TPoint; X0,X1,Y0,Y1:Integer):Boolean; begin result:=PointInPolygon(P,[ TeePoint(X0,Y0), TeePoint((X0+X1) div 2,Y1), TeePoint(X1,Y0) ]); end; Function PointInHorizTriangle(Const P:TPoint; Y0,Y1,X0,X1:Integer):Boolean; begin result:=PointInPolygon(P,[ TeePoint(X0,Y0), TeePoint(X1,(Y0+Y1) div 2), TeePoint(X0,Y1) ]); end; Function PointInEllipse(Const P:TPoint; Left,Top,Right,Bottom:Integer):Boolean; var tmpWidth : Integer; tmpHeight : Integer; tmpXCenter : Integer; tmpYCenter : Integer; begin tmpXCenter:=(Left+Right) div 2; // 6.01 tmpYCenter:=(Top+Bottom) div 2; tmpWidth :=Sqr(tmpXCenter-Left); tmpHeight:=Sqr(tmpYCenter-Top); result:=(tmpWidth<>0) and (tmpHeight<>0) and ( (Sqr(1.0*P.X-tmpXCenter) / tmpWidth ) + (Sqr(1.0*P.Y-tmpYCenter) / tmpHeight) <= 1 ); end; Function PointInEllipse(Const P:TPoint; Const Rect:TRect):Boolean; begin with Rect do result:=PointInEllipse(P,Left,Top,Right,Bottom); end; Function DelphiToLocalFormat(Const Format:String):String; var t : Integer; begin result:=Format; for t:=1 to Length(result) do if result[t]=',' then result[t]:=ThousandSeparator{$IFDEF CLR}[1]{$ENDIF} else if result[t]='.' then result[t]:=DecimalSeparator{$IFDEF CLR}[1]{$ENDIF}; end; Function LocalToDelphiFormat(Const Format:String):String; var t : Integer; begin result:=Format; for t:=1 to Length(result) do if result[t]=ThousandSeparator{$IFDEF CLR}[1]{$ENDIF} then result[t]:=',' else if result[t]=DecimalSeparator then result[t]:='.'; end; Procedure EnableControls(Enable:Boolean; Const ControlArray:Array of TControl); var t : Integer; begin for t:=Low(ControlArray) to High(ControlArray) do if Assigned(ControlArray[t]) then ControlArray[t].Enabled:=Enable; end; Function TeeRoundDate(Const ADate:TDateTime; AStep:TDateTimeStep):TDateTime; var Year : Word; Month : Word; Day : Word; begin if ADate<=Tee19000101 then result:=ADate else begin DecodeDate(ADate,Year,Month,Day); Case AStep of dtHalfMonth : if Day>=15 then Day:=15 else Day:=1; dtOneMonth, dtTwoMonths, dtThreeMonths, dtFourMonths, dtSixMonths : Day:=1; dtOneYear : begin Day:=1; Month:=1; end; end; result:=EncodeDate(Year,Month,Day); end; end; Procedure TeeDateTimeIncrement( IsDateTime:Boolean; Increment:Boolean; Var Value:Double; Const AnIncrement:Double; tmpWhichDateTime:TDateTimeStep); var Year : Word; Month : Word; Day : Word; Procedure DecMonths(HowMany:Word); begin Day:=1; if Month>HowMany then Dec(Month,HowMany) else begin Dec(Year); Month:=12-(HowMany-Month); end; end; Procedure IncMonths(HowMany:Word); begin Day:=1; Inc(Month,HowMany); if Month>12 then begin Inc(Year); Month:=Month-12; end; end; Procedure IncDecMonths(HowMany:Word); begin if Increment then IncMonths(HowMany) else DecMonths(HowMany); end; begin if IsDateTime then begin DecodeDate(Value,year,month,day); Case tmpWhichDateTime of dtHalfMonth : Begin if Day>15 then Day:=15 else if Day>1 then Day:=1 else begin IncDecMonths(1); Day:=15; end; end; dtOneMonth : IncDecMonths(1); dtTwoMonths : IncDecMonths(2); dtThreeMonths : IncDecMonths(3); dtFourMonths : IncDecMonths(4); dtSixMonths : IncDecMonths(6); dtOneYear : if Increment then Inc(year) else Dec(year); else begin if Increment then Value:=Value+AnIncrement else Value:=Value-AnIncrement; Exit; end; end; Value:=EncodeDate(year,month,day); end else begin if Increment then Value:=Value+AnIncrement else Value:=Value-AnIncrement; end; end; Procedure TeeSort( StartIndex,EndIndex:Integer; CompareFunc:TTeeSortCompare; SwapFunc:TTeeSortSwap); procedure PrivateSort(l,r:Integer); var i : Integer; j : Integer; x : Integer; begin i:=l; j:=r; x:=(i+j) shr 1; while i<j do begin while CompareFunc(i,x)<0 do inc(i); while CompareFunc(x,j)<0 do dec(j); if i<j then begin SwapFunc(i,j); if i=x then x:=j else if j=x then x:=i; end; if i<=j then begin inc(i); dec(j) end; end; if l<j then PrivateSort(l,j); if i<r then PrivateSort(i,r); end; begin PrivateSort(StartIndex,EndIndex); end; { Helper functions } Function TeeGetUniqueName(AOwner:TComponent; Const AStartName:String):TComponentName; Function FindNameLoop:String; var tmp : Integer; begin tmp:={$IFDEF TEEOCX}0{$ELSE}1{$ENDIF}; if Assigned(AOwner) then while Assigned(AOwner.FindComponent(AStartName+TeeStr(tmp))) do Inc(tmp); result:=AStartName+TeeStr(tmp); end; {$IFNDEF D6} {$IFNDEF CLX} {$IFNDEF TEEOCX} var tmpForm : TCustomForm; Designer : {$IFDEF D5}IDesigner{$ELSE}IFormDesigner{$ENDIF}; {$ENDIF} begin result:=''; if Assigned(AOwner) then begin {$IFNDEF TEEOCX} if AOwner is TCustomForm then begin tmpForm:=TCustomForm(AOwner); if Assigned(tmpForm.Designer) then begin Designer:=nil; tmpForm.Designer.QueryInterface({$IFDEF D5}IDesigner{$ELSE}IFormDesigner{$ENDIF},Designer); if Assigned(Designer) then result:=Designer.UniqueName('T'+AStartName); end; end; {$ENDIF} if result='' then result:=FindNameLoop; end; {$ELSE} begin result:=FindNameLoop; {$ENDIF} {$ELSE} begin result:=FindNameLoop; {$ENDIF} end; { returns number of sections in St string separated by ";" } Function TeeNumFields(St:String):Integer; var i : Integer; begin if St='' then result:=0 else begin result:=1; i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeFieldsSeparator,St); While i>0 do begin Inc(result); Delete(St,1,i); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeFieldsSeparator,St); end; end; end; Function TeeNumFields(const St,Separator:String):Integer; var Old : String; begin Old:=TeeFieldsSeparator; TeeFieldsSeparator:=Separator; try result:=TeeNumFields(St); finally TeeFieldsSeparator:=Old; end; end; { returns the index-th section in St string separated by ";" } Function TeeExtractField(St:String; Index:Integer):String; var i : Integer; begin result:=''; if (St<>'') and (Index>0) then { 5.03 } begin i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeFieldsSeparator,St); While i>0 do begin Dec(Index); if Index=0 then begin result:=Copy(St,1,i-1); exit; end; Delete(St,1,i); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeFieldsSeparator,St); end; result:=St; end; end; Function TeeExtractField(St:String; Index:Integer; const Separator:String):String; var Old : String; begin Old:=TeeFieldsSeparator; TeeFieldsSeparator:=Separator; try result:=TeeExtractField(St,Index); finally TeeFieldsSeparator:=Old; end; end; {$IFNDEF CLR} type PTeeBitmap=^TTeeBitmap; TTeeBitmap=packed record Name1 : String; Name2 : String; Bitmap : TBitmap; end; { Load the Bitmap resource with Name1 or Name2 name } function LoadTeeBitmap(AInstance: Integer; Data: Pointer): Boolean; { Try to find a resource bitmap and load it } Function TryFindResource(Const ResName:String):Boolean; var tmpSt : TeeString256; begin StrPCopy(tmpSt,ResName); if FindResource(AInstance, tmpSt, RT_BITMAP)<>0 then begin PTeeBitmap(Data)^.Bitmap.LoadFromResourceName(AInstance,ResName); result:=True; end else result:=False; end; begin result:=True; try With PTeeBitmap(Data)^ do if TryFindResource(Name1) or TryFindResource(Name2) then result:=False; except on Exception do ; end; end; {$ENDIF} Procedure TeeLoadBitmap(Bitmap:TBitmap; Const Name1,Name2:String); var {$IFDEF CLR} tmpStream : Stream; {$ELSE} tmpBitmap : TTeeBitmap; {$ENDIF} begin {$IFDEF CLR} tmpStream:=Assembly.GetExecutingAssembly.GetManifestResourceStream(Name1+'.bmp'); if Assigned(tmpStream) then Bitmap.Assign(System.Drawing.Bitmap.Create(tmpStream)) else begin tmpStream:=Assembly.GetExecutingAssembly.GetManifestResourceStream(Name2+'.bmp'); if Assigned(tmpStream) then Bitmap.Assign(System.Drawing.Bitmap.Create(tmpStream)) end; {$ELSE} tmpBitmap.Bitmap:=Bitmap; tmpBitmap.Name1:=Name1; tmpBitmap.Name2:=Name2; EnumModules(LoadTeeBitmap,@tmpBitmap); {$ENDIF} end; { Returns a bitmap from the linked resources that has the same name than our class name or parent class name } Procedure TeeGetBitmapEditor(AObject:TObject; Var Bitmap:TBitmap); begin TeeLoadBitmap(Bitmap,AObject.ClassName,AObject.ClassParent.ClassName); end; {$IFNDEF D6} function StrToFloatDef(const S: string; const Default: Extended): Extended; begin if not TextToFloat(PChar(S), Result, fvExtended) then Result := Default; end; {$ENDIF} // Returns True when lines X1Y1->X2Y2 and X3Y3->X4Y4 cross. // Returns crossing position at x and y var parameters. function CrossingLines(const X1,Y1,X2,Y2,X3,Y3,X4,Y4:Double; var x,y:Double):Boolean; var slope1 : Double; slope2 : Double; intercept1 : Double; intercept2 : Double; Dif, A1, B1, C1, A2, B2, C2 : Double; begin A1:=Y2-Y1; A2:=Y4-Y3; B1:=X2-X1; B2:=X4-X3; slope1 := A1 / B1; slope2 := A2 / B2; Intercept1 := Y1 - (slope1 * X1); Intercept2 := Y3 - (slope2 * X3); Dif:=slope2-slope1; if Abs(Dif)>1E-15 then X:= (Intercept1-Intercept2) / Dif else X:=X2; Y:= (slope1 * X) + Intercept1; C1:=(X1*Y2)-(X2*Y1); C2:=(X3*Y4)-(X4*Y3); result:=(((A1*X3-B1*Y3-C1>0) xor (A1*X4-B1*Y4-C1>0)) and ((A2*X1-B2*Y1-C2>0) xor (A2*X2-B2*Y2-C2>0))); end; // TRANSLATIONS Procedure TeeTranslateControl(AControl:TControl); begin // if current language is English, do not translate... if Assigned(TeeTranslateHook) then TeeTranslateHook(AControl); end; Function ReplaceChar(AString:String; Search:{$IFDEF NET}String{$ELSE}Char{$ENDIF}; Replace:Char=#0):String; Var i : Integer; begin Repeat i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(Search,AString); if i>0 then if Replace=#0 then Delete(AString,i,1) else AString[i]:=Replace; // 6.01 Until i=0; result:=AString; end; type TCanvas3DAccess=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCanvas3D); Function TeeAntiAlias(Panel:TCustomTeePanel):TBitmap; {$IFDEF CLR} begin result:=Panel.TeeCreateBitmap(Panel.Color,Panel.ClientRect,TeePixelFormat); end; {$ELSE} const Factor=2; SqrFactor=4; BytesPerPixel={$IFDEF CLX}4{$ELSE}3{$ENDIF}; var b : TBitmap; tmpx2, tmpx3, tmpy, x,y, h,w : Integer; bline1, bline2, b2line : PByteArray; cr,cg,cb : Integer; Old, OldB : Boolean; OldFontZoom : Integer; begin Old:=Panel.AutoRepaint; Panel.AutoRepaint:=False; h:=Panel.Height; w:=Panel.Width; with Panel.View3DOptions {Canvas} do begin OldFontZoom:=FontZoom; FontZoom:=FontZoom*Factor; end; OldB:=Panel.BufferedDisplay; TCanvas3DAccess(Panel.Canvas).FBufferedDisplay:=False; try b:=Panel.TeeCreateBitmap(Panel.Color,TeeRect(0,0,Factor*w,Factor*h),TeePixelFormat); finally Panel.BufferedDisplay:=OldB; Panel.View3DOptions{Canvas}.FontZoom:=OldFontZoom; end; result:=TBitmap.Create; {$IFNDEF CLX} result.IgnorePalette:=True; {$ENDIF} result.PixelFormat:=TeePixelFormat; result.Width:=w; result.Height:=h; for y:=0 to h-1 do begin b2line:=result.ScanLine[y]; tmpY:=Factor*y; bline1:=b.ScanLine[tmpY]; bline2:=b.ScanLine[tmpY+1]; for x:=0 to w-1 do begin tmpx3:=BytesPerPixel*Factor*x; cr:=bline1[tmpx3]+bline2[tmpx3]; Inc(tmpx3); cg:=bline1[tmpx3]+bline2[tmpx3]; Inc(tmpx3); cb:=bline1[tmpx3]+bline2[tmpx3]; tmpX2:=BytesPerPixel*x; {$IFDEF CLX} Inc(tmpx3); {$ENDIF} Inc(tmpx3); b2line[tmpx2]:=(cr+bline1[tmpx3]+bline2[tmpx3]) div SqrFactor; Inc(tmpx3); b2line[1+tmpx2]:=(cg+bline1[tmpx3]+bline2[tmpx3]) div SqrFactor; Inc(tmpx3); b2line[2+tmpx2]:=(cb+bline1[tmpx3]+bline2[tmpx3]) div SqrFactor; end; end; b.Free; Panel.AutoRepaint:=Old; end; {$ENDIF} {$IFDEF CLR} Constructor TTeeEvent.Create; begin inherited Create; end; {$ENDIF} Const DefaultPalette:Array[0..MaxDefaultColors] of TColor= ( clRed, clGreen, clYellow, clBlue, clWhite, clGray, clFuchsia, clTeal, clNavy, clMaroon, clLime, clOlive, clPurple, clSilver, clAqua, clBlack, clMoneyGreen, clSkyBlue, clCream, clMedGray ); Procedure SetDefaultColorPalette; overload; begin SetDefaultColorPalette(DefaultPalette); end; Procedure SetDefaultColorPalette(const Palette:Array of TColor); overload; var t:Integer; begin if High(Palette)=0 then SetDefaultColorPalette else begin ColorPalette:=nil; SetLength(ColorPalette,High(Palette)+1); // +1 ?? for t:=Low(Palette) to High(Palette) do ColorPalette[t]:=Palette[t]; end; end; function TeeReadBoolOption(const AKey:String; DefaultValue:Boolean):Boolean; begin result:=DefaultValue; {$IFDEF LINUX} with TIniFile.Create(ExpandFileName('~/.teechart')) do try result:=ReadBool('Editor', AKey, DefaultValue); {$ELSE} with TRegistry.Create do try if OpenKeyReadOnly(TeeMsg_EditorKey) and ValueExists(AKey) then result:=ReadBool(AKey); {$ENDIF} finally Free; end; end; procedure TeeSaveBoolOption(const AKey:String; Value:Boolean); begin {$IFDEF LINUX} with TIniFile.Create(ExpandFileName('~/.teechart')) do try WriteBool('Editor',AKey,Value); {$ELSE} with TRegistry.Create do try if OpenKey(TeeMsg_EditorKey,True) then WriteBool(AKey,Value); {$ENDIF} finally Free; end; end; Function TeeReadIntegerOption(const AKey:String; DefaultValue:Integer):Integer; begin result:=DefaultValue; {$IFDEF LINUX} with TIniFile.Create(ExpandFileName('~/.teechart')) do try result:=ReadInteger('Editor', AKey, DefaultValue); {$ELSE} With TRegistry.Create do try if OpenKeyReadOnly(TeeMsg_EditorKey) and ValueExists(AKey) then result:=ReadInteger(AKey); {$ENDIF} finally Free; end; end; procedure TeeSaveIntegerOption(const AKey:String; Value:Integer); begin {$IFDEF LINUX} with TIniFile.Create(ExpandFileName('~/.teechart')) do try WriteInteger('Editor',AKey,Value); {$ELSE} With TRegistry.Create do try if OpenKey(TeeMsg_EditorKey,True) then WriteInteger(AKey,Value); {$ENDIF} finally Free; end; end; Const NullCursor={$IFDEF CLX}nil{$ELSE}0{$ENDIF}; initialization SetDefaultColorPalette; {$IFDEF CLR} Screen.Cursors[crTeeHand]:=Screen.Cursors[crHandPoint]; {$ELSE} {$IFDEF CLX} Screen.Cursors[crTeeHand]:=QCursorH(0); {$ELSE} Screen.Cursors[crTeeHand]:=LoadCursor(HInstance,'TEE_CURSOR_HAND'); {$ENDIF} {$ENDIF} { Optimization for TeeRoundDate function } Tee19000101:=EncodeDate(1900,1,1); finalization ColorPalette:=nil; {$IFNDEF CLR} Screen.Cursors[crTeeHand]:=NullCursor; {$ENDIF} end.
{*******************************************} { TeeChart Pro Metafile exporting } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {*******************************************} unit TeeEmfOptions; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} TeeProcs, TeeExport; type TEMFOptions = class(TForm) CBEnhanced: TCheckBox; private { Private declarations } public { Public declarations } end; TEMFExportFormat=class(TTeeExportFormat) private FProperties: TEMFOptions; function GetEnhanced: Boolean; procedure SetEnhanced(const Value: Boolean); protected Procedure DoCopyToClipboard; override; function FileFilterIndex: Integer; override; procedure IncFileFilterIndex(var FilterIndex: Integer); override; {$IFDEF CLR} public {$ENDIF} function WantsFilterIndex(Index:Integer):Boolean; override; public function Description:String; override; function FileExtension:String; override; function FileFilter:String; override; Function Metafile:TMetafile; Function Options(Check:Boolean=True):TForm; override; Procedure SaveToStream(Stream:TStream); override; property Enhanced:Boolean read GetEnhanced write SetEnhanced; end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLX} QClipbrd, {$ELSE} Clipbrd, {$ENDIF} TeCanvas, TeeConst; function TEMFExportFormat.Description:String; begin result:=TeeMsg_AsEMF; end; function TEMFExportFormat.FileFilter:String; begin result:=TeeMsg_EMFFilter; end; function TEMFExportFormat.FileExtension:String; begin if Enhanced then result:='emf' else result:='wmf'; end; function TEMFExportFormat.FileFilterIndex: Integer; begin if Enhanced then result:=FFilterIndex else result:=Succ(FFilterIndex); end; procedure TEMFExportFormat.IncFileFilterIndex(var FilterIndex: Integer); begin inherited; Inc(FilterIndex); end; Function TEMFExportFormat.Metafile:TMetafile; begin CheckSize; result:=Panel.TeeCreateMetafile(Enhanced,TeeRect(0,0,Width,Height)); end; Function TEMFExportFormat.Options(Check:Boolean=True):TForm; begin if Check and (not Assigned(FProperties)) then FProperties:=TEMFOptions.Create(nil); result:=FProperties; end; procedure TEMFExportFormat.DoCopyToClipboard; var tmp : TMetafile; begin tmp:=Metafile; try Clipboard.Assign(tmp); finally tmp.Free; end; end; procedure TEMFExportFormat.SaveToStream(Stream:TStream); begin With Metafile do try SaveToStream(Stream); finally Free; end; end; function TEMFExportFormat.GetEnhanced: Boolean; begin if Assigned(FProperties) then result:=FProperties.CBEnhanced.Checked else result:=True; end; procedure TEMFExportFormat.SetEnhanced(const Value: Boolean); begin Options; FProperties.CBEnhanced.Checked:=Value; end; // Special case only for Metafile export format, that // supports both "emf" and "wmf" extensions. function TEMFExportFormat.WantsFilterIndex(Index: Integer): Boolean; // 6.01 begin result:=FFilterIndex=Index; if (not result) and (Succ(FFilterIndex)=Index) then begin Enhanced:=False; result:=True; end; end; { TEMFOptions } initialization RegisterTeeExportFormat(TEMFExportFormat); finalization UnRegisterTeeExportFormat(TEMFExportFormat); end.
unit uCComunicacao; interface uses System.SysUtils, System.Classes, System.TypInfo, System.Generics.Collections, System.Types, System.JSON, Data.DBXJSONReflect, REST.Client, REST.Types, REST.JSON, REST.Response.Adapter, FireDAC.Comp.Client, IPPeerClient, Data.Bind.Components, Data.Bind.ObjectScope, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, System.Net.HttpClient; const _API_USUARIO = '/logindelphi/.json'; _API_OBJETOS = '/tdevrocks-80dcb/.json'; _API_OS = '/beaconCelSOS/IMEI_CELULAR/.json'; type TComunicacao = class private FBaseURL: string; FResponseJson: string; FRESTResponse: TRESTResponse; FRESTClient: TRESTClient; FRESTRequest: TRESTRequest; FRESTResponseDataSetAdapter: TRESTResponseDataSetAdapter; FMemTable: TFDMemTable; public constructor Create(ABaseURL: string = ''); function ObtemDados(APIResource: string): Boolean;overload; function ObtemDados(AMemTable: TFDMemTable; APIResource: string): Boolean; overload; function ObtemDados(APIResource: string; Carregar: Boolean): String; overload; function GravaDados(APIResource: string; AJson: string): Boolean; property BaseURL: string read FBaseURL write FBaseURL; property Response: TFDMemTable read FMemTable write FMemTable; property ResponseJson: string read FResponseJson; end; implementation { TSincronismo } constructor TComunicacao.Create(ABaseURL: string); begin FRESTRequest := TRESTRequest.Create(nil); FRESTResponse := TRESTResponse.Create(FRESTRequest); FRESTClient := TRESTClient.Create(''); FRESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; FRESTClient.AcceptCharset := 'UTF-8, *;q=0.8'; FRESTClient.AcceptEncoding := 'identity'; FRESTRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; FRESTRequest.AcceptCharset := 'UTF-8, *;q=0.8'; FRESTRequest.AcceptEncoding := 'identity'; FRESTRequest.Client := FRESTClient; FRESTRequest.Response := FRESTResponse; FMemTable := TFDMemTable.Create(FRESTRequest); FRESTResponseDataSetAdapter := TRESTResponseDataSetAdapter.Create(FRESTRequest); FRESTResponseDataSetAdapter.Dataset := FMemTable; FRESTResponseDataSetAdapter.Response := FRESTResponse; FBaseURL := ABaseURL; end; function TComunicacao.GravaDados(APIResource, AJson: string): Boolean; var lJsonStream: TStringStream; lIdHTTP: TIdHTTP; lResponse: string; lUrl: string; begin try lJsonStream := TStringStream.Create(Utf8Encode(AJson)); lIdHTTP := TIdHTTP.Create(nil); lIdHTTP.Request.Method := 'PUT'; lIdHTTP.Request.ContentType := 'application/json'; lIdHTTP.Request.CharSet := 'utf-8'; lUrl := FBaseURL + APIResource; lResponse := lIdHTTP.Put(lUrl, lJsonStream); result := true; except result := false; end; (* var lJsonStream: TStringStream; lIdHTTP: THTTPClient; lResponse: string; lUrl: string; AResponseContent : TStringStream; begin try lJsonStream := TStringStream.Create(Utf8Encode(AJson)); lIdHTTP := THTTPClient.Create; lIdHTTP.CustomHeaders['auth'] := 'anonymous'; lIdHTTP.CustomHeaders['uid'] := '769d853d-393d-4228-94ca-592f6a9c563a'; lIdHTTP.ContentType := 'application/json'; lUrl := FBaseURL + APIResource; AResponseContent := TStringStream.Create(); lIdHTTP.Put(lUrl, lJsonStream, AResponseContent); result := true; except result := false; end; *) end; function TComunicacao.ObtemDados(APIResource: string; Carregar: Boolean): String; begin try FRESTClient.BaseURL := FBaseURL; FRESTRequest.Method := rmGET; FRESTRequest.resource := APIResource; FRESTRequest.Execute; FResponseJson := FRESTResponse.Content; FRESTResponseDataSetAdapter.Active := true; FMemTable.Active := True; result := FRESTResponse.Content; except result := 'erro'; end; end; function TComunicacao.ObtemDados(AMemTable: TFDMemTable; APIResource: string): Boolean; begin try FRESTClient.BaseURL := FBaseURL; FRESTRequest.Method := rmGET; FRESTRequest.resource := APIResource; FRESTRequest.Execute; FResponseJson := FRESTResponse.Content; FRESTResponseDataSetAdapter.Active := true; FMemTable.Active := True; AMemTable.Data := FMemTable.Data; result := True; except result := false; end; end; function TComunicacao.ObtemDados(APIResource: string): Boolean; begin try FRESTClient.BaseURL := FBaseURL; FRESTRequest.Method := rmGET; FRESTRequest.resource := APIResource; FRESTRequest.Execute; FResponseJson := FRESTResponse.Content; FRESTResponseDataSetAdapter.Active := true; FMemTable.Active := true; result := true; except result := false; end; end; end.
unit Connection.COM; interface uses Windows, SysUtils, GMConst, GMGlobals, Connection.Base, AnsiStrings, StrUtils; type TConnectionObjectCOM = class(TConnectionObjectBase) private hPort : cardinal; StateComPort: bool; FLastError: string; function CheckPortBuf: TComStat; function SendBuf: TCheckCOMResult; function ReceiveBuf: TCheckCOMResult; protected procedure PrepareEquipment; override; function ConnectionEquipmentInitialized(): bool; override; function MakeExchange(etAction: TExchangeType): TCheckCOMResult; override; function LogSignature: string; override; function GetLastConnectionError: string; override; public nPort, nBaudRate, nWordLen, nParity, nStopBits: int; function SendBreak: bool; procedure FreePort; override; constructor Create(); override; end; implementation { TConnectionObjectCOM } function TConnectionObjectCOM.ConnectionEquipmentInitialized: bool; begin Result := StateComPort; end; constructor TConnectionObjectCOM.Create; begin inherited Create(); hPort:=INVALID_HANDLE_VALUE; nBaudRate := 9600; nWordLen := 8; nParity := 0; nStopBits := 0; end; procedure TConnectionObjectCOM.FreePort; begin if hPort <> INVALID_HANDLE_VALUE then begin try CloseHandle(hPort); except end; hPort := INVALID_HANDLE_VALUE; StateComPort := false; end; end; function TConnectionObjectCOM.GetLastConnectionError: string; begin Result := FLastError; end; function TConnectionObjectCOM.LogSignature: string; begin Result := 'COM_' + IntToStr(nPort); end; function TConnectionObjectCOM.CheckPortBuf(): TComStat; var Errors: DWORD; Stat : TComStat; // buffer for communications status begin Result.cbInQue:=0; Result.cbOutQue:=0; if ClearCommError(hPort, Errors, @Stat) then Result:=Stat; end; function TConnectionObjectCOM.SendBreak: bool; begin PrepareEquipment(); if not StateComPort then Exit(false); if not SetCommBreak(hPort) then begin FLastError := 'SetCommBreak ' + SysErrorMessage(GetLastError()); Exit(false); end; Sleep(WaitNext); Result := ClearCommBreak(hPort); if not Result then FLastError := 'ClearCommBreak ' + SysErrorMessage(GetLastError()); end; function TConnectionObjectCOM.SendBuf(): TCheckCOMResult; var tick, t: int64; NumberOfBytesWritten : DWORD; begin Result := ccrEmpty; //Очистка порта if not PurgeComm(hPort, PURGE_TXABORT or PURGE_RXABORT or PURGE_TXCLEAR or PURGE_RXCLEAR) then begin FLastError := 'PurgeComm ' + SysErrorMessage(GetLastError()); Exit(ccrError); end; //Пауза в 0,01 сек tick := GetTickCount(); while (tick + 10 > GetTickCount()) do sleep(10); //Передача сообщения if not WriteFile(hPort, buffers.BufSend, buffers.LengthSend, NumberOfBytesWritten, NIL) then begin FLastError := 'WriteFile ' + SysErrorMessage(GetLastError()); Exit(ccrError); end; //дождемся окончания приема, максимум тупим минуту t := GetTickCount(); while (hPort <> INVALID_HANDLE_VALUE) and (CheckPortBuf().cbOutQue > 0) and (Abs(t - GetTickCount()) < 60000) do Sleep(100); end; function TConnectionObjectCOM.ReceiveBuf(): TCheckCOMResult; var tick: UInt64; Errors: DWORD; n: Cardinal; Stat: TComStat; // buffer for communications status i: WORD; Buf: array [0..102400] of byte; begin //Ожидаем первого символа tick := GetTickCount64(); Repeat if ParentTerminated then Exit(ccrEmpty); Sleep(100); ZeroMemory(@Stat, SizeOf(Stat)); if not ClearCommError(hPort, Errors, @Stat) then begin FLastError := 'ClearCommError ' + SysErrorMessage(GetLastError()); Exit(ccrError); end; if Abs(tick - GetTickCount64()) > WaitFirst then Exit(ccrEmpty); Until Stat.cbInQue > 0; Result := ccrEmpty; tick := GetTickCount64(); Repeat if Stat.cbInQue > 0 then begin if not ReadFile(hPort, Buf, Stat.cbInQue, n, NIL) then begin FLastError := Format('ReadFile %d bytes - %s', [Stat.cbInQue, SysErrorMessage(GetLastError())]); Exit(ccrError); end; if n>0 then begin for i:=0 to n-1 do buffers.BufRec[buffers.NumberOfBytesRead + i] := Buf[i]; // Abs поставил, чтобы убить Warning, n и так всегда положительный buffers.NumberOfBytesRead := buffers.NumberOfBytesRead + Abs(n); Result := ccrBytes; tick := GetTickCount64(); end; if CheckGetAllData() then break; end; Sleep(100); if not ClearCommError(hPort, Errors, @Stat) then begin FLastError := 'ClearCommError ' + SysErrorMessage(GetLastError()); Exit(ccrError); end; Until ParentTerminated or ((Stat.cbInQue = 0)and (Abs(GetTickCount64() - tick) > WaitNext)); PurgeComm(hPort, PURGE_TXABORT or PURGE_RXABORT or PURGE_TXCLEAR or PURGE_RXCLEAR); end; function TConnectionObjectCOM.MakeExchange(etAction: TExchangeType): TCheckCOMResult; begin Result := ccrEmpty; buffers.NumberOfBytesRead := 0; if (etAction in [etSend, etSenRec]) and (buffers.LengthSend > 0) then begin Result := SendBuf(); if Result = ccrError then Exit; end; if etAction in [etRec, etSenRec] then Result := ReceiveBuf(); end; procedure TConnectionObjectCOM.PrepareEquipment(); var Buf : array [0..10] of char; Param : TDCB; begin FreePort(); if (nPort <= 0) or (nPort > 999) then Exit; StrPCopy(Buf, IfThen(nPort >= 10, '\\.\') + 'COM' + IntToStr(nPort)); // для портов 10 и выше формат '\\.\COMхх' hPort := CreateFile( Buf, GENERIC_READ or GENERIC_WRITE, 0, // comm devices must be opened w/exclusive-access NIL, // no security attributes OPEN_EXISTING, // comm devices must use OPEN_EXISTING 0, // not overlapped I/O 0); // hTemplate must be NULL for comm devices If (hPort = INVALID_HANDLE_VALUE) then begin FLastError := 'CreateFile ' + SysErrorMessage(GetLastError()); Exit; end; if not GetCommState(hPort, Param) then begin FLastError := 'GetCommState ' + SysErrorMessage(GetLastError()); FreePort(); Exit; end; Param.BaudRate := nBaudRate; Param.ByteSize := nWordLen; Param.Parity := nParity; Param.StopBits := nStopBits; If not SetCommState(hPort, Param) then begin FLastError := 'SetCommState ' + SysErrorMessage(GetLastError()); FreePort(); Exit; end; if not (SetupComm(hPort, 1024, 1024)) then begin FLastError := 'SetupComm ' + SysErrorMessage(GetLastError()); FreePort(); Exit; end; StateComPort := true; end; end.
{**************************************************} { TCurveFittingFunction } { TTrendFunction } { Copyright (c) 1995-2004 by David Berneda } {**************************************************} unit CurvFitt; {$I TeeDefs.inc} interface { TCustomFittingFunction derives from standard TTeeFunction. TCurveFittingFunction and TTrendFunction both derive from TCustomFittingFunction. Based on a Polynomial degree value (# of polynomy items), a curve fitting is calculated for each X,Y pair value to determine the new Y position for each source X value. } Uses Classes, TeePoly, StatChar, TeEngine; Type TTypeFitting=( cfPolynomial ); TCustomFittingFunction=class(TTeeFunction) private FFactor : Integer; FFirstPoint : Integer; FFirstCalcPoint : Integer; FLastPoint : Integer; FLastCalcPoint : Integer; FPolyDegree : Integer; { <-- between 1 and 20 } FTypeFitting : TTypeFitting; { internal } IAnswerVector : TDegreeVector; IMinYValue : Double; Procedure SetFactor(const Value:Integer); Procedure SetFirstCalcPoint(Value:Integer); Procedure SetFirstPoint(Value:Integer); Procedure SetIntegerProperty(Var Variable:Integer; Value:Integer); Procedure SetLastCalcPoint(Value:Integer); Procedure SetLastPoint(Value:Integer); Procedure SetPolyDegree(Value:Integer); Procedure SetTypeFitting(Value:TTypeFitting); protected Function GetAnswerVector(Index:Integer):Double; procedure AddFittedPoints(Source:TChartSeries); virtual; property Factor:Integer read FFactor write SetFactor; public Constructor Create(AOwner: TComponent); override; procedure AddPoints(Source:TChartSeries); override; Function GetCurveYValue(Source:TChartSeries; Const X:Double):Double; // properties property AnswerVector[Index:Integer]:Double read GetAnswerVector; property FirstCalcPoint:Integer read FFirstCalcPoint write SetFirstCalcPoint default -1; property FirstPoint:Integer read FFirstPoint write SetFirstPoint default -1; property LastCalcPoint:Integer read FLastCalcPoint write SetLastCalcPoint default -1; property LastPoint:Integer read FLastPoint write SetLastPoint default -1; property PolyDegree:Integer read FPolyDegree write SetPolyDegree default 5; property TypeFitting:TTypeFitting read FTypeFitting write SetTypeFitting default cfPolynomial; end; TCurveFittingFunction=class(TCustomFittingFunction) published property Factor default 1; property FirstCalcPoint; property FirstPoint; property LastCalcPoint; property LastPoint; property PolyDegree; property TypeFitting; end; TTrendStyle=(tsNormal,tsLogarithmic,tsExponential); TCustomTrendFunction=class(TTeeFunction) private IStyle : TTrendStyle; ICount : Integer; SumX : Double; SumXY : Double; SumY : Double; SumX2 : Double; SumY2 : Double; function CalculateValues(Source:TChartSeries; FirstIndex,LastIndex:Integer):Boolean; protected Procedure CalculatePeriod( Source:TChartSeries; Const tmpX:Double; FirstIndex,LastIndex:Integer); override; Procedure CalculateAllPoints( Source:TChartSeries; NotMandatorySource:TChartValueList); override; public Constructor Create(AOwner: TComponent); override; Function Calculate(SourceSeries:TChartSeries; First,Last:Integer):Double; override; Function CalculateMany(SourceSeriesList:TList; ValueIndex:Integer):Double; override; Function CalculateTrend( Var m,b:Double; Source:TChartSeries; FirstIndex,LastIndex:Integer):Boolean; // 6.02 Function Coefficient(Source:TChartSeries; FirstIndex,LastIndex:Integer):Double; end; TTrendFunction=class(TCustomTrendFunction); TExpTrendFunction=class(TCustomTrendFunction) public Constructor Create(AOwner: TComponent); override; end; TCorrelationFunction=class(TCustomTrendFunction) protected Procedure CalculatePeriod( Source:TChartSeries; Const tmpX:Double; FirstIndex,LastIndex:Integer); override; public Function Calculate(SourceSeries:TChartSeries; First,Last:Integer):Double; override; Function CalculateMany(SourceSeriesList:TList; ValueIndex:Integer):Double; override; end; implementation Uses Math, SysUtils, TeeProCo, Chart, TeeProcs, TeeConst, TeCanvas; { TCurveFittingFunction } Constructor TCustomFittingFunction.Create(AOwner: TComponent); Begin inherited; CanUsePeriod:=False; InternalSetPeriod(1); FPolyDegree:=5; FTypeFitting:=cfPolynomial; FFirstPoint:=-1; FLastPoint:=-1; FFirstCalcPoint:=-1; FLastCalcPoint:=-1; FFactor:=1; end; Procedure TCustomFittingFunction.SetIntegerProperty(Var Variable:Integer; Value:Integer); Begin if Variable<>Value then Begin Variable:=Value; Recalculate; end; end; Procedure TCustomFittingFunction.SetFirstPoint(Value:Integer); Begin SetIntegerProperty(FFirstPoint,Value); End; Procedure TCustomFittingFunction.SetLastPoint(Value:Integer); Begin SetIntegerProperty(FLastPoint,Value); End; Procedure TCustomFittingFunction.SetFactor(const Value:Integer); begin SetIntegerProperty(FFactor,Math.Max(1,Value)); end; Procedure TCustomFittingFunction.SetFirstCalcPoint(Value:Integer); Begin SetIntegerProperty(FFirstCalcPoint,Value); End; Procedure TCustomFittingFunction.SetLastCalcPoint(Value:Integer); Begin SetIntegerProperty(FLastCalcPoint,Value); End; Procedure TCustomFittingFunction.SetTypeFitting(Value:TTypeFitting); Begin if FTypeFitting<>Value then Begin FTypeFitting:=Value; Recalculate; end; end; Procedure TCustomFittingFunction.SetPolyDegree(Value:Integer); Begin if FPolyDegree<>Value then begin if (Value<1) or (Value>20) then Raise Exception.Create(TeeMsg_PolyDegreeRange); FPolyDegree:=Value; Recalculate; end; end; Function TCustomFittingFunction.GetAnswerVector(Index:Integer):Double; Begin if (Index<1) or (Index>FPolyDegree) then Raise Exception.CreateFmt(TeeMsg_AnswerVectorIndex,[FPolyDegree]); result:=IAnswerVector[Index]; End; procedure TCustomFittingFunction.AddFittedPoints(Source:TChartSeries); Var tmpX : Double; tmpX2 : Double; tmpMinXValue : Double; tmpStep : Double; t : Integer; tt : Integer; tmpStart : Integer; tmpEnd : Integer; begin IMinYValue:=ValueList(Source).MinValue; With Source do begin tmpMinXValue:=XValues.MinValue; if FFirstPoint=-1 then tmpStart:=0 else tmpStart:=FFirstPoint; if FLastPoint=-1 then tmpEnd:=Count-1 else tmpEnd:=FLastPoint; FFactor:=Math.Max(1,Factor); for t:=tmpStart to tmpEnd-1 do { 1 to 1 relationship between source and self } begin tmpX:=XValues.Value[t]; tmpStep:=(XValues.Value[t+1]-tmpX)/Factor; for tt:=0 to Factor-1 do begin tmpX2:=tmpX+tmpStep*tt; ParentSeries.AddXY( tmpX2, CalcFitting( FPolyDegree, IAnswerVector, tmpX2-tmpMinXValue)+IMinYValue); end; end; tmpX2:=XValues.Value[tmpEnd]; ParentSeries.AddXY( tmpX2, CalcFitting( FPolyDegree, IAnswerVector, tmpX2-tmpMinXValue)+IMinYValue); end; end; procedure TCustomFittingFunction.AddPoints(Source:TChartSeries); var t : Integer; tmpStart : Integer; tmpEnd : Integer; tmpCount : Integer; tmpPos : Integer; IXVector : TVector; IYVector : TVector; tmpMinXValue : Double; AList : TChartValueList; Begin ParentSeries.Clear; With Source do if Count>=FPolyDegree then begin AList:=ValueList(Source); tmpMinXValue:=XValues.MinValue; IMinYValue:=AList.MinValue; if FFirstCalcPoint=-1 then tmpStart:=0 else tmpStart:=Math.Max(0,FFirstCalcPoint); if FLastCalcPoint=-1 then tmpEnd:=Count-1 else tmpEnd:=Math.Min(Count-1,FLastCalcPoint); tmpCount:=(tmpEnd-tmpStart+1); if tmpCount>0 then begin SetLength(IXVector,tmpCount+1); SetLength(IYVector,tmpCount+1); try for t:=1 to tmpCount do begin tmpPos:=t+tmpStart-1; IXVector[t]:=XValues.Value[tmpPos]-tmpMinXValue; IYVector[t]:=AList.Value[tmpPos]-IMinYValue; end; PolyFitting(tmpCount,FPolyDegree,IXVector,IYVector,IAnswerVector); AddFittedPoints(Source); finally IYVector:=nil; IXVector:=nil; end; end; end; end; { calculates and returns the Y value corresponding to a X value } Function TCustomFittingFunction.GetCurveYValue(Source:TChartSeries; Const X:Double):Double; Begin result:=CalcFitting(FPolyDegree,IAnswerVector,X-Source.XValues.MinValue)+IMinYValue; end; { TCustomTrendFunction } constructor TCustomTrendFunction.Create(AOwner: TComponent); begin inherited; IStyle:=tsNormal; end; Function TCustomTrendFunction.Calculate(SourceSeries:TChartSeries; First,Last:Integer):Double; begin result:=0; end; Function TCustomTrendFunction.CalculateMany(SourceSeriesList:TList; ValueIndex:Integer):Double; begin result:=0; end; Procedure TCustomTrendFunction.CalculateAllPoints( Source:TChartSeries; NotMandatorySource:TChartValueList); begin CalculatePeriod(Source,0,0,Source.Count-1); end; Procedure TCustomTrendFunction.CalculatePeriod( Source:TChartSeries; Const tmpX:Double; FirstIndex,LastIndex:Integer); Var m : Double; b : Double; Procedure AddPoint(Const Value:Double); var tmp : Double; begin Case IStyle of tsNormal : tmp:=m*Value+b; tsLogarithmic: tmp:=m*Ln(Value*b); else tmp:=m*Exp(b*Value); end; if Source.YMandatory then ParentSeries.AddXY(Value, tmp) else ParentSeries.AddXY(tmp, Value) end; begin if CalculateTrend(m,b,Source,FirstIndex,LastIndex) then With Source.NotMandatoryValueList do begin if Order=loNone then begin AddPoint(MinValue); AddPoint(MaxValue); end else begin AddPoint(Value[FirstIndex]); AddPoint(Value[LastIndex]); end; end; end; Function TCustomTrendFunction.CalculateValues(Source:TChartSeries; FirstIndex,LastIndex:Integer):Boolean; var tmpAll : Boolean; t : Integer; x : TChartValue; y : TChartValue; begin if FirstIndex=TeeAllValues then begin FirstIndex:=0; LastIndex:=Source.Count-1; end; ICount:=LastIndex-FirstIndex+1; result:=ICount>1; if result then With Source do begin tmpAll:=(IStyle=tsNormal) and (ICount=Count); if tmpAll then begin SumX:=NotMandatoryValueList.Total; SumY:=ValueList(Source).Total; end else begin SumX:=0; SumY:=0; end; SumX2:=0; SumY2:=0; SumXY:=0; With ValueList(Source) do for t:=FirstIndex to LastIndex do begin x:=NotMandatoryValueList.Value[t]; if IStyle=tsNormal then y:=Value[t] else if Value[t]<>0 then y:=Ln(Value[t]) else y:=0; SumXY:=SumXY+x*y; SumX2:=SumX2+Sqr(x); SumY2:=SumY2+Sqr(y); if not tmpAll then begin SumX:=SumX+x; SumY:=SumY+y; end; end; end; end; Function TCustomTrendFunction.Coefficient(Source:TChartSeries; FirstIndex,LastIndex:Integer):Double; var tmpNumerator : Double; tmpDenominator : Double; begin if CalculateValues(Source,FirstIndex,LastIndex) then begin tmpNumerator:=SumXY - SumX*SumY/ICount; tmpDenominator:=Sqrt( (SumX2 - SumX*SumX/ICount) * (SumY2 - SumY*SumY/ICount) ); if tmpDenominator=0 then result:=1 else result:=tmpNumerator/tmpDenominator; end else result:=1; end; Function TCustomTrendFunction.CalculateTrend(Var m,b:Double; Source:TChartSeries; FirstIndex,LastIndex:Integer):Boolean; var Divisor : Double; begin result:=CalculateValues(Source,FirstIndex,LastIndex); if result then if IStyle=tsNormal then begin Divisor:=ICount*SumX2-Sqr(SumX); if Divisor<>0 then begin m:=( (ICount*SumXY) - (SumX*SumY) ) / Divisor; b:=( (SumY*SumX2) - (SumX*SumXY) ) / Divisor; end else begin m:=1; b:=0; end; end else begin SumX:=SumX/ICount; SumY:=SumY/ICount; Divisor:= (SumX2-(ICount*SumX*SumX)); if Divisor=0 then b:=1 else b:=(SumXY-(ICount*SumX*SumY))/Divisor; if IStyle=tsLogarithmic then m:=SumY-b*SumX else m:=Exp(SumY-b*SumX); end; end; { TExpTrendFunction } constructor TExpTrendFunction.Create(AOwner: TComponent); begin inherited; IStyle:=tsExponential; end; { TCorrelationFunction } function TCorrelationFunction.Calculate(SourceSeries: TChartSeries; First, Last: Integer): Double; begin result:=Coefficient(SourceSeries,First,Last); end; function TCorrelationFunction.CalculateMany(SourceSeriesList: TList; ValueIndex: Integer): Double; begin result:=0; end; procedure TCorrelationFunction.CalculatePeriod(Source: TChartSeries; const tmpX: Double; FirstIndex, LastIndex: Integer); procedure AddPoint(const x,y:Double); begin with ParentSeries do if YMandatory then ParentSeries.AddXY(x,y) else ParentSeries.AddXY(y,x); end; var tmp : Double; begin tmp:=Calculate(Source,FirstIndex,LastIndex); if ParentSeries.AllowSinglePoint then ParentSeries.Add(tmp) else begin AddPoint(Source.NotMandatoryValueList.MinValue,tmp); AddPoint(Source.NotMandatoryValueList.MaxValue,tmp); end; end; initialization RegisterTeeFunction( TCurveFittingFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionCurveFitting, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended ); RegisterTeeFunction( TTrendFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionTrend, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended ); RegisterTeeFunction( TExpTrendFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionExpTrend, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended ); RegisterTeeFunction( TCorrelationFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionCorrelation, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended ); finalization UnRegisterTeeFunctions([ TCurveFittingFunction, TTrendFunction, TExpTrendFunction, TCorrelationFunction ]); end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ApplicationEvents; interface {$SCOPEDENUMS ON} uses System.Messaging, System.Classes, FMX.Types, FMX.Platform, FMX.Forms, FGX.Consts, FMX.Controls; type { TfgApplicationEvents } TfgDeviceOrientationChanged = procedure (const AOrientation: TScreenOrientation) of object; TfgMainFormChanged = procedure (Sender: TObject; const ANewForm: TCommonCustomForm) of object; TfgMainFormCaptionChanged = procedure (Sender: TObject; const ANewForm: TCommonCustomForm; const ANewCaption: string) of object; TfgStyleChanged = procedure (Sender: TObject; const AScene: IScene; const AStyleBook: TStyleBook) of object; TfgFormNotify = procedure (Sender: TObject; const AForm: TCommonCustomForm) of object; [ComponentPlatformsAttribute(fgAllPlatform)] TfgApplicationEvents = class(TFmxObject) private FOnActionUpdate: TActionEvent; FOnActionExecute: TActionEvent; FOnException: TExceptionEvent; FOnOrientationChanged: TfgDeviceOrientationChanged; FOnFormSizeChanged: TfgFormNotify; FOnMainFormChanged: TfgMainFormChanged; FOnMainFormCaptionChanged: TfgMainFormCaptionChanged; FOnIdle: TIdleEvent; FOnSaveState: TNotifyEvent; FOnStateChanged: TApplicationEventHandler; FOnStyleChanged: TfgStyleChanged; FOnFormsCreated: TNotifyEvent; FOnFormReleased: TfgFormNotify; procedure SetOnActionExecute(const Value: TActionEvent); procedure SetOnActionUpdate(const Value: TActionEvent); procedure SetOnException(const Value: TExceptionEvent); procedure SetOnIdle(const Value: TIdleEvent); { Handlers } procedure ApplicationEventChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure OrientationChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure FormSizeChangedHandler(const ASender: TObject; const AMessage: TMessage); procedure FormReleasedHandler(const ASender: TObject; const AMessage: TMessage); procedure FormsCreatedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure MainFormChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure MainFormCaptionChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure StyleChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); procedure SaveStateMessageHandler(const ASender: TObject; const AMessage: TMessage); protected procedure DoStateChanged(const AEventData: TApplicationEventData); virtual; procedure DoOrientationChanged(const AOrientation: TScreenOrientation); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnActionExecute: TActionEvent read FOnActionExecute write SetOnActionExecute; property OnActionUpdate: TActionEvent read FOnActionUpdate write SetOnActionUpdate; property OnException: TExceptionEvent read FOnException write SetOnException; property OnIdle: TIdleEvent read FOnIdle write SetOnIdle; property OnFormSizeChanged: TfgFormNotify read FOnFormSizeChanged write FOnFormSizeChanged; property OnSaveState: TNotifyEvent read FOnSaveState write FOnSaveState; property OnStateChanged: TApplicationEventHandler read FOnStateChanged write FOnStateChanged; property OnStyleChanged: TfgStyleChanged read FOnStyleChanged write FOnStyleChanged; property OnOrientationChanged: TfgDeviceOrientationChanged read FOnOrientationChanged write FOnOrientationChanged; property OnFormsCreated: TNotifyEvent read FOnFormsCreated write FOnFormsCreated; property OnFormReleased: TfgFormNotify read FOnFormReleased write FOnFormReleased; property OnMainFormChanged: TfgMainFormChanged read FOnMainFormChanged write FOnMainFormChanged; property OnMainFormCaptionChanged: TfgMainFormCaptionChanged read FOnMainFormCaptionChanged write FOnMainFormCaptionChanged; end; implementation uses FGX.Helpers, FGX.Asserts; { TfgApplicationEvents } constructor TfgApplicationEvents.Create(AOwner: TComponent); begin inherited Create(AOwner); TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ApplicationEventChangedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, OrientationChangedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TFormsCreatedMessage, FormsCreatedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TMainFormChangedMessage, MainFormChangedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TMainCaptionChangedMessage, MainFormCaptionChangedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TStyleChangedMessage, StyleChangedMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TSaveStateMessage, SaveStateMessageHandler); TMessageManager.DefaultManager.SubscribeToMessage(TSizeChangedMessage, FormSizeChangedHandler); TMessageManager.DefaultManager.SubscribeToMessage(TFormReleasedMessage, FormReleasedHandler); { TODO -oBrovin Y.D. -cNextRelease : Need to add event handlers for these messages } // TScaleChangedMessage // TBeforeStyleChangingMessage end; destructor TfgApplicationEvents.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TFormReleasedMessage, FormReleasedHandler); TMessageManager.DefaultManager.Unsubscribe(TSizeChangedMessage, FormSizeChangedHandler); TMessageManager.DefaultManager.Unsubscribe(TSaveStateMessage, SaveStateMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TStyleChangedMessage, StyleChangedMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TMainCaptionChangedMessage, MainFormCaptionChangedMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TMainFormChangedMessage, MainFormChangedMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TFormsCreatedMessage, FormsCreatedMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, OrientationChangedMessageHandler); TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ApplicationEventChangedMessageHandler); inherited Destroy; end; procedure TfgApplicationEvents.ApplicationEventChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); var EventData: TApplicationEventData; begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TApplicationEventMessage); if AMessage is TApplicationEventMessage then begin EventData := TApplicationEventMessage(AMessage).Value; DoStateChanged(EventData) end; end; procedure TfgApplicationEvents.DoOrientationChanged(const AOrientation: TScreenOrientation); begin if Assigned(OnOrientationChanged) then OnOrientationChanged(AOrientation); end; procedure TfgApplicationEvents.OrientationChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TOrientationChangedMessage); if AMessage is TOrientationChangedMessage then DoOrientationChanged(Screen.Orientation); end; procedure TfgApplicationEvents.SaveStateMessageHandler(const ASender: TObject; const AMessage: TMessage); begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TSaveStateMessage); if AMessage is TSaveStateMessage then if Assigned(OnSaveState) then OnSaveState(Self); end; procedure TfgApplicationEvents.SetOnActionExecute(const Value: TActionEvent); begin AssertIsNotNil(Application); FOnActionExecute := Value; Application.OnActionExecute := Value; end; procedure TfgApplicationEvents.SetOnActionUpdate(const Value: TActionEvent); begin AssertIsNotNil(Application); FOnActionUpdate := Value; Application.OnActionUpdate := Value; end; procedure TfgApplicationEvents.SetOnException(const Value: TExceptionEvent); begin AssertIsNotNil(Application); FOnException := Value; Application.OnException := Value; end; procedure TfgApplicationEvents.SetOnIdle(const Value: TIdleEvent); begin AssertIsNotNil(Application); FOnIdle := Value; Application.OnIdle := Value; end; procedure TfgApplicationEvents.StyleChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); var Scene: IScene; StyleBook: TStyleBook; begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TStyleChangedMessage); if (AMessage is TStyleChangedMessage) and Assigned(OnStyleChanged) then begin Scene := TStyleChangedMessage(AMessage).Scene; StyleBook := TStyleChangedMessage(AMessage).Value; OnStyleChanged(Self, Scene, StyleBook); end; end; procedure TfgApplicationEvents.DoStateChanged(const AEventData: TApplicationEventData); begin if Assigned(OnStateChanged) then OnStateChanged(AEventData.Event, AEventData.Context); end; procedure TfgApplicationEvents.FormReleasedHandler(const ASender: TObject; const AMessage: TMessage); var Form: TCommonCustomForm; begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TFormReleasedMessage); AssertIsClass(ASender, TCommonCustomForm); if (AMessage is TFormReleasedMessage) and Assigned(OnFormReleased) then begin Form := TCommonCustomForm(ASender); OnFormReleased(Self, Form); end; end; procedure TfgApplicationEvents.FormsCreatedMessageHandler(const ASender: TObject; const AMessage: TMessage); begin if Assigned(OnFormsCreated) then OnFormsCreated(Self); end; procedure TfgApplicationEvents.FormSizeChangedHandler(const ASender: TObject; const AMessage: TMessage); var Form: TCommonCustomForm; begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TSizeChangedMessage); AssertIsClass(ASender, TCommonCustomForm); if (AMessage is TSizeChangedMessage) and Assigned(OnFormSizeChanged) then begin Form := TCommonCustomForm(ASender); OnFormSizeChanged(Self, Form); end; end; procedure TfgApplicationEvents.MainFormCaptionChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); var MainForm: TCommonCustomForm; Caption: string; begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TMainCaptionChangedMessage); if AMessage is TMainCaptionChangedMessage then begin if Assigned(OnMainFormCaptionChanged) then begin MainForm := TMainCaptionChangedMessage(AMessage).Value; if MainForm <> nil then Caption := mainForm.Caption else Caption := ''; OnMainFormCaptionChanged(Self, MainForm, Caption); end; end; end; procedure TfgApplicationEvents.MainFormChangedMessageHandler(const ASender: TObject; const AMessage: TMessage); begin AssertIsNotNil(AMessage); AssertIsClass(AMessage, TMainFormChangedMessage); if AMessage is TMainFormChangedMessage then begin if Assigned(OnMainFormChanged) then OnMainFormChanged(Self, TMainFormChangedMessage(AMessage).Value); end; end; initialization RegisterFmxClasses([TfgApplicationEvents]); end.
unit uIndicadorOperacoes; interface uses Contnrs, uRegistro; type TIndicadorOperacoes = class(TRegistro) private fID : Integer; // Toda chave primaria nossa no banco dentro do objeto vai chamar ID fCodigo : String; fDescricao : String; procedure SetCodigo(const Value: String); procedure SetDescricao(const Value: String); procedure SetID(const Value: Integer); public property ID : Integer read fID write SetID; property Descricao : String read fDescricao write SetDescricao; property Codigo : String read fCodigo write SetCodigo; function Todos : TObjectList; function Procurar () : TRegistro; constructor create(); end; implementation uses uIndicadorOperacoesBD; { TIndicadorOperacoes } constructor TIndicadorOperacoes.create; begin end; function TIndicadorOperacoes.Procurar: TRegistro; var lIndicadorOperacoesBD : TIndicadorOperacoesBD; begin lIndicadorOperacoesBD := TIndicadorOperacoesBD.Create; result := lIndicadorOperacoesBD.Procurar(self); // lIndicadorOperacoesBD.Free; // lIndicadorOperacoesBD := nil; end; procedure TIndicadorOperacoes.SetCodigo(const Value: String); begin fCodigo := Value; end; procedure TIndicadorOperacoes.SetDescricao(const Value: String); begin fDescricao := Value; end; procedure TIndicadorOperacoes.SetID(const Value: Integer); begin fID := Value; end; function TIndicadorOperacoes.Todos: TObjectList; var lIndicadorOperacoesBD : TIndicadorOperacoesBD; begin lIndicadorOperacoesBD := TIndicadorOperacoesBD.Create; result := lIndicadorOperacoesBD.Todos(); end; end.
{ "Windows Screen Utils (VCL)" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcVScreenUtilsWIN; interface {$include rtcDefs.inc} uses Types, Windows, Messages, Classes, SysUtils, {$IFDEF IDE_XEUp} VCL.Graphics, {$ELSE} Graphics, {$ENDIF} Registry, rtcTypes, rtcSystem, rtcInfo, rtcLog, rtcXJPEGConst, rtcXBmpUtils, rtcXScreenUtils, rtcVWinStation, rtcVMirrorDriver; function GetScreenBitmapInfo:TRtcBitmapInfo; function ScreenCapture(var Image: TRtcBitmapInfo; Forced:boolean):boolean; function WindowCapture(DW:HWND; Region:TRect; var Image:TRtcBitmapInfo):boolean; procedure MouseSetup; procedure GrabMouse; // Returns mouse cursor data for the last captured Screen. // Use ONLY after "ScreenCapture", or "MouseSetup" + "GrabMouse": function CaptureMouseCursorDelta: RtcByteArray; function CaptureMouseCursor: RtcByteArray; function GetScreenHeight: Integer; function GetScreenWidth: Integer; function GetDesktopTop: Integer; function GetDesktopLeft: Integer; function GetDesktopHeight: Integer; function GetDesktopWidth: Integer; function EnableMirrorDriver:boolean; procedure DisableMirrorDriver; function CurrentMirrorDriver:boolean; procedure EnableAero; procedure DisableAero; function CurrentAero:boolean; procedure ShowWallpaper; function HideWallpaper: String; procedure Control_MouseDown(const user: Cardinal; X, Y: integer; Button: TMouse_Button); procedure Control_MouseUp(const user: Cardinal; X, Y: integer; Button: TMouse_Button); procedure Control_MouseMove(const user: Cardinal; X, Y: integer); procedure Control_MouseWheel(Wheel: integer); procedure Control_KeyDown(key: word); // ; Shift: TShiftState); procedure Control_KeyUp(key: word); // ; Shift: TShiftState); procedure Control_SetKeys(capslock, lWithShift, lWithCtrl, lWithAlt: boolean); procedure Control_ResetKeys(capslock, lWithShift, lWithCtrl, lWithAlt: boolean); procedure Control_KeyPress(const AText: RtcString; AKey: word); procedure Control_KeyPressW(const AText: WideString; AKey: word); function Control_CtrlAltDel(fromLauncher: boolean = False): boolean; procedure Control_LWinKey(key: word); procedure Control_RWinKey(key: word); procedure Control_AltTab; procedure Control_ShiftAltTab; procedure Control_CtrlAltTab; procedure Control_ShiftCtrlAltTab; procedure Control_Win; procedure Control_RWin; procedure Control_ReleaseAllKeys; function Control_checkKeyPress(Key: longint): RtcChar; function Get_ComputerName: RtcString; function Get_UserName: RtcString; implementation var mirror:TVideoDriver=nil; updates:TRectUpdateRegion; MouseCS:TRtcCritSec; MyProcessID:Cardinal; function GetScreenBitmapInfo:TRtcBitmapInfo; begin FillChar(Result,SizeOf(Result),0); Result.Reverse:=True; Result.BuffType:=btBGRA32; Result.BytesPerPixel:=4; CompleteBitmapInfo(Result); end; function EnableMirrorDriver:boolean; begin {$IFNDEF WIN32} Result:=False; Exit; {$ENDIF} if assigned(mirror) then Result:=True else begin try mirror:=TVideoDriver.Create; mirror.MultiMonitor:=True; if not mirror.ExistMirrorDriver then begin FreeAndNil(mirror); Result:=False; end else if not mirror.ActivateMirrorDriver then begin FreeAndNil(mirror); Result:=False; end else begin Sleep(1000); if not mirror.MapSharedBuffers then begin FreeAndNil(mirror); Result:=False; end else begin Result:=True; updates:=TRectUpdateRegion.Create; end; end; except FreeAndNil(mirror); Result:=False; end; end; end; procedure DisableMirrorDriver; begin if assigned(mirror) then begin mirror.DeactivateMirrorDriver; FreeAndNil(mirror); FreeAndNil(updates); end; end; function CurrentMirrorDriver:boolean; begin Result:=assigned(mirror); end; function GetScreenHeight: Integer; begin Result := GetSystemMetrics(SM_CYSCREEN); end; function GetScreenWidth: Integer; begin Result := GetSystemMetrics(SM_CXSCREEN); end; function GetDesktopTop: Integer; begin Result := GetSystemMetrics(SM_YVIRTUALSCREEN); end; function GetDesktopLeft: Integer; begin Result := GetSystemMetrics(SM_XVIRTUALSCREEN); end; function GetDesktopHeight: Integer; begin Result := GetSystemMetrics(SM_CYVIRTUALSCREEN); end; function GetDesktopWidth: Integer; begin Result := GetSystemMetrics(SM_CXVIRTUALSCREEN); end; function IsWinNT: boolean; var OS: TOSVersionInfo; begin ZeroMemory(@OS, SizeOf(OS)); OS.dwOSVersionInfoSize := SizeOf(OS); GetVersionEx(OS); Result := OS.dwPlatformId = VER_PLATFORM_WIN32_NT; end; type TDwmEnableComposition = function(uCompositionAction: UINT): HRESULT; stdcall; TDwmIsCompositionEnabled = function(var pfEnabled: BOOL): HRESULT; stdcall; const DWM_EC_DISABLECOMPOSITION = 0; DWM_EC_ENABLECOMPOSITION = 1; var DwmEnableComposition: TDwmEnableComposition = nil; DwmIsCompositionEnabled: TDwmIsCompositionEnabled = nil; ChangedAero: boolean = False; OriginalAero: LongBool = True; DWMLibLoaded : boolean = False; DWMlibrary: THandle; procedure LoadDwmLibs; begin if not DWMLibLoaded then begin DWMlibrary := LoadLibrary('DWMAPI.dll'); if DWMlibrary <> 0 then begin DWMLibLoaded := True; DwmEnableComposition := GetProcAddress(DWMlibrary, 'DwmEnableComposition'); DwmIsCompositionEnabled := GetProcAddress(DWMlibrary, 'DwmIsCompositionEnabled'); end; end; end; procedure UnloadDwmLibs; begin if DWMLibLoaded then begin DWMLibLoaded := False; @DwmEnableComposition := nil; @DwmIsCompositionEnabled := nil; FreeLibrary(DWMLibrary); end; end; function CurrentAero:boolean; var CurrAero: LongBool; begin Result:=False; LoadDWMLibs; if @DwmIsCompositionEnabled <> nil then begin DwmIsCompositionEnabled(CurrAero); Result:=CurrAero; end; end; procedure EnableAero; begin if not CurrentAero then if @DwmEnableComposition <> nil then DwmEnableComposition(DWM_EC_ENABLECOMPOSITION); end; procedure DisableAero; begin if CurrentAero then if @DwmEnableComposition <> nil then DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); end; type TBlockInputProc = function(fBlockInput: boolean): DWord; stdcall; TGetCursorInfo = function(var pci: TCursorInfo): BOOL; stdcall; var User32Loaded: boolean = False; // User32 DLL loaded ? User32Handle: HInst; // User32 DLL handle BlockInputProc: TBlockInputProc = nil; GetCursorInfoProc: TGetCursorInfo = nil; function GetOSVersionInfo(var Info: TOSVersionInfo): boolean; begin FillChar(Info, sizeof(TOSVersionInfo), 0); Info.dwOSVersionInfoSize := sizeof(TOSVersionInfo); Result := GetVersionEx(Info); if (not Result) then begin FillChar(Info, sizeof(TOSVersionInfo), 0); Info.dwOSVersionInfoSize := sizeof(TOSVersionInfo); Result := GetVersionEx(Info); if (not Result) then Info.dwOSVersionInfoSize := 0; end; end; procedure LoadUser32; var osi: TOSVersionInfo; begin if not User32Loaded then begin User32Handle := LoadLibrary(user32); if User32Handle = 0 then Exit; // if loading fails, exit. User32Loaded := True; if GetOSVersionInfo(osi) then begin if osi.dwMajorVersion >= 5 then begin @BlockInputProc := GetProcAddress(User32Handle, 'BlockInput'); @GetCursorInfoProc := GetProcAddress(User32Handle, 'GetCursorInfo'); end; end; end; end; procedure UnLoadUser32; begin if User32Loaded then begin @BlockInputProc := nil; @GetCursorInfoProc := nil; FreeLibrary(User32Handle); User32Loaded := False; end; end; function Block_UserInput(fBlockInput: boolean): DWord; begin if not User32Loaded then LoadUser32; if @BlockInputProc <> nil then Result := BlockInputProc(fBlockInput) else Result := 0; end; function Get_CursorInfo(var pci: TCursorInfo): BOOL; begin if not User32Loaded then LoadUser32; if @GetCursorInfoProc <> nil then Result := GetCursorInfoProc(pci) else Result := False; end; var FCaptureLeft, FCaptureTop:integer; FMouseX, FMouseY, FMouseIconW, FMouseIconH, FMouseIconMaskW, FMouseIconMaskH, FMouseHotX, FMouseHotY: integer; FMouseVisible: boolean; FMouseHandle: HICON; FMouseIcon: TBitmap = nil; FMouseIconMask: TBitmap = nil; FMouseIconData:RtcByteArray = nil; FMouseIconMaskData:RtcByteArray = nil; FMouseUser, FLastMouseUser: Cardinal; FLastMouseX, FLastMouseY: integer; FLastMouseSkip: boolean; FMouseInit: boolean; FMouseChangedShape: boolean; FMouseMoved: boolean; FMouseLastVisible: boolean; procedure MouseSetup; begin FMouseChangedShape:=True; FMouseMoved:=True; FMouseHandle := INVALID_HANDLE_VALUE; FMouseInit := True; MouseCS.Acquire; try FLastMouseUser := 0; FLastMouseX := -1; FLastMouseY := -1; FLastMouseSkip := False; finally MouseCS.Release; end; FMouseUser := 0; FMouseX := -1; FMouseY := -1; RtcFreeAndNil(FMouseIcon); RtcFreeAndNil(FMouseIconMask); SetLength(FMouseIconData,0); SetLength(FMouseIconMaskData,0); end; procedure GrabMouse; var ci: TCursorInfo; icinfo: TIconInfo; pt: TPoint; ImgData:PColorBGR32; Y:integer; begin MouseCS.Acquire; try ci.cbSize := SizeOf(ci); if Get_CursorInfo(ci) then begin if ci.flags = CURSOR_SHOWING then begin FMouseVisible := True; if FMouseInit or (ci.ptScreenPos.X <> FMouseX) or (ci.ptScreenPos.Y <> FMouseY) then begin FMouseMoved := True; FMouseX := ci.ptScreenPos.X; FMouseY := ci.ptScreenPos.Y; if (FLastMouseUser <> 0) and (FMouseX >= FLastMouseX - 8) and (FMouseX <= FLastMouseX + 8) and (FMouseY >= FLastMouseY - 8) and (FMouseY <= FLastMouseY + 8) then FMouseUser := FLastMouseUser else begin FMouseUser := 0; FLastMouseX := -1; FLastMouseY := -1; FLastMouseSkip := False; end; end; if FMouseInit or (ci.hCursor <> FMouseHandle) then begin FMouseChangedShape := True; FMouseHandle := ci.hCursor; RtcFreeAndNil(FMouseIcon); RtcFreeAndNil(FMouseIconMask); SetLength(FMouseIconData,0); SetLength(FMouseIconMaskData,0); // send cursor image if GetIconInfo(ci.hCursor, icinfo) then begin FMouseHotX := icinfo.xHotspot; FMouseHotY := icinfo.yHotspot; if icinfo.hbmMask <> INVALID_HANDLE_VALUE then begin FMouseIconMask := TBitmap.Create; try FMouseIconMask.Handle := icinfo.hbmMask; FMouseIconMask.PixelFormat:=pf32bit; FMouseIconMaskW:=FMouseIconMask.Width; FMouseIconMaskH:=FMouseIconMask.Height; SetLength(FMouseIconMaskData,FMouseIconMaskW*FMouseIconMaskH*4); ImgData:=PColorBGR32(Addr(FMouseIconMaskData[0])); for Y := 0 to FMouseIconMask.Height - 1 do begin Move(FMouseIconMask.ScanLine[Y]^, ImgData^, FMouseIconMaskW*4); Inc(ImgData,FMouseIconMaskW); end; finally RtcFreeAndNil(FMouseIconMask); end; end; if icinfo.hbmColor <> INVALID_HANDLE_VALUE then begin FMouseIcon := TBitmap.Create; try FMouseIcon.Handle := icinfo.hbmColor; FMouseIcon.PixelFormat:=pf32bit; FMouseIconW:=FMouseIcon.Width; FMouseIconH:=FMouseIcon.Height; SetLength(FMouseIconData,FMouseIconW*FMouseIconH*4); ImgData:=PColorBGR32(Addr(FMouseIconData[0])); for Y := 0 to FMouseIcon.Height - 1 do begin Move(FMouseIcon.ScanLine[Y]^, ImgData^, FMouseIconW*4); Inc(ImgData,FMouseIconW); end; finally RtcFreeAndNil(FMouseIcon); end; end; end; end; FMouseInit := False; end else FMouseVisible := False; end else if GetCursorPos(pt) then begin FMouseVisible := True; if FMouseInit or (pt.X <> FMouseX) or (pt.Y <> FMouseY) then begin FMouseMoved := True; FMouseX := pt.X; FMouseY := pt.Y; if (FLastMouseUser <> 0) and (FMouseX >= FLastMouseX - 8) and (FMouseX <= FLastMouseX + 8) and (FMouseY >= FLastMouseY - 8) and (FMouseY <= FLastMouseY + 8) then FMouseUser := FLastMouseUser else begin FMouseUser := 0; FLastMouseX := -1; FLastMouseY := -1; FLastMouseSkip := False; end; end; FMouseInit := False; end else FMouseVisible := False; finally MouseCS.Release; end; end; var LastMirror: boolean; LastDW: HWND; LastDC: HDC; LastBMP: TBitmap; RTC_CAPTUREBLT: DWORD = $40000000; function WindowCapture(DW:HWND; Region:TRect; var Image:TRtcBitmapInfo):boolean; var SDC: HDC; X, Y, NewWid, NewHig, Wid, Hig:integer; ImgData: PColorBGR32; function CaptureNow(toDC:HDC):boolean; begin if RtcCaptureSettings.LayeredWindows then Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY or RTC_CAPTUREBLT) else Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY); end; begin Result:=False; Wid := Region.Right-Region.Left; Hig := Region.Bottom-Region.Top; if (Wid=0) or (Hig=0) then Exit; NewWid:=((Wid+7) div 8) * 8; NewHig:=((Hig+7) div 8) * 8; SDC := GetDC(DW); if SDC <> 0 then begin X := Region.Left; Y := Region.Top; Wid := Region.Right-Region.Left; Hig := Region.Bottom-Region.Top; if (Image.Width<>NewWid) or (Image.Height<>NewHig) then ResizeBitmapInfo(Image,NewWid,NewHig,False); if not assigned(LastBMP) then begin LastBMP:=TBitmap.Create; LastBMP.PixelFormat:=pf32bit; end; if (LastBMP.Width<>Image.Width) or (LastBMP.Height<>Image.Height) then begin LastBmp.Width:=Image.Width; LastBmp.Height:=Image.Height; end; LastBMP.Canvas.Lock; try Result:=CaptureNow(LastBMP.Canvas.Handle); if Result then begin ImgData:=PColorBGR32(Image.TopData); for Y := 0 to LastBMP.Height - 1 do begin Move(LastBMP.ScanLine[Y]^, ImgData^, Image.BytesPerLine); Inc(ImgData,Image.PixelsToNextLine); end; end; finally LastBMP.Canvas.Unlock; end; ReleaseDC(DW, SDC); end; end; function ScreenCapture(var Image: TRtcBitmapInfo; Forced:boolean):boolean; var DW: HWND; ImgData: PColorBGR32; SDC: HDC; X, Y: integer; X1, Y1, X2, Y2: integer; NewWid, NewHig, Wid, Hig, borLeft, borTop: integer; initial, changed, switched: boolean; function PrepareDC:boolean; begin if LastDC<>0 then begin try ReleaseDC(LastDW,LastDC); except end; LastDW:=0; LastDC:=0; end; DW := GetDesktopWindow; try SDC := GetDC(DW); except SDC := 0; end; if (DW <> 0) and (SDC = 0) then begin DW := 0; try SDC := GetDC(DW); except SDC := 0; end; end; LastDC:=SDC; LastDW:=DW; Result:=LastDC<>0; end; function CaptureNow(toDC:HDC):boolean; begin if RtcCaptureSettings.LayeredWindows then Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY or RTC_CAPTUREBLT) else Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY); if not Result then begin SwitchToActiveDesktop(true); if PrepareDC then if RtcCaptureSettings.LayeredWindows then Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY or RTC_CAPTUREBLT) else Result:=BitBlt(toDC, 0, 0, Wid, Hig, SDC, X, Y, SRCCOPY); end; end; begin Result:=False; switched:=SwitchToActiveDesktop(false); borLeft:=GetDesktopLeft; borTop:=GetDesktopTop; if RtcCaptureSettings.AllMonitors then begin Wid := GetDesktopWidth; Hig := GetDesktopHeight; X := borLeft; Y := borTop; end else begin Wid := GetScreenWidth; Hig := GetScreenHeight; X := 0; Y := 0; end; FCaptureLeft:=X; FCaptureTop:=Y; NewWid:=((Wid+7) div 8) * 8; NewHig:=((Hig+7) div 8) * 8; if (Image.Data=nil) or (Image.Width<>NewWid) or (Image.Height<>NewHig) then begin initial:=True; ResizeBitmapInfo(Image,NewWid,NewHig,False); end else initial:=False; if Forced then initial:=True; if assigned(mirror) then begin if not LastMirror then initial:=True; LastMirror:=True; Dec(X,borLeft); Dec(Y,borTop); updates.Region:=Rect(X,Y,X+Wid,Y+Hig); if mirror.UpdateIncremental(updates) then changed:=updates.changed else changed:=False; if initial then begin changed:=True; updates.Left:=X; updates.Top:=Y; updates.Right:=X+Wid; updates.Bottom:=Y+Hig; end; if changed then begin X1:=updates.Left-X; X2:=updates.Right-X; Y1:=updates.Top-Y; Y2:=updates.Bottom-Y; if X1<0 then X1:=0 else if X1>Wid then X1:=Wid; if Y1<0 then Y1:=0 else if Y1>Hig then Y1:=Hig; if X2<0 then X2:=0 else if X2>Wid then X2:=Wid; if Y2<0 then Y2:=0 else if Y2>Hig then Y2:=Hig; if (X2>X1) and (Y2>Y1) then begin if RtcCaptureSettings.CompleteBitmap then begin X1:=0;Y1:=0; X2:=Wid;Y2:=Hig; end; Result:=mirror.CaptureRect(Rect(X1+X,Y1+Y,X2+X,Y2+Y), Rect(X1,Y1,X2,Y2), Image.PixelsToNextLine*4, Image.TopData); end; end; end else begin LastMirror:=False; if (LastDC<>0) and not switched then SDC:=LastDC else if not PrepareDC then Exit; if not assigned(LastBMP) then begin LastBMP:=TBitmap.Create; LastBMP.PixelFormat:=pf32bit; end; if (LastBMP.Width<>Image.Width) or (LastBMP.Height<>Image.Height) then begin LastBMP.Width:=Image.Width; LastBMP.Height:=Image.Height; end; LastBMP.Canvas.Lock; try Result:=CaptureNow(LastBMP.Canvas.Handle); if Result then begin ImgData:=PColorBGR32(Image.TopData); for Y := 0 to LastBMP.Height - 1 do begin Move(LastBMP.ScanLine[Y]^, ImgData^, Image.BytesPerLine); Inc(ImgData,Image.PixelsToNextLine); end; end; finally LastBMP.Canvas.Unlock; end; end; end; function CaptureMouseCursorDelta: RtcByteArray; var rec:TRtcRecord; begin if FMouseMoved or FMouseChangedShape or (FMouseLastVisible <> FMouseVisible) then begin rec := TRtcRecord.Create; try if FMouseLastVisible <> FMouseVisible then rec.asBoolean['V'] := FMouseVisible; if FMouseMoved then begin rec.asInteger['X'] := FMouseX - FCaptureLeft; rec.asInteger['Y'] := FMouseY - FCaptureTop; if FMouseUser <> 0 then rec.asCardinal['A'] := FMouseUser; end; if FMouseChangedShape then begin rec.asInteger['HX'] := FMouseHotX; rec.asInteger['HY'] := FMouseHotY; if length(FMouseIconData)>0 then begin rec.asInteger['IW']:=FMouseIconW; rec.asInteger['IH']:=FMouseIconH; rec.asByteArray['I']:=FMouseIconData; SetLength(FMouseIconData,0); end; if length(FMouseIconMaskData)>0 then begin rec.asInteger['MW']:=FMouseIconMaskW; rec.asInteger['MH']:=FMouseIconMaskH; rec.asByteArray['M']:=FMouseIconMaskData; SetLength(FMouseIconMaskData,0); end; end; Result:=rec.toCodeEx; finally RtcFreeAndNil(rec); end; FMouseMoved := False; FMouseChangedShape := False; FMouseLastVisible := FMouseVisible; end else Result:=nil; end; function CaptureMouseCursor: RtcByteArray; begin FMouseChangedShape := True; FMouseMoved := True; FMouseLastVisible := not FMouseVisible; Result := CaptureMouseCursorDelta; end; procedure FreeMouseCursorStorage; begin FMouseHandle:=INVALID_HANDLE_VALUE; RtcFreeAndNil(FMouseIcon); RtcFreeAndNil(FMouseIconMask); SetLength(FMouseIconData,0); SetLength(FMouseIconMaskData,0); end; function okToClick(X, Y: integer): boolean; var P: TPoint; W: HWND; hit: integer; pid: Cardinal; begin P.X := X; P.Y := Y; W := WindowFromPoint(P); if GetWindowThreadProcessId(W,pid)=0 then Result:=True else if pid<>MyProcessID then Result := True else begin hit := SendMessage(W, WM_NCHITTEST, 0, P.X + (P.Y shl 16)); // XLog('X='+IntToStr(P.X)+', Y='+IntToStr(P.Y)+', H='+IntToStr(hit)); Result := not(hit in [HTCLOSE, HTMAXBUTTON, HTMINBUTTON, HTTOP]); end; end; {function okToUnClick(X, Y: integer): boolean; var P: TPoint; R: TRect; W: HWND; hit: integer; begin P.X := X; P.Y := Y; W := WindowFromPoint(P); hit := SendMessage(W, WM_NCHITTEST, 0, P.X + (P.Y shl 16)); Result := not(hit in [HTCLOSE, HTMAXBUTTON, HTMINBUTTON]); if not Result then begin case hit of HTCLOSE: PostMessage(W, WM_SYSCOMMAND, SC_CLOSE, 0); HTMINBUTTON: PostMessage(W, WM_SYSCOMMAND, SC_MINIMIZE, 0); HTMAXBUTTON: begin GetWindowRect(W, R); if (R.Left=0) and (R.Top=0) and (R.Right=GetScreenWidth) and (R.Bottom=GetScreenHeight) then PostMessage(W, WM_SYSCOMMAND, SC_RESTORE, 0) else PostMessage(W, WM_SYSCOMMAND, SC_MAXIMIZE, 0); end; end; end; end;} procedure Post_MouseDown(Button: TMouse_Button); begin case Button of mb_Left: mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mb_Right: mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); mb_Middle: mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0); end; end; procedure Post_MouseUp(Button: TMouse_Button); begin case Button of mb_Left: mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); mb_Right: mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); mb_Middle: mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0); end; end; procedure Post_MouseWheel(Wheel: integer); begin mouse_event(MOUSEEVENTF_WHEEL, 0, 0, Wheel, 0); end; procedure Post_MouseMove(X, Y: integer); begin if GetScreenWidth > 0 then begin X := round(X / (GetScreenWidth - 1) * 65535); Y := round(Y / (GetScreenHeight - 1) * 65535); mouse_event(MOUSEEVENTF_MOVE or MOUSEEVENTF_ABSOLUTE, X, Y, 0, 0); end else SetCursorPos(X, Y); end; procedure Control_MouseDown(const user: Cardinal; X, Y: integer; Button: TMouse_Button); var LX,LY:integer; begin if Button in [mb_Left, mb_Right] then if GetSystemMetrics(SM_SWAPBUTTON) <> 0 then case Button of mb_Left: Button := mb_Right; mb_Right: Button := mb_Left; end; MouseCS.Acquire; try FLastMouseUser := user; FLastMouseX := X + FCaptureLeft; FLastMouseY := Y + FCaptureTop; LX:=FLastMouseX; LY:=FLastMouseY; FLastMouseSkip:=False; SetCursorPos(FLastMouseX, FLastMouseY); Post_MouseMove(FLastMouseX, FLastMouseY); finally MouseCS.Release; end; if Button <> mb_Left then Post_MouseDown(Button) else if not okToClick(LX, LY) then FLastMouseSkip:=True else Post_MouseDown(Button); end; procedure Control_MouseUp(const user: Cardinal; X, Y: integer; Button: TMouse_Button); begin if Button in [mb_Left, mb_Right] then if GetSystemMetrics(SM_SWAPBUTTON) <> 0 then case Button of mb_Left: Button := mb_Right; mb_Right: Button := mb_Left; end; MouseCS.Acquire; try FLastMouseUser := user; FLastMouseX := X + FCaptureLeft; FLastMouseY := Y + FCaptureTop; Post_MouseMove(FLastMouseX, FLastMouseY); finally MouseCS.Release; end; if Button <> mb_Left then begin FLastMouseSkip:=False; Post_MouseUp(Button); end else if FLastMouseSkip then begin FLastMouseSkip:=False; Post_MouseDown(Button); Post_MouseUp(Button); end else Post_MouseUp(Button); end; procedure Control_MouseMove(const user: Cardinal; X, Y: integer); begin MouseCS.Acquire; try FLastMouseUser := user; FLastMouseX := X + FCaptureLeft; FLastMouseY := Y + FCaptureTop; Post_MouseMove(FLastMouseX, FLastMouseY); finally MouseCS.Release; end; end; procedure Control_MouseWheel(Wheel: integer); begin Post_MouseWheel(Wheel); end; var FShiftDown:boolean=False; FCtrlDown:boolean=False; FAltDown:boolean=False; procedure keybdevent(key: word; Down: boolean = True); var vk: integer; begin vk := MapVirtualKey(key, 0); if Down then keybd_event(key, vk, 0, 0) else keybd_event(key, vk, KEYEVENTF_KEYUP, 0); end; procedure Control_KeyDown(key: word); // ; Shift: TShiftState); var numlock: boolean; begin case key of VK_SHIFT: if FShiftDown then Exit else FShiftDown := True; VK_CONTROL: if FCtrlDown then Exit else FCtrlDown := True; VK_MENU: if FAltDown then Exit else FAltDown := True; end; if (Key >= $21) and (Key <= $2E) then begin numlock := (GetKeyState(VK_NUMLOCK) and 1 = 1); if numlock then begin keybdevent(VK_NUMLOCK); keybdevent(VK_NUMLOCK, False); end; keybd_event(key,MapVirtualKey(key, 0), KEYEVENTF_EXTENDEDKEY, 0) // have to be Exctended ScanCodes end else begin numlock := False; keybdevent(Key); end; if numlock then begin keybdevent(VK_NUMLOCK, False); keybdevent(VK_NUMLOCK); end; end; procedure Control_KeyUp(key: word); // ; Shift: TShiftState); var numlock: boolean; begin case key of VK_SHIFT: if not FShiftDown then Exit else FShiftDown := False; VK_CONTROL: if not FCtrlDown then Exit else FCtrlDown := False; VK_MENU: if not FAltDown then Exit else FAltDown := False; end; if (key >= $21) and (key <= $2E) then begin numlock := (GetKeyState(VK_NUMLOCK) and 1 = 1); if numlock then begin // turn NUM LOCK off keybdevent(VK_NUMLOCK); keybdevent(VK_NUMLOCK, False); end; end else numlock := False; keybdevent(key, False); if numlock then begin // turn NUM LOCK on keybdevent(VK_NUMLOCK); keybdevent(VK_NUMLOCK, False); end; end; procedure Control_SetKeys(capslock, lWithShift, lWithCtrl, lWithAlt: boolean); begin if capslock then begin // turn CAPS LOCK off keybdevent(VK_CAPITAL); keybdevent(VK_CAPITAL, False); end; if lWithShift <> FShiftDown then keybdevent(VK_SHIFT, lWithShift); if lWithCtrl <> FCtrlDown then keybdevent(VK_CONTROL, lWithCtrl); if lWithAlt <> FAltDown then keybdevent(VK_MENU, lWithAlt); end; procedure Control_ResetKeys(capslock, lWithShift, lWithCtrl, lWithAlt: boolean); begin if lWithAlt <> FAltDown then keybdevent(VK_MENU, FAltDown); if lWithCtrl <> FCtrlDown then keybdevent(VK_CONTROL, FCtrlDown); if lWithShift <> FShiftDown then keybdevent(VK_SHIFT, FShiftDown); if capslock then begin // turn CAPS LOCK on keybdevent(VK_CAPITAL); keybdevent(VK_CAPITAL, False); end; end; procedure Control_KeyPress(const AText: RtcString; AKey: word); var a: integer; lScanCode: Smallint; lWithAlt, lWithCtrl, lWithShift: boolean; capslock: boolean; begin for a := 1 to length(AText) do begin {$IFDEF RTC_BYTESTRING} lScanCode := VkKeyScanA(AText[a]); {$ELSE} lScanCode := VkKeyScanW(AText[a]); {$ENDIF} if lScanCode = -1 then begin if not(AKey in [VK_MENU, VK_SHIFT, VK_CONTROL, VK_CAPITAL, VK_NUMLOCK]) then begin keybdevent(AKey); keybdevent(AKey, False); end; end else begin lWithShift := lScanCode and $100 <> 0; lWithCtrl := lScanCode and $200 <> 0; lWithAlt := lScanCode and $400 <> 0; lScanCode := lScanCode and $F8FF; // remove Shift, Ctrl and Alt from the scan code capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, lWithShift, lWithCtrl, lWithAlt); keybdevent(lScanCode); keybdevent(lScanCode, False); Control_ResetKeys(capslock, lWithShift, lWithCtrl, lWithAlt); end; end; end; procedure Control_KeyPressW(const AText: WideString; AKey: word); var a: integer; lScanCode: Smallint; lWithAlt, lWithCtrl, lWithShift: boolean; capslock: boolean; begin for a := 1 to length(AText) do begin lScanCode := VkKeyScanW(AText[a]); if lScanCode = -1 then begin if not(AKey in [VK_MENU, VK_SHIFT, VK_CONTROL, VK_CAPITAL, VK_NUMLOCK]) then begin keybdevent(AKey); keybdevent(AKey, False); end; end else begin lWithShift := lScanCode and $100 <> 0; lWithCtrl := lScanCode and $200 <> 0; lWithAlt := lScanCode and $400 <> 0; lScanCode := lScanCode and $F8FF; // remove Shift, Ctrl and Alt from the scan code capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, lWithShift, lWithCtrl, lWithAlt); keybdevent(lScanCode); keybdevent(lScanCode, False); Control_ResetKeys(capslock, lWithShift, lWithCtrl, lWithAlt); end; end; end; procedure Control_LWinKey(key: word); begin Control_SetKeys(False, False, False, False); keybdevent(VK_LWIN); keybdevent(key); keybdevent(key, False); keybdevent(VK_LWIN, False); Control_ResetKeys(False, False, False, False); end; procedure Control_RWinKey(key: word); begin Control_SetKeys(False, False, False, False); keybdevent(VK_RWIN); keybdevent(key); keybdevent(key, False); keybdevent(VK_RWIN, False); Control_ResetKeys(False, False, False, False); end; procedure Control_AltTab; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, False, False, True); keybdevent(VK_TAB); keybdevent(VK_TAB, False); Control_ResetKeys(capslock, False, False, True); end; procedure Control_ShiftAltTab; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, True, False, True); keybdevent(VK_TAB); keybdevent(VK_TAB, False); Control_ResetKeys(capslock, True, False, True); end; procedure Control_CtrlAltTab; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, False, True, True); keybdevent(VK_TAB); keybdevent(VK_TAB, False); Control_ResetKeys(capslock, False, True, True); end; procedure Control_ShiftCtrlAltTab; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, True, True, True); keybdevent(VK_TAB); keybdevent(VK_TAB, False); Control_ResetKeys(capslock, True, True, True); end; procedure Control_Win; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, False, False, False); keybdevent(VK_LWIN); keybdevent(VK_LWIN, False); Control_ResetKeys(capslock, False, False, False); end; procedure Control_RWin; var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; Control_SetKeys(capslock, False, False, False); keybdevent(VK_RWIN); keybdevent(VK_RWIN, False); Control_ResetKeys(capslock, False, False, False); end; (* procedure Control_SpecialKey(const AKey: RtcString); var capslock: boolean; begin capslock := GetKeyState(VK_CAPITAL) > 0; if AKey = 'CAD' then begin // Ctrl+Alt+Del if UpperCase(Get_UserName) = 'SYSTEM' then begin XLog('Executing CtrlAltDel as SYSTEM user ...'); SetKeys(capslock, False, False, False); if not Post_CtrlAltDel then begin XLog('CtrlAltDel execution failed as SYSTEM user'); if rtcGetProcessID(AppFileName) > 0 then begin XLog('Sending CtrlAltDel request to Host Service ...'); Write_File(ChangeFileExt(AppFileName, '.cad'), ''); end; end else XLog('CtrlAltDel execution successful'); ResetKeys(capslock, False, False, False); end else begin if rtcGetProcessID(AppFileName) > 0 then begin XLog('Sending CtrlAltDel request to Host Service ...'); Write_File(ChangeFileExt(AppFileName, '.cad'), ''); end else begin XLog('Emulating CtrlAltDel as "'+Get_UserName+'" user ...'); SetKeys(capslock, False, True, True); keybdevent(VK_ESCAPE); keybdevent(VK_ESCAPE, False); ResetKeys(capslock, False, True, True); end; end; end else if AKey = 'COPY' then begin // Ctrl+C SetKeys(capslock, False, True, False); keybdevent(Ord('C')); keybdevent(Ord('C'), False); ResetKeys(capslock, False, True, False); end else if AKey = 'HDESK' then begin // Hide Wallpaper Hide_Wallpaper; end else if AKey = 'SDESK' then begin // Show Wallpaper Show_Wallpaper; end; end; *) procedure Control_ReleaseAllKeys; begin if FShiftDown then Control_KeyUp(VK_SHIFT); //, []); if FAltDown then Control_KeyUp(VK_MENU); // , []); if FCtrlDown then Control_KeyUp(VK_CONTROL); // , []); end; function Get_ComputerName: RtcString; var buf: array [0 .. 256] of AnsiChar; len: DWord; begin len := sizeof(buf); GetComputerNameA(@buf, len); Result := RtcString(PAnsiChar(@buf)); end; function Get_UserName: RtcString; var buf: array [0 .. 256] of AnsiChar; len: DWord; begin len := sizeof(buf); GetUserNameA(@buf, len); Result := RtcString(PAnsiChar(@buf)); end; type TSendCtrlAltDel = function(asUser: Bool; iSession: integer) : Cardinal; stdcall; function Call_CAD:boolean; var nr : integer; sendcad: TSendCtrlAltDel; lib : Cardinal; begin Result:=False; lib := LoadLibrary('aw_sas32.dll'); if lib <> 0 then begin try @sendcad := GetProcAddress(lib, 'sendCtrlAltDel'); if assigned(sendcad) then begin nr := sendcad(False, -1); if nr<>0 then XLog('SendCtrlAltDel execution failed, Error Code = ' + inttostr(nr)) else begin XLog('SendCtrlAltDel executed OK using aw_sas32.dll'); Result:=True; end; end else XLog('Loading sendCtrlAltDel from aw_sas32.dll failed'); finally FreeLibrary(lib); end; end else XLog('Loading aw_sas32.dll failed, can not execute sendCtrlAltDel'); end; function Control_CtrlAltDel(fromLauncher: boolean = False): boolean; var LogonDesktop, CurDesktop: HDESK; dummy: Cardinal; new_name: array [0 .. 256] of AnsiChar; begin if (Win32MajorVersion >= 6 { vista\server 2k8 } ) then Result := Call_CAD else Result := false; if not Result then begin { dwSessionId := WTSGetActiveConsoleSessionId; myPID:= GetCurrentProcessId; winlogonSessId := 0; if (ProcessIdToSessionId(myPID, winlogonSessId) and (winlogonSessId = dwSessionId)) then } XLog('Executing CtrlAltDel through WinLogon ...'); Result := False; LogonDesktop := OpenDesktopA('Winlogon', 0, False, DESKTOP_ALL); if (LogonDesktop <> 0) and (GetUserObjectInformationA(LogonDesktop, UOI_NAME, @new_name, 256, dummy)) then try CurDesktop := GetThreadDesktop(GetCurrentThreadID); if (CurDesktop = LogonDesktop) or SetThreadDesktop(LogonDesktop) then try PostMessageA(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT or MOD_CONTROL, VK_DELETE)); Result := True; finally if CurDesktop <> LogonDesktop then SetThreadDesktop(CurDesktop); end else begin PostMessageA(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT or MOD_CONTROL, VK_DELETE)); end; finally CloseDesktop(LogonDesktop); end else begin PostMessageA(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT or MOD_CONTROL, VK_DELETE)); end; end; end; var WallpaperVisible: boolean = True; procedure ShowWallpaper; var reg: TRegIniFile; Result: String; begin Result := ''; reg := TRegIniFile.Create('Control Panel\Desktop'); Result := Trim(reg.ReadString('', 'Wallpaper', '')); reg.Free; if Result <> '' then begin WallpaperVisible := True; // Return the old value back to Registry. if Result <> '' then begin reg := TRegIniFile.Create('Control Panel\Desktop'); try reg.WriteString('', 'Wallpaper', Result); finally reg.Free; end; end; // // let everyone know that we changed // a system parameter // SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, PChar(Result), SPIF_UPDATEINIFILE + SPIF_SENDWININICHANGE); end; end; const SPI_GETDESKWALLPAPER = $0073; function HideWallpaper: String; var reg: TRegIniFile; aWall: PChar; begin if WallpaperVisible then begin WallpaperVisible := False; // // change registry // // HKEY_CURRENT_USER // Control Panel\Desktop // TileWallpaper (REG_SZ) // Wallpaper (REG_SZ) // Result := ''; GetMem(aWall, 32767); try SystemParametersInfo(SPI_GETDESKWALLPAPER, 32767, Pointer(aWall), 0); Result := strPas(aWall); finally FreeMem(aWall); end; // // let everyone know that we changed // a system parameter // SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, PChar(''), SPIF_UPDATEINIFILE + SPIF_SENDWININICHANGE); // Return the old value back to Registry. if Result <> '' then begin reg := TRegIniFile.Create('Control Panel\Desktop'); try reg.WriteString('', 'Wallpaper', Result); finally reg.Free; end; end; end; end; function Control_checkKeyPress(Key: longint): RtcChar; var pc: array [1 .. 10] of RtcChar; ks: TKeyboardState; begin FillChar(ks, SizeOf(ks), 0); GetKeyboardState(ks); {$IFDEF RTC_BYTESTRING} if ToAscii(Key, MapVirtualKey(Key, 0), ks, @pc[1], 0) = 1 then begin Result := pc[1]; if vkKeyScanA(Result) and $FF <> Key and $FF then Result := #0; end {$ELSE} if ToUnicode(Key, MapVirtualKey(Key, 0), ks, pc[1], 10, 0) = 1 then begin Result := pc[1]; if vkKeyScanW(Result) and $FF <> Key and $FF then Result := #0; end {$ENDIF} else Result := #0; end; initialization LastDC:=0; LastDW:=0; if not IsWinNT then RTC_CAPTUREBLT := 0; MouseCS:=TRtcCritSec.Create; MyProcessID:=GetCurrentProcessId; finalization Control_ReleaseAllKeys; RtcFreeAndNil(LastBMP); RtcFreeAndNil(MouseCS); FreeMouseCursorStorage; DisableMirrorDriver; UnloadDwmLibs; UnLoadUser32; end.
unit Horse.CodeGen.Templates; interface resourcestring sHorseDPR = 'program %0:s;' + sLineBreak + sLineBreak + '{$APPTYPE CONSOLE}' + sLineBreak + sLineBreak + 'uses' + sLineBreak + ' Horse;' + sLineBreak + sLineBreak + '{$R *.res}' + sLineBreak + sLineBreak + 'var' + sLineBreak + ' App: THorse;' + sLineBreak + sLineBreak + 'begin' + sLineBreak + ' App := THorse.Create(9000);' + sLineBreak + sLineBreak + ' App.Get(''/ping'',' + sLineBreak + ' procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)' + sLineBreak + ' begin' + sLineBreak + ' Res.Send(''pong'');' + sLineBreak + ' end);' + sLineBreak + sLineBreak + ' App.Start;' + sLineBreak + 'end.' + sLineBreak; implementation end.
{*********************************************} { TeeGrid Software Library } { Base abstract Control class } { Copyright (c) 2016 by Steema Software } { All Rights Reserved } {*********************************************} unit Tee.Control; {$I Tee.inc} interface uses {System.}Classes, {$IFNDEF FPC} {System.}Types, {$ENDIF} Tee.Format, Tee.Painter; type TCustomTeeControl=class(TComponent) private FBack: TFormat; IChanged : TNotifyEvent; procedure SetBack(const Value: TFormat); protected IUpdating : Integer; procedure BeginUpdate; inline; procedure EndUpdate; procedure Changed(Sender:TObject); property OnChange:TNotifyEvent read IChanged write IChanged; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; procedure Assign(Source:TPersistent); override; procedure Paint; virtual; function ClientHeight:Single; virtual; function ClientWidth:Single; virtual; function Height:Single; virtual; abstract; function Painter:TPainter; virtual; abstract; function Width:Single; virtual; abstract; published property Back:TFormat read FBack write SetBack; end; implementation
unit MDIEdit; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ComCtrls; type TEditForm = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; New1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Saveas1: TMenuItem; Print1: TMenuItem; N2: TMenuItem; Exit1: TMenuItem; Edit1: TMenuItem; Cut1: TMenuItem; Copy1: TMenuItem; Paste1: TMenuItem; Delete1: TMenuItem; N3: TMenuItem; Selectall1: TMenuItem; Character1: TMenuItem; Left1: TMenuItem; Right1: TMenuItem; Center1: TMenuItem; N4: TMenuItem; Wordwrap1: TMenuItem; N5: TMenuItem; Font1: TMenuItem; Editor: TRichEdit; PopupMenu1: TPopupMenu; Cut2: TMenuItem; Copy2: TMenuItem; Paste2: TMenuItem; SaveFileDialog: TSaveDialog; FontDialog1: TFontDialog; Printersetup1: TMenuItem; Close1: TMenuItem; PrinterSetupDialog1: TPrinterSetupDialog; PrintDialog1: TPrintDialog; procedure Exit1Click(Sender: TObject); procedure New1Click(Sender: TObject); procedure AlignClick(Sender: TObject); procedure Wordwrap1Click(Sender: TObject); procedure Cut1Click(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure Paste1Click(Sender: TObject); procedure Selectall1Click(Sender: TObject); procedure Delete1Click(Sender: TObject); procedure Edit1Click(Sender: TObject); procedure Saveas1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Font1Click(Sender: TObject); procedure Close1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure Printersetup1Click(Sender: TObject); procedure Print1Click(Sender: TObject); procedure Open1Click(Sender: TObject); private { Private declarations } PathName: string; public { Public declarations } procedure Open(const AFileName: string); end; var EditForm: TEditForm; const DefaultFileName = 'Untitled'; implementation uses Clipbrd, Printers, MDIFrame; {$R *.dfm} procedure TEditForm.Exit1Click(Sender: TObject); begin FrameForm.Exit1Click(Sender); end; procedure TEditForm.New1Click(Sender: TObject); begin FrameForm.New1Click(Sender); end; procedure TEditForm.Open1Click(Sender: TObject); begin FrameForm.Open1Click(Sender); end; procedure TEditForm.AlignClick(Sender: TObject); begin Left1.Checked := False; Right1.Checked := False; Center1.Checked := False; with Sender as TMenuItem do Checked := True; with Editor.Paragraph do if Left1.Checked then Alignment := taLeftJustify else if Right1.Checked then Alignment := taRightJustify else if Center1.Checked then Alignment := taCenter; end; procedure TEditForm.Wordwrap1Click(Sender: TObject); begin with Editor do begin WordWrap := not WordWrap; { toggle word wrapping } if WordWrap then ScrollBars := ssVertical else ScrollBars := ssBoth; WordWrap1.Checked := WordWrap; { set menu item check } end; end; procedure TEditForm.Cut1Click(Sender: TObject); begin Editor.CutToClipboard; end; procedure TEditForm.Copy1Click(Sender: TObject); begin Editor.CopyToClipboard; end; procedure TEditForm.Paste1Click(Sender: TObject); begin Editor.PasteFromClipboard; end; procedure TEditForm.Selectall1Click(Sender: TObject); begin Editor.SelectAll; end; procedure TEditForm.Delete1Click(Sender: TObject); begin Editor.ClearSelection; end; procedure TEditForm.Edit1Click(Sender: TObject); var HasSelection: Boolean; begin Paste1.Enabled := Clipboard.HasFormat(CF_TEXT); Paste2.Enabled := Paste1.Enabled; HasSelection := Editor.SelLength > 0; Cut1.Enabled := HasSelection; Cut2.Enabled := HasSelection; Copy1.Enabled := HasSelection; Copy2.Enabled := HasSelection; Delete1.Enabled := HasSelection; end; procedure TEditForm.Open(const AFileName: string); begin PathName := AFileName; Caption := ExtractFileName(AFileName); with Editor do begin Lines.LoadFromFile(PathName); SelStart := 0; Modified := False; end; end; procedure TEditForm.Saveas1Click(Sender: TObject); begin SaveFileDialog.FileName := PathName; if SaveFileDialog.Execute then begin PathName := SaveFileDialog.FileName; Caption := ExtractFileName(PathName); Save1Click(Sender); end; end; procedure TEditForm.Save1Click(Sender: TObject); begin if PathName = DefaultFileName then SaveAs1Click(Sender) else begin Editor.Lines.SaveToFile(PathName); Editor.Modified := False; end; end; procedure TEditForm.Font1Click(Sender: TObject); begin FontDialog1.Font := Editor.Font; if FontDialog1.Execute then Editor.SelAttributes.Assign(FontDialog1.Font); end; procedure TEditForm.Close1Click(Sender: TObject); begin Close; end; procedure TEditForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TEditForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); const SWarningText = 'Save changes to %s?'; begin if Editor.Modified then begin case MessageDlg(Format(SWarningText, [PathName]), mtConfirmation, [mbYes, mbNo, mbCancel], 0) of idYes: Save1Click(Self); idCancel: CanClose := False; end; end; end; procedure TEditForm.FormCreate(Sender: TObject); begin PathName := DefaultFileName; end; procedure TEditForm.Printersetup1Click(Sender: TObject); begin PrinterSetupDialog1.Execute; end; procedure TEditForm.Print1Click(Sender: TObject); begin if PrintDialog1.Execute then Editor.Print(PathName); end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DBXOdbcReadOnlyMetaData; interface uses Data.DBXCommon, Data.DBXOdbc, Data.DBXMetaDataReader, Data.DBXMetaDataCommandFactory; type TDBXOdbcMetaDataCommandFactory = class(TDBXMetaDataCommandFactory) public function CreateCommand(DbxContext: TDBXContext; Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand; override; function CreateMetaDataReader: TDBXMetaDataReader; overload; override; function CreateMetaDataReader(OdbcConnection: TDBXOdbcConnection): TDBXMetaDataReader; reintroduce; overload; end; implementation uses Data.DBXOdbcMetaDataReader; function TDBXOdbcMetaDataCommandFactory.CreateCommand(DbxContext: TDBXContext; Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand; var Reader: TDBXMetaDataReader; ProviderContext: TDBXDataExpressProviderContext; begin Reader := TDBXMetaDataReader(TDBXDriverHelp.GetMetaDataReader(Connection)); if Reader = nil then begin Reader := CreateMetaDataReader(TDBXOdbcConnection(Connection)); ProviderContext := TDBXDataExpressProviderContext.Create; ProviderContext.Connection := Connection; ProviderContext.UseAnsiStrings := TDBXProviderContext.UseAnsiString(Reader.ProductName); ProviderContext.RemoveIsNull := True; Reader.Context := ProviderContext; Reader.Version := TDBXConnection(Connection).ProductVersion; TDBXDriverHelp.SetMetaDataReader(Connection, Reader); end; Result := TDBXMetaDataCommand.Create(DBXContext, MorphicCommand, Reader); end; function TDBXOdbcMetaDataCommandFactory.CreateMetaDataReader: TDBXMetaDataReader; begin Result := TDBXOdbcMetaDataReader.Create; end; function TDBXOdbcMetaDataCommandFactory.CreateMetaDataReader(OdbcConnection: TDBXOdbcConnection): TDBXMetaDataReader; begin Result := TDBXOdbcMetaDataReader.Create(OdbcConnection); end; initialization TDBXMetaDataCommandFactory.RegisterMetaDataCommandFactory(TDBXOdbcMetaDataCommandFactory); finalization TDBXMetaDataCommandFactory.UnRegisterMetaDataCommandFactory(TDBXOdbcMetaDataCommandFactory); end.
unit uVersionCheck; interface uses ORSystem, rMisc; function IsCorrectVersion(anOption: String; bDebug: Boolean = False): Boolean; implementation uses ORNet, ORFn, Windows, VAUtils, Forms, System.SysUtils; const TX_VER1 = 'This is version '; TX_VER2 = ' of CPRSChart.exe.'; TX_VER3 = CRLF + 'The running server version is '; TX_VER_REQ = ' version server is required.'; TX_VER_OLD = CRLF + 'It is strongly recommended that you upgrade.'; TX_VER_OLD2 = CRLF + 'The program cannot be run until the client is upgraded.'; TX_VER_NEW = CRLF + 'The program cannot be run until the server is upgraded.'; TC_VER = 'Server/Client Incompatibility'; TC_CLIERR = 'Client Specifications Mismatch'; TX_CLIENT_MISMATCH = 'Server newer than Client'; function IsCorrectVersion(anOption: String; bDebug: Boolean = False): Boolean; var ClientVer, ServerVer, ServerReq: string; begin Result := bDebug; ClientVer := ClientVersion(Application.ExeName); ServerVer := ServerVersion(anOPTION, ClientVer); if (ServerVer = '0.0.0.0') then begin InfoBox('Unable to determine current version of server.', anOPTION, MB_OK); // Close; Exit; end; ServerReq := Piece(FileVersionValue(Application.ExeName, FILE_VER_INTERNALNAME), ' ', 1); if (ClientVer <> ServerReq) then begin InfoBox('Client "version" does not match client "required" server.', TC_CLIERR, MB_OK); // Close; Exit; end; if (CompareVersion(ServerVer, ServerReq) <> 0) then begin if (sCallV('ORWU DEFAULT DIVISION', [nil]) = '1') then begin if (InfoBox('Proceed with mismatched Client and Server versions?', TC_CLIERR, MB_YESNO) = ID_NO) then begin // Close; Exit; end; end else begin if (CompareVersion(ServerVer, ServerReq) > 0) then // Server newer than Required begin // NEXT LINE COMMENTED OUT - CHANGED FOR VERSION 19.16, PATCH OR*3*155: // if GetUserParam('ORWOR REQUIRE CURRENT CLIENT') = '1' then if (true) then // "True" statement guarantees "required" current version client. begin InfoBox(TX_VER1 + ClientVer + TX_VER2 + CRLF + ServerReq + TX_VER_REQ + TX_VER3 + ServerVer + '.' + TX_VER_OLD2, TC_VER, MB_OK); // Close; Exit; end; end else InfoBox(TX_VER1 + ClientVer + TX_VER2 + CRLF + ServerReq + TX_VER_REQ + TX_VER3 + ServerVer + '.' + TX_VER_OLD, TC_VER, MB_OK); end; if (CompareVersion(ServerVer, ServerReq) < 0) then // Server older then Required begin InfoBox(TX_VER1 + ClientVer + TX_VER2 + CRLF + ServerReq + TX_VER_REQ + TX_VER3 + ServerVer + '.' + TX_VER_NEW, TC_VER, MB_OK); // Close; Exit; end; end; Result := True; end; end.
unit Getter.CodesignVerifier; interface uses SysUtils, Windows, Getter.CodesignVerifier.Publisher; type TCodesignVerifier = class private type TWinTrustFileInfo = record cbStruct: DWORD; pcwszFilePath: PWideChar; hFile: THandle; pgKnownSubject: PGUID; end; TWinTrustData = record cbStruct: DWORD; pPolicyCallbackData: Pointer; pSIPClientData: Pointer; dwUIChoice: DWORD; fdwRevocationChecks: DWORD; dwUnionChoice: DWORD; pFile: Pointer; dwStateAction: DWORD; hWVTStateData: THandle; pwszURLReference: PWideChar; dwProvFlags: DWORD; dwsUIContext: DWORD; end; const WINTRUST_ACTION_GENERIC_VERIFY_V2: TGUID = '{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}'; const WTD_REVOKE_NONE = 0; WTD_REVOKE_WHOLECHAIN = 1; const WTD_UI_ALL = 1; WTD_UI_NONE = 2; WTD_UI_NOBAD = 3; WTD_UI_NOGOOD = 4; const WTD_CHOICE_FILE = 1; WTD_CHOICE_CATALOG = 2; WTD_CHOICE_BLOB = 3; WTD_CHOICE_SIGNER = 4; WTD_CHOICE_CERT = 5; private WinTrustFileInfo: TWinTrustFileInfo; WinTrustData: TWinTrustData; procedure SetWinTrustData; procedure SetWinTrustFileInfo(const PathToVerify: String); function VerifyAndReturnResult: Boolean; function IsCodeSigned(const PathToVerify: String): Boolean; function VerifyPublisher(const PathToVerify, ExpectedPublisher: string): Boolean; public function VerifySignByPublisher(const PathToVerify, ExpectedPublisher: string): Boolean; end; implementation { TCodesignVerifier } procedure TCodesignVerifier.SetWinTrustFileInfo(const PathToVerify: String); begin ZeroMemory(@WinTrustFileInfo, SizeOf(WinTrustFileInfo)); WinTrustFileInfo.cbStruct := sizeof(WinTrustFileInfo); WinTrustFileInfo.pcwszFilePath := PWideChar(WideString(PathToVerify)); end; procedure TCodesignVerifier.SetWinTrustData; begin ZeroMemory(@WinTrustData, SizeOf(WinTrustData)); WinTrustData.cbStruct := sizeof(WinTrustData); WinTrustData.dwUIChoice := WTD_UI_NONE; WinTrustData.fdwRevocationChecks := WTD_REVOKE_NONE; WinTrustData.dwUnionChoice := WTD_CHOICE_FILE; WinTrustData.pFile := @WinTrustFileInfo; end; function TCodesignVerifier.VerifyAndReturnResult: Boolean; var ErrorCode: Cardinal; begin ErrorCode := WinVerifyTrust(INVALID_HANDLE_VALUE, WINTRUST_ACTION_GENERIC_VERIFY_V2, @WinTrustData); result := ErrorCode = ERROR_SUCCESS; end; function TCodesignVerifier.VerifyPublisher(const PathToVerify, ExpectedPublisher: string): Boolean; var CodesignPublisherVerifier: TCodesignPublisherVerifier; begin CodesignPublisherVerifier := TCodesignPublisherVerifier.Create; result := CodesignPublisherVerifier.VerifySignByPublisher(PathToVerify, ExpectedPublisher); FreeAndNil(CodesignPublisherVerifier); end; function TCodesignVerifier.VerifySignByPublisher(const PathToVerify, ExpectedPublisher: string): Boolean; begin exit(true); result := IsCodeSigned(PathToVerify); if ExtractFileExt(PathToVerify) <> '.exe' then exit; if not result then exit else result := VerifyPublisher(PathToVerify, ExpectedPublisher); end; function TCodesignVerifier.IsCodeSigned(const PathToVerify: String): Boolean; begin SetWinTrustFileInfo(PathToVerify); SetWinTrustData; result := VerifyAndReturnResult; end; end.
unit test_unit2; interface const MAX_EPISODIOS_POR_TEMPORADA = 25; MAX_TEMPORADAS_POR_SERIE = 10; MAX_CANTIDAD_SERIES = 4; MAX_VISUALIZACIONES_POR_USUARIO = 100; MAX_USUARIOS = 50; CANT_TOP = 10; Type tmlogico = integer; tTitulo = string[72]; tDescripcionVideo = string[234]; tDuracionEnSegundos = longint; tVisualizaciones = longint; {Estructura de datos de las series} trVideo = record titulo : tTitulo; descripcion : tDescripcionVideo; duracionEnSegundos : tDuracionEnSegundos; visualizaciones : tVisualizaciones end; tvVideo = array[1..MAX_EPISODIOS_POR_TEMPORADA] of trVideo; tAnioDeEmision = string[4]; tCantEpiDeTemp = byte; trTemp = record anioDeEmision : tAnioDeEmision; cantEpiDeTemp : tCantEpiDeTemp; vVideo : tvVideo end; tvTemp = array[1..MAX_TEMPORADAS_POR_SERIE] of trTemp; tNombre = string[71]; tDescripcionSerie = string[140]; tCantTemp = byte; trSerie = record nombre : tNombre; descripcion : tDescripcionSerie; cantTemp : tCantTemp; vTemp : tvTemp end; tvSerie = array[1..MAX_CANTIDAD_SERIES] of trSerie; tmlvSerie = tmlogico; {Estructura de datos del usuario} tPosSerieEnvSerie = longint; tNumTempEnLaSerie = byte; tNumEpiDeLaTemp = byte; tCantVisualizaciones = byte; trVisualizacion = record posSerieEnvSerie : tPosSerieEnvSerie; numTempEnLaSerie : tNumTempEnLaSerie; numEpiDeLaTemp : tNumEpiDeLaTemp; cantVisualizaciones : tCantVisualizaciones end; tvVisualizacion = array[1..MAX_VISUALIZACIONES_POR_USUARIO] of trVisualizacion; tmlvVisualizacion = tmlogico; tNombreUsuario = string[8]; trUsuario = record nombreUsuario : tNombreUsuario; vVisualizacion : tvVisualizacion; mlvVisualizacion : tmlvVisualizacion; end; tvUsuario = array[1..MAX_USUARIOS] of trUsuario; tmlvUsuario = tmlogico; {Estructura de datos del vector auxiliar} tvTop = array[1..CANT_TOP] of trVideo; var vSerie: tvSerie; mlvSerie: tmlvSerie; vUsuario: tvUsuario; mlvUsuario: tmlvUsuario; vTop: tvTop; procedure cargarDatosSerie(var vSerie: tvSerie; var mlvSerie: tmlvSerie); implementation procedure cargarDatosSerie(var vSerie: tvSerie; var mlvSerie: tmlvSerie); {Pre: Recibe el vector Series * Post: Devuelve el vector serie con series cargadas} begin vSerie[1].nombre := 'Friends'; vSerie[1].descripcion := 'Friends fue una serie de television estadounidense creada y producida por Marta Kauffman y David Crane.'; vSerie[1].cantTemp := 3; vSerie[1].vTemp[1].anioDeEmision := '1994'; vSerie[1].vTemp[1].cantEpiDeTemp := 5; vSerie[1].vTemp[1].vVideo[1].titulo := 'En el que Monica tiene una nueva companiera'; vSerie[1].vTemp[1].vVideo[1].descripcion := 'S01E01 Friends'; vSerie[1].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[2].titulo := 'El de la ecografia al final'; vSerie[1].vTemp[1].vVideo[2].descripcion := 'S01E02 Friends'; vSerie[1].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[3].titulo := 'El del pulgar'; vSerie[1].vTemp[1].vVideo[3].descripcion := 'S01E03 Friends'; vSerie[1].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[4].titulo := 'El de George Stephanopoulos'; vSerie[1].vTemp[1].vVideo[4].descripcion := 'S01E04 Friends'; vSerie[1].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[5].titulo := 'El del detergente germano oriental extrafuerte '; vSerie[1].vTemp[1].vVideo[5].descripcion := 'S01E05 Friends'; vSerie[1].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[1].vTemp[2].anioDeEmision := '1995'; vSerie[1].vTemp[2].cantEpiDeTemp := 5; vSerie[1].vTemp[2].vVideo[1].titulo := 'El de la nueva novia de Ross'; vSerie[1].vTemp[2].vVideo[1].descripcion := 'S02E01 Friends'; vSerie[1].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[2].titulo := 'El de la leche materna '; vSerie[1].vTemp[2].vVideo[2].descripcion := 'S02E02 Friends'; vSerie[1].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[3].titulo := 'En el que Heckles muere'; vSerie[1].vTemp[2].vVideo[3].descripcion := 'S02E03 Friends'; vSerie[1].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[4].titulo := 'El del marido de Phoebe'; vSerie[1].vTemp[2].vVideo[4].descripcion := 'S02E04 Friends'; vSerie[1].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[5].titulo := 'El de los cinco filetes y la berenjena '; vSerie[1].vTemp[2].vVideo[5].descripcion := 'S02E05 Friends'; vSerie[1].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[1].vTemp[3].anioDeEmision := '1996'; vSerie[1].vTemp[3].cantEpiDeTemp := 5; vSerie[1].vTemp[3].vVideo[1].titulo := 'El de la fantasia de la princesa Leia' ; vSerie[1].vTemp[3].vVideo[1].descripcion := 'S03E01 Friends'; vSerie[1].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[2].titulo := 'En el que ninguno esta preparado'; vSerie[1].vTemp[3].vVideo[2].descripcion := 'S03E02 Friends'; vSerie[1].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[3].titulo := 'El de la mermelada'; vSerie[1].vTemp[3].vVideo[3].descripcion := 'S03E03 Friends'; vSerie[1].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[4].titulo := 'El del tunel metaforico'; vSerie[1].vTemp[3].vVideo[4].descripcion := 'S03E04 Friends'; vSerie[1].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[5].titulo := 'El de Frank Jr.'; vSerie[1].vTemp[3].vVideo[5].descripcion := 'S03E05 Friends'; vSerie[1].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[2].nombre := 'Futurama'; vSerie[2].descripcion := 'Futurama se desarrolla durante el siglo XXXI, un siglo lleno de maravillas tecnologicas'; vSerie[2].cantTemp := 3; vSerie[2].vTemp[1].anioDeEmision := '1999'; vSerie[2].vTemp[1].cantEpiDeTemp := 5; vSerie[2].vTemp[1].vVideo[1].titulo := 'Piloto espacial 3000 '; vSerie[2].vTemp[1].vVideo[1].descripcion := 'S01E01 Futurama'; vSerie[2].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[2].titulo := 'La serie ha aterrizado '; vSerie[2].vTemp[1].vVideo[2].descripcion := 'S01E02 Futurama'; vSerie[2].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[3].titulo := 'Yo, companiero de piso'; vSerie[2].vTemp[1].vVideo[3].descripcion := 'S01E03 Futurama'; vSerie[2].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[4].titulo := 'Obras de amor perdidas en el espacio'; vSerie[2].vTemp[1].vVideo[4].descripcion := 'S01E04 Futurama'; vSerie[2].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[5].titulo := 'Temor a un planeta robot '; vSerie[2].vTemp[1].vVideo[5].descripcion := 'S01E05 Futurama'; vSerie[2].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[2].vTemp[2].anioDeEmision := '1999'; vSerie[2].vTemp[2].cantEpiDeTemp := 5; vSerie[2].vTemp[2].vVideo[1].titulo := 'Yo siento esa mocion'; vSerie[2].vTemp[2].vVideo[1].descripcion := 'S02E01 Futurama'; vSerie[2].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[2].titulo := 'Brannigan, comienza de nuevo'; vSerie[2].vTemp[2].vVideo[2].descripcion := 'S02E02 Futurama'; vSerie[2].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[3].titulo := 'A la cabeza en las encuestas'; vSerie[2].vTemp[2].vVideo[3].descripcion := 'S02E03 Futurama'; vSerie[2].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[4].titulo := 'Cuento de Navidad'; vSerie[2].vTemp[2].vVideo[4].descripcion := 'S02E04 Futurama'; vSerie[2].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[5].titulo := 'Por que debo ser un crustaceo enamorado?'; vSerie[2].vTemp[2].vVideo[5].descripcion := 'S02E05 Futurama'; vSerie[2].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[2].vTemp[3].anioDeEmision := '2001'; vSerie[2].vTemp[3].cantEpiDeTemp := 5; vSerie[2].vTemp[3].vVideo[1].titulo := 'Amazonas enamoradas'; vSerie[2].vTemp[3].vVideo[1].descripcion := 'S03E01 Futurama'; vSerie[2].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[2].titulo := 'Parasitos perdidos'; vSerie[2].vTemp[3].vVideo[2].descripcion := 'S03E02 Futurama'; vSerie[2].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[3].titulo := 'Historia de dos Santa Claus'; vSerie[2].vTemp[3].vVideo[3].descripcion := 'S03E03 Futurama'; vSerie[2].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[4].titulo := 'La suerte de los Fry'; vSerie[2].vTemp[3].vVideo[4].descripcion := 'S03E04 Futurama'; vSerie[2].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[5].titulo := 'El ave robot del Helacatraz'; vSerie[2].vTemp[3].vVideo[5].descripcion := 'S03E05 Futurama'; vSerie[2].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[3].nombre := 'Game of Thrones'; vSerie[3].descripcion := 'Esta basada en la serie de novelas Cancion de Hielo y Fuego del escritor George R. R. Martin.'; vSerie[3].cantTemp := 3; vSerie[3].vTemp[1].anioDeEmision := '2011'; vSerie[3].vTemp[1].cantEpiDeTemp := 5; vSerie[3].vTemp[1].vVideo[1].titulo := 'Se acerca el invierno'; vSerie[3].vTemp[1].vVideo[1].descripcion := 'S01E01 Game of Thrones'; vSerie[3].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[2].titulo := 'El camino real'; vSerie[3].vTemp[1].vVideo[2].descripcion := 'S01E02 Game of Thrones'; vSerie[3].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[3].titulo := 'Lord Nieve'; vSerie[3].vTemp[1].vVideo[3].descripcion := 'S01E03 Game of Thrones'; vSerie[3].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[4].titulo := 'Tullidos, bastardos y cosas rotas'; vSerie[3].vTemp[1].vVideo[4].descripcion := 'S01E04 Game of Thrones'; vSerie[3].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[5].titulo := 'El lobo y el leon'; vSerie[3].vTemp[1].vVideo[5].descripcion := 'S01E05 Game of Thrones'; vSerie[3].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[3].vTemp[2].anioDeEmision := '2012'; vSerie[3].vTemp[2].cantEpiDeTemp := 5; vSerie[3].vTemp[2].vVideo[1].titulo := 'El Norte no olvida'; vSerie[3].vTemp[2].vVideo[1].descripcion := 'S02E01 Game of Thrones'; vSerie[3].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[2].titulo := 'Las tierras de la noche'; vSerie[3].vTemp[2].vVideo[2].descripcion := 'S02E02 Game of Thrones'; vSerie[3].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[3].titulo := 'Lo que esta muerto no puede morir'; vSerie[3].vTemp[2].vVideo[3].descripcion := 'S02E03 Game of Thrones'; vSerie[3].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[4].titulo := 'Jardin de Huesos'; vSerie[3].vTemp[2].vVideo[4].descripcion := 'S02E04 Game of Thrones'; vSerie[3].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[5].titulo := 'El Fantasma de Harrenhal'; vSerie[3].vTemp[2].vVideo[5].descripcion := 'S02E05 Game of Thrones'; vSerie[3].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[3].vTemp[3].anioDeEmision := '2013'; vSerie[3].vTemp[3].cantEpiDeTemp := 5; vSerie[3].vTemp[3].vVideo[1].titulo := 'Valar Dohaeris'; vSerie[3].vTemp[3].vVideo[1].descripcion := 'S03E01 Game of Thrones'; vSerie[3].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[2].titulo := 'Alas negras, palabras negras'; vSerie[3].vTemp[3].vVideo[2].descripcion := 'S03E02 Game of Thrones'; vSerie[3].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[3].titulo := 'El Camino del Castigo'; vSerie[3].vTemp[3].vVideo[3].descripcion := 'S03E03 Game of Thrones'; vSerie[3].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[4].titulo := 'Y ahora su guardia ha terminado'; vSerie[3].vTemp[3].vVideo[4].descripcion := 'S03E04 Game of Thrones'; vSerie[3].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[5].titulo := 'Besado por el fuego'; vSerie[3].vTemp[3].vVideo[5].descripcion := 'S03E05 Game of Thrones'; vSerie[3].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[4].nombre := 'Los Simuladores'; vSerie[4].descripcion := 'Serie argentina acerca de un grupo de cuatro socios.'; vSerie[4].cantTemp := 2; vSerie[4].vTemp[1].anioDeEmision := '2002'; vSerie[4].vTemp[1].cantEpiDeTemp := 5; vSerie[4].vTemp[1].vVideo[1].titulo := 'Tarjeta de navidad'; vSerie[4].vTemp[1].vVideo[1].descripcion := 'S01E01 Los Simuladores'; vSerie[4].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[2].titulo := 'Diagnostico rectoscopico'; vSerie[4].vTemp[1].vVideo[2].descripcion := 'S01E02 Los Simuladores'; vSerie[4].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[3].titulo := 'Seguro de desempleo'; vSerie[4].vTemp[1].vVideo[3].descripcion := 'S01E03 Los Simuladores'; vSerie[4].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[4].titulo := 'El testigo espaniol'; vSerie[4].vTemp[1].vVideo[4].descripcion := 'S01E04 Los Simuladores'; vSerie[4].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[5].titulo := 'El joven simulador'; vSerie[4].vTemp[1].vVideo[5].descripcion := 'S01E05 Los Simuladores'; vSerie[4].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[4].vTemp[2].anioDeEmision := '2003'; vSerie[4].vTemp[2].cantEpiDeTemp := 5; vSerie[4].vTemp[2].vVideo[1].titulo := 'Los cuatro notables'; vSerie[4].vTemp[2].vVideo[1].descripcion := 'S02E01 Los Simuladores'; vSerie[4].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[2].titulo := 'Z-9000'; vSerie[4].vTemp[2].vVideo[2].descripcion := 'S02E02 Los Simuladores'; vSerie[4].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[3].titulo := 'La gargantilla de las cuatro estaciones'; vSerie[4].vTemp[2].vVideo[3].descripcion := 'S02E03 Los Simuladores'; vSerie[4].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[4].titulo := 'El Clan Motul'; vSerie[4].vTemp[2].vVideo[4].descripcion := 'S02E04 Los Simuladores'; vSerie[4].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[5].titulo := 'El vengador infantil'; vSerie[4].vTemp[2].vVideo[5].descripcion := 'S01E05 Los Simuladores'; vSerie[4].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[5].visualizaciones := 0; mlvSerie := 4; end; begin end.
// // Created by the DataSnap proxy generator. // unit UDBAccess; interface uses DBXCommon, DBXJSON, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, DBClient, Variants; type TDBAccess = class(TComponent) private FConnection: TDBXConnection; FErrorCode: Integer; FErrorText: string; function CreateCommand(Text: string): TDBXCommand; public // 对象创建及释放 constructor Create(AOwner: TComponent); override; destructor Destroy; override; function EchoString(Value: string): string; // 获取错误信息 function GetLastError: string; function GetLastErrorCode: Integer; // 获取服务器信息函数 function GetServerDateTime(var Value: TDateTime): Boolean; procedure GetServerLastError(var ErrorCode: Integer; var ErrorText: string); // 数据操作(DML)语句 function ReadDataSet(AStrSql: string; Cds: TClientDataSet): Boolean; function ReadMultipleDataSets(ASqlList: TStrings; CdsArr: array of TClientDataSet): Boolean; function ReadTableHead(TableName: string; var Data: OleVariant): Boolean; function QueryData(AStrSql: string; APageSize, APageNo: Integer; Cds: TClientDataSet): Boolean; function GetSQLStringValue(AStrSql: string): string; function GetSQLIntegerValue(AStrSql: string): Integer; function DataSetIsEmpty(AStrSql: string): Integer; function ApplyUpdates(TableName: string; Delta: OleVariant; var ErrorCount: Integer): Boolean; overload; function ApplyUpdates(TableName: string; Delta: OleVariant): Boolean; overload; function ApplyUpdates(TableName: string; Cds: TClientDataSet): Boolean; overload; function ExecuteSQL(AStrSql: string): Boolean; function ExecuteBatchSQL(AList: TStrings): Boolean; function ParamsMethod(InParams: TParams; var OutParams: TParams): Boolean; overload; function ParamsMethod(InParams: TParams): Boolean; overload; published property Connection: TDBXConnection read FConnection write FConnection; end; var DBAccess: TDBAccess; implementation uses UErrorConst; constructor TDBAccess.Create(AOwner: TComponent); begin inherited Create(AOwner); end; function TDBAccess.CreateCommand(Text: string): TDBXCommand; begin Result := FConnection.CreateCommand; Result.CommandType := TDBXCommandTypes.DSServerMethod; Result.Text := Text; Result.Prepare; end; function TDBAccess.EchoString(Value: string): string; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.EchoString'); try lCommand.Parameters[0].Value.SetWideString(Value); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetWideString; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetLastError: string; begin Result := FErrorText; FErrorText := ''; end; procedure TDBAccess.GetServerLastError(var ErrorCode: Integer; var ErrorText: string); var lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.GetServerLastError'); try lCommand.Parameters[0].Value.SetInt32(ErrorCode); lCommand.Parameters[1].Value.SetWideString(ErrorText); lCommand.ExecuteUpdate; ErrorCode := lCommand.Parameters[0].Value.GetInt32; ErrorText := lCommand.Parameters[1].Value.GetWideString; finally FreeAndNil(lCommand); end; except on E: Exception do begin FErrorCode := ERRCODE_CLIENT_GetServerLastError; FErrorText := E.Message; end; end; end; function TDBAccess.GetLastErrorCode: Integer; begin Result := FErrorCode; FErrorCode := ERRCODE_CLIENT; end; function TDBAccess.ReadDataSet(AStrSql: string; Cds: TClientDataSet): Boolean; var lData: OleVariant; lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.ReadDataSet'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.AsVariant := lData; lCommand.ExecuteUpdate; Result := lCommand.Parameters[2].Value.AsBoolean; if Result then begin lData := lCommand.Parameters[1].Value.AsVariant; Cds.Data := lData; end; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ReadDataSet; FErrorText := E.Message; end; 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; function TDBAccess.ReadMultipleDataSets(ASqlList: TStrings; CdsArr: array of TClientDataSet): Boolean; var lData: OleVariant; lCommand: TDBXCommand; I: Integer; begin try Result := False; if ASqlList.Count = 0 then Exit; if ASqlList.Count <> (Length(CdsArr)) then Exit; lCommand := CreateCommand('TServerMethods.ReadMultipleDataSets'); try lCommand.Parameters[0].Value.AsVariant := VarArrayFromStrings(ASqlList); lCommand.Parameters[1].Value.AsVariant := lData; lCommand.ExecuteUpdate; Result := lCommand.Parameters[2].Value.AsBoolean; if Result then begin lData := lCommand.Parameters[1].Value.AsVariant; if VarIsEmpty(lData) or (not VarIsArray(lData)) then begin Result := False; Exit; end; for I := VarArrayLowBound(lData, 1) to VarArrayHighBound(lData, 1) do CdsArr[I].Data := lData[I]; end; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ReadMultipleDataSets; FErrorText := E.Message; end; end; end; function TDBAccess.ReadTableHead(TableName: string; var Data: OleVariant): Boolean; var lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.ReadTableHead'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Data; lCommand.ExecuteUpdate; Result := lCommand.Parameters[2].Value.AsBoolean; if Result then Data := lCommand.Parameters[1].Value.AsVariant; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ReadTableHead; FErrorText := E.Message; end; end; end; function TDBAccess.ApplyUpdates(TableName: string; Delta: OleVariant; var ErrorCount: Integer): Boolean; var lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.ApplyUpdates'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Delta; lCommand.Parameters[2].Value.SetInt32(ErrorCount); lCommand.ExecuteUpdate; ErrorCount := lCommand.Parameters[2].Value.AsInt32; Result := lCommand.Parameters[3].Value.AsBoolean; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ApplyUpdates; FErrorText := E.Message; end; end; end; function TDBAccess.ApplyUpdates(TableName: string; Delta: OleVariant): Boolean; var lErrCount: Integer; lCommand: TDBXCommand; begin if VarIsNull(Delta) then begin Result := True; Exit; end; try lCommand := CreateCommand('TServerMethods.ApplyUpdates'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Delta; lErrCount := 0; lCommand.Parameters[2].Value.SetInt32(lErrCount); lCommand.ExecuteUpdate; //lErrCount := lCommand.Parameters[2].Value.GetInt32; Result := lCommand.Parameters[3].Value.AsBoolean; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ApplyUpdates; FErrorText := E.Message; end; end; end; function TDBAccess.ApplyUpdates(TableName: string; Cds: TClientDataSet): Boolean; var lErrCount: Integer; lCommand: TDBXCommand; begin try if Cds.State in [dsInsert, dsEdit] then Cds.Post; if Cds.ChangeCount = 0 then begin Result := True; Exit; end; lCommand := CreateCommand('TServerMethods.ApplyUpdates'); try lCommand.Parameters[0].Value.SetWideString(TableName); lCommand.Parameters[1].Value.AsVariant := Cds.Delta; lErrCount := 0; lCommand.Parameters[2].Value.SetInt32(lErrCount); lCommand.ExecuteUpdate; //lErrCount := lCommand.Parameters[2].Value.GetInt32; Result := lCommand.Parameters[3].Value.AsBoolean; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ApplyUpdates; FErrorText := E.Message; end; end; end; function TDBAccess.DataSetIsEmpty(AStrSql: string): Integer; var lCommand: TDBXCommand; begin lCommand := CreateCommand('TServerMethods.DataSetIsEmpty'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetInt32; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetServerDateTime(var Value: TDateTime): Boolean; var lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.GetServerDateTime'); try lCommand.Parameters[0].Value.AsDateTime := Value; lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.AsBoolean; if Result then Value := lCommand.Parameters[0].Value.AsDateTime; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_GetServerDateTime; FErrorText := E.Message; end; end; end; function TDBAccess.GetSQLStringValue(AStrSql: string): string; var lCommand: TDBXCommand; lValue: string; begin lCommand := CreateCommand('TServerMethods.GetSQLStringValue'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.SetWideString(lValue); lCommand.ExecuteUpdate; if lCommand.Parameters[2].Value.AsBoolean then Result := lCommand.Parameters[1].Value.GetWideString else Result := ''; finally FreeAndNil(lCommand); end; end; function TDBAccess.QueryData(AStrSql: string; APageSize, APageNo: Integer; Cds: TClientDataSet): Boolean; var lCommand: TDBXCommand; lData: OleVariant; begin lCommand := CreateCommand('TServerMethods.QueryData'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.Parameters[1].Value.AsInt32 := APageSize; lCommand.Parameters[2].Value.AsInt32 := APageNo; lCommand.Parameters[3].Value.AsVariant := lData; lCommand.ExecuteUpdate; Result := lCommand.Parameters[4].Value.AsBoolean; if Result then begin lData := lCommand.Parameters[3].Value.AsVariant; Cds.Data := lData; end; finally FreeAndNil(lCommand); end; end; function TDBAccess.GetSQLIntegerValue(AStrSql: string): Integer; var lCommand: TDBXCommand; Value: Integer; begin lCommand := CreateCommand('TServerMethods.GetSQLIntegerValue'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); Value := -1; lCommand.Parameters[1].Value.SetInt32(Value); lCommand.ExecuteUpdate; if lCommand.Parameters[2].Value.AsBoolean then Result := lCommand.Parameters[1].Value.AsInt32 else Result := -1; finally FreeAndNil(lCommand); end; end; function TDBAccess.ExecuteBatchSQL(AList: TStrings): Boolean; var lCommand: TDBXCommand; lStream: TMemoryStream; begin try lCommand := CreateCommand('TServerMethods.ExecuteBatchSQL'); lStream := TMemoryStream.Create; try AList.SaveToStream(lStream); lStream.Position := 0; lCommand.Parameters[0].Value.SetStream(lStream, False); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetBoolean; finally lStream.Free; FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ExecuteBatchSQL; FErrorText := E.Message; end; end; end; function TDBAccess.ExecuteSQL(AStrSql: string): Boolean; var lCommand: TDBXCommand; begin try lCommand := CreateCommand('TServerMethods.ExecuteSQL'); try lCommand.Parameters[0].Value.SetWideString(AStrSql); lCommand.ExecuteUpdate; Result := lCommand.Parameters[1].Value.GetBoolean; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ExecuteSQL; FErrorText := E.Message; end; end; end; destructor TDBAccess.Destroy; begin inherited; end; function TDBAccess.ParamsMethod(InParams: TParams; var OutParams: TParams): Boolean; var lCommand: TDBXCommand; lStream: TStream; begin try lCommand := CreateCommand('TServerMethods.ParamsMethod'); try lCommand.Parameters[0].Value.SetDBXReader(TDBXParamsReader.Create(InParams, False), True); lCommand.Parameters[1].Value.SetDBXReader(TDBXParamsReader.Create(OutParams, False), True); lCommand.ExecuteUpdate; OutParams := TDBXParamsReader.ToParams(nil, lCommand.Parameters[1].Value.GetDBXReader(False), True); Result := True; finally FreeAndNil(lCommand); end; except on E: Exception do begin Result := False; FErrorCode := ERRCODE_CLIENT_ExecuteSQL; FErrorText := E.Message; end; end; end; function TDBAccess.ParamsMethod(InParams: TParams): Boolean; var OutParams: TParams; begin Result := False; OutParams := TParams.Create(nil); try if not ParamsMethod(InParams, OutParams) then Exit; Result := OutParams.ParamByName('Result').AsBoolean; if not Result then begin FErrorText := OutParams.ParamByName('ErrorText').AsString; FErrorCode := OutParams.ParamByName('ErrorCode').AsInteger; end; finally OutParams.Free; end; end; end.
unit UDBShortNavigator; // UDBShortNavigator.pas - Toggles between short list of buttons // and long list // Copyright (c) 2000. All Rights Reserved. // by Software Conceptions, Inc. Okemos, MI USA (800) 471-5890 // Written by Paul Kimmel interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, DBCtrls; type TNavigatorButtonSet = ( nbsFull, nbsPartial ); TDBShortNavigator = class(TDBNavigator) private { Private declarations } FButtonSet : TNavigatorButtonSet; procedure SetButtonSet(const Value: TNavigatorButtonSet); protected { Protected declarations } public { Public declarations } published { Published declarations } property ButtonSet : TNavigatorButtonSet read FButtonSet write SetButtonSet; end; procedure Register; implementation procedure Register; begin RegisterComponents('PKTools', [TDBShortNavigator]); end; { TDBShortNavigator } procedure TDBShortNavigator.SetButtonSet(const Value: TNavigatorButtonSet); const FULL_SET = [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh]; PARTIAL_SET = [nbFirst, nbPrior, nbNext, nbLast]; SETS : array[TNavigatorButtonSet] of TButtonSet = (FULL_SET, PARTIAL_SET); begin if( FButtonSet = Value ) then exit; FButtonSet := Value; VisibleButtons := SETS[FButtonSet]; end; end.
unit MenuPizzaria; interface uses System.SysUtils, ItensDoMenu, IteratorMenu; type TMenuPizzaria = class private ListaMenu: ListaDeMenus; Posicao: Integer; public constructor Create; procedure AdicionarItem(Nome: string; Descricao: string; Preco: currency; Vegano: boolean); function CriarIterator: TMenuIterator; end; implementation { TMenuPizzaria } procedure TMenuPizzaria.AdicionarItem(Nome, Descricao: string; Preco: currency; Vegano: boolean); var NovoItemDoMenu: TItensMenu; begin NovoItemDoMenu := TItensMenu.Create(Nome, Descricao, Preco, Vegano); ListaMenu := ListaMenu + [NovoItemDoMenu]; Posicao := Posicao + 1; end; constructor TMenuPizzaria.Create; begin Posicao := 0; AdicionarItem('Pizza De Frango', 'Vem Com Frango', 18.50, False); AdicionarItem('Pizza De Mussarela', 'Vem Com Queijo', 20.00, False); AdicionarItem('Pizza De Mato', 'Vem Com Mato', 15.50, True); end; function TMenuPizzaria.CriarIterator: TMenuIterator; var Iterator: TMenuIterator; begin Iterator := TMenuIterator.Create(ListaMenu); Result := Iterator; end; end.
unit UAccounts; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} { Copyright (c) 2016 by Albert Molina Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of Pascal Coin, a P2P crypto currency without need of historical operations. If you like it, consider a donation using BitCoin: 16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk } interface uses Classes, UConst, UCrypto, SyncObjs, UThread, UBaseTypes, UCommon; {$I config.inc} Type TAccountKey = TECDSA_Public; PAccountKey = ^TAccountKey; TAccountState = (as_Unknown, as_Normal, as_ForSale); TAccountInfo = Record state: TAccountState; accountKey: TAccountKey; // Trade info, only when state=as_ForSale locked_until_block: Cardinal; // 0 = Not locked price: UInt64; // 0 = invalid price account_to_pay: Cardinal; // <> itself new_publicKey: TAccountKey; end; TOperationBlock = Record block: Cardinal; account_key: TAccountKey; reward: UInt64; fee: UInt64; protocol_version: Word; // Protocol version protocol_available: Word; // Used to upgrade protocol timestamp: Cardinal; // Timestamp creation compact_target: Cardinal; // Target in compact form nonce: Cardinal; // Random value to generate a new P-o-W block_payload: TRawBytes; // RAW Payload that a miner can include to a blockchain initial_safe_box_hash: TRawBytes; // RAW Safe Box Hash value (32 bytes, it's a Sha256) operations_hash: TRawBytes; // RAW sha256 (32 bytes) of Operations proof_of_work: TRawBytes; // RAW Double Sha256 end; { TPascalCoinProtocol } TPascalCoinProtocol = Class public Class Function GetRewardForNewLine(line_index: Cardinal): UInt64; Class Function TargetToCompact(target: TRawBytes): Cardinal; Class Function TargetFromCompact(encoded: Cardinal): TRawBytes; Class Function GetNewTarget(vteorical, vreal: Cardinal; Const actualTarget: TRawBytes): TRawBytes; Class Procedure CalcProofOfWork_Part1(const operationBlock: TOperationBlock; var Part1: TRawBytes); Class Procedure CalcProofOfWork_Part3(const operationBlock: TOperationBlock; var Part3: TRawBytes); Class Procedure CalcProofOfWork(const operationBlock: TOperationBlock; var PoW: TRawBytes); end; { TAccountComp } TAccountComp = Class private public Class Function IsValidAccountKey(const account: TAccountKey; var errors: AnsiString): Boolean; Class Function IsValidAccountInfo(const accountInfo: TAccountInfo; var errors: AnsiString): Boolean; Class Function IsAccountForSale(const accountInfo: TAccountInfo): Boolean; Class Function IsAccountForSaleAcceptingTransactions(const accountInfo: TAccountInfo): Boolean; Class Function GetECInfoTxt(Const EC_OpenSSL_NID: Word): AnsiString; Class Procedure ValidsEC_OpenSSL_NID(list: TList); Class Function AccountKey2RawString(const account: TAccountKey): TRawBytes; overload; Class procedure AccountKey2RawString(const account: TAccountKey; var dest: TRawBytes); overload; Class Function RawString2Accountkey(const rawaccstr: TRawBytes): TAccountKey; overload; Class procedure RawString2Accountkey(const rawaccstr: TRawBytes; var dest: TAccountKey); overload; Class Function PrivateToAccountkey(key: TECPrivateKey): TAccountKey; Class Function IsAccountBlockedByProtocol(account_number, blocks_count: Cardinal): Boolean; Class Function EqualAccountInfos(const accountInfo1, accountInfo2: TAccountInfo): Boolean; Class Function EqualAccountKeys(const account1, account2: TAccountKey): Boolean; Class Function AccountNumberToAccountTxtNumber(account_number: Cardinal): AnsiString; Class function AccountTxtNumberToAccountNumber(Const account_txt_number: AnsiString; var account_number: Cardinal): Boolean; Class function FormatMoney(Money: Int64): AnsiString; Class Function TxtToMoney(Const moneytxt: AnsiString; var Money: Int64): Boolean; Class Function AccountKeyFromImport(Const HumanReadable: AnsiString; var account: TAccountKey; var errors: AnsiString): Boolean; Class Function AccountPublicKeyExport(Const account: TAccountKey): AnsiString; Class Function AccountPublicKeyImport(Const HumanReadable: AnsiString; var account: TAccountKey; var errors: AnsiString): Boolean; Class Function AccountBlock(Const account_number: Cardinal): Cardinal; Class Function AccountInfo2RawString(const accountInfo: TAccountInfo): TRawBytes; overload; Class procedure AccountInfo2RawString(const accountInfo: TAccountInfo; var dest: TRawBytes); overload; Class Function RawString2AccountInfo(const rawaccstr: TRawBytes): TAccountInfo; overload; Class procedure RawString2AccountInfo(const rawaccstr: TRawBytes; var dest: TAccountInfo); overload; Class Function IsAccountLocked(const accountInfo: TAccountInfo; blocks_count: Cardinal): Boolean; Class procedure SaveTOperationBlockToStream(const stream: TStream; const operationBlock: TOperationBlock); Class Function LoadTOperationBlockFromStream(const stream: TStream; var operationBlock: TOperationBlock): Boolean; End; TAccount = Record account: Cardinal; // FIXED value. Account number accountInfo: TAccountInfo; balance: UInt64; // Balance, always >= 0 updated_block: Cardinal; // Number of block where was updated n_operation: Cardinal; // count number of owner operations (when receive, this is not updated) name: TRawBytes; // Protocol 2. Unique name account_type: Word; // Protocol 2. Layer 2 use case previous_updated_block: Cardinal; // New Build 1.0.8 -> Only used to store this info to storage. It helps App to search when an account was updated. NOT USED FOR HASH CALCULATIONS! End; PAccount = ^TAccount; { Protocol 2: Introducing OperationBlock info on the safebox, this will allow checkpointing a safebox because each row of the safebox (TBlockAccount) will have data about how to calculate its PoW, so next row will use row-1 info to check it's good generated thanks to PoW This solution does not include operations, but include operations_hash value, that is a SHA256 of operations. If someone wants to change the safebox and spam, will need to find values to alter safebox accounts of last checkpoint and also find new blocks prior to honest nodes, that will be only accepted by nodes that does not have last blocks (only fresh nodes). This is a very hard job and not efficient because usually there will be few new fresh nodes per period, so only can spam new fresh nodes because old nodes does not need to download a checkpointing. This solution was created by Herman Schoenfeld (Thanks!) } TBlockAccount = Record blockchainInfo: TOperationBlock; accounts: Array [0 .. CT_AccountsPerBlock - 1] of TAccount; block_hash: AnsiString; // Calculated on every block change (on create and on accounts updated) accumulatedWork: UInt64; // Accumulated work (previous + target) this value can be calculated. end; TCardinalsArray = Array of Cardinal; { Estimated TAccount size: 4 + 200 (max aprox) + 8 + 4 + 4 = 220 max aprox Estimated TBlockAccount size: 4 + (5 * 220) + 4 + 32 = 1140 max aprox } TOrderedCardinalList = Class private FOrderedList: TList; FDisabledsCount: Integer; FModifiedWhileDisabled: Boolean; FOnListChanged: TNotifyEvent; Procedure NotifyChanged; public Constructor Create; Destructor Destroy; override; Function Add(Value: Cardinal): Integer; Procedure Remove(Value: Cardinal); Procedure Clear; Function Get(index: Integer): Cardinal; Function Count: Integer; Function Find(const Value: Cardinal; var index: Integer): Boolean; Procedure Disable; Procedure Enable; Property OnListChanged: TNotifyEvent read FOnListChanged write FOnListChanged; Procedure CopyFrom(Sender: TOrderedCardinalList); Function ToArray: TCardinalsArray; End; TPCSafeBox = Class; TPCSafeBoxHeader = Record protocol: Word; startBlock, endBlock, blocksCount: Cardinal; safeBoxHash: TRawBytes; end; // This is a class to quickly find accountkeys and their respective account number/s TOrderedAccountKeysList = Class Private FAutoAddAll: Boolean; FAccountList: TPCSafeBox; FOrderedAccountKeysList: TList; // An ordered list of pointers to quickly find account keys in account list Function Find(Const accountKey: TAccountKey; var index: Integer): Boolean; function GetAccountKeyList(index: Integer): TOrderedCardinalList; function GetAccountKey(index: Integer): TAccountKey; protected Procedure ClearAccounts(RemoveAccountList: Boolean); public Constructor Create(AccountList: TPCSafeBox; AutoAddAll: Boolean); Destructor Destroy; override; Procedure AddAccountKey(Const accountKey: TAccountKey); Procedure RemoveAccountKey(Const accountKey: TAccountKey); Procedure AddAccounts(Const accountKey: TAccountKey; const accounts: Array of Cardinal); Procedure RemoveAccounts(Const accountKey: TAccountKey; const accounts: Array of Cardinal); Function IndexOfAccountKey(Const accountKey: TAccountKey): Integer; Property AccountKeyList[index: Integer]: TOrderedCardinalList read GetAccountKeyList; Property accountKey[index: Integer]: TAccountKey read GetAccountKey; Function Count: Integer; Property SafeBox: TPCSafeBox read FAccountList; Procedure Clear; End; // Maintains a TRawBytes (AnsiString) list ordered to quick search withoud duplicates TOrderedRawList = Class private FList: TList; Function Find(const RawData: TRawBytes; var index: Integer): Boolean; public Constructor Create; Destructor Destroy; Override; Procedure Clear; Function Add(Const RawData: TRawBytes; tagValue: Integer = 0): Integer; Function Count: Integer; Function Get(index: Integer): TRawBytes; Procedure Delete(index: Integer); procedure SetTag(Const RawData: TRawBytes; newTagValue: Integer); function GetTag(Const RawData: TRawBytes): Integer; overload; function GetTag(index: Integer): Integer; overload; Function IndexOf(Const RawData: TRawBytes): Integer; End; // SafeBox is a box that only can be updated using SafeBoxTransaction, and this // happens only when a new BlockChain is included. After this, a new "SafeBoxHash" // is created, so each SafeBox has a unique SafeBoxHash { TPCSafeBox } TPCSafeBox = Class private FBlockAccountsList: TList; FListOfOrderedAccountKeysList: TList; FBufferBlocksHash: TRawBytes; FOrderedByName: TOrderedRawList; FTotalBalance: Int64; FTotalFee: Int64; FSafeBoxHash: TRawBytes; FLock: TPCCriticalSection; // Thread safe FWorkSum: UInt64; FCurrentProtocol: Integer; Procedure SetAccount(account_number: Cardinal; const newAccountInfo: TAccountInfo; const newName: TRawBytes; newType: Word; newBalance: UInt64; newN_operation: Cardinal); Procedure AccountKeyListAddAccounts(Const accountKey: TAccountKey; const accounts: Array of Cardinal); Procedure AccountKeyListRemoveAccount(Const accountKey: TAccountKey; const accounts: Array of Cardinal); protected Function AddNew(Const blockChain: TOperationBlock): TBlockAccount; function DoUpgradeToProtocol2: Boolean; public Constructor Create; Destructor Destroy; override; function AccountsCount: Integer; Function blocksCount: Integer; Procedure CopyFrom(accounts: TPCSafeBox); Class Function CalcBlockHash(const block: TBlockAccount; useProtocol2Method: Boolean): TRawBytes; Class Function BlockAccountToText(Const block: TBlockAccount): AnsiString; Function LoadSafeBoxFromStream(stream: TStream; checkAll: Boolean; var LastReadBlock: TBlockAccount; var errors: AnsiString): Boolean; Class Function LoadSafeBoxStreamHeader(stream: TStream; var sbHeader: TPCSafeBoxHeader): Boolean; Class Function SaveSafeBoxStreamHeader(stream: TStream; protocol: Word; OffsetStartBlock, OffsetEndBlock, CurrentSafeBoxBlocksCount: Cardinal): Boolean; Class Function MustSafeBoxBeSaved(blocksCount: Cardinal): Boolean; Procedure SaveSafeBoxBlockToAStream(stream: TStream; nBlock: Cardinal); Procedure SaveSafeBoxToAStream(stream: TStream; FromBlock, ToBlock: Cardinal); class Function CopySafeBoxStream(Source, dest: TStream; FromBlock, ToBlock: Cardinal; var errors: AnsiString): Boolean; class Function ConcatSafeBoxStream(Source1, Source2, dest: TStream; var errors: AnsiString): Boolean; class function ValidAccountName(const new_name: TRawBytes; var errors: AnsiString): Boolean; Function IsValidNewOperationsBlock(Const newOperationBlock: TOperationBlock; checkSafeBoxHash: Boolean; var errors: AnsiString): Boolean; Function GetActualTargetHash(UseProtocolV2: Boolean): TRawBytes; Function GetActualCompactTargetHash(UseProtocolV2: Boolean): Cardinal; Function FindAccountByName(aName: AnsiString): Integer; Procedure Clear; Function account(account_number: Cardinal): TAccount; Function block(block_number: Cardinal): TBlockAccount; Function CalcSafeBoxHash: TRawBytes; Function CalcBlockHashRateInKhs(block_number: Cardinal; Previous_blocks_average: Cardinal): Int64; Property TotalBalance: Int64 read FTotalBalance; Procedure StartThreadSafe; Procedure EndThreadSave; Property safeBoxHash: TRawBytes read FSafeBoxHash; Property WorkSum: UInt64 read FWorkSum; Property CurrentProtocol: Integer read FCurrentProtocol; function CanUpgradeToProtocol2: Boolean; procedure CheckMemory; End; TOrderedAccountList = Class private FList: TList; Function Find(const account_number: Cardinal; var index: Integer): Boolean; public Constructor Create; Destructor Destroy; Override; Procedure Clear; Function Add(Const account: TAccount): Integer; Function Count: Integer; Function Get(index: Integer): TAccount; End; { TPCSafeBoxTransaction } TPCSafeBoxTransaction = Class private FOrderedList: TOrderedAccountList; FFreezedAccounts: TPCSafeBox; FTotalBalance: Int64; FTotalFee: Int64; FOldSafeBoxHash: TRawBytes; FAccountNames_Deleted: TOrderedRawList; FAccountNames_Added: TOrderedRawList; Function GetInternalAccount(account_number: Cardinal): PAccount; protected public Constructor Create(SafeBox: TPCSafeBox); Destructor Destroy; override; Function TransferAmount(Sender, target: Cardinal; n_operation: Cardinal; amount, fee: UInt64; var errors: AnsiString): Boolean; Function UpdateAccountInfo(signer_account, signer_n_operation, target_account: Cardinal; accountInfo: TAccountInfo; newName: TRawBytes; newType: Word; fee: UInt64; var errors: AnsiString): Boolean; Function BuyAccount(buyer, account_to_buy, seller: Cardinal; n_operation: Cardinal; amount, account_price, fee: UInt64; const new_account_key: TAccountKey; var errors: AnsiString): Boolean; Function Commit(Const operationBlock: TOperationBlock; var errors: AnsiString): Boolean; Function account(account_number: Cardinal): TAccount; Procedure Rollback; Function CheckIntegrity: Boolean; Property FreezedSafeBox: TPCSafeBox read FFreezedAccounts; Property TotalFee: Int64 read FTotalFee; Property TotalBalance: Int64 read FTotalBalance; Procedure CopyFrom(transaction: TPCSafeBoxTransaction); Procedure CleanTransaction; Function ModifiedCount: Integer; Function Modified(index: Integer): TAccount; End; TStreamOp = Class public class Function WriteAnsiString(stream: TStream; const Value: AnsiString): Integer; overload; class Function ReadAnsiString(stream: TStream; var Value: AnsiString): Integer; overload; class Function WriteAccountKey(stream: TStream; const Value: TAccountKey): Integer; class Function ReadAccountKey(stream: TStream; var Value: TAccountKey): Integer; End; Const CT_OperationBlock_NUL: TOperationBlock = (block: 0; account_key: (EC_OpenSSL_NID: 0; x: ''; y: ''); reward: 0; fee: 0; protocol_version: 0; protocol_available: 0; timestamp: 0; compact_target: 0; nonce: 0; block_payload: ''; operations_hash: ''; proof_of_work: ''); CT_AccountInfo_NUL: TAccountInfo = (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); CT_Account_NUL: TAccount = (account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0); CT_BlockAccount_NUL: TBlockAccount = (blockchainInfo: (block: 0; account_key: (EC_OpenSSL_NID: 0; x: ''; y: ''); reward: 0; fee: 0; protocol_version: 0; protocol_available: 0; timestamp: 0; compact_target: 0; nonce: 0; block_payload: ''; operations_hash: ''; proof_of_work: ''); accounts: ((account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0), (account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0), (account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0), (account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0), (account: 0; accountInfo: (state: as_Unknown; accountKey: (EC_OpenSSL_NID: 0; x: ''; y: ''); locked_until_block: 0; price: 0; account_to_pay: 0; new_publicKey: (EC_OpenSSL_NID: 0; x: ''; y: '')); balance: 0; updated_block: 0; n_operation: 0; name: ''; account_type: 0; previous_updated_block: 0)); block_hash: ''; accumulatedWork: 0); CT_SafeBoxChunkIdentificator = 'SafeBoxChunk'; CT_PCSafeBoxHeader_NUL: TPCSafeBoxHeader = (protocol: 0; startBlock: 0; endBlock: 0; blocksCount: 0; safeBoxHash: ''); implementation uses SysUtils, ULog, UOpenSSLdef, UOpenSSL; { TPascalCoinProtocol } class function TPascalCoinProtocol.GetNewTarget(vteorical, vreal: Cardinal; Const actualTarget: TRawBytes): TRawBytes; Var bnact, bnaux, bnmindiff, bnremainder, bn: TBigNum; ts1, ts2: Cardinal; tsTeorical, tsReal, factor1000, factor1000Min, factor1000Max: Int64; begin { Given a teorical time in seconds (vteorical>0) and a real time in seconds (vreal>0) and an actual target, calculates a new target by % of difference of teorical vs real. Increment/decrement is adjusted to +-200% in a full CT_CalcNewTargetBlocksAverage round ...so each new target is a maximum +-(100% DIV (CT_CalcNewTargetBlocksAverage DIV 2)) of previous target. This makes target more stable. } tsTeorical := vteorical; tsReal := vreal; factor1000 := (((tsTeorical - tsReal) * 1000) DIV (tsTeorical)) * (-1); { Important: Note that a -500 is the same that divide by 2 (-100%), and 1000 is the same that multiply by 2 (+100%), so we limit increase in a limit [-500..+1000] for a complete (CT_CalcNewTargetBlocksAverage DIV 2) round } if CT_CalcNewTargetBlocksAverage > 1 then begin factor1000Min := (-500) DIV (CT_CalcNewTargetBlocksAverage DIV 2); factor1000Max := (1000) DIV (CT_CalcNewTargetBlocksAverage DIV 2); end else begin factor1000Min := (-500); factor1000Max := (1000); end; if factor1000 < factor1000Min then factor1000 := factor1000Min else if factor1000 > factor1000Max then factor1000 := factor1000Max else if factor1000 = 0 then begin Result := actualTarget; exit; end; // Calc new target by increasing factor (-500 <= x <= 1000) bn := TBigNum.Create(factor1000); bnact := TBigNum.Create(0); try bnact.RawValue := actualTarget; bnaux := bnact.Copy; try bnact.Multiply(factor1000).Divide(1000).Add(bnaux); finally bnaux.Free; end; // Adjust to TargetCompact limitations: Result := TargetFromCompact(TargetToCompact(bnact.RawValue)); finally bn.Free; bnact.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork_Part1(const operationBlock: TOperationBlock; var Part1: TRawBytes); var ms: TMemoryStream; s: AnsiString; begin ms := TMemoryStream.Create; try // Part 1 ms.Write(operationBlock.block, Sizeof(operationBlock.block)); // Little endian s := TAccountComp.AccountKey2RawString(operationBlock.account_key); ms.WriteBuffer(s[1], length(s)); ms.Write(operationBlock.reward, Sizeof(operationBlock.reward)); // Little endian ms.Write(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); // Little endian ms.Write(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); // Little endian ms.Write(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); // Little endian SetLength(Part1, ms.Size); ms.Position := 0; ms.Read(Part1[1], ms.Size); finally ms.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork_Part3(const operationBlock: TOperationBlock; var Part3: TRawBytes); var ms: TMemoryStream; begin ms := TMemoryStream.Create; try ms.WriteBuffer(operationBlock.initial_safe_box_hash[1], length(operationBlock.initial_safe_box_hash)); ms.WriteBuffer(operationBlock.operations_hash[1], length(operationBlock.operations_hash)); // Note about fee: Fee is stored in 8 bytes, but only digest first 4 low bytes ms.Write(operationBlock.fee, 4); SetLength(Part3, ms.Size); ms.Position := 0; ms.ReadBuffer(Part3[1], ms.Size); finally ms.Free; end; end; class procedure TPascalCoinProtocol.CalcProofOfWork(const operationBlock: TOperationBlock; var PoW: TRawBytes); var ms: TMemoryStream; s: AnsiString; begin ms := TMemoryStream.Create; try // Part 1 ms.Write(operationBlock.block, Sizeof(operationBlock.block)); // Little endian s := TAccountComp.AccountKey2RawString(operationBlock.account_key); ms.WriteBuffer(s[1], length(s)); ms.Write(operationBlock.reward, Sizeof(operationBlock.reward)); // Little endian ms.Write(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); // Little endian ms.Write(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); // Little endian ms.Write(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); // Little endian // Part 2 ms.WriteBuffer(operationBlock.block_payload[1], length(operationBlock.block_payload)); // Part 3 ms.WriteBuffer(operationBlock.initial_safe_box_hash[1], length(operationBlock.initial_safe_box_hash)); ms.WriteBuffer(operationBlock.operations_hash[1], length(operationBlock.operations_hash)); // Note about fee: Fee is stored in 8 bytes (Int64), but only digest first 4 low bytes ms.Write(operationBlock.fee, 4); ms.Write(operationBlock.timestamp, 4); ms.Write(operationBlock.nonce, 4); TCrypto.DoDoubleSha256(ms.Memory, ms.Size, PoW); finally ms.Free; end; end; class function TPascalCoinProtocol.GetRewardForNewLine(line_index: Cardinal): UInt64; Var n, i: Cardinal; begin n := (line_index + 1) DIV CT_NewLineRewardDecrease; Result := CT_FirstReward; for i := 1 to n do begin Result := Result DIV 2; end; if (Result < CT_MinReward) then Result := CT_MinReward; end; class function TPascalCoinProtocol.TargetFromCompact(encoded: Cardinal): TRawBytes; Var nbits, high, offset, i: Cardinal; bn: TBigNum; raw: TRawBytes; begin { Compact Target is a 4 byte value that tells how many "0" must have the hash at left if presented in binay format. First byte indicates haw many "0 bits" are on left, so can be from 0x00 to 0xE7 (Because 24 bits are reserved for 3 bytes, and 1 bit is implicit, max: 256-24-1=231=0xE7) Next 3 bytes indicates next value in XOR, stored in RAW format Example: If we want a hash lower than 0x0000 0000 0000 65A0 A2F4 +29 bytes Binary "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 1111 0100" That is 49 zeros on left before first 1. So first byte is 49 decimal = 0x31 After we have "110 0101 1010 0000 1010 0010 1111 0100 1111 0100" but we only can accept first 3 bytes, also note that first "1" is implicit, so value is transformed in binary as "10 0101 1010 0000 1010 0010 11" that is 0x96828B But note that we must XOR this value, so result offset is: 0x697D74 Compacted value is: 0x31697D74 When translate compact target back to target: ( 0x31697D74 ) 0x31 = 49 bits at "0", then 1 bit at "1" followed by XOR 0x697D74 = 0x96828B 49 "0" bits "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0" 0x96828B "1001 0110 1000 0010 1000 1011" Hash target = "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 11.. ...." Fill last "." with "1" Hash target = "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0101 1010 0000 1010 0010 1111 1111" Hash target = 0x00 00 00 00 00 00 65 A0 A2 FF + 29 bytes Note that is not exactly the same than expected due to compacted format } nbits := encoded shr 24; i := CT_MinCompactTarget shr 24; if nbits < i then nbits := i; // min nbits if nbits > 231 then nbits := 231; // max nbits offset := (encoded shl 8) shr 8; // Make a XOR at offset and put a "1" on the left offset := ((offset XOR $00FFFFFF) OR ($01000000)); bn := TBigNum.Create(offset); Try bn.LShift(256 - nbits - 25); raw := bn.RawValue; SetLength(Result, 32); FillChar(Result[1], 32, 0); for i := 1 to length(raw) do begin Result[i + 32 - length(raw)] := raw[i]; end; Finally bn.Free; End; end; class function TPascalCoinProtocol.TargetToCompact(target: TRawBytes): Cardinal; Var bn, bn2: TBigNum; i: Int64; nbits: Cardinal; c: AnsiChar; raw: TRawBytes; j: Integer; begin { See instructions in explanation of TargetFromCompact } Result := 0; if length(target) > 32 then begin raise Exception.Create('Invalid target to compact: ' + TCrypto.ToHexaString(target) + ' (' + inttostr(length(target)) + ')'); end; SetLength(raw, 32); FillChar(raw[1], 32, 0); for j := 1 to length(target) do begin raw[j + 32 - length(target)] := target[j]; end; target := raw; bn := TBigNum.Create(0); bn2 := TBigNum.Create('8000000000000000000000000000000000000000000000000000000000000000'); // First bit 1 followed by 0 try bn.RawValue := target; nbits := 0; while (bn.CompareTo(bn2) < 0) And (nbits < 231) do begin bn2.RShift(1); inc(nbits); end; i := CT_MinCompactTarget shr 24; if (nbits < i) then begin Result := CT_MinCompactTarget; exit; end; bn.RShift((256 - 25) - nbits); Result := (nbits shl 24) + ((bn.Value AND $00FFFFFF) XOR $00FFFFFF); finally bn.Free; bn2.Free; end; end; { TStreamOp } class function TStreamOp.ReadAccountKey(stream: TStream; var Value: TAccountKey): Integer; begin if stream.Size - stream.Position < 2 then begin Value := CT_TECDSA_Public_Nul; Result := -1; exit; end; stream.Read(Value.EC_OpenSSL_NID, Sizeof(Value.EC_OpenSSL_NID)); if (ReadAnsiString(stream, Value.x) <= 0) then begin Value := CT_TECDSA_Public_Nul; exit; end; if (ReadAnsiString(stream, Value.y) <= 0) then begin Value := CT_TECDSA_Public_Nul; exit; end; Result := Value.EC_OpenSSL_NID; end; class function TStreamOp.ReadAnsiString(stream: TStream; var Value: AnsiString): Integer; Var l: Word; begin if stream.Size - stream.Position < 2 then begin Value := ''; Result := -1; exit; end; stream.Read(l, 2); if stream.Size - stream.Position < l then begin stream.Position := stream.Position - 2; // Go back! Value := ''; Result := -1; exit; end; SetLength(Value, l); stream.ReadBuffer(Value[1], l); Result := l + 2; end; class function TStreamOp.WriteAccountKey(stream: TStream; const Value: TAccountKey): Integer; begin Result := stream.Write(Value.EC_OpenSSL_NID, Sizeof(Value.EC_OpenSSL_NID)); Result := Result + WriteAnsiString(stream, Value.x); Result := Result + WriteAnsiString(stream, Value.y); end; class function TStreamOp.WriteAnsiString(stream: TStream; const Value: AnsiString): Integer; Var l: Word; begin if (length(Value) > (256 * 256)) then begin TLog.NewLog(lterror, Classname, 'Invalid stream size! ' + inttostr(length(Value))); raise Exception.Create('Invalid stream size! ' + inttostr(length(Value))); end; l := length(Value); stream.Write(l, 2); if (l > 0) then stream.WriteBuffer(Value[1], length(Value)); Result := l + 2; end; { TAccountComp } Const CT_Base58: AnsiString = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; class function TAccountComp.AccountBlock(const account_number: Cardinal): Cardinal; begin Result := account_number DIV CT_AccountsPerBlock; end; class function TAccountComp.AccountInfo2RawString(const accountInfo: TAccountInfo): TRawBytes; begin AccountInfo2RawString(accountInfo, Result); end; class procedure TAccountComp.AccountInfo2RawString(const accountInfo: TAccountInfo; var dest: TRawBytes); Var ms: TMemoryStream; w: Word; begin case accountInfo.state of as_Normal: AccountKey2RawString(accountInfo.accountKey, dest); as_ForSale: begin ms := TMemoryStream.Create; Try w := CT_AccountInfo_ForSale; ms.Write(w, Sizeof(w)); // TStreamOp.WriteAccountKey(ms, accountInfo.accountKey); ms.Write(accountInfo.locked_until_block, Sizeof(accountInfo.locked_until_block)); ms.Write(accountInfo.price, Sizeof(accountInfo.price)); ms.Write(accountInfo.account_to_pay, Sizeof(accountInfo.account_to_pay)); TStreamOp.WriteAccountKey(ms, accountInfo.new_publicKey); SetLength(dest, ms.Size); ms.Position := 0; ms.Read(dest[1], ms.Size); Finally ms.Free; end; end; else raise Exception.Create('DEVELOP ERROR 20170214-1'); end; end; class function TAccountComp.AccountKey2RawString(const account: TAccountKey): TRawBytes; begin AccountKey2RawString(account, Result); end; class procedure TAccountComp.AccountKey2RawString(const account: TAccountKey; var dest: TRawBytes); Var s: TMemoryStream; begin s := TMemoryStream.Create; try TStreamOp.WriteAccountKey(s, account); SetLength(dest, s.Size); s.Position := 0; s.Read(dest[1], s.Size); finally s.Free; end; end; class function TAccountComp.AccountKeyFromImport(const HumanReadable: AnsiString; var account: TAccountKey; var errors: AnsiString): Boolean; Var raw: TRawBytes; bn, bnaux, BNBase: TBigNum; i, j: Integer; s1, s2: AnsiString; i64: Int64; b: Byte; begin Result := false; errors := 'Invalid length'; account := CT_TECDSA_Public_Nul; if length(HumanReadable) < 20 then exit; bn := TBigNum.Create(0); bnaux := TBigNum.Create; BNBase := TBigNum.Create(1); try for i := length(HumanReadable) downto 1 do begin if (HumanReadable[i] <> ' ') then begin j := pos(HumanReadable[i], CT_Base58); if j = 0 then begin errors := 'Invalid char "' + HumanReadable[i] + '" at pos ' + inttostr(i) + '/' + inttostr(length(HumanReadable)); exit; end; bnaux.Value := j - 1; bnaux.Multiply(BNBase); bn.Add(bnaux); BNBase.Multiply(length(CT_Base58)); end; end; // Last 8 hexa chars are the checksum of others s1 := Copy(bn.HexaValue, 3, length(bn.HexaValue)); s2 := Copy(s1, length(s1) - 7, 8); s1 := Copy(s1, 1, length(s1) - 8); raw := TCrypto.HexaToRaw(s1); s1 := TCrypto.ToHexaString(TCrypto.DoSha256(raw)); if Copy(s1, 1, 8) <> s2 then begin // Invalid checksum errors := 'Invalid checksum'; exit; end; try account := TAccountComp.RawString2Accountkey(raw); Result := true; errors := ''; except // Nothing to do... invalid errors := 'Error on conversion from Raw to Account key'; end; Finally bn.Free; BNBase.Free; bnaux.Free; end; end; class function TAccountComp.AccountNumberToAccountTxtNumber(account_number: Cardinal): AnsiString; Var an: Int64; begin an := account_number; // Converting to int64 to prevent overflow when *101 an := ((an * 101) MOD 89) + 10; Result := inttostr(account_number) + '-' + inttostr(an); end; class function TAccountComp.AccountPublicKeyExport(const account: TAccountKey): AnsiString; Var raw: TRawBytes; bn, BNMod, BNDiv: TBigNum; i: Integer; begin Result := ''; raw := AccountKey2RawString(account); bn := TBigNum.Create; BNMod := TBigNum.Create; BNDiv := TBigNum.Create(length(CT_Base58)); try bn.HexaValue := '01' + TCrypto.ToHexaString(raw) + TCrypto.ToHexaString(Copy(TCrypto.DoSha256(raw), 1, 4)); while (Not bn.IsZero) do begin bn.Divide(BNDiv, BNMod); If (BNMod.Value >= 0) And (BNMod.Value < length(CT_Base58)) then Result := CT_Base58[Byte(BNMod.Value) + 1] + Result else raise Exception.Create('Error converting to Base 58'); end; finally bn.Free; BNMod.Free; BNDiv.Free; end; end; class function TAccountComp.AccountPublicKeyImport(const HumanReadable: AnsiString; var account: TAccountKey; var errors: AnsiString): Boolean; Var raw: TRawBytes; bn, bnaux, BNBase: TBigNum; i, j: Integer; s1, s2: AnsiString; i64: Int64; b: Byte; begin Result := false; errors := 'Invalid length'; account := CT_TECDSA_Public_Nul; if length(HumanReadable) < 20 then exit; bn := TBigNum.Create(0); bnaux := TBigNum.Create; BNBase := TBigNum.Create(1); try for i := length(HumanReadable) downto 1 do begin j := pos(HumanReadable[i], CT_Base58); if j = 0 then begin errors := 'Invalid char "' + HumanReadable[i] + '" at pos ' + inttostr(i) + '/' + inttostr(length(HumanReadable)); exit; end; bnaux.Value := j - 1; bnaux.Multiply(BNBase); bn.Add(bnaux); BNBase.Multiply(length(CT_Base58)); end; // Last 8 hexa chars are the checksum of others s1 := Copy(bn.HexaValue, 3, length(bn.HexaValue)); s2 := Copy(s1, length(s1) - 7, 8); s1 := Copy(s1, 1, length(s1) - 8); raw := TCrypto.HexaToRaw(s1); s1 := TCrypto.ToHexaString(TCrypto.DoSha256(raw)); if Copy(s1, 1, 8) <> s2 then begin // Invalid checksum errors := 'Invalid checksum'; exit; end; try account := TAccountComp.RawString2Accountkey(raw); Result := true; errors := ''; except // Nothing to do... invalid errors := 'Error on conversion from Raw to Account key'; end; Finally bn.Free; BNBase.Free; bnaux.Free; end; end; class function TAccountComp.AccountTxtNumberToAccountNumber(const account_txt_number: AnsiString; var account_number: Cardinal): Boolean; Var i: Integer; char1: AnsiChar; char2: AnsiChar; an, rn, anaux: Int64; begin Result := false; if length(trim(account_txt_number)) = 0 then exit; an := 0; i := 1; while (i <= length(account_txt_number)) do begin if account_txt_number[i] in ['0' .. '9'] then begin an := (an * 10) + ord(account_txt_number[i]) - ord('0'); end else begin break; end; inc(i); end; account_number := an; if (i > length(account_txt_number)) then begin Result := true; exit; end; if (account_txt_number[i] in ['-', '.', ' ']) then inc(i); if length(account_txt_number) - 1 <> i then exit; rn := StrToIntDef(Copy(account_txt_number, i, length(account_txt_number)), 0); anaux := ((an * 101) MOD 89) + 10; Result := rn = anaux; end; class function TAccountComp.EqualAccountInfos(const accountInfo1, accountInfo2: TAccountInfo): Boolean; begin Result := (accountInfo1.state = accountInfo2.state) And (EqualAccountKeys(accountInfo1.accountKey, accountInfo2.accountKey)) And (accountInfo1.locked_until_block = accountInfo2.locked_until_block) And (accountInfo1.price = accountInfo2.price) And (accountInfo1.account_to_pay = accountInfo2.account_to_pay) and (EqualAccountKeys(accountInfo1.new_publicKey, accountInfo2.new_publicKey)); end; class function TAccountComp.EqualAccountKeys(const account1, account2: TAccountKey): Boolean; begin Result := (account1.EC_OpenSSL_NID = account2.EC_OpenSSL_NID) And (account1.x = account2.x) And (account1.y = account2.y); end; class function TAccountComp.FormatMoney(Money: Int64): AnsiString; begin Result := FormatFloat('#,###0.0000', (Money / 10000)); end; class function TAccountComp.GetECInfoTxt(const EC_OpenSSL_NID: Word): AnsiString; begin case EC_OpenSSL_NID of CT_NID_secp256k1: begin Result := 'secp256k1'; end; CT_NID_secp384r1: begin Result := 'secp384r1'; end; CT_NID_sect283k1: Begin Result := 'secp283k1'; End; CT_NID_secp521r1: begin Result := 'secp521r1'; end else Result := '(Unknown ID:' + inttostr(EC_OpenSSL_NID) + ')'; end; end; class function TAccountComp.IsAccountBlockedByProtocol(account_number, blocks_count: Cardinal): Boolean; begin if blocks_count < CT_WaitNewBlocksBeforeTransaction then Result := true else begin Result := ((blocks_count - CT_WaitNewBlocksBeforeTransaction) * CT_AccountsPerBlock) <= account_number; end; end; class function TAccountComp.IsAccountForSale(const accountInfo: TAccountInfo): Boolean; begin Result := (accountInfo.state = as_ForSale); end; class function TAccountComp.IsAccountForSaleAcceptingTransactions(const accountInfo: TAccountInfo): Boolean; var errors: AnsiString; begin Result := (accountInfo.state = as_ForSale) And (IsValidAccountKey(accountInfo.new_publicKey, errors)); end; class function TAccountComp.IsAccountLocked(const accountInfo: TAccountInfo; blocks_count: Cardinal): Boolean; begin Result := (accountInfo.state = as_ForSale) And ((accountInfo.locked_until_block) >= blocks_count); end; class procedure TAccountComp.SaveTOperationBlockToStream(const stream: TStream; const operationBlock: TOperationBlock); begin stream.Write(operationBlock.block, Sizeof(operationBlock.block)); TStreamOp.WriteAccountKey(stream, operationBlock.account_key); stream.Write(operationBlock.reward, Sizeof(operationBlock.reward)); stream.Write(operationBlock.fee, Sizeof(operationBlock.fee)); stream.Write(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); stream.Write(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); stream.Write(operationBlock.timestamp, Sizeof(operationBlock.timestamp)); stream.Write(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); stream.Write(operationBlock.nonce, Sizeof(operationBlock.nonce)); TStreamOp.WriteAnsiString(stream, operationBlock.block_payload); TStreamOp.WriteAnsiString(stream, operationBlock.initial_safe_box_hash); TStreamOp.WriteAnsiString(stream, operationBlock.operations_hash); TStreamOp.WriteAnsiString(stream, operationBlock.proof_of_work); end; class function TAccountComp.LoadTOperationBlockFromStream(const stream: TStream; var operationBlock: TOperationBlock): Boolean; begin Result := false; operationBlock := CT_OperationBlock_NUL; If stream.Read(operationBlock.block, Sizeof(operationBlock.block)) < Sizeof(operationBlock.block) then exit; TStreamOp.ReadAccountKey(stream, operationBlock.account_key); stream.Read(operationBlock.reward, Sizeof(operationBlock.reward)); stream.Read(operationBlock.fee, Sizeof(operationBlock.fee)); stream.Read(operationBlock.protocol_version, Sizeof(operationBlock.protocol_version)); stream.Read(operationBlock.protocol_available, Sizeof(operationBlock.protocol_available)); stream.Read(operationBlock.timestamp, Sizeof(operationBlock.timestamp)); stream.Read(operationBlock.compact_target, Sizeof(operationBlock.compact_target)); stream.Read(operationBlock.nonce, Sizeof(operationBlock.nonce)); if TStreamOp.ReadAnsiString(stream, operationBlock.block_payload) < 0 then exit; if TStreamOp.ReadAnsiString(stream, operationBlock.initial_safe_box_hash) < 0 then exit; if TStreamOp.ReadAnsiString(stream, operationBlock.operations_hash) < 0 then exit; if TStreamOp.ReadAnsiString(stream, operationBlock.proof_of_work) < 0 then exit; Result := true; end; class function TAccountComp.IsValidAccountInfo(const accountInfo: TAccountInfo; var errors: AnsiString): Boolean; Var s: AnsiString; begin errors := ''; case accountInfo.state of as_Unknown: begin errors := 'Account state is unknown'; Result := false; end; as_Normal: begin Result := IsValidAccountKey(accountInfo.accountKey, errors); end; as_ForSale: begin If Not IsValidAccountKey(accountInfo.accountKey, s) then errors := errors + ' ' + s; Result := errors = ''; end; else raise Exception.Create('DEVELOP ERROR 20170214-3'); end; end; class function TAccountComp.IsValidAccountKey(const account: TAccountKey; var errors: AnsiString): Boolean; begin errors := ''; case account.EC_OpenSSL_NID of CT_NID_secp256k1, CT_NID_secp384r1, CT_NID_sect283k1, CT_NID_secp521r1: begin Result := TECPrivateKey.IsValidPublicKey(account); if Not Result then begin errors := Format('Invalid AccountKey type:%d - Length x:%d y:%d Error:%s', [account.EC_OpenSSL_NID, length(account.x), length(account.y), ERR_error_string(ERR_get_error(), nil)]); end; end; else errors := Format('Invalid AccountKey type:%d (Unknown type) - Length x:%d y:%d', [account.EC_OpenSSL_NID, length(account.x), length(account.y)]); Result := false; end; if (errors = '') And (Not Result) then errors := ERR_error_string(ERR_get_error(), nil); end; class function TAccountComp.PrivateToAccountkey(key: TECPrivateKey): TAccountKey; begin Result := key.PublicKey; end; class function TAccountComp.RawString2AccountInfo(const rawaccstr: TRawBytes): TAccountInfo; begin RawString2AccountInfo(rawaccstr, Result); end; class procedure TAccountComp.RawString2AccountInfo(const rawaccstr: TRawBytes; var dest: TAccountInfo); Var ms: TMemoryStream; w: Word; begin if length(rawaccstr) = 0 then begin dest := CT_AccountInfo_NUL; exit; end; ms := TMemoryStream.Create; Try ms.WriteBuffer(rawaccstr[1], length(rawaccstr)); ms.Position := 0; If ms.Read(w, Sizeof(w)) <> Sizeof(w) then exit; case w of CT_NID_secp256k1, CT_NID_secp384r1, CT_NID_sect283k1, CT_NID_secp521r1: Begin dest.state := as_Normal; RawString2Accountkey(rawaccstr, dest.accountKey); dest.locked_until_block := CT_AccountInfo_NUL.locked_until_block; dest.price := CT_AccountInfo_NUL.price; dest.account_to_pay := CT_AccountInfo_NUL.account_to_pay; dest.new_publicKey := CT_AccountInfo_NUL.new_publicKey; End; CT_AccountInfo_ForSale: Begin TStreamOp.ReadAccountKey(ms, dest.accountKey); ms.Read(dest.locked_until_block, Sizeof(dest.locked_until_block)); ms.Read(dest.price, Sizeof(dest.price)); ms.Read(dest.account_to_pay, Sizeof(dest.account_to_pay)); TStreamOp.ReadAccountKey(ms, dest.new_publicKey); dest.state := as_ForSale; End; else raise Exception.Create('DEVELOP ERROR 20170214-2'); end; Finally ms.Free; end; end; class function TAccountComp.RawString2Accountkey(const rawaccstr: TRawBytes): TAccountKey; begin RawString2Accountkey(rawaccstr, Result); end; class procedure TAccountComp.RawString2Accountkey(const rawaccstr: TRawBytes; var dest: TAccountKey); Var ms: TMemoryStream; begin if length(rawaccstr) = 0 then begin dest := CT_TECDSA_Public_Nul; exit; end; ms := TMemoryStream.Create; try ms.WriteBuffer(rawaccstr[1], length(rawaccstr)); ms.Position := 0; TStreamOp.ReadAccountKey(ms, dest); finally ms.Free; end; end; class function TAccountComp.TxtToMoney(const moneytxt: AnsiString; var Money: Int64): Boolean; Var s: AnsiString; i: Integer; DecimalSep, ThousandSep: Char; begin Money := 0; if trim(moneytxt) = '' then begin Result := true; exit; end; try {$IFDEF FPC} DecimalSep := DecimalSeparator; ThousandSep := ThousandSeparator; {$ELSE} DecimalSep := FormatSettings.DecimalSeparator; ThousandSep := FormatSettings.ThousandSeparator; {$ENDIF} If pos(FormatSettings.DecimalSeparator, moneytxt) <= 0 then begin // No decimal separator, consider ThousandSeparator as a decimal separator s := StringReplace(moneytxt, ThousandSep, DecimalSep, [rfReplaceAll]); end else begin s := StringReplace(moneytxt, ThousandSep, '', [rfReplaceAll]); end; Money := Round(StrToFloat(s) * 10000); Result := true; Except Result := false; end; end; class procedure TAccountComp.ValidsEC_OpenSSL_NID(list: TList); begin list.Clear; list.Add(TObject(CT_NID_secp256k1)); // = 714 list.Add(TObject(CT_NID_secp384r1)); // = 715 list.Add(TObject(CT_NID_sect283k1)); // = 729 list.Add(TObject(CT_NID_secp521r1)); // = 716 end; { TPCSafeBox } // New on version 2: To reduce mem usage {$DEFINE uselowmem} {$IFDEF uselowmem} Type { In order to store less memory on RAM, those types will be used to store in RAM memory (better than to use original ones) This will reduce 10-15% of memory usage. For future versions, will be a good solution to use those instead of originals, but } TMemAccount = Record // TAccount with less memory usage // account number is discarded (-4 bytes) accountInfo: TDynRawBytes; balance: UInt64; updated_block: Cardinal; n_operation: Cardinal; name: TRawBytes; account_type: Word; previous_updated_block: Cardinal; End; TMemOperationBlock = Record // TOperationBlock with less memory usage // block number is discarded (-4 bytes) account_key: TDynRawBytes; reward: UInt64; fee: UInt64; protocol_version: Word; protocol_available: Word; timestamp: Cardinal; compact_target: Cardinal; nonce: Cardinal; block_payload: TDynRawBytes; initial_safe_box_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) operations_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) proof_of_work: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) end; TMemBlockAccount = Record // TBlockAccount with less memory usage blockchainInfo: TMemOperationBlock; accounts: Array [0 .. CT_AccountsPerBlock - 1] of TMemAccount; block_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes) accumulatedWork: UInt64; end; Type PBlockAccount = ^TMemBlockAccount; {$ELSE} Type PBlockAccount = ^TBlockAccount; TMemAccount = TAccount; TMemBlockAccount = TBlockAccount; {$ENDIF} procedure ToTMemAccount(Const Source: TAccount; var dest: TMemAccount); {$IFDEF uselowmem} Var raw: TRawBytes; {$ENDIF} begin {$IFDEF uselowmem} TAccountComp.AccountInfo2RawString(Source.accountInfo, raw); TBaseType.To256RawBytes(raw, dest.accountInfo); dest.balance := Source.balance; dest.updated_block := Source.updated_block; dest.n_operation := Source.n_operation; dest.name := Source.name; dest.account_type := Source.account_type; dest.previous_updated_block := Source.previous_updated_block; {$ELSE} dest := Source; {$ENDIF} end; procedure ToTAccount(const Source: TMemAccount; account_number: Cardinal; var dest: TAccount); {$IFDEF uselowmem} var raw: TRawBytes; {$ENDIF} begin {$IFDEF uselowmem} dest.account := account_number; TBaseType.ToRawBytes(Source.accountInfo, raw); TAccountComp.RawString2AccountInfo(raw, dest.accountInfo); dest.balance := Source.balance; dest.updated_block := Source.updated_block; dest.n_operation := Source.n_operation; dest.name := Source.name; dest.account_type := Source.account_type; dest.previous_updated_block := Source.previous_updated_block; {$ELSE} dest := Source; {$ENDIF} end; procedure ToTMemBlockAccount(const Source: TBlockAccount; var dest: TMemBlockAccount); {$IFDEF uselowmem} var i: Integer; var raw: TRawBytes; {$ENDIF} Begin {$IFDEF uselowmem} TAccountComp.AccountKey2RawString(Source.blockchainInfo.account_key, raw); TBaseType.To256RawBytes(raw, dest.blockchainInfo.account_key); dest.blockchainInfo.reward := Source.blockchainInfo.reward; dest.blockchainInfo.fee := Source.blockchainInfo.fee; dest.blockchainInfo.protocol_version := Source.blockchainInfo.protocol_version; dest.blockchainInfo.protocol_available := Source.blockchainInfo.protocol_available; dest.blockchainInfo.timestamp := Source.blockchainInfo.timestamp; dest.blockchainInfo.compact_target := Source.blockchainInfo.compact_target; dest.blockchainInfo.nonce := Source.blockchainInfo.nonce; TBaseType.To256RawBytes(Source.blockchainInfo.block_payload, dest.blockchainInfo.block_payload); TBaseType.To32Bytes(Source.blockchainInfo.initial_safe_box_hash, dest.blockchainInfo.initial_safe_box_hash); TBaseType.To32Bytes(Source.blockchainInfo.operations_hash, dest.blockchainInfo.operations_hash); TBaseType.To32Bytes(Source.blockchainInfo.proof_of_work, dest.blockchainInfo.proof_of_work); for i := Low(Source.accounts) to High(Source.accounts) do begin ToTMemAccount(Source.accounts[i], dest.accounts[i]); end; TBaseType.To32Bytes(Source.block_hash, dest.block_hash); dest.accumulatedWork := Source.accumulatedWork; {$ELSE} dest := Source; {$ENDIF} end; procedure ToTBlockAccount(const Source: TMemBlockAccount; block_number: Cardinal; var dest: TBlockAccount); {$IFDEF uselowmem} var i: Integer; raw: TRawBytes; {$ENDIF} begin {$IFDEF uselowmem} dest.blockchainInfo.block := block_number; TBaseType.ToRawBytes(Source.blockchainInfo.account_key, raw); TAccountComp.RawString2Accountkey(raw, dest.blockchainInfo.account_key); dest.blockchainInfo.reward := Source.blockchainInfo.reward; dest.blockchainInfo.fee := Source.blockchainInfo.fee; dest.blockchainInfo.protocol_version := Source.blockchainInfo.protocol_version; dest.blockchainInfo.protocol_available := Source.blockchainInfo.protocol_available; dest.blockchainInfo.timestamp := Source.blockchainInfo.timestamp; dest.blockchainInfo.compact_target := Source.blockchainInfo.compact_target; dest.blockchainInfo.nonce := Source.blockchainInfo.nonce; TBaseType.ToRawBytes(Source.blockchainInfo.block_payload, dest.blockchainInfo.block_payload); TBaseType.ToRawBytes(Source.blockchainInfo.initial_safe_box_hash, dest.blockchainInfo.initial_safe_box_hash); TBaseType.ToRawBytes(Source.blockchainInfo.operations_hash, dest.blockchainInfo.operations_hash); TBaseType.ToRawBytes(Source.blockchainInfo.proof_of_work, dest.blockchainInfo.proof_of_work); for i := Low(Source.accounts) to High(Source.accounts) do begin ToTAccount(Source.accounts[i], (block_number * CT_AccountsPerBlock) + i, dest.accounts[i]); end; TBaseType.ToRawBytes(Source.block_hash, dest.block_hash); dest.accumulatedWork := Source.accumulatedWork; {$ELSE} dest := Source; {$ENDIF} end; function TPCSafeBox.account(account_number: Cardinal): TAccount; var b: Cardinal; begin b := account_number DIV CT_AccountsPerBlock; if (b < 0) Or (b >= FBlockAccountsList.Count) then raise Exception.Create('Invalid account: ' + inttostr(account_number)); ToTAccount(PBlockAccount(FBlockAccountsList.Items[b])^.accounts[account_number MOD CT_AccountsPerBlock], account_number, Result); end; function TPCSafeBox.AddNew(const blockChain: TOperationBlock): TBlockAccount; var i, base_addr: Integer; P: PBlockAccount; accs: Array of Cardinal; begin Result := CT_BlockAccount_NUL; Result.blockchainInfo := blockChain; If blockChain.block <> blocksCount then Raise Exception.Create('ERROR DEV 20170427-2'); If blockChain.fee <> FTotalFee then Raise Exception.Create('ERROR DEV 20170427-3'); base_addr := blocksCount * CT_AccountsPerBlock; SetLength(accs, length(Result.accounts)); for i := Low(Result.accounts) to High(Result.accounts) do begin Result.accounts[i] := CT_Account_NUL; Result.accounts[i].account := base_addr + i; Result.accounts[i].accountInfo.state := as_Normal; Result.accounts[i].accountInfo.accountKey := blockChain.account_key; Result.accounts[i].updated_block := blocksCount; Result.accounts[i].n_operation := 0; if i = Low(Result.accounts) then begin // Only first account wins the reward + fee Result.accounts[i].balance := blockChain.reward + blockChain.fee; end else begin end; accs[i] := base_addr + i; end; inc(FWorkSum, Result.blockchainInfo.compact_target); Result.accumulatedWork := FWorkSum; // Calc block hash Result.block_hash := CalcBlockHash(Result, FCurrentProtocol >= CT_PROTOCOL_2); New(P); ToTMemBlockAccount(Result, P^); FBlockAccountsList.Add(P); FBufferBlocksHash := FBufferBlocksHash + Result.block_hash; inc(FTotalBalance, blockChain.reward + blockChain.fee); Dec(FTotalFee, blockChain.fee); AccountKeyListAddAccounts(blockChain.account_key, accs); // Calculating new value of safebox FSafeBoxHash := CalcSafeBoxHash; end; procedure TPCSafeBox.AccountKeyListAddAccounts(const accountKey: TAccountKey; const accounts: array of Cardinal); Var i: Integer; begin for i := 0 to FListOfOrderedAccountKeysList.Count - 1 do begin TOrderedAccountKeysList(FListOfOrderedAccountKeysList[i]).AddAccounts(accountKey, accounts); end; end; procedure TPCSafeBox.AccountKeyListRemoveAccount(const accountKey: TAccountKey; const accounts: array of Cardinal); Var i: Integer; begin for i := 0 to FListOfOrderedAccountKeysList.Count - 1 do begin TOrderedAccountKeysList(FListOfOrderedAccountKeysList[i]).RemoveAccounts(accountKey, accounts); end; end; function TPCSafeBox.AccountsCount: Integer; begin Result := blocksCount * CT_AccountsPerBlock; end; function TPCSafeBox.block(block_number: Cardinal): TBlockAccount; begin if (block_number < 0) Or (block_number >= FBlockAccountsList.Count) then raise Exception.Create('Invalid block number: ' + inttostr(block_number)); ToTBlockAccount(PBlockAccount(FBlockAccountsList.Items[block_number])^, block_number, Result); end; class function TPCSafeBox.BlockAccountToText(const block: TBlockAccount): AnsiString; begin Result := Format('Block:%d Timestamp:%d BlockHash:%s', [block.blockchainInfo.block, block.blockchainInfo.timestamp, TCrypto.ToHexaString(block.block_hash)]); end; function TPCSafeBox.blocksCount: Integer; begin Result := FBlockAccountsList.Count; end; class function TPCSafeBox.CalcBlockHash(const block: TBlockAccount; useProtocol2Method: Boolean): TRawBytes; // Protocol v2 update: // In order to store values to generate PoW and allow Safebox checkpointing, we // store info about TOperationBlock on each row and use it to obtain blockchash Var raw: TRawBytes; ms: TMemoryStream; i: Integer; begin ms := TMemoryStream.Create; try If (Not useProtocol2Method) then begin // PROTOCOL 1 BlockHash calculation ms.Write(block.blockchainInfo.block, 4); // Little endian for i := Low(block.accounts) to High(block.accounts) do begin ms.Write(block.accounts[i].account, 4); // Little endian raw := TAccountComp.AccountInfo2RawString(block.accounts[i].accountInfo); ms.WriteBuffer(raw[1], length(raw)); // Raw bytes ms.Write(block.accounts[i].balance, Sizeof(UInt64)); // Little endian ms.Write(block.accounts[i].updated_block, 4); // Little endian ms.Write(block.accounts[i].n_operation, 4); // Little endian end; ms.Write(block.blockchainInfo.timestamp, 4); // Little endian end else begin // PROTOCOL 2 BlockHash calculation TAccountComp.SaveTOperationBlockToStream(ms, block.blockchainInfo); for i := Low(block.accounts) to High(block.accounts) do begin ms.Write(block.accounts[i].account, 4); // Little endian raw := TAccountComp.AccountInfo2RawString(block.accounts[i].accountInfo); ms.WriteBuffer(raw[1], length(raw)); // Raw bytes ms.Write(block.accounts[i].balance, Sizeof(UInt64)); // Little endian ms.Write(block.accounts[i].updated_block, 4); // Little endian ms.Write(block.accounts[i].n_operation, 4); // Little endian // Use new Protocol 2 fields If length(block.accounts[i].name) > 0 then begin ms.WriteBuffer(block.accounts[i].name[1], length(block.accounts[i].name)); end; ms.Write(block.accounts[i].account_type, 2); end; ms.Write(block.accumulatedWork, Sizeof(block.accumulatedWork)); end; Result := TCrypto.DoSha256(ms.Memory, ms.Size) finally ms.Free; end; end; function TPCSafeBox.CalcBlockHashRateInKhs(block_number: Cardinal; Previous_blocks_average: Cardinal): Int64; Var c, t: Cardinal; t_sum: Extended; bn, bn_sum: TBigNum; begin FLock.Acquire; Try bn_sum := TBigNum.Create; try if (block_number = 0) then begin Result := 1; exit; end; if (block_number < 0) Or (block_number >= FBlockAccountsList.Count) then raise Exception.Create('Invalid block number: ' + inttostr(block_number)); if (Previous_blocks_average <= 0) then raise Exception.Create('Dev error 20161016-1'); if (Previous_blocks_average > block_number) then Previous_blocks_average := block_number; // c := (block_number - Previous_blocks_average) + 1; t_sum := 0; while (c <= block_number) do begin bn := TBigNum.TargetToHashRate(PBlockAccount(FBlockAccountsList.Items[c])^.blockchainInfo.compact_target); try bn_sum.Add(bn); finally bn.Free; end; t_sum := t_sum + (PBlockAccount(FBlockAccountsList.Items[c])^.blockchainInfo.timestamp - PBlockAccount(FBlockAccountsList.Items[c - 1]) ^.blockchainInfo.timestamp); inc(c); end; bn_sum.Divide(Previous_blocks_average); // Obtain target average t_sum := t_sum / Previous_blocks_average; // time average t := Round(t_sum); if (t <> 0) then begin bn_sum.Divide(t); end; Result := bn_sum.Divide(1024).Value; // Value in Kh/s Finally bn_sum.Free; end; Finally FLock.Release; End; end; function TPCSafeBox.CalcSafeBoxHash: TRawBytes; begin // If No buffer to hash is because it's firts block... so use Genesis: CT_Genesis_Magic_String_For_Old_Block_Hash if (FBufferBlocksHash = '') then Result := TCrypto.DoSha256(CT_Genesis_Magic_String_For_Old_Block_Hash) else Result := TCrypto.DoSha256(FBufferBlocksHash); end; function TPCSafeBox.CanUpgradeToProtocol2: Boolean; begin Result := (FCurrentProtocol < CT_PROTOCOL_2) and (blocksCount >= CT_Protocol_Upgrade_v2_MinBlock); end; procedure TPCSafeBox.CheckMemory; { Note about Free Pascal compiler When compiling using Delphi it's memory manager more is efficient and does not increase, but When compiling using Free Pascal Compiler, is a good solution to "force" generate a new SafeBox in order to free memory not used. Tested with FPC 3.0 } {$IFDEF FPC} Var sb: TPCSafeBox; tc: Cardinal; {$ENDIF} begin {$IFDEF FPC} StartThreadSafe; try tc := GetTickCount; sb := TPCSafeBox.Create; try sb.CopyFrom(Self); Self.Clear; Self.CopyFrom(sb); finally sb.Free; end; tc := GetTickCount - tc; TLog.NewLog(ltDebug, Classname, 'Checked memory ' + inttostr(tc) + ' miliseonds'); finally EndThreadSave; end; {$ENDIF} end; procedure TPCSafeBox.Clear; Var i: Integer; P: PBlockAccount; begin StartThreadSafe; Try for i := 0 to FBlockAccountsList.Count - 1 do begin P := FBlockAccountsList.Items[i]; Dispose(P); end; FOrderedByName.Clear; FBlockAccountsList.Clear; For i := 0 to FListOfOrderedAccountKeysList.Count - 1 do begin TOrderedAccountKeysList(FListOfOrderedAccountKeysList[i]).ClearAccounts(false); end; FBufferBlocksHash := ''; FTotalBalance := 0; FTotalFee := 0; FSafeBoxHash := CalcSafeBoxHash; FWorkSum := 0; FCurrentProtocol := CT_PROTOCOL_1; Finally EndThreadSave; end; end; procedure TPCSafeBox.CopyFrom(accounts: TPCSafeBox); Var i, j: Cardinal; P: PBlockAccount; BA: TBlockAccount; begin StartThreadSafe; Try accounts.StartThreadSafe; try if accounts = Self then exit; Clear; if accounts.blocksCount > 0 then begin FBlockAccountsList.Capacity := accounts.blocksCount; for i := 0 to accounts.blocksCount - 1 do begin BA := accounts.block(i); New(P); ToTMemBlockAccount(BA, P^); FBlockAccountsList.Add(P); for j := Low(BA.accounts) to High(BA.accounts) do begin If (BA.accounts[j].name <> '') then FOrderedByName.Add(BA.accounts[j].name, BA.accounts[j].account); AccountKeyListAddAccounts(BA.accounts[j].accountInfo.accountKey, [BA.accounts[j].account]); end; end; end; FTotalBalance := accounts.TotalBalance; FTotalFee := accounts.FTotalFee; FBufferBlocksHash := accounts.FBufferBlocksHash; FSafeBoxHash := accounts.FSafeBoxHash; FWorkSum := accounts.FWorkSum; FCurrentProtocol := accounts.FCurrentProtocol; finally accounts.EndThreadSave; end; finally EndThreadSave; end; end; constructor TPCSafeBox.Create; begin FLock := TPCCriticalSection.Create('TPCSafeBox_Lock'); FBlockAccountsList := TList.Create; FListOfOrderedAccountKeysList := TList.Create; FCurrentProtocol := CT_PROTOCOL_1; FOrderedByName := TOrderedRawList.Create; Clear; end; destructor TPCSafeBox.Destroy; Var i: Integer; begin Clear; for i := 0 to FListOfOrderedAccountKeysList.Count - 1 do begin TOrderedAccountKeysList(FListOfOrderedAccountKeysList[i]).FAccountList := Nil; end; FreeAndNil(FBlockAccountsList); FreeAndNil(FListOfOrderedAccountKeysList); FreeAndNil(FLock); FreeAndNil(FOrderedByName); inherited; end; function TPCSafeBox.DoUpgradeToProtocol2: Boolean; var block_number: Cardinal; aux: TRawBytes; begin // Upgrade process to protocol 2 Result := false; If Not CanUpgradeToProtocol2 then exit; // Recalc all BlockAccounts block_hash value aux := CalcSafeBoxHash; TLog.NewLog(ltInfo, Classname, 'Start Upgrade to protocol 2 - Old Safeboxhash:' + TCrypto.ToHexaString(FSafeBoxHash) + ' calculated: ' + TCrypto.ToHexaString(aux) + ' Blocks: ' + inttostr(blocksCount)); FBufferBlocksHash := ''; for block_number := 0 to blocksCount - 1 do begin {$IFDEF uselowmem} TBaseType.To32Bytes(CalcBlockHash(block(block_number), true), PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash); FBufferBlocksHash := FBufferBlocksHash + TBaseType.ToRawBytes(PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash); {$ELSE} PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash := CalcBlockHash(block(block_number), true); FBufferBlocksHash := FBufferBlocksHash + PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash; {$ENDIF} end; FSafeBoxHash := CalcSafeBoxHash; FCurrentProtocol := CT_PROTOCOL_2; Result := true; TLog.NewLog(ltInfo, Classname, 'End Upgraded to protocol 2 - New safeboxhash:' + TCrypto.ToHexaString(FSafeBoxHash)); end; procedure TPCSafeBox.EndThreadSave; begin FLock.Release; end; function TPCSafeBox.LoadSafeBoxFromStream(stream: TStream; checkAll: Boolean; var LastReadBlock: TBlockAccount; var errors: AnsiString): Boolean; Var iblock, iacc: Cardinal; s: AnsiString; block: TBlockAccount; P: PBlockAccount; i, j: Integer; savedSBH: TRawBytes; nPos, posOffsetZone: Int64; offsets: Array of Cardinal; sbHeader: TPCSafeBoxHeader; begin StartThreadSafe; try Clear; Result := false; Try If not LoadSafeBoxStreamHeader(stream, sbHeader) then begin errors := 'Invalid stream. Invalid header/version'; exit; end; errors := 'Invalid version or corrupted stream'; case sbHeader.protocol of CT_PROTOCOL_1: FCurrentProtocol := 1; CT_PROTOCOL_2: FCurrentProtocol := 2; else exit; end; if (sbHeader.blocksCount = 0) Or (sbHeader.startBlock <> 0) Or (sbHeader.endBlock <> (sbHeader.blocksCount - 1)) then begin errors := Format('Safebox Stream contains blocks from %d to %d (of %d blocks). Not valid', [sbHeader.startBlock, sbHeader.endBlock, sbHeader.blocksCount]); exit; end; // Offset zone posOffsetZone := stream.Position; If checkAll then begin SetLength(offsets, sbHeader.blocksCount + 1); // Last offset = End of blocks stream.Read(offsets[0], 4 * (sbHeader.blocksCount + 1)); end else begin nPos := stream.Position + ((sbHeader.blocksCount + 1) * 4); if stream.Size < nPos then exit; stream.Position := nPos; end; // Build 1.3.0 to increase reading speed: FBlockAccountsList.Capacity := sbHeader.blocksCount; SetLength(FBufferBlocksHash, sbHeader.blocksCount * 32); // Initialize for high speed reading errors := 'Corrupted stream'; for iblock := 0 to sbHeader.blocksCount - 1 do begin errors := 'Corrupted stream reading block blockchain ' + inttostr(iblock + 1) + '/' + inttostr(sbHeader.blocksCount); if (checkAll) then begin If (offsets[iblock] <> stream.Position - posOffsetZone) then begin errors := errors + Format(' - offset[%d]:%d <> %d Position:%d offset:%d', [iblock, offsets[iblock], stream.Position - posOffsetZone, stream.Position, posOffsetZone]); exit; end; end; block := CT_BlockAccount_NUL; If Not TAccountComp.LoadTOperationBlockFromStream(stream, block.blockchainInfo) then exit; if block.blockchainInfo.block <> iblock then exit; for iacc := Low(block.accounts) to High(block.accounts) do begin errors := 'Corrupted stream reading account ' + inttostr(iacc + 1) + '/' + inttostr(length(block.accounts)) + ' of block ' + inttostr(iblock + 1) + '/' + inttostr(sbHeader.blocksCount); if stream.Read(block.accounts[iacc].account, 4) < 4 then exit; if TStreamOp.ReadAnsiString(stream, s) < 0 then exit; block.accounts[iacc].accountInfo := TAccountComp.RawString2AccountInfo(s); if stream.Read(block.accounts[iacc].balance, Sizeof(UInt64)) < Sizeof(UInt64) then exit; if stream.Read(block.accounts[iacc].updated_block, 4) < 4 then exit; if stream.Read(block.accounts[iacc].n_operation, 4) < 4 then exit; If FCurrentProtocol >= CT_PROTOCOL_2 then begin if TStreamOp.ReadAnsiString(stream, block.accounts[iacc].name) < 0 then exit; if stream.Read(block.accounts[iacc].account_type, 2) < 2 then exit; end; // if stream.Read(block.accounts[iacc].previous_updated_block, 4) < 4 then exit; // check valid If (block.accounts[iacc].name <> '') then begin if FOrderedByName.IndexOf(block.accounts[iacc].name) >= 0 then begin errors := errors + ' Duplicate name "' + block.accounts[iacc].name + '"'; exit; end; if Not TPCSafeBox.ValidAccountName(block.accounts[iacc].name, s) then begin errors := errors + ' > Invalid name "' + block.accounts[iacc].name + '": ' + s; exit; end; FOrderedByName.Add(block.accounts[iacc].name, block.accounts[iacc].account); end; If checkAll then begin if not TAccountComp.IsValidAccountInfo(block.accounts[iacc].accountInfo, s) then begin errors := errors + ' > ' + s; exit; end; end; inc(FTotalBalance, block.accounts[iacc].balance); end; errors := 'Corrupted stream reading block ' + inttostr(iblock + 1) + '/' + inttostr(sbHeader.blocksCount); If TStreamOp.ReadAnsiString(stream, block.block_hash) < 0 then exit; If stream.Read(block.accumulatedWork, Sizeof(block.accumulatedWork)) < Sizeof(block.accumulatedWork) then exit; if checkAll then begin // Check is valid: // STEP 1: Validate the block If not IsValidNewOperationsBlock(block.blockchainInfo, false, s) then begin errors := errors + ' > ' + s; exit; end; // STEP 2: Check if valid block hash if CalcBlockHash(block, FCurrentProtocol >= CT_PROTOCOL_2) <> block.block_hash then begin errors := errors + ' > Invalid block hash ' + inttostr(iblock + 1) + '/' + inttostr(sbHeader.blocksCount); exit; end; // STEP 3: Check accumulatedWork if (iblock > 0) then begin If (Self.block(iblock - 1).accumulatedWork) + block.blockchainInfo.compact_target <> block.accumulatedWork then begin errors := errors + ' > Invalid accumulatedWork'; exit; end; end; end; // Add New(P); ToTMemBlockAccount(block, P^); FBlockAccountsList.Add(P); for j := low(block.accounts) to High(block.accounts) do begin AccountKeyListAddAccounts(block.accounts[j].accountInfo.accountKey, [block.accounts[j].account]); end; // BufferBlocksHash fill with data j := (length(P^.block_hash) * (iblock)); for i := 1 to length(P^.block_hash) do begin {$IFDEF FPC} FBufferBlocksHash[i + j] := AnsiChar(P^.block_hash[i - (low(FBufferBlocksHash) - low(P^.block_hash))]); {$ELSE} FBufferBlocksHash[i + j] := AnsiChar(P^.block_hash[i - {$IFDEF uselowmem}1{$ELSE}0{$ENDIF}]); {$ENDIF} end; LastReadBlock := block; inc(FWorkSum, block.blockchainInfo.compact_target); end; If checkAll then begin If (offsets[sbHeader.blocksCount] <> 0) And (offsets[sbHeader.blocksCount] <> stream.Position - posOffsetZone) then begin errors := errors + Format(' - Final offset[%d]=%d <> Eof Position:%d offset:%d', [sbHeader.blocksCount, offsets[sbHeader.blocksCount], stream.Position - posOffsetZone, posOffsetZone]); exit; end; end; // Finally load SafeBoxHash If TStreamOp.ReadAnsiString(stream, savedSBH) < 0 then begin errors := 'No SafeBoxHash value'; exit; end; // Check worksum value If sbHeader.blocksCount > 0 then begin If (FWorkSum <> Self.block(sbHeader.blocksCount - 1).accumulatedWork) then begin errors := 'Invalid WorkSum value'; exit; end; end; // Calculating safe box hash FSafeBoxHash := CalcSafeBoxHash; // Checking saved SafeBoxHash If FSafeBoxHash <> savedSBH then begin errors := 'Invalid SafeBoxHash value in stream ' + TCrypto.ToHexaString(FSafeBoxHash) + '<>' + TCrypto.ToHexaString(savedSBH) + ' Last block:' + inttostr(LastReadBlock.blockchainInfo.block); exit; end; Result := true; Finally if Not Result then Clear else errors := ''; End; Finally EndThreadSave; end; end; class function TPCSafeBox.LoadSafeBoxStreamHeader(stream: TStream; var sbHeader: TPCSafeBoxHeader): Boolean; // This function reads SafeBox stream info and sets position at offset start zone if valid, otherwise sets position to actual position Var w: Word; s: AnsiString; safeBoxBankVersion: Word; offsetPos, initialPos: Int64; endBlocks: Cardinal; begin Result := false; sbHeader := CT_PCSafeBoxHeader_NUL; initialPos := stream.Position; try TStreamOp.ReadAnsiString(stream, s); if (s <> CT_MagicIdentificator) then exit; if stream.Size < 8 then exit; stream.Read(w, Sizeof(w)); if not(w in [1, 2]) then exit; sbHeader.protocol := w; stream.Read(safeBoxBankVersion, 2); if safeBoxBankVersion <> CT_SafeBoxBankVersion then exit; stream.Read(sbHeader.blocksCount, 4); stream.Read(sbHeader.startBlock, 4); stream.Read(sbHeader.endBlock, 4); if (sbHeader.blocksCount <= 0) Or (sbHeader.blocksCount > (CT_NewLineSecondsAvg * 2000000)) then exit; // Protection for corrupted data... offsetPos := stream.Position; // Go to read SafeBoxHash If (stream.Size < offsetPos + (((sbHeader.endBlock - sbHeader.startBlock) + 2) * 4)) then exit; stream.Position := offsetPos + (((sbHeader.endBlock - sbHeader.startBlock) + 1) * 4); stream.Read(endBlocks, 4); // Go to end If (stream.Size < offsetPos + (endBlocks)) then exit; stream.Position := offsetPos + endBlocks; If TStreamOp.ReadAnsiString(stream, sbHeader.safeBoxHash) < 0 then exit; // Back stream.Position := offsetPos; Result := true; finally If not Result then stream.Position := initialPos; end; end; class function TPCSafeBox.SaveSafeBoxStreamHeader(stream: TStream; protocol: Word; OffsetStartBlock, OffsetEndBlock, CurrentSafeBoxBlocksCount: Cardinal): Boolean; var c: Cardinal; begin Result := false; // Header zone TStreamOp.WriteAnsiString(stream, CT_MagicIdentificator); stream.Write(protocol, Sizeof(protocol)); stream.Write(CT_SafeBoxBankVersion, Sizeof(CT_SafeBoxBankVersion)); c := CurrentSafeBoxBlocksCount; stream.Write(c, Sizeof(c)); // Save Total blocks of the safebox c := OffsetStartBlock; stream.Write(c, Sizeof(c)); // Save first block saved c := OffsetEndBlock; stream.Write(c, Sizeof(c)); // Save last block saved Result := true; end; class function TPCSafeBox.MustSafeBoxBeSaved(blocksCount: Cardinal): Boolean; begin Result := (blocksCount MOD CT_BankToDiskEveryNBlocks) = 0; end; procedure TPCSafeBox.SaveSafeBoxBlockToAStream(stream: TStream; nBlock: Cardinal); var b: TBlockAccount; iacc: Integer; begin b := block(nBlock); TAccountComp.SaveTOperationBlockToStream(stream, b.blockchainInfo); for iacc := Low(b.accounts) to High(b.accounts) do begin stream.Write(b.accounts[iacc].account, Sizeof(b.accounts[iacc].account)); TStreamOp.WriteAnsiString(stream, TAccountComp.AccountInfo2RawString(b.accounts[iacc].accountInfo)); stream.Write(b.accounts[iacc].balance, Sizeof(b.accounts[iacc].balance)); stream.Write(b.accounts[iacc].updated_block, Sizeof(b.accounts[iacc].updated_block)); stream.Write(b.accounts[iacc].n_operation, Sizeof(b.accounts[iacc].n_operation)); If FCurrentProtocol >= CT_PROTOCOL_2 then begin TStreamOp.WriteAnsiString(stream, b.accounts[iacc].name); stream.Write(b.accounts[iacc].account_type, Sizeof(b.accounts[iacc].account_type)); end; stream.Write(b.accounts[iacc].previous_updated_block, Sizeof(b.accounts[iacc].previous_updated_block)); end; TStreamOp.WriteAnsiString(stream, b.block_hash); stream.Write(b.accumulatedWork, Sizeof(b.accumulatedWork)); end; procedure TPCSafeBox.SaveSafeBoxToAStream(stream: TStream; FromBlock, ToBlock: Cardinal); Var totalBlocks, iblock: Cardinal; b: TBlockAccount; posOffsetZone, posFinal: Int64; offsets: TCardinalsArray; raw: TRawBytes; begin If (FromBlock > ToBlock) Or (ToBlock >= blocksCount) then Raise Exception.Create(Format('Cannot save SafeBox from %d to %d (currently %d blocks)', [FromBlock, ToBlock, blocksCount])); StartThreadSafe; Try // Header zone SaveSafeBoxStreamHeader(stream, FCurrentProtocol, FromBlock, ToBlock, blocksCount); totalBlocks := ToBlock - FromBlock + 1; // Offsets zone posOffsetZone := stream.Position; SetLength(raw, (totalBlocks + 1) * 4); // Last position = end FillChar(raw[1], length(raw), 0); stream.WriteBuffer(raw[1], length(raw)); SetLength(offsets, totalBlocks + 1); // c = total blocks - Last position = offset to end // Blocks zone for iblock := FromBlock to ToBlock do begin offsets[iblock] := stream.Position - posOffsetZone; SaveSafeBoxBlockToAStream(stream, iblock); end; offsets[High(offsets)] := stream.Position - posOffsetZone; // Save offsets zone with valid values posFinal := stream.Position; stream.Position := posOffsetZone; for iblock := FromBlock to ToBlock + 1 do begin stream.Write(offsets[iblock], Sizeof(offsets[iblock])); end; stream.Position := posFinal; // Final zone: Save safeboxhash for next block If (ToBlock + 1 < blocksCount) then begin b := block(ToBlock); TStreamOp.WriteAnsiString(stream, b.blockchainInfo.initial_safe_box_hash); end else begin TStreamOp.WriteAnsiString(stream, FSafeBoxHash); end; Finally EndThreadSave; end; end; class function TPCSafeBox.CopySafeBoxStream(Source, dest: TStream; FromBlock, ToBlock: Cardinal; var errors: AnsiString): Boolean; Var iblock: Cardinal; raw: TRawBytes; posOffsetZoneSource, posOffsetZoneDest, posFinal, posBlocksZoneDest, posInitial: Int64; offsetsSource, offsetsDest: TCardinalsArray; destTotalBlocks: Cardinal; sbHeader: TPCSafeBoxHeader; begin Result := false; errors := ''; posInitial := Source.Position; try If (FromBlock > ToBlock) then begin errors := Format('Invalid CopySafeBoxStream(from %d, to %d)', [FromBlock, ToBlock]); exit; end; If not LoadSafeBoxStreamHeader(Source, sbHeader) then begin errors := 'Invalid stream. Invalid header/version'; exit; end; if (sbHeader.startBlock > FromBlock) Or (sbHeader.endBlock < ToBlock) Or ((sbHeader.startBlock + sbHeader.blocksCount) < ToBlock) then begin errors := Format('Stream contain blocks from %d to %d (of %d). Need between %d and %d !', [sbHeader.startBlock, sbHeader.endBlock, sbHeader.blocksCount, FromBlock, ToBlock]); exit; end; destTotalBlocks := ToBlock - FromBlock + 1; TLog.NewLog(ltInfo, Classname, Format('CopySafeBoxStream from safebox with %d to %d (of %d sbh:%s) to safebox with %d and %d', [sbHeader.startBlock, sbHeader.endBlock, sbHeader.blocksCount, TCrypto.ToHexaString(sbHeader.safeBoxHash), FromBlock, ToBlock])); // Read Source Offset zone posOffsetZoneSource := Source.Position; SetLength(offsetsSource, (sbHeader.endBlock - sbHeader.startBlock) + 2); Source.Read(offsetsSource[0], 4 * length(offsetsSource)); // DEST STREAM: // Init dest stream // Header zone SaveSafeBoxStreamHeader(dest, sbHeader.protocol, FromBlock, ToBlock, sbHeader.blocksCount); // Offsets zone posOffsetZoneDest := dest.Position; SetLength(raw, (destTotalBlocks + 1) * 4); // Cardinal = 4 bytes for each block + End position FillChar(raw[1], length(raw), 0); dest.WriteBuffer(raw[1], length(raw)); SetLength(offsetsDest, destTotalBlocks + 1); // Blocks zone posBlocksZoneDest := dest.Position; TLog.NewLog(ltInfo, Classname, Format('Copying Safebox Stream from source Position %d (size:%d) to dest %d bytes - OffsetSource[%d] - OffsetSource[%d]', [posOffsetZoneSource + offsetsSource[FromBlock - sbHeader.startBlock], Source.Size, offsetsSource[ToBlock - sbHeader.startBlock + 1] - offsetsSource[FromBlock - sbHeader.startBlock], ToBlock - sbHeader.startBlock + 1, FromBlock - sbHeader.startBlock])); Source.Position := posOffsetZoneSource + offsetsSource[FromBlock - sbHeader.startBlock]; dest.CopyFrom(Source, offsetsSource[ToBlock - sbHeader.startBlock + 1] - offsetsSource[FromBlock - sbHeader.startBlock]); // Save offsets zone with valid values posFinal := dest.Position; dest.Position := posOffsetZoneDest; for iblock := FromBlock to ToBlock do begin offsetsDest[iblock - FromBlock] := offsetsSource[iblock - (sbHeader.startBlock)] - offsetsSource[FromBlock - sbHeader.startBlock] + (posBlocksZoneDest - posOffsetZoneDest); end; offsetsDest[high(offsetsDest)] := posFinal - posOffsetZoneDest; dest.WriteBuffer(offsetsDest[0], length(offsetsDest) * 4); dest.Position := posFinal; Source.Position := offsetsSource[High(offsetsSource)] + posOffsetZoneSource; TStreamOp.ReadAnsiString(Source, raw); TStreamOp.WriteAnsiString(dest, raw); Result := true; finally Source.Position := posInitial; end; end; class function TPCSafeBox.ConcatSafeBoxStream(Source1, Source2, dest: TStream; var errors: AnsiString): Boolean; function MinCardinal(v1, v2: Cardinal): Cardinal; begin if v1 < v2 then Result := v1 else Result := v2; end; function MaxCardinal(v1, v2: Cardinal): Cardinal; begin if v1 > v2 then Result := v1 else Result := v2; end; function ReadSafeBoxBlockFromStream(safeBoxStream: TStream; offsetIndex: Cardinal; destStream: TStream): Cardinal; // PRE: safeBoxStream is a valid SafeBox Stream (with enough size) located at Offsets zone, and offsetIndex is >=0 and <= end block // Returns the size of the saved block at destStream var offsetPos, auxPos: Int64; c, cNext: Cardinal; begin Result := 0; offsetPos := safeBoxStream.Position; try safeBoxStream.Seek(4 * offsetIndex, soFromCurrent); safeBoxStream.Read(c, 4); safeBoxStream.Read(cNext, 4); if cNext < c then exit; Result := cNext - c; // Result is the offset difference between blocks if Result <= 0 then exit; auxPos := offsetPos + c; if safeBoxStream.Size < auxPos + Result then exit; // Invalid safeBoxStream.Position := auxPos; destStream.CopyFrom(safeBoxStream, Result); finally safeBoxStream.Position := offsetPos; end; end; procedure WriteSafeBoxBlockToStream(stream, safeBoxStream: TStream; nBytes: Integer; offsetIndex, totalOffsets: Cardinal); // PRE: safeBoxStream is a valid SafeBox Stream located at Offsets zone, and offsetIndex=0 or offsetIndex-1 has a valid value var offsetPos: Int64; c, cLength: Cardinal; begin offsetPos := safeBoxStream.Position; try if offsetIndex = 0 then begin // First c := ((totalOffsets + 1) * 4); safeBoxStream.Write(c, 4); end else begin safeBoxStream.Seek(4 * (offsetIndex), soFromCurrent); safeBoxStream.Read(c, 4); // c is position end; cLength := c + nBytes; safeBoxStream.Write(cLength, 4); safeBoxStream.Position := offsetPos + c; safeBoxStream.CopyFrom(stream, nBytes); finally safeBoxStream.Position := offsetPos; end; end; Var destStartBlock, destEndBlock, nBlock: Cardinal; source1InitialPos, source2InitialPos, destOffsetPos: Int64; ms: TMemoryStream; c: Cardinal; destOffsets: TCardinalsArray; i: Integer; s1Header, s2Header: TPCSafeBoxHeader; begin Result := false; errors := ''; source1InitialPos := Source1.Position; source2InitialPos := Source2.Position; Try If not LoadSafeBoxStreamHeader(Source1, s1Header) then begin errors := 'Invalid source 1 stream. Invalid header/version'; exit; end; If not LoadSafeBoxStreamHeader(Source2, s2Header) then begin errors := 'Invalid source 2 stream. Invalid header/version'; exit; end; // Check SBH and blockcount if (s1Header.safeBoxHash <> s2Header.safeBoxHash) or (s1Header.blocksCount <> s2Header.blocksCount) Or (s1Header.protocol <> s2Header.protocol) then begin errors := Format('Source1 and Source2 have diff safebox. Source 1 %d %s (protocol %d) Source 2 %d %s (protocol %d)', [s1Header.blocksCount, TCrypto.ToHexaString(s1Header.safeBoxHash), s1Header.protocol, s2Header.blocksCount, TCrypto.ToHexaString(s2Header.safeBoxHash), s2Header.protocol]); exit; end; // Save dest heaer destStartBlock := MinCardinal(s1Header.startBlock, s2Header.startBlock); destEndBlock := MaxCardinal(s1Header.endBlock, s2Header.endBlock); SaveSafeBoxStreamHeader(dest, s1Header.protocol, destStartBlock, destEndBlock, s1Header.blocksCount); // Save offsets destOffsetPos := dest.Position; SetLength(destOffsets, ((destEndBlock - destStartBlock) + 2)); for i := low(destOffsets) to high(destOffsets) do destOffsets[i] := 0; dest.Write(destOffsets[0], ((destEndBlock - destStartBlock) + 2) * 4); dest.Position := destOffsetPos; // nBlock := destStartBlock; ms := TMemoryStream.Create; try for nBlock := destStartBlock to destEndBlock do begin ms.Clear; if (nBlock >= s1Header.startBlock) And (nBlock <= s1Header.endBlock) then begin c := ReadSafeBoxBlockFromStream(Source1, nBlock - s1Header.startBlock, ms); ms.Position := 0; WriteSafeBoxBlockToStream(ms, dest, c, nBlock - destStartBlock, destEndBlock - destStartBlock + 1); end else if (nBlock >= s2Header.startBlock) and (nBlock <= s2Header.endBlock) then begin c := ReadSafeBoxBlockFromStream(Source2, nBlock - s2Header.startBlock, ms); ms.Position := 0; WriteSafeBoxBlockToStream(ms, dest, c, nBlock - destStartBlock, destEndBlock - destStartBlock + 1); end else Raise Exception.Create('ERROR DEV 20170518-1'); end; Finally ms.Free; end; // Save SafeBoxHash at the end dest.Seek(0, soFromEnd); TStreamOp.WriteAnsiString(dest, s1Header.safeBoxHash); Result := true; Finally Source1.Position := source1InitialPos; Source2.Position := source2InitialPos; end; end; class function TPCSafeBox.ValidAccountName(const new_name: TRawBytes; var errors: AnsiString): Boolean; { Note: This function is case senstive, and only lower case chars are valid. Execute a LowerCase() prior to call this function! } Const CT_PascalCoin_Base64_Charset: ShortString = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+{}[]\_:"|<>,.?/~'; // First char can't start with a number CT_PascalCoin_FirstChar_Charset: ShortString = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+{}[]\_:"|<>,.?/~'; CT_PascalCoin_name_min_length = 3; CT_PascalCoin_name_max_length = 64; var i, j: Integer; begin Result := false; errors := ''; if (length(new_name) < CT_PascalCoin_name_min_length) Or (length(new_name) > CT_PascalCoin_name_max_length) then begin errors := 'Invalid length:' + inttostr(length(new_name)) + ' (valid from ' + inttostr(CT_PascalCoin_name_max_length) + ' to ' + inttostr(CT_PascalCoin_name_max_length) + ')'; exit; end; for i := 1 to length(new_name) do begin j := 1; if (i = 1) then begin // First char can't start with a number While (j <= length(CT_PascalCoin_FirstChar_Charset)) and (new_name[i] <> CT_PascalCoin_FirstChar_Charset[j]) do inc(j); if j > length(CT_PascalCoin_FirstChar_Charset) then begin errors := 'Invalid char ' + new_name[i] + ' at first pos'; exit; // Not found end; end else begin While (j <= length(CT_PascalCoin_Base64_Charset)) and (new_name[i] <> CT_PascalCoin_Base64_Charset[j]) do inc(j); if j > length(CT_PascalCoin_Base64_Charset) then begin errors := 'Invalid char ' + new_name[i] + ' at pos ' + inttostr(i); exit; // Not found end; end; end; Result := true; end; function TPCSafeBox.IsValidNewOperationsBlock(const newOperationBlock: TOperationBlock; checkSafeBoxHash: Boolean; var errors: AnsiString): Boolean; { This function will check a OperationBlock info as a valid candidate to be included in the safebox TOperationBlock contains the info of the new block EXCEPT the operations, including only operations_hash value (SHA256 of the Operations) So, cannot check operations and fee values } var target_hash, PoW: TRawBytes; i: Integer; lastBlock: TOperationBlock; begin Result := false; errors := ''; If blocksCount > 0 then lastBlock := block(blocksCount - 1).blockchainInfo else lastBlock := CT_OperationBlock_NUL; // Check block if (blocksCount <> newOperationBlock.block) then begin errors := 'block (' + inttostr(newOperationBlock.block) + ') is not new position (' + inttostr(blocksCount) + ')'; exit; end; // Check Account key if Not TAccountComp.IsValidAccountKey(newOperationBlock.account_key, errors) then begin exit; end; // reward if (newOperationBlock.reward <> TPascalCoinProtocol.GetRewardForNewLine(newOperationBlock.block)) then begin errors := 'Invalid reward'; exit; end; // fee: Cannot be checked only with the safebox // protocol available is not checked if (newOperationBlock.block > 0) then begin // protocol if (newOperationBlock.protocol_version <> CurrentProtocol) then begin // Protocol must be 1 or 2. If 1 then all prior blocksmust be 1 and never 2 (invalide blockchain version scenario v1...v2...v1) If (lastBlock.protocol_version > newOperationBlock.protocol_version) then begin errors := 'Invalid PascalCoin protocol version: ' + inttostr(newOperationBlock.protocol_version) + ' Current: ' + inttostr(CurrentProtocol) + ' Previous:' + inttostr(lastBlock.protocol_version); exit; end; If (newOperationBlock.protocol_version = CT_PROTOCOL_2) then begin If (newOperationBlock.block < CT_Protocol_Upgrade_v2_MinBlock) then begin errors := 'Upgrade to protocol version 2 available at block: ' + inttostr(CT_Protocol_Upgrade_v2_MinBlock); exit; end; end else if (newOperationBlock.protocol_version <> CT_PROTOCOL_1) then begin errors := 'Invalid protocol version change to ' + inttostr(newOperationBlock.protocol_version); exit; end; end else if (Not(newOperationBlock.protocol_version in [CT_PROTOCOL_1, CT_PROTOCOL_2])) then begin errors := 'Invalid protocol version ' + inttostr(newOperationBlock.protocol_version); exit; end; // timestamp if ((newOperationBlock.timestamp) < (lastBlock.timestamp)) then begin errors := 'Invalid timestamp (Back timestamp: New timestamp:' + inttostr(newOperationBlock.timestamp) + ' < last timestamp (' + inttostr(blocksCount - 1) + '):' + inttostr(lastBlock.timestamp) + ')'; exit; end; end else begin if (CT_Zero_Block_Proof_of_work_in_Hexa <> '') then begin // Check if valid Zero block if Not(AnsiSameText(TCrypto.ToHexaString(newOperationBlock.proof_of_work), CT_Zero_Block_Proof_of_work_in_Hexa)) then begin errors := 'Zero block not valid, Proof of Work invalid: ' + TCrypto.ToHexaString(newOperationBlock.proof_of_work) + '<>' + CT_Zero_Block_Proof_of_work_in_Hexa; exit; end; end; end; // compact_target target_hash := GetActualTargetHash(newOperationBlock.protocol_version = CT_PROTOCOL_2); if (newOperationBlock.compact_target <> TPascalCoinProtocol.TargetToCompact(target_hash)) then begin errors := 'Invalid target found:' + IntToHex(newOperationBlock.compact_target, 8) + ' actual:' + IntToHex(TPascalCoinProtocol.TargetToCompact(target_hash), 8); exit; end; // nonce: Not checked // block_payload: Checking Miner payload size if length(newOperationBlock.block_payload) > CT_MaxPayloadSize then begin errors := 'Invalid Miner Payload length: ' + inttostr(length(newOperationBlock.block_payload)); exit; end; // Checking Miner Payload valid chars for i := 1 to length(newOperationBlock.block_payload) do begin if Not(newOperationBlock.block_payload[i] in [#32 .. #254]) then begin errors := 'Invalid Miner Payload character at pos ' + inttostr(i) + ' value:' + inttostr(ord(newOperationBlock.block_payload[i])); exit; end; end; // initial_safe_box_hash: Only can be checked when adding new blocks, not when restoring a safebox If checkSafeBoxHash then begin // TODO: Can use FSafeBoxHash instead of CalcSafeBoxHash ???? Quick speed if possible if (newOperationBlock.initial_safe_box_hash <> CalcSafeBoxHash) then begin errors := 'BlockChain Safe box hash invalid: ' + TCrypto.ToHexaString(newOperationBlock.initial_safe_box_hash) + ' var: ' + TCrypto.ToHexaString(FSafeBoxHash) + ' Calculated:' + TCrypto.ToHexaString(CalcSafeBoxHash); exit; end; end; // operations_hash: NOT CHECKED WITH OPERATIONS! If (length(newOperationBlock.operations_hash) <> 32) then begin errors := 'Invalid Operations hash value: ' + TCrypto.ToHexaString(newOperationBlock.operations_hash) + ' length=' + inttostr(length(newOperationBlock.operations_hash)); exit; end; // proof_of_work: TPascalCoinProtocol.CalcProofOfWork(newOperationBlock, PoW); if (PoW <> newOperationBlock.proof_of_work) then begin errors := 'Proof of work is bad calculated ' + TCrypto.ToHexaString(newOperationBlock.proof_of_work) + ' <> Good: ' + TCrypto.ToHexaString(PoW); exit; end; if (newOperationBlock.proof_of_work > target_hash) then begin errors := 'Proof of work is higher than target ' + TCrypto.ToHexaString(newOperationBlock.proof_of_work) + ' > ' + TCrypto.ToHexaString(target_hash); exit; end; Result := true; end; function TPCSafeBox.GetActualTargetHash(UseProtocolV2: Boolean): TRawBytes; { Target is calculated in each block with avg obtained in previous CT_CalcNewDifficulty blocks. If Block is lower than CT_CalcNewDifficulty then is calculated with all previous blocks. } Var ts1, ts2, tsTeorical, tsReal, tsTeoricalStop, tsRealStop: Int64; CalcBack: Integer; lastBlock: TOperationBlock; begin if (blocksCount <= 1) then begin // Important: CT_MinCompactTarget is applied for blocks 0 until ((CT_CalcNewDifficulty*2)-1) Result := TPascalCoinProtocol.TargetFromCompact(CT_MinCompactTarget); end else begin if blocksCount > CT_CalcNewTargetBlocksAverage then CalcBack := CT_CalcNewTargetBlocksAverage else CalcBack := blocksCount - 1; lastBlock := block(blocksCount - 1).blockchainInfo; // Calc new target! ts1 := lastBlock.timestamp; ts2 := block(blocksCount - CalcBack - 1).blockchainInfo.timestamp; tsTeorical := (CalcBack * CT_NewLineSecondsAvg); tsReal := (ts1 - ts2); If (Not UseProtocolV2) then begin Result := TPascalCoinProtocol.GetNewTarget(tsTeorical, tsReal, TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target)); end else begin CalcBack := CalcBack DIV CT_CalcNewTargetLimitChange_SPLIT; If CalcBack = 0 then CalcBack := 1; ts2 := block(blocksCount - CalcBack - 1).blockchainInfo.timestamp; tsTeoricalStop := (CalcBack * CT_NewLineSecondsAvg); tsRealStop := (ts1 - ts2); { Protocol 2 change: Only will increase/decrease Target if (CT_CalcNewTargetBlocksAverage DIV 10) needs to increase/decrease too, othewise use current Target. This will prevent sinusoidal movement and provide more stable hashrate, computing always time from CT_CalcNewTargetBlocksAverage } If ((tsTeorical > tsReal) and (tsTeoricalStop > tsRealStop)) Or ((tsTeorical < tsReal) and (tsTeoricalStop < tsRealStop)) then begin Result := TPascalCoinProtocol.GetNewTarget(tsTeorical, tsReal, TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target)); end else begin // Nothing to do! Result := TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target); end; end; end; end; function TPCSafeBox.GetActualCompactTargetHash(UseProtocolV2: Boolean): Cardinal; begin Result := TPascalCoinProtocol.TargetToCompact(GetActualTargetHash(UseProtocolV2)); end; function TPCSafeBox.FindAccountByName(aName: AnsiString): Integer; Var nameLower: AnsiString; i: Integer; begin nameLower := LowerCase(aName); i := FOrderedByName.IndexOf(aName); if i >= 0 then Result := FOrderedByName.GetTag(i) else Result := -1; end; procedure TPCSafeBox.SetAccount(account_number: Cardinal; const newAccountInfo: TAccountInfo; const newName: TRawBytes; newType: Word; newBalance: UInt64; newN_operation: Cardinal); Var iblock: Cardinal; i, j, iAccount: Integer; lastbalance: UInt64; acc: TAccount; bacc: TBlockAccount; P: PBlockAccount; begin iblock := account_number DIV CT_AccountsPerBlock; iAccount := account_number MOD CT_AccountsPerBlock; acc := account(account_number); P := FBlockAccountsList.Items[iblock]; if (NOT TAccountComp.EqualAccountKeys(acc.accountInfo.accountKey, newAccountInfo.accountKey)) then begin AccountKeyListRemoveAccount(acc.accountInfo.accountKey, [account_number]); AccountKeyListAddAccounts(newAccountInfo.accountKey, [account_number]); end; acc.accountInfo := newAccountInfo; // Name: If acc.name <> newName then begin If acc.name <> '' then begin i := FOrderedByName.IndexOf(acc.name); if i < 0 then TLog.NewLog(lterror, Classname, 'ERROR DEV 20170606-1') else FOrderedByName.Delete(i); end; acc.name := newName; If acc.name <> '' then begin i := FOrderedByName.IndexOf(acc.name); if i >= 0 then TLog.NewLog(lterror, Classname, 'ERROR DEV 20170606-2') else FOrderedByName.Add(acc.name, account_number); end; end; acc.account_type := newType; lastbalance := acc.balance; acc.balance := newBalance; // Will update previous_updated_block only on first time/block If acc.updated_block <> blocksCount then begin acc.previous_updated_block := acc.updated_block; acc.updated_block := blocksCount; end; acc.n_operation := newN_operation; // Save new account values ToTMemAccount(acc, P^.accounts[iAccount]); // Update block_hash bacc := block(iblock); {$IFDEF uselowmem} TBaseType.To32Bytes(CalcBlockHash(bacc, FCurrentProtocol >= CT_PROTOCOL_2), P^.block_hash); {$ELSE} P^.block_hash := CalcBlockHash(bacc, FCurrentProtocol >= CT_PROTOCOL_2); {$ENDIF} // Update buffer block hash j := (length(P^.block_hash) * (iblock)); for i := 1 to length(P^.block_hash) do begin {$IFDEF FPC} FBufferBlocksHash[i + j] := AnsiChar(P^.block_hash[i - (low(FBufferBlocksHash) - low(P^.block_hash))]); {$ELSE} FBufferBlocksHash[i + j] := AnsiChar(P^.block_hash[i - {$IFDEF uselowmem}1{$ELSE}0{$ENDIF}]); {$ENDIF} end; FTotalBalance := FTotalBalance - (Int64(lastbalance) - Int64(newBalance)); FTotalFee := FTotalFee + (Int64(lastbalance) - Int64(newBalance)); end; procedure TPCSafeBox.StartThreadSafe; begin TPCThread.ProtectEnterCriticalSection(Self, FLock); end; { TPCSafeBoxTransaction } function TPCSafeBoxTransaction.account(account_number: Cardinal): TAccount; Var i: Integer; begin if FOrderedList.Find(account_number, i) then Result := PAccount(FOrderedList.FList[i])^ else begin Result := FreezedSafeBox.account(account_number); end; end; function TPCSafeBoxTransaction.BuyAccount(buyer, account_to_buy, seller: Cardinal; n_operation: Cardinal; amount, account_price, fee: UInt64; const new_account_key: TAccountKey; var errors: AnsiString): Boolean; Var PaccBuyer, PaccAccountToBuy, PaccSeller: PAccount; begin Result := false; errors := ''; if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction'; exit; end; if (buyer < 0) Or (buyer >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) Or (account_to_buy < 0) Or (account_to_buy >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) Or (seller < 0) Or (seller >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) then begin errors := 'Invalid account number on buy'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(buyer, FFreezedAccounts.blocksCount) then begin errors := 'Buyer account is blocked for protocol'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(account_to_buy, FFreezedAccounts.blocksCount) then begin errors := 'Account to buy is blocked for protocol'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(seller, FFreezedAccounts.blocksCount) then begin errors := 'Seller account is blocked for protocol'; exit; end; PaccBuyer := GetInternalAccount(buyer); PaccAccountToBuy := GetInternalAccount(account_to_buy); PaccSeller := GetInternalAccount(seller); if (PaccBuyer^.n_operation + 1 <> n_operation) then begin errors := 'Incorrect n_operation'; exit; end; if (PaccBuyer^.balance < (amount + fee)) then begin errors := 'Insuficient founds'; exit; end; if (fee > CT_MaxTransactionFee) then begin errors := 'Max fee'; exit; end; if (TAccountComp.IsAccountLocked(PaccBuyer^.accountInfo, FFreezedAccounts.blocksCount)) then begin errors := 'Buyer account is locked until block ' + inttostr(PaccBuyer^.accountInfo.locked_until_block); exit; end; If not(TAccountComp.IsAccountForSale(PaccAccountToBuy^.accountInfo)) then begin errors := 'Account is not for sale'; exit; end; if (PaccAccountToBuy^.accountInfo.new_publicKey.EC_OpenSSL_NID <> CT_TECDSA_Public_Nul.EC_OpenSSL_NID) And (Not TAccountComp.EqualAccountKeys(PaccAccountToBuy^.accountInfo.new_publicKey, new_account_key)) then begin errors := 'New public key is not equal to allowed new public key for account'; exit; end; // Buy an account applies when account_to_buy.amount + operation amount >= price // Then, account_to_buy.amount will be (account_to_buy.amount + amount - price) // and buyer.amount will be buyer.amount + price if (PaccAccountToBuy^.accountInfo.price > (PaccAccountToBuy^.balance + amount)) then begin errors := 'Account price ' + TAccountComp.FormatMoney(PaccAccountToBuy^.accountInfo.price) + ' < balance ' + TAccountComp.FormatMoney(PaccAccountToBuy^.balance) + ' + amount ' + TAccountComp.FormatMoney(amount); exit; end; If PaccBuyer^.updated_block <> FFreezedAccounts.blocksCount then begin PaccBuyer^.previous_updated_block := PaccBuyer^.updated_block; PaccBuyer^.updated_block := FFreezedAccounts.blocksCount; end; If PaccAccountToBuy^.updated_block <> FFreezedAccounts.blocksCount then begin PaccAccountToBuy^.previous_updated_block := PaccAccountToBuy^.updated_block; PaccAccountToBuy^.updated_block := FFreezedAccounts.blocksCount; end; If PaccSeller^.updated_block <> FFreezedAccounts.blocksCount then begin PaccSeller^.previous_updated_block := PaccSeller^.updated_block; PaccSeller^.updated_block := FFreezedAccounts.blocksCount; end; // Inc buyer n_operation PaccBuyer^.n_operation := n_operation; // Set new balance values PaccBuyer^.balance := PaccBuyer^.balance - (amount + fee); PaccAccountToBuy^.balance := PaccAccountToBuy^.balance + amount - PaccAccountToBuy^.accountInfo.price; PaccSeller^.balance := PaccSeller^.balance + PaccAccountToBuy^.accountInfo.price; // After buy, account will be unlocked and set to normal state and new account public key changed PaccAccountToBuy^.accountInfo := CT_AccountInfo_NUL; PaccAccountToBuy^.accountInfo.state := as_Normal; PaccAccountToBuy^.accountInfo.accountKey := new_account_key; Dec(FTotalBalance, fee); inc(FTotalFee, fee); Result := true; end; function TPCSafeBoxTransaction.CheckIntegrity: Boolean; begin Result := FOldSafeBoxHash = FFreezedAccounts.FSafeBoxHash; end; procedure TPCSafeBoxTransaction.CleanTransaction; begin FOrderedList.Clear; FOldSafeBoxHash := FFreezedAccounts.FSafeBoxHash; FTotalBalance := FFreezedAccounts.FTotalBalance; FTotalFee := 0; FAccountNames_Added.Clear; FAccountNames_Deleted.Clear; end; function TPCSafeBoxTransaction.Commit(const operationBlock: TOperationBlock; var errors: AnsiString): Boolean; Var i, j: Integer; b: TBlockAccount; Pa: PAccount; begin Result := false; errors := ''; FFreezedAccounts.StartThreadSafe; try if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction on commit'; exit; end; for i := 0 to FOrderedList.FList.Count - 1 do begin Pa := PAccount(FOrderedList.FList[i]); FFreezedAccounts.SetAccount(Pa^.account, Pa^.accountInfo, Pa^.name, Pa^.account_type, Pa^.balance, Pa^.n_operation); end; // if (FFreezedAccounts.TotalBalance <> FTotalBalance) then begin TLog.NewLog(lterror, Classname, Format('Invalid integrity balance! StrongBox:%d Transaction:%d', [FFreezedAccounts.TotalBalance, FTotalBalance])); end; if (FFreezedAccounts.FTotalFee <> FTotalFee) then begin TLog.NewLog(lterror, Classname, Format('Invalid integrity fee! StrongBox:%d Transaction:%d', [FFreezedAccounts.FTotalFee, FTotalFee])); end; b := FFreezedAccounts.AddNew(operationBlock); if (b.accounts[0].balance <> (operationBlock.reward + FTotalFee)) then begin TLog.NewLog(lterror, Classname, Format('Invalid integrity reward! Account:%d Balance:%d Reward:%d Fee:%d (Reward+Fee:%d)', [b.accounts[0].account, b.accounts[0].balance, operationBlock.reward, FTotalFee, operationBlock.reward + FTotalFee])); end; CleanTransaction; // if (FFreezedAccounts.FCurrentProtocol < CT_PROTOCOL_2) And (operationBlock.protocol_version = CT_PROTOCOL_2) then begin // First block with new protocol! if FFreezedAccounts.CanUpgradeToProtocol2 then begin TLog.NewLog(ltInfo, Classname, 'Protocol upgrade to v2'); If not FFreezedAccounts.DoUpgradeToProtocol2 then begin raise Exception.Create('Cannot upgrade to protocol v2 !'); end; end; end; Result := true; finally FFreezedAccounts.EndThreadSave; end; end; procedure TPCSafeBoxTransaction.CopyFrom(transaction: TPCSafeBoxTransaction); Var i: Integer; P: PAccount; begin if transaction = Self then exit; if transaction.FFreezedAccounts <> FFreezedAccounts then raise Exception.Create('Invalid Freezed accounts to copy'); CleanTransaction; for i := 0 to transaction.FOrderedList.FList.Count - 1 do begin P := PAccount(transaction.FOrderedList.FList[i]); FOrderedList.Add(P^); end; FOldSafeBoxHash := transaction.FOldSafeBoxHash; FTotalBalance := transaction.FTotalBalance; FTotalFee := transaction.FTotalFee; end; constructor TPCSafeBoxTransaction.Create(SafeBox: TPCSafeBox); begin FOrderedList := TOrderedAccountList.Create; FFreezedAccounts := SafeBox; FOldSafeBoxHash := SafeBox.FSafeBoxHash; FTotalBalance := FFreezedAccounts.FTotalBalance; FTotalFee := 0; FAccountNames_Added := TOrderedRawList.Create; FAccountNames_Deleted := TOrderedRawList.Create; end; destructor TPCSafeBoxTransaction.Destroy; begin CleanTransaction; FreeAndNil(FOrderedList); FreeAndNil(FAccountNames_Added); FreeAndNil(FAccountNames_Deleted); inherited; end; function TPCSafeBoxTransaction.GetInternalAccount(account_number: Cardinal): PAccount; Var i: Integer; P: PAccount; begin if FOrderedList.Find(account_number, i) then Result := PAccount(FOrderedList.FList[i]) else begin i := FOrderedList.Add(FreezedSafeBox.account(account_number)); Result := PAccount(FOrderedList.FList[i]); end; end; function TPCSafeBoxTransaction.Modified(index: Integer): TAccount; begin Result := FOrderedList.Get(index); end; function TPCSafeBoxTransaction.ModifiedCount: Integer; begin Result := FOrderedList.Count; end; procedure TPCSafeBoxTransaction.Rollback; begin CleanTransaction; end; function TPCSafeBoxTransaction.TransferAmount(Sender, target: Cardinal; n_operation: Cardinal; amount, fee: UInt64; var errors: AnsiString): Boolean; Var intSender, intTarget: Integer; PaccSender, PaccTarget: PAccount; begin Result := false; errors := ''; if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction'; exit; end; if (Sender < 0) Or (Sender >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) Or (target < 0) Or (target >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) then begin errors := 'Invalid sender or target on transfer'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(Sender, FFreezedAccounts.blocksCount) then begin errors := 'Sender account is blocked for protocol'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(target, FFreezedAccounts.blocksCount) then begin errors := 'Target account is blocked for protocol'; exit; end; PaccSender := GetInternalAccount(Sender); PaccTarget := GetInternalAccount(target); if (PaccSender^.n_operation + 1 <> n_operation) then begin errors := 'Incorrect n_operation'; exit; end; if (PaccSender^.balance < (amount + fee)) then begin errors := 'Insuficient founds'; exit; end; if ((PaccTarget^.balance + amount) > CT_MaxWalletAmount) then begin errors := 'Max account balance'; exit; end; if (fee > CT_MaxTransactionFee) then begin errors := 'Max fee'; exit; end; if (TAccountComp.IsAccountLocked(PaccSender^.accountInfo, FFreezedAccounts.blocksCount)) then begin errors := 'Sender account is locked until block ' + inttostr(PaccSender^.accountInfo.locked_until_block); exit; end; If PaccSender^.updated_block <> FFreezedAccounts.blocksCount then begin PaccSender^.previous_updated_block := PaccSender^.updated_block; PaccSender^.updated_block := FFreezedAccounts.blocksCount; end; If PaccTarget^.updated_block <> FFreezedAccounts.blocksCount then begin PaccTarget^.previous_updated_block := PaccTarget.updated_block; PaccTarget^.updated_block := FFreezedAccounts.blocksCount; end; PaccSender^.n_operation := n_operation; PaccSender^.balance := PaccSender^.balance - (amount + fee); PaccTarget^.balance := PaccTarget^.balance + (amount); Dec(FTotalBalance, fee); inc(FTotalFee, fee); Result := true; end; function TPCSafeBoxTransaction.UpdateAccountInfo(signer_account, signer_n_operation, target_account: Cardinal; accountInfo: TAccountInfo; newName: TRawBytes; newType: Word; fee: UInt64; var errors: AnsiString): Boolean; Var i: Integer; P_signer, P_target: PAccount; begin Result := false; errors := ''; if (signer_account < 0) Or (signer_account >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) Or (target_account < 0) Or (target_account >= (FFreezedAccounts.blocksCount * CT_AccountsPerBlock)) Then begin errors := 'Invalid account'; exit; end; if (TAccountComp.IsAccountBlockedByProtocol(signer_account, FFreezedAccounts.blocksCount)) Or (TAccountComp.IsAccountBlockedByProtocol(target_account, FFreezedAccounts.blocksCount)) then begin errors := 'account is blocked for protocol'; exit; end; P_signer := GetInternalAccount(signer_account); P_target := GetInternalAccount(target_account); if (P_signer^.n_operation + 1 <> signer_n_operation) then begin errors := 'Incorrect n_operation'; exit; end; if (P_signer^.balance < fee) then begin errors := 'Insuficient founds'; exit; end; if (TAccountComp.IsAccountLocked(P_signer^.accountInfo, FFreezedAccounts.blocksCount)) then begin errors := 'Signer account is locked until block ' + inttostr(P_signer^.accountInfo.locked_until_block); exit; end; if (TAccountComp.IsAccountLocked(P_target^.accountInfo, FFreezedAccounts.blocksCount)) then begin errors := 'Target account is locked until block ' + inttostr(P_target^.accountInfo.locked_until_block); exit; end; if P_signer^.updated_block <> FFreezedAccounts.blocksCount then begin P_signer^.previous_updated_block := P_signer^.updated_block; P_signer^.updated_block := FFreezedAccounts.blocksCount; end; if (signer_account <> target_account) then begin if P_target^.updated_block <> FFreezedAccounts.blocksCount then begin P_target^.previous_updated_block := P_target^.updated_block; P_target^.updated_block := FFreezedAccounts.blocksCount; end; end; if Not TAccountComp.EqualAccountKeys(P_signer^.accountInfo.accountKey, P_target^.accountInfo.accountKey) then begin errors := 'Signer and target have diff key'; exit; end; if (newName <> P_target^.name) then begin // NEW NAME CHANGE CHECK: if (newName <> '') then begin If Not FFreezedAccounts.ValidAccountName(newName, errors) then begin errors := 'Invalid account name "' + newName + '" length:' + inttostr(length(newName)) + ': ' + errors; exit; end; i := FFreezedAccounts.FindAccountByName(newName); if (i >= 0) then begin // This account name is in the safebox... check if deleted: i := FAccountNames_Deleted.IndexOf(newName); if i < 0 then begin errors := 'Account name "' + newName + '" is in current use'; exit; end; end; i := FAccountNames_Added.IndexOf(newName); if (i >= 0) then begin // This account name is added in this transaction! (perhaps deleted also, but does not allow to "double add same name in same block") errors := 'Account name "' + newName + '" is in same transaction'; exit; end; end; // Ok, include if (P_target^.name <> '') then begin // In use in the safebox, mark as deleted FAccountNames_Deleted.Add(P_target^.name, target_account); end; if (newName <> '') then begin FAccountNames_Added.Add(newName, target_account); end; end; P_signer^.n_operation := signer_n_operation; P_target^.accountInfo := accountInfo; P_target^.name := newName; P_target^.account_type := newType; Dec(P_signer^.balance, fee); // Signer is who pays the fee Dec(FTotalBalance, fee); inc(FTotalFee, fee); Result := true; end; { TOrderedAccountList } Function TOrderedAccountList.Add(const account: TAccount): Integer; Var P: PAccount; begin if Find(account.account, Result) then begin PAccount(FList[Result])^ := account; end else begin New(P); P^ := account; FList.Insert(Result, P); end; end; procedure TOrderedAccountList.Clear; Var i: Integer; P: PAccount; begin for i := 0 to FList.Count - 1 do begin P := FList[i]; Dispose(P); end; FList.Clear; end; function TOrderedAccountList.Count: Integer; begin Result := FList.Count; end; constructor TOrderedAccountList.Create; begin FList := TList.Create; end; destructor TOrderedAccountList.Destroy; begin Clear; FreeAndNil(FList); inherited; end; function TOrderedAccountList.Find(const account_number: Cardinal; var index: Integer): Boolean; var l, H, i: Integer; c: Int64; begin Result := false; l := 0; H := FList.Count - 1; while l <= H do begin i := (l + H) shr 1; c := Int64(PAccount(FList[i]).account) - Int64(account_number); if c < 0 then l := i + 1 else begin H := i - 1; if c = 0 then begin Result := true; l := i; end; end; end; Index := l; end; function TOrderedAccountList.Get(index: Integer): TAccount; begin Result := PAccount(FList.Items[index])^; end; { TOrderedAccountKeysList } Type TOrderedAccountKeyList = Record rawaccountkey: TRawBytes; accounts_number: TOrderedCardinalList; end; POrderedAccountKeyList = ^TOrderedAccountKeyList; function SortOrdered(Item1, Item2: Pointer): Integer; begin Result := PtrInt(Item1) - PtrInt(Item2); end; procedure TOrderedAccountKeysList.AddAccountKey(const accountKey: TAccountKey); Var P: POrderedAccountKeyList; i, j: Integer; begin if Not Find(accountKey, i) then begin New(P); P^.rawaccountkey := TAccountComp.AccountKey2RawString(accountKey); P^.accounts_number := TOrderedCardinalList.Create; FOrderedAccountKeysList.Insert(i, P); // Search this key in the AccountsList and add all... j := 0; if Assigned(FAccountList) then begin For i := 0 to FAccountList.AccountsCount - 1 do begin If TAccountComp.EqualAccountKeys(FAccountList.account(i).accountInfo.accountKey, accountKey) then begin // Note: P^.accounts will be ascending ordered due to "for i:=0 to ..." P^.accounts_number.Add(i); end; end; TLog.NewLog(ltDebug, Classname, Format('Adding account key (%d of %d) %s', [j, FAccountList.AccountsCount, TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(accountKey))])); end else begin TLog.NewLog(ltDebug, Classname, Format('Adding account key (no Account List) %s', [TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(accountKey))])); end; end; end; procedure TOrderedAccountKeysList.AddAccounts(const accountKey: TAccountKey; const accounts: array of Cardinal); Var P: POrderedAccountKeyList; i, i2: Integer; begin if Find(accountKey, i) then begin P := POrderedAccountKeyList(FOrderedAccountKeysList[i]); end else if (FAutoAddAll) then begin New(P); P^.rawaccountkey := TAccountComp.AccountKey2RawString(accountKey); P^.accounts_number := TOrderedCardinalList.Create; FOrderedAccountKeysList.Insert(i, P); end else exit; for i := Low(accounts) to High(accounts) do begin P^.accounts_number.Add(accounts[i]); end; end; procedure TOrderedAccountKeysList.Clear; begin ClearAccounts(true); end; procedure TOrderedAccountKeysList.ClearAccounts(RemoveAccountList: Boolean); Var P: POrderedAccountKeyList; i: Integer; begin for i := 0 to FOrderedAccountKeysList.Count - 1 do begin P := FOrderedAccountKeysList[i]; if RemoveAccountList then begin P^.accounts_number.Free; Dispose(P); end else begin P^.accounts_number.Clear; end; end; if RemoveAccountList then begin FOrderedAccountKeysList.Clear; end; end; function TOrderedAccountKeysList.Count: Integer; begin Result := FOrderedAccountKeysList.Count; end; constructor TOrderedAccountKeysList.Create(AccountList: TPCSafeBox; AutoAddAll: Boolean); Var i: Integer; begin TLog.NewLog(ltDebug, Classname, 'Creating an Ordered Account Keys List adding all:' + CT_TRUE_FALSE[AutoAddAll]); FAutoAddAll := AutoAddAll; FAccountList := AccountList; FOrderedAccountKeysList := TList.Create; if Assigned(AccountList) then begin AccountList.FListOfOrderedAccountKeysList.Add(Self); if AutoAddAll then begin for i := 0 to AccountList.AccountsCount - 1 do begin AddAccountKey(AccountList.account(i).accountInfo.accountKey); end; end; end; end; destructor TOrderedAccountKeysList.Destroy; begin TLog.NewLog(ltDebug, Classname, 'Destroying an Ordered Account Keys List adding all:' + CT_TRUE_FALSE[FAutoAddAll]); if Assigned(FAccountList) then begin FAccountList.FListOfOrderedAccountKeysList.Remove(Self); end; ClearAccounts(true); FreeAndNil(FOrderedAccountKeysList); inherited; end; function TOrderedAccountKeysList.Find(const accountKey: TAccountKey; var index: Integer): Boolean; var l, H, i, c: Integer; rak: TRawBytes; begin Result := false; rak := TAccountComp.AccountKey2RawString(accountKey); l := 0; H := FOrderedAccountKeysList.Count - 1; while l <= H do begin i := (l + H) shr 1; c := CompareStr(POrderedAccountKeyList(FOrderedAccountKeysList[i]).rawaccountkey, rak); if c < 0 then l := i + 1 else begin H := i - 1; if c = 0 then begin Result := true; l := i; end; end; end; Index := l; end; function TOrderedAccountKeysList.GetAccountKey(index: Integer): TAccountKey; Var raw: TRawBytes; begin raw := POrderedAccountKeyList(FOrderedAccountKeysList[index]).rawaccountkey; Result := TAccountComp.RawString2Accountkey(raw); end; function TOrderedAccountKeysList.GetAccountKeyList(index: Integer): TOrderedCardinalList; begin Result := POrderedAccountKeyList(FOrderedAccountKeysList[index]).accounts_number; end; function TOrderedAccountKeysList.IndexOfAccountKey(const accountKey: TAccountKey): Integer; begin If Not Find(accountKey, Result) then Result := -1; end; procedure TOrderedAccountKeysList.RemoveAccounts(const accountKey: TAccountKey; const accounts: array of Cardinal); Var P: POrderedAccountKeyList; i, j: Integer; begin if Not Find(accountKey, i) then exit; // Nothing to do P := POrderedAccountKeyList(FOrderedAccountKeysList[i]); for j := Low(accounts) to High(accounts) do begin P^.accounts_number.Remove(accounts[j]); end; if (P^.accounts_number.Count = 0) And (FAutoAddAll) then begin // Remove from list FOrderedAccountKeysList.Delete(i); // Free it P^.accounts_number.Free; Dispose(P); end; end; procedure TOrderedAccountKeysList.RemoveAccountKey(const accountKey: TAccountKey); Var P: POrderedAccountKeyList; i, j: Integer; begin if Not Find(accountKey, i) then exit; // Nothing to do P := POrderedAccountKeyList(FOrderedAccountKeysList[i]); // Remove from list FOrderedAccountKeysList.Delete(i); // Free it P^.accounts_number.Free; Dispose(P); end; { TOrderedCardinalList } function TOrderedCardinalList.Add(Value: Cardinal): Integer; begin if Find(Value, Result) then exit else begin FOrderedList.Insert(Result, TObject(Value)); NotifyChanged; end; end; procedure TOrderedCardinalList.Clear; begin FOrderedList.Clear; NotifyChanged; end; procedure TOrderedCardinalList.CopyFrom(Sender: TOrderedCardinalList); Var i: Integer; begin if Self = Sender then exit; Disable; Try Clear; for i := 0 to Sender.Count - 1 do begin Add(Sender.Get(i)); end; Finally Enable; End; end; function TOrderedCardinalList.Count: Integer; begin Result := FOrderedList.Count; end; constructor TOrderedCardinalList.Create; begin FOrderedList := TList.Create; FDisabledsCount := 0; FModifiedWhileDisabled := false; end; destructor TOrderedCardinalList.Destroy; begin FOrderedList.Free; inherited; end; procedure TOrderedCardinalList.Disable; begin inc(FDisabledsCount); end; procedure TOrderedCardinalList.Enable; begin if FDisabledsCount <= 0 then raise Exception.Create('Dev error. Invalid disabled counter'); Dec(FDisabledsCount); if (FDisabledsCount = 0) And (FModifiedWhileDisabled) then NotifyChanged; end; function TOrderedCardinalList.Find(const Value: Cardinal; var index: Integer): Boolean; var l, H, i: Integer; c: Int64; begin Result := false; l := 0; H := FOrderedList.Count - 1; while l <= H do begin i := (l + H) shr 1; c := Int64(FOrderedList[i]) - Int64(Value); if c < 0 then l := i + 1 else begin H := i - 1; if c = 0 then begin Result := true; l := i; end; end; end; Index := l; end; function TOrderedCardinalList.Get(index: Integer): Cardinal; begin Result := Cardinal(FOrderedList[index]); end; procedure TOrderedCardinalList.NotifyChanged; begin if FDisabledsCount > 0 then begin FModifiedWhileDisabled := true; exit; end; FModifiedWhileDisabled := false; if Assigned(FOnListChanged) then FOnListChanged(Self); end; procedure TOrderedCardinalList.Remove(Value: Cardinal); Var i: Integer; begin if Find(Value, i) then begin FOrderedList.Delete(i); NotifyChanged; end; end; Function TOrderedCardinalList.ToArray: TCardinalsArray; var i: Integer; begin SetLength(Result, Self.Count); for i := 0 to Self.Count - 1 do Result[i] := Self.Get(i); end; { TOrderedRawList } Type TRawListData = Record RawData: TRawBytes; tag: Integer; End; PRawListData = ^TRawListData; function TOrderedRawList.Add(const RawData: TRawBytes; tagValue: Integer = 0): Integer; Var P: PRawListData; begin if Find(RawData, Result) then begin PRawListData(FList[Result])^.tag := tagValue; end else begin New(P); P^.RawData := RawData; P^.tag := tagValue; FList.Insert(Result, P); end; end; procedure TOrderedRawList.Clear; Var P: PRawListData; i: Integer; begin for i := FList.Count - 1 downto 0 do begin P := FList[i]; Dispose(P); end; FList.Clear; end; function TOrderedRawList.Count: Integer; begin Result := FList.Count; end; constructor TOrderedRawList.Create; begin FList := TList.Create; end; procedure TOrderedRawList.Delete(index: Integer); Var P: PRawListData; begin P := PRawListData(FList[index]); FList.Delete(index); Dispose(P); end; destructor TOrderedRawList.Destroy; begin Clear; FreeAndNil(FList); inherited; end; function TOrderedRawList.Find(const RawData: TRawBytes; var index: Integer): Boolean; var l, H, i: Integer; c: Integer; begin Result := false; l := 0; H := FList.Count - 1; while l <= H do begin i := (l + H) shr 1; c := BinStrComp(PRawListData(FList[i])^.RawData, RawData); if c < 0 then l := i + 1 else begin H := i - 1; if c = 0 then begin Result := true; l := i; end; end; end; Index := l; end; function TOrderedRawList.Get(index: Integer): TRawBytes; begin Result := PRawListData(FList[index])^.RawData; end; function TOrderedRawList.GetTag(index: Integer): Integer; begin Result := PRawListData(FList[index])^.tag; end; function TOrderedRawList.GetTag(const RawData: TRawBytes): Integer; Var i: Integer; begin if Not Find(RawData, i) then begin Result := 0; end else begin Result := PRawListData(FList[i])^.tag; end; end; function TOrderedRawList.IndexOf(const RawData: TRawBytes): Integer; begin if Not Find(RawData, Result) then Result := -1; end; procedure TOrderedRawList.SetTag(const RawData: TRawBytes; newTagValue: Integer); begin Add(RawData, newTagValue); end; end.
program labEX6; uses graph,crt; const Triangle: Array [1..32] of PointType = ((X: 50; Y: 50), (X: 100; Y:50), (X: 100; Y: 80), (X: 200; Y: 80), (X: 200; Y: 90), (X: 210; Y: 90), (X: 210; Y: 80), (X: 200; Y: 40), (X: 230; Y: 40), (X: 220; Y: 80), (X: 220; Y: 90), (X: 227; Y: 100), (X: 230; Y: 110), (X: 227; Y: 120), (X: 220; Y: 130), (X: 230; Y: 130), (X: 230; Y: 140), (X: 220; Y: 140), (X: 240; Y: 155), (X: 200; Y: 155), (X: 200; Y: 140), (X: 195; Y: 140), (X: 195; Y: 130), (X: 200; Y: 130), (X: 190; Y: 120), (X: 90; Y: 120), (X: 80; Y: 130), (X: 80; Y: 150), (X: 40; Y: 150), (X: 40; Y: 110), (X: 50; Y: 110), (X: 50; Y: 50)); label 1; var gd,gm,n,x1,x2,y1,y2,x1kol,x2kol,x3kol,ykol,xporsh,yporsh:integer; Poezd,Hor:pointer; SizeP,SizeH,speed:word; arrow:char; begin gd:=0; DetectGraph(gd,gm); InitGraph(gd,gm,''); if GraphResult<>0 then begin writeln('mistake:',GraphResult); halt end; SetBkColor(Blue); SetFillStyle(Solidfill,8); SetTextStyle(TriplexFont,0,1); ClearDevice; OutTextXY(280,300,'PRESS ARROWS:'); OutTextXY(200,320,'BUTTON /LEFT/ FOR LOW SPEED'); OutTextXY(330,340,'OR'); OutTextXY(200,360,'BUTTON /RIGHT/ FOR MORE SPEED'); OutTextXY(240,380,'BUTTON /ESC/ FOR EXIT'); FillPoly(32,Triangle); SetFillStyle(Solidfill,Red); FillEllipse(105,140,15,15); FillEllipse(140,140,15,15); FillEllipse(175,140,15,15); Circle(105,140,13); Circle(140,140,13); Circle(175,140,13); Circle(105,140,5); Circle(140,140,5); Circle(175,140,5); SetFillStyle(Emptyfill,0); Bar(60,60,90,90); Rectangle(60,60,90,90); x1:=40; y1:=40; x2:=240; y2:=155; SizeP:=Imagesize(x1,y1,x2,y2); Getmem(Poezd,SizeP); Getimage(x1,y1,x2,y2,Poezd^); x1kol:=105; x2kol:=140; x3kol:=175; ykol:=153; xporsh:=195;yporsh:=135; line(x1kol,ykol,xporsh,yporsh); line(x2kol,ykol,xporsh,yporsh); line(x3kol,ykol,xporsh,yporsh); line(x1kol,ykol,x3kol,ykol); SizeH:=Imagesize(x1kol,ykol,x3kol,ykol); Getmem(Hor,SizeH); Getimage(x1kol,ykol,x3kol,ykol,Hor^); n:=0; speed:=100; Repeat 1:arrow:=readkey; Case arrow of #75:begin speed:=speed+10; if speed<20 then speed:=20; Repeat if xporsh>580 then begin x1:=40; y1:=40; x1kol:=105; x2kol:=140; x3kol:=175; ykol:=153; xporsh:=195; yporsh:=135; n:=1; end; x1:=x1+5; x1kol:=round(4*sin(pi*n/10-pi/2))+x1kol; x2kol:=round(4*sin(pi*n/10-pi/2))+x2kol; x3kol:=round(4*sin(pi*n/10-pi/2))+x3kol; ykol:=round(-4*cos(pi*n/10-pi/2))+ykol; x1kol:=x1kol+5; x2kol:=x2kol+5; x3kol:=x3kol+5; xporsh:=xporsh+5; n:=n+1; delay(speed); ClearDevice; Putimage(x1,y1,Poezd^,0); Putimage(x1kol,ykol,Hor^,0); line(x1kol,ykol,xporsh,yporsh); line(x2kol,ykol,xporsh,yporsh); line(x3kol,ykol,xporsh,yporsh); Until keypressed; goto 1; end; #77:begin speed:=speed-10; if speed<20 then speed:=20; Repeat if xporsh>580 then begin x1:=40; y1:=40; x1kol:=105; x2kol:=140; x3kol:=175; ykol:=153; xporsh:=195; yporsh:=135; n:=1; end; x1:=x1+5; x1kol:=round(4*sin(pi*n/10-pi/2))+x1kol; x2kol:=round(4*sin(pi*n/10-pi/2))+x2kol; x3kol:=round(4*sin(pi*n/10-pi/2))+x3kol; ykol:=round(-4*cos(pi*n/10-pi/2))+ykol; x1kol:=x1kol+5; x2kol:=x2kol+5; x3kol:=x3kol+5; xporsh:=xporsh+5; n:=n+1; delay(speed); ClearDevice; Putimage(x1,y1,Poezd^,0); Putimage(x1kol,ykol,Hor^,0); line(x1kol,ykol,xporsh,yporsh); line(x2kol,ykol,xporsh,yporsh); line(x3kol,ykol,xporsh,yporsh); Until keypressed; goto 1; end; end; Until arrow=#27; FreeMem(Poezd,SizeP); FreeMem(Hor,SizeH); CloseGraph; end.
unit JASysInfo; {$mode objfpc}{$H+} interface uses sysutils, exec, amigados, Intuition, AGraphics, layers, GadTools, Utility, picasso96api, cybergraphics, linklist, JATypes, JALog; type TJASysInfoCPU = ( JACPU_86000=0, JACPU_86010=1, JACPU_86020=2, JACPU_86030=3, JACPU_86040=4, JACPU_86060=5, JACPU_86080=6 ); TJASysInfoFPU = ( JAFPU_None = 0, JAFPU_CPU = 1, JAFPU_68881 = 2, JAFPU_68882 = 3 ); TJASysInfoMMU = ( JAMMU_None = 0, JAMMU_MMU = 1, JAMMU_EC = 2 ); TJASysInfoPicassoBoard = record Name : string; RGBFormats : SInt32; MemorySize : SInt32; FreeMemory : SInt32; LargestFreeMemory : SInt32; MemoryClock : SInt32; MoniSwitch : SInt32; end; TJAVideoStandard = (JAVIDEO_NTSC = 1, JAVIDEO_GENLOC = 2, JAVIDEO_PAL = 4, JAVIDEO_TODA_SAFE = 8, JAVIDEO_REALLY_PAL = 16); TJASysInfo = record CPU : TJASysInfoCPU; CPUName : string; FPU : boolean; FPUName : string; MMU : TJASysInfoMMU; MMUName : string; MemoryChip : UInt32; MemoryFast : UInt32; MemorySlow : UInt32; MemoryGraphics : UInt32; VideoStandard : TJAVideoStandard; PicassoAPI : boolean; PicassoBoards : array of TJASysInfoPicassoBoard; PicassoBoardsCount : SInt32; CybergraphicsAPI : boolean; end; const TJASysInfoCPUNames : array[0..6] of string = ( '86000', '86010', '86020', '86030', '86040', '86060', '86080' ); TJASysInfoFPUNames : array[0..3] of string = ( 'None', 'CPU', '68881', '68882' ); TJASysInfoMMUNames : array[0..2] of string = ( 'None', 'MMU', 'EC' ); var SysInfo : TJASysInfo; procedure JASysInfoQuery(); implementation { identify library - if we have it - contains tons of sysinfo style stuff. IDENTIFYNAME : PChar = 'identify.library'; } { LOOK HERE !!! - struct ExecBase /* The next ULONG contains the system "E" clock frequency, ** expressed in Hertz. The E clock is used as a timebase for ** the Amiga's 8520 I/O chips. (E is connected to "02"). ** Typical values are 715909 for NTSC, or 709379 for PAL. */ ULONG ex_EClockFrequency; /* (readable) While we're talking about CPUs: you can also differentiate the various processors that the different versions of AmigaOS run on. For the earlier 68k CPUs a single bit from "ExecBase->AttnFlags" was enough to distinguish a 68000 from a 68030 or a 68060. Since bits tend to run out eventually and it's only a very rough method there's also a function to get the processor's name string. You can call IExec->GetCPUInfoTags() with GCIT_xxx tags (from exec/exectags.h). As the function was introduced with AmigaOS 4 this program can never run on older versions. See the complete example "DeterminateProcessor.c" for details. } { IExpansion->GetMachineInfo() AttnFlags ******* Bit defines for AttnFlags (see above) ******************************* * Processors and Co-processors: BITDEF AF,68010,0 ; also set for 68020 BITDEF AF,68020,1 ; also set for 68030 BITDEF AF,68030,2 ; also set for 68040 BITDEF AF,68040,3 BITDEF AF,68881,4 ; also set for 68882 BITDEF AF,68882,5 BITDEF AF,FPU40,6 ; Set if 68040 FPU ; ; The AFB_FPU40 bit is set when a working 68040 FPU ; is in the system. If this bit is set and both the ; AFB_68881 and AFB_68882 bits are not set, then the 68040 ; math emulation code has not been loaded and only 68040 ; FPU instructions are available. This bit is valid *ONLY* ; if the AFB_68040 bit is set. ; ; BITDEF AF,RESERVED8,8 ; BITDEF AF,RESERVED9,9 BITDEF AF,PRIVATE,15 ; Just what it says } procedure JASysInfoQueryCPU(); begin end; procedure JASysInfoQueryMemory(); begin { MEMF_ANY = %000000000000000000000000; { * Any type of memory will do * } MEMF_PUBLIC = %000000000000000000000001; MEMF_CHIP = %000000000000000000000010; MEMF_FAST = %000000000000000000000100; MEMF_LOCAL = %000000000000000100000000; MEMF_24BITDMA = %000000000000001000000000; { * DMAable memory within 24 bits of address * } MEMF_KICK = %000000000000010000000000; { Memory that can be used for KickTags } MEMF_CLEAR = %000000010000000000000000; MEMF_LARGEST = %000000100000000000000000; MEMF_REVERSE = %000001000000000000000000; MEMF_TOTAL = %000010000000000000000000; { * AvailMem: return total size of memory * } MEMF_NO_EXPUNGE = $80000000; {AllocMem: Do not cause expunge on failure } MEM_BLOCKSIZE = 8; MEM_BLOCKMASK = MEM_BLOCKSIZE-1; } SysInfo.MemoryChip := AvailMem(MEMF_CHIP); SysInfo.MemoryFast := AvailMem(MEMF_FAST); {TODO : this obviously isn't right - but lookup how to query and figure out all the memory correctly} SysInfo.MemoryGraphics := AvailMem(MEMF_PUBLIC); end; procedure JASysInfoQueryGraphics(); var I : SInt32; BoardName : Pchar; BoardNameTemp : array[0..200] of char; PixelFormatsString : string; clock : Longint; tmp : Longint; RGBFormats, MemorySize, FreeMemory, LargestFreeMemory, MemoryClock, MoniSwitch : Longint; width, height, depth, DisplayID : longint; dim : tDimensionInfo; rda : pRDArgs; const template : pchar = 'Width=W/N,Height=H/N,Depth=D/N'; vecarray : Array[0..2] of longint = (0,0,0); function RGBTest(ABoardIndex : SInt32; ARGBFormat : SInt32) : boolean; begin Result := (SysInfo.PicassoBoards[ABoardIndex].RGBFormats and ARGBFormat) <> 0; end; begin {PAL or NTSC startup mode detection} if ((pGfxBase(GfxBase)^.DisplayFlags and PAL) <> 0) then SysInfo.VideoStandard := JAVIDEO_PAL else if ((pGfxBase(GfxBase)^.DisplayFlags and NTSC) <> 0) then SysInfo.VideoStandard := JAVIDEO_NTSC else if ((pGfxBase(GfxBase)^.DisplayFlags and GENLOC) <> 0) then SysInfo.VideoStandard := JAVIDEO_GENLOC else if ((pGfxBase(GfxBase)^.DisplayFlags and TODA_SAFE) <> 0) then SysInfo.VideoStandard := JAVIDEO_TODA_SAFE else if ((pGfxBase(GfxBase)^.DisplayFlags and 16) <> 0) then SysInfo.VideoStandard := JAVIDEO_REALLY_PAL; case SysInfo.VideoStandard of JAVIDEO_PAL : Log('JASysInfo','System is PAL'); JAVIDEO_NTSC : Log('JASysInfo','System is NTSC'); JAVIDEO_GENLOC : Log('JASysInfo','System is GENLOC'); JAVIDEO_TODA_SAFE : Log('JASysInfo','System is TODA SAFE'); JAVIDEO_REALLY_PAL : Log('JASysInfo','System is REALLY PAL'); end; {intuition.library version} Log('JASysInfo', JALibNameIntuition + ' v' + inttostr(pIntuitionBase(IntuitionBase)^.libnode.lib_version) + '.' + inttostr(pIntuitionBase(IntuitionBase)^.libnode.lib_Revision) + ' found'); {graphics.library version} Log('JASysInfo',JALibNameGraphics + ' v' + inttostr(pGfxBase(GfxBase)^.libnode.lib_version) + '.' + inttostr(pGfxBase(GfxBase)^.libnode.lib_Revision) + ' found'); {layers.library version} Log('JASysInfo', JALibNameLayers + ' v' + inttostr(LayersBase^.lib_Version) + '.' + inttostr(LayersBase^.lib_Revision) + ' found'); {Query Picasso} if P96Base=nil then begin SysInfo.PicassoAPI := false; Log('JASysInfo',JALibNamePicasso96API + ' not found'); end else begin SysInfo.PicassoAPI := true; Log('JASysInfo',JALibNamePicasso96API + ' v' + inttostr(P96Base^.lib_Version) + '.' + inttostr(P96Base^.lib_Revision) + ' found'); //p96GetRTGDataTagList //p96GetBoardDataTagList BoardName := @BoardNameTemp; tmp := p96GetRTGDataTags([P96RD_NumberOfBoards, AsTag(@SysInfo.PicassoBoardsCount), TAG_END]); SetLength(SysInfo.PicassoBoards, SysInfo.PicassoBoardsCount); Log('JASysInfo','Found ' + inttostr(SysInfo.PicassoBoardsCount) + ' Picasso96 Boards'); for I := 0 to SysInfo.PicassoBoardsCount-1 do begin p96GetBoardDataTags(I, [P96BD_BoardName, AsTag(@BoardName), P96BD_RGBFormats, AsTag(@SysInfo.PicassoBoards[I].RGBFormats), P96BD_TotalMemory, AsTag(@SysInfo.PicassoBoards[I].MemorySize), P96BD_FreeMemory, AsTag(@SysInfo.PicassoBoards[I].FreeMemory), P96BD_LargestFreeMemory, AsTag(@SysInfo.PicassoBoards[I].LargestFreeMemory), P96BD_MemoryClock, AsTag(@SysInfo.PicassoBoards[I].MemoryClock), P96BD_MonitorSwitch, AsTag(@SysInfo.PicassoBoards[I].MoniSwitch), TAG_END]); SysInfo.PicassoBoards[I].Name := BoardName; Log('JASysInfo','Board[' + inttostr(i) + '].Name = ' + SysInfo.PicassoBoards[I].Name); Log('JASysInfo','Board[' + inttostr(i) + '].MemorySize = ' + inttostr(SysInfo.PicassoBoards[I].MemorySize)); Log('JASysInfo','Board[' + inttostr(i) + '].FreeMemory = ' + inttostr(SysInfo.PicassoBoards[I].FreeMemory)); Log('JASysInfo','Board[' + inttostr(i) + '].LargestFreeMemory = ' + inttostr(SysInfo.PicassoBoards[I].LargestFreeMemory)); clock := (SysInfo.PicassoBoards[I].MemoryClock+50000) div 100000; Log('JASysInfo','Board[' + inttostr(i) + '].MemoryClock = ' + inttostr(clock div 10) + '.' + inttostr(clock mod 10) + 'Mhz'); PixelFormatsString := ''; if RGBTest(I, RGBFF_NONE) then PixelFormatsString += 'PLANAR ' else if RGBTest(I, RGBFF_CLUT) then PixelFormatsString += 'CHUNKY ' else if RGBTest(I, RGBFF_R5G5B5) then PixelFormatsString += 'tR5G5B5 ' else if RGBTest(I, RGBFF_R5G5B5PC) then PixelFormatsString += 'R5G5B5PC ' else if RGBTest(I, RGBFF_B5G5R5PC) then PixelFormatsString += 'B5G5R5PC ' else if RGBTest(I, RGBFF_R5G6B5) then PixelFormatsString += 'R5G6B5 ' else if RGBTest(I, RGBFF_R5G6B5PC) then PixelFormatsString += 'R5G6B5PC ' else if RGBTest(I, RGBFF_B5G6R5PC) then PixelFormatsString += 'B5G6R5PC ' else if RGBTest(I, RGBFF_R8G8B8) then PixelFormatsString += 'R8G8B8 ' else if RGBTest(I, RGBFF_B8G8R8) then PixelFormatsString += 'B8G8R8 ' else if RGBTest(I, RGBFF_A8R8G8B8) then PixelFormatsString += 'A8R8G8B8 ' else if RGBTest(I, RGBFF_A8B8G8R8) then PixelFormatsString += 'A8B8G8R8 ' else if RGBTest(I, RGBFF_R8G8B8A8) then PixelFormatsString += 'R8G8B8A8 ' else if RGBTest(I, RGBFF_B8G8R8A8) then PixelFormatsString += 'B8G8R8A8 ' else if RGBTest(I, RGBFF_Y4U2V2) then PixelFormatsString += 'Y4U2V2 ' else if RGBTest(I, RGBFF_Y4U1V1) then PixelFormatsString += 'Y4U1V1 '; Log('JASysInfo','Board[' + inttostr(i) + '].RGBFormats = ' + PixelFormatsString); end; end; {Query Cybergraphics} if CyberGfxBase=nil then begin SysInfo.CybergraphicsAPI := false; Log('JASysInfo',JALibNameCybergraphics + ' not found'); end else begin Log('JASysInfo',JALibNameCybergraphics + ' v' + inttostr(CyberGfxBase^.lib_Version) + '.' + inttostr(CyberGfxBase^.lib_Revision) + ' found'); end; end; procedure JASysInfoQueryAudio(); begin end; procedure JASysInfoQueryVolumes(); begin end; procedure JASysInfoQuery(); begin JASysInfoQueryCPU(); JASysInfoQueryMemory(); JASysInfoQueryGraphics(); JASysInfoQueryAudio(); JASysInfoQueryVolumes(); end; initialization JASysInfoQuery(); finalization SetLength(SysInfo.PicassoBoards, SysInfo.PicassoBoardsCount); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; type tColor = (Red, Green, Yellow, Blue); tStr = (Wood, Metall, Cardboard); tCube = record ec: real; color: tColor; material: tStr end; const aColor: array[Red..Blue] of string = ('Красный', 'Зелёный', 'Жёлтый', 'Синий'); aStr: array[Wood..Cardboard] of string = ('Деревянный', 'Металлический', 'Картонный'); var x: tCube; f: file of tCube; bColor: array[Red..Blue] of integer; s:real; i:tColor; implementation {$R *.dfm} procedure PutCube(var p:tCube); var s1, s2: string; begin Write(p.ec,', '); case p.color of Red: s1:=aColor[Red]; Green: s1:=aColor[Green]; Yellow: s1:=aColor[Yellow]; Blue: s1:=aColor[Blue]; else s1:='Error' end; case p.material of Wood: s2:=aStr[Wood]; Metall: s2:=aStr[Metall]; Cardboard: s2:=aStr[cardboard]; else s2:='Error' end; Writeln(s1,', ',s2) end; begin Assign(f, 'fCube.bin'); Reset(f); for i:=Red to Blue do bColor[i]:=0; s:=0; while (not Eof(f)) do begin Read(f,x); s:=s+x.ec*sqr(x.ec); case x.color of Red: Inc(bColor[Red]); Green: Inc(bColor[Green]); Yellow: Inc(bColor[Yellow]); Blue: Inc(bColor[Blue]); end end; Close(f); Writeln('Колличекство по цветам'); for i:=Red to Blue do Writeln(aColor[i],' ',bColor[i]); Writeln('Суммарный объём',s:0:3); end. end.
unit Unit1; interface uses System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, //GLScene GLScene, GLObjects, GLCadencer, GLVectorFileObjects, GLWin32Viewer, GLTexture, GLVectorGeometry, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) Viewer: TGLSceneViewer; GLScene: TGLScene; GLCadencer: TGLCadencer; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; DCCamTarg: TGLDummyCube; Timer1: TTimer; GLMaterialLibrary: TGLMaterialLibrary; GLLightSource2: TGLLightSource; Panel1: TPanel; Button1: TButton; GLLines1: TGLLines; GLPoints1: TGLPoints; Label1: TLabel; CheckBox1: TCheckBox; GLCube1: TGLCube; CheckBox2: TCheckBox; GLDummyCube1: TGLDummyCube; DCCube1: TGLDummyCube; LabelFPS: TLabel; procedure GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormResize(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Button1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private mdx, mdy : Integer; public end; var Form1 : TForm1; BoxPos, BoxScale, RayStart, RayDir : TAffineVector; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin Randomize; RayStart := AffineVectorMake(Random*2 -1, Random *2 -1, Random *2 -1); end; procedure TForm1.Button1Click(Sender: TObject); var iPnt, afScale : TAffineVector; begin // Change pos. if CheckBox2.Checked then begin BoxPos := AffineVectorMake(Random*2 -1, Random *2 -1, Random *2 -1); DCCamTarg.Position.SetPoint(BoxPos); BoxScale := AffineVectorMake(Random*1 +0.5, Random*1 +0.5, Random*1 +0.5); DCCube1.Scale.SetVector(BoxScale); afScale := VectorScale(BoxScale, 0.5); RayStart := AffineVectorMake(Random*3 -1.5, Random *3 -1.5, Random *3 -1.5); end; RayDir := AffineVectorMake(Random*2 -1, Random *2 -1, Random *2 -1); NormalizeVector(RayDir); GLLines1.Nodes.Clear; GLLines1.Nodes.AddNode(RayStart); GLLines1.Nodes.AddNode( VectorAdd(RayStart, VectorScale(RayDir, 8)) ); GLPoints1.Positions.Clear; GLPoints1.Positions.Add(RayStart); GLPoints1.Positions.Add(BoxPos); GLPoints1.Positions.Add(VectorSubtract(BoxPos, afScale)); GLPoints1.Positions.Add(VectorAdd( BoxPos, afScale)); if RayCastBoxIntersect( RayStart, RayDir, VectorSubtract(BoxPos, afScale), VectorAdd( BoxPos, afScale), @iPnt) then begin Label1.Caption := Format('Intersect point: %.3f %.3f %.3f', [iPnt.V[0], iPnt.V[1], iPnt.V[2]]); GLPoints1.Positions.Add(iPnt); beep; end else begin Label1.Caption := 'no intersection'; end; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin GLCube1.Visible := CheckBox1.Checked; end; procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); begin if Form1.Active then Viewer.Invalidate end; procedure TForm1.Timer1Timer(Sender: TObject); begin LabelFPS.Caption := Format('%.1f FPS', [Viewer.FramesPerSecond]); Viewer.ResetPerformanceMonitor; end; procedure TForm1.ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Shift = [ssLeft] then GLCamera1.MoveAroundTarget(mdy -y, mdx -x); mdx := x; mdy := y; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin GLCamera1.AdjustDistanceToTarget(Power(1.02, WheelDelta/120)); end; procedure TForm1.ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Viewer.SetFocus; end; procedure TForm1.FormResize(Sender: TObject); begin GLCamera1.FocalLength := MinInteger(Height, Width) / 10; end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then close; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSProxyDelphiNative; interface uses Datasnap.DSCommonProxy, Datasnap.DSProxyDelphi, DataSnap.DSProxyWriter, System.Classes; type TDSClientProxyWriterDelphi = class(TDSProxyWriter) public function CreateProxyWriter: TDSCustomProxyWriter; override; function Properties: TDSProxyWriterProperties; override; function FileDescriptions: TDSProxyFileDescriptions; override; end; TDSCustomDelphiProxyWriter = class abstract(TDSCustomExtendedProxyWriter) public constructor Create; procedure WriteProxy; override; protected FUnitName: string; procedure WriteInterface; override; procedure WriteImplementation; override; function GetAssignmentString: string; override; function GetCreateDataSetReader(const Param: TDSProxyParameter): string; override; function GetCreateParamsReader(const Param: TDSProxyParameter): string; override; private procedure WriteInterfaceUses; procedure WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean); procedure WriteClassInterface(const ProxyClass: TDSProxyClass); procedure WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod); procedure WriteOutgoingParameter(const Lhs: string; const InRhs: string; const Param: TDSProxyParameter; const CommandName: string; const ParamName: string); procedure WriteClassImplementation(const ProxyClass: TDSProxyClass); end; TDSDelphiProxyWriter = class(TDSCustomDelphiProxyWriter) private FStreamWriter: TStreamWriter; protected procedure DerivedWrite(const Line: string); override; procedure DerivedWriteLine; override; public property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter; destructor Destroy; override; end; const sDelphiDBXProxyWriter = 'Delphi DBX'; sObjectPascalDBXProxyWriter = 'Object Pascal DBX'; implementation uses Data.DBXCommon, System.SysUtils; { TDSClientProxyWriterDelphi } function TDSClientProxyWriterDelphi.CreateProxyWriter: TDSCustomProxyWriter; begin Result := TDSDelphiProxyWriter.Create; end; function TDSClientProxyWriterDelphi.Properties: TDSProxyWriterProperties; begin Result.UsesUnits := 'Datasnap.DSProxyDelphi'; Result.DefaultExcludeClasses := sDSMetadataClassName + ';' + sDSAdminClassName; // 'DSMetadata;DSAdmin'; Result.DefaultExcludeMethods := sASMethodsPrefix; Result.Author := 'Embarcadero'; // do not localize Result.Comment := ''; Result.Language := sDSProxyDelphiLanguage; Result.Features := [feConnectsWithDSRestConnection, feDBXClient]; Result.DefaultEncoding := TEncoding.UTF8; end; function TDSClientProxyWriterDelphi.FileDescriptions: TDSProxyFileDescriptions; begin SetLength(Result, 1); Result[0].ID := sImplementation; Result[0].DefaultFileExt := '.pas'; end; { TDSCustomDelphiProxyWriter } constructor TDSCustomDelphiProxyWriter.Create; begin inherited Create; FIndentIncrement := 2; FIndentString := ''; AddCustomTypeMap(TDbxDataTypes.AnsiStringType, TDSProxyParamAccess.Create('string', 'GetString', 'SetString')); AddCustomTypeMap(TDbxDataTypes.BinaryBlobType, TDBXSubDataTypes.JSONStreamSubType, TDSProxyParamAccess.Create('TDBXJSONStream', 'GetJSONStream', 'SetJSONStream', 'Data.DBXCommon')); // do not localize end; procedure TDSCustomDelphiProxyWriter.WriteProxy; begin FUnitName := ChangeFileExt(ExtractFileName(FUnitFileName), ''); inherited; end; procedure TDSCustomDelphiProxyWriter.WriteInterfaceUses; var Item: TDSProxyClass; PMethod: TDSProxyMethod; PParam: TDSProxyParameter; Line, UnitName: string; begin Line := 'uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders,'; Item := Metadata.Classes; while Item <> nil do begin if IncludeClass(Item) then begin PMethod := Item.FirstMethod; while PMethod <> nil do begin PParam := PMethod.Parameters; while PParam <> nil do begin UnitName := GetDelphiUnitName(PParam); if (UnitName.Length > 0) and (not (string.Compare('system', UnitName, True) = 0)) then begin UnitName := ' ' + UnitName + ','; if Line.IndexOf(UnitName) <= 0 then Line := Line + UnitName; end; PParam := PParam.Next; end; PMethod := PMethod.Next; end; end; Item := Item.Next; end; Line := Line + ' Data.DBXJSONReflect;'; WriteLine(Line); end; procedure TDSCustomDelphiProxyWriter.WriteMethodSignature(const ProxyClass: TDSProxyClass; const Method: TDSProxyMethod; const IsInterface: Boolean); var Line: string; ParamCount: Integer; ProcessedCount: Integer; Parameters: TDSProxyParameter; Param: TDSProxyParameter; begin Parameters := Method.Parameters; ParamCount := Method.ParameterCount; if Method.HasReturnValue then begin ParamCount := ParamCount - 1; Line := 'function '; end else Line := 'procedure '; if IsInterface then Line := Line + Method.ProxyMethodName else Line := Line + ProxyClass.ProxyClassName + 'Client.' + Method.ProxyMethodName; if ParamCount > 0 then begin Line := Line + '('; Param := Parameters; ProcessedCount := 0; while (Param <> nil) and (ProcessedCount < ParamCount) do begin case Param.ParameterDirection of TDBXParameterDirections.OutParameter: Line := Line + 'out '; TDBXParameterDirections.InOutParameter: if not IsKnownDBXValueTypeName(Param.TypeName) then Line := Line + 'var '; end; Line := Line + Param.ParameterName + ': ' + GetDelphiTypeName(Param); ProcessedCount := ProcessedCount + 1; if (ProcessedCount) < ParamCount then Line := Line + '; '; Param := Param.Next; end; Line := Line + ')'; end; if Method.HasReturnValue then begin Param := Method.ReturnParameter; Line := Line + ': ' + GetDelphiTypeName(Param); end; WriteLine(Line + ';'); end; procedure TDSCustomDelphiProxyWriter.WriteClassInterface(const ProxyClass: TDSProxyClass); var Methods: TDSProxyMethod; begin Indent; WriteLine(ProxyClass.ProxyClassName + 'Client = class(TDSAdminClient)'); WriteLine('private'); Indent; Methods := ProxyClass.FirstMethod; while Methods <> nil do begin if IncludeMethod(Methods) then WriteLine('F' + Methods.ProxyMethodName + 'Command: TDBXCommand;'); Methods := Methods.Next; end; Outdent; WriteLine('public'); Indent; WriteLine('constructor Create(ADBXConnection: TDBXConnection); overload;'); WriteLine('constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;'); WriteLine('destructor Destroy; override;'); Methods := ProxyClass.FirstMethod; while Methods <> nil do begin if IncludeMethod(Methods) then WriteMethodSignature(ProxyClass, Methods, True); Methods := Methods.Next; end; Outdent; WriteLine('end;'); Outdent; WriteLine; end; procedure TDSCustomDelphiProxyWriter.WriteInterface; var Item: TDSProxyClass; lTypeWritten: Boolean; begin WriteLine('unit ' + FUnitName + ';'); WriteLine; WriteLine('interface'); WriteLine; WriteInterfaceUses; WriteLine; lTypeWritten := False; Item := Metadata.Classes; while Item <> nil do begin if IncludeClass(Item) then begin if not lTypeWritten then begin lTypeWritten := True; WriteLine('type'); end; WriteClassInterface(Item); end; Item := Item.Next; end; end; procedure TDSCustomDelphiProxyWriter.WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod); var CommandName: string; ParamCount: Integer; Params: TDSProxyParameter; Param: TDSProxyParameter; InputCount: Integer; OutputCount: Integer; Ordinal: Integer; Rhs: string; Lhs: string; begin WriteMethodSignature(ProxyClass, ProxyMethod, False); WriteLine('begin'); Indent; CommandName := 'F' + ProxyMethod.ProxyMethodName + 'Command'; WriteLine('if ' + CommandName + ' = nil then'); WriteLine('begin'); Indent; WriteLine(CommandName + ' := FDBXConnection.CreateCommand;'); WriteLine(CommandName + '.CommandType := TDBXCommandTypes.DSServerMethod;'); WriteLine(CommandName + '.Text := ''' + ProxyMethod.MethodAlias + ''';'); WriteLine(CommandName + '.Prepare;'); Outdent; WriteLine('end;'); Params := ProxyMethod.Parameters; ParamCount := ProxyMethod.ParameterCount; if ProxyMethod.HasReturnValue then ParamCount := ParamCount - 1; InputCount := ProxyMethod.InputCount; OutputCount := ProxyMethod.OutputCount; if InputCount > 0 then begin Param := Params; Ordinal := 0; while Param <> nil do begin if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.InParameter) then begin if IsKnownDBXValueTypeName(Param.TypeName) then begin WriteLine('if ' + Param.ParameterName + ' = nil then'); Indent; WriteLine(CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.SetNull'); Outdent; WriteLine('else'); Indent; WriteLine(CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.SetValue(' + Param.ParameterName + ');'); Outdent; end else if (Param.DataType = TDBXDataTypes.JsonValueType) and not IsKnownJSONTypeName(Param.TypeName) then begin WriteLine('if not Assigned(' + Param.ParameterName + ') then'); Indent; WriteLine(CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.SetNull'); Outdent; WriteLine('else'); WriteLine('begin'); Indent; WriteLine('FMarshal := TDBXClientCommand(' + CommandName + '.Parameters[' + IntToStr(Ordinal) + '].ConnectionHandler).GetJSONMarshaler;'); WriteLine('try'); Indent; WriteLine(CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.SetJSONValue(FMarshal.Marshal(' + Param.ParameterName + '), True);'); WriteLine('if FInstanceOwner then'); Indent; WriteLine(Param.ParameterName + '.Free'); Outdent; Outdent; WriteLine('finally'); Indent; WriteLine('FreeAndNil(FMarshal)'); Outdent; WriteLine('end'); Outdent; WriteLine('end;'); end else WriteLine(CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.' + GetSetter(Param) + ';'); end; Ordinal := Ordinal + 1; Param := Param.Next; end; end; WriteLine(CommandName + '.ExecuteUpdate;'); if OutputCount > 0 then begin Param := Params; Ordinal := 0; while Param <> nil do begin if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Param.ParameterDirection = TDBXParameterDirections.OutParameter) then begin if IsKnownDBXValueTypeName(Param.TypeName) then begin WriteLine('if ' + Param.ParameterName + ' <> nil then'); Indent; WriteLine(Param.ParameterName + '.SetValue(' + CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value);'); Outdent; end else if (Param.DataType = TDBXDataTypes.JsonValueType) and not IsKnownJSONTypeName(Param.TypeName) then begin WriteLine('if not ' + CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.IsNull then'); WriteLine('begin'); Indent; WriteLine('FUnMarshal := TDBXClientCommand(' + CommandName + '.Parameters[' + IntToStr(Ordinal) + '].ConnectionHandler).GetJSONUnMarshaler;'); WriteLine('try'); Indent; WriteLine(Param.ParameterName + ' := ' + Param.TypeName + '(FUnMarshal.UnMarshal(' + CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.GetJSONValue(True)));'); WriteLine('if FInstanceOwner then'); Indent; WriteLine(CommandName + '.FreeOnExecute(' + Param.ParameterName + ');'); OutDent; Outdent; WriteLine('finally'); Indent; WriteLine('FreeAndNil(FUnMarshal)'); Outdent; WriteLine('end;'); Outdent; WriteLine('end'); WriteLine('else'); Indent; WriteLine(Param.ParameterName + ' := nil;'); Outdent; end else begin Lhs := Param.ParameterName + ' := '; Rhs := CommandName + '.Parameters[' + IntToStr(Ordinal) + '].Value.' + GetGetter(Param); WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, Param.ParameterName); end; end; Ordinal := Ordinal + 1; Param := Param.Next; end; end; if ProxyMethod.HasReturnValue then begin if ProxyMethod.ReturnParameter.DataType = TDBXDataTypes.DbxConnectionType then WriteLine('Result := FDBXConnection;') else if IsKnownDBXValueTypeName(ProxyMethod.ReturnParameter.TypeName) then begin WriteLine('Result := ' + ProxyMethod.ReturnParameter.TypeName + '.Create;'); WriteLine('Result.SetValue(' + CommandName + '.Parameters[' + IntToStr(ParamCount) + '].Value)'); end else if (ProxyMethod.ReturnParameter.DataType = TDBXDataTypes.JsonValueType) and not IsKnownJSONTypeName(ProxyMethod.ReturnParameter.TypeName) then begin Param := ProxyMethod.ReturnParameter; WriteLine('if not ' + CommandName + '.Parameters[' + IntToStr(ParamCount) + '].Value.IsNull then'); WriteLine('begin'); Indent; WriteLine('FUnMarshal := TDBXClientCommand(' + CommandName + '.Parameters[' + IntToStr(ParamCount) + '].ConnectionHandler).GetJSONUnMarshaler;'); WriteLine('try'); Indent; WriteLine('Result := ' + Param.TypeName + '(FUnMarshal.UnMarshal(' + CommandName + '.Parameters[' + IntToStr(ParamCount) + '].Value.GetJSONValue(True)));'); WriteLine('if FInstanceOwner then'); Indent; WriteLine(CommandName + '.FreeOnExecute(Result);'); OutDent; Outdent; WriteLine('finally'); Indent; WriteLine('FreeAndNil(FUnMarshal)'); Outdent; WriteLine('end'); Outdent; WriteLine('end'); WriteLine('else'); Indent; WriteLine('Result := nil;'); Outdent; end else begin Lhs := 'Result := '; Param := ProxyMethod.ReturnParameter; Rhs := CommandName + '.Parameters[' + IntToStr(ParamCount) + '].Value.' + GetGetter(Param); WriteOutgoingParameter(Lhs, Rhs, Param, CommandName, 'Result'); end; end; Outdent; WriteLine('end;'); WriteLine; end; procedure TDSCustomDelphiProxyWriter.WriteOutgoingParameter(const Lhs: string; const InRhs: string; const Param: TDSProxyParameter; const CommandName: string; const ParamName: string); var Rhs: string; begin Rhs := InRhs; if (Param.DataType = TDBXDataTypes.TableType) and IsKnownTableTypeName(Param.TypeName) then begin if string.Compare(Param.TypeName, 'TDataSet', True) = 0 then begin Rhs := 'TCustomSQLDataSet.Create(nil, ' + Rhs + '(False), True)'; WriteLine(Lhs + Rhs + ';'); WriteLine(ParamName + '.Open;'); end else if string.Compare(Param.TypeName, 'TParams', True) = 0 then begin Rhs := 'TDBXParamsReader.ToParams(nil, ' + Rhs + '(False), True)'; WriteLine(Lhs + Rhs + ';'); end else WriteLine(Lhs + Rhs + ';'); WriteLine('if FInstanceOwner then'); Indent; WriteLine(CommandName + '.FreeOnExecute(' + ParamName + ');'); Outdent; end else if (Param.DataType = TDBXDataTypes.TableType) or (Param.DataType = TDBXDataTypes.BinaryBlobType) then WriteLine(Lhs + Rhs + '(FInstanceOwner);') else if Param.DataType = TDBXDataTypes.JsonValueType then WriteLine(Lhs + Param.TypeName + '(' + Rhs + '(FInstanceOwner)' + ');') else WriteLine(Lhs + Rhs + ';'); end; procedure TDSCustomDelphiProxyWriter.WriteClassImplementation(const ProxyClass: TDSProxyClass); var Methods: TDSProxyMethod; begin Methods := ProxyClass.FirstMethod; while Methods <> nil do begin if IncludeMethod(Methods) then WriteMethodImplementation(ProxyClass, Methods); Methods := Methods.Next; end; WriteLine('constructor ' + ProxyClass.ProxyClassName + 'Client.Create(ADBXConnection: TDBXConnection);'); WriteLine('begin'); Indent; WriteLine('inherited Create(ADBXConnection);'); Outdent; WriteLine('end;'); WriteLine; WriteLine('constructor ' + ProxyClass.ProxyClassName + 'Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);'); WriteLine('begin'); Indent; WriteLine('inherited Create(ADBXConnection, AInstanceOwner);'); Outdent; WriteLine('end;'); WriteLine; WriteLine('destructor ' + ProxyClass.ProxyClassName + 'Client.Destroy;'); WriteLine('begin'); Indent; Methods := ProxyClass.FirstMethod; while Methods <> nil do begin if IncludeMethod(Methods) then WriteLine('F' + Methods.ProxyMethodName + 'Command.DisposeOf;'); Methods := Methods.Next; end; WriteLine('inherited;'); Outdent; WriteLine('end;'); WriteLine; end; procedure TDSCustomDelphiProxyWriter.WriteImplementation; var Item: TDSProxyClass; begin WriteLine('implementation'); WriteLine; Item := Metadata.Classes; while Item <> nil do begin if IncludeClass(Item) then WriteClassImplementation(Item); Item := Item.Next; end; WriteLine('end.'); end; function TDSCustomDelphiProxyWriter.GetAssignmentString: string; begin Result := ':='; end; function TDSCustomDelphiProxyWriter.GetCreateDataSetReader(const Param: TDSProxyParameter): string; begin Result := '(TDBXDataSetReader.Create(' + Param.ParameterName + ', FInstanceOwner), True)'; end; function TDSCustomDelphiProxyWriter.GetCreateParamsReader(const Param: TDSProxyParameter): string; begin Result := '(TDBXParamsReader.Create(' + Param.ParameterName + ', FInstanceOwner), True)'; end; { TDSDelphiProxyWriter } procedure TDSDelphiProxyWriter.DerivedWrite(const Line: string); begin if Assigned(StreamWriter) then StreamWriter.Write(Line) else ProxyWriters[sImplementation].Write(Line); end; procedure TDSDelphiProxyWriter.DerivedWriteLine; begin if Assigned(StreamWriter) then StreamWriter.WriteLine else ProxyWriters[sImplementation].WriteLine; end; destructor TDSDelphiProxyWriter.Destroy; begin FreeAndNil(FStreamWriter); inherited; end; initialization TDSProxyWriterFactory.RegisterWriter(sDelphiDBXProxyWriter, TDSClientProxyWriterDelphi); //Keept to save compatibility with old apps TDSProxyWriterFactory.RegisterWriter(sObjectPascalDBXProxyWriter, TDSClientProxyWriterDelphi); finalization TDSProxyWriterFactory.UnregisterWriter(sDelphiDBXProxyWriter); TDSProxyWriterFactory.UnregisterWriter(sObjectPascalDBXProxyWriter); end.
unit WasmSample_Callback; interface uses System.Classes, System.StrUtils, System.SysUtils, Wasm, Ownership {$ifndef USE_WASMER} , Wasmtime {$else} , Wasmer {$ifend} ; function CallbackSample_Clike() : Boolean; function CallbackSample() : Boolean; implementation procedure wasm_val_print(val : TWasmVal); begin case val.kind of WASM_I32: writeln(IntToStr(val.i32)); WASM_I64: writeln(IntToStr(val.i64)); WASM_F32: writeln(FloatToStr(val.f32)); WASM_F64: writeln(FloatToStr(val.f64)); WASM_ANYREF, WASM_FUNCREF: if val.ref = nil then writeln('nil') else writeln(IntToHex(Int64(val.ref), 16)); end; end; // A function to be called from Wasm code. function print_callback(const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl; begin write('Calling back...'#10'> '); wasm_val_print(args.data^); writeln(''); TWasm.val_copy(results.data, args.data); result := nil; end; // A function closure. function closure_callback(env : Pointer; const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl; begin var i := (PInteger(env))^; writeln('Calling back closure...'); writeln('> '+IntToStr(i)); results.data.kind := WASM_I32; results.data.i32 := Integer(i); result := nil; end; function CallbackSample_Clike() : Boolean; begin // Initialize. writeln('Initializing...'); var engine := TWasm.engine_new(); var store := TWasm.store_new(engine); // Load binary. writeln('Loading binary...'); var binary : TWasmByteVec; {$ifdef USE_WASMFILE} var stream := TFileStream.Create('callback.wasm', fmOpenRead); try var file_size := stream.Size; TWasm.byte_vec_new_uninitialized(@binary, file_size); if stream.ReadData(binary.data, file_size) <> file_size then begin writeln('> Error loading module!'); exit(false); end; finally stream.Free; end; {$else} var wat := '(module'+ ' (func $print (import "" "print") (param i32) (result i32))'+ ' (func $closure (import "" "closure") (result i32))'+ ' (func (export "run") (param $x i32) (param $y i32) (result i32)'+ ' (i32.add'+ ' (call $print (i32.add (local.get $x) (local.get $y)))'+ ' (call $closure)'+ ' )'+ ' )'+ ')'; binary.Wat2Wasm(wat); {$ifend} // Compile. writeln('Compiling module...'); var module := TWasm.module_new(store, @binary); if module = nil then begin writeln('> Error compiling module!'); exit(false); end; TWasm.byte_vec_delete(@binary); // Create external print functions. writeln('Creating callback...'); var print_type := TWasm.functype_new_1_1(TWasm.valtype_new_i32(), TWasm.valtype_new_i32()); var print_func := TWasm.func_new(store, print_type, print_callback); var i := 42; var closure_type := TWasm.functype_new_0_1(TWasm.valtype_new_i32()); var closure_func := TWasm.func_new_with_env(store, closure_type, closure_callback, @i, nil); TWasm.functype_delete(print_type); TWasm.functype_delete(closure_type); // Instantiate. Writeln('Instantiating module...'); var externs : TArray<PWasmExtern> := [ TWasm.func_as_extern(print_func), TWasm.func_as_extern(closure_func) ]; var imports := TWasmExternVec.Create(externs); var instance := TWasm.instance_new(store, module, @imports, nil); if instance = nil then begin writeln('> Error instantiating module!'); exit(false); end; TWasm.func_delete(print_func); TWasm.func_delete(closure_func); // Extract export. writeln('Extracting export...'); var exportfns : TWasmExternVec; TWasm.instance_exports(instance, @exportfns); if exportfns.size = 0 then begin writeln('> Error accessing exports!'); exit(false); end; var run_func := TWasm.extern_as_func(exportfns.data^); if run_func = nil then begin writeln('> Error accessing export!'); exit(false); end; TWasm.module_delete(module); TWasm.instance_delete(instance); // Call. writeln('Calling export...'); var arg := [ WASM_I32_VAL(3), WASM_I32_VAL(4) ]; var rs := [ WASM_INIT_VAL ]; var args := TWasmValVec.Create(arg); var results := TWasmValVec.Create(rs); if TWasm.func_call(run_func, @args, @results) <> nil then begin writeln('> Error calling function!'); exit(false); end; TWasm.extern_vec_delete(@exportfns); // Print result. writeln('Printing result...'); writeln('> '+IntToStr(rs[0].i32)); // Shut down. writeln('Shutting down...'); TWasm.store_delete(store); TWasm.engine_delete(engine); // All done. writeln('Done.'); exit(true); end; function CallbackSample() : Boolean; begin // Initialize. writeln('Initializing...'); var engine := TWasmEngine.New(); var store := TWasmStore.New(+engine); var module : TOwnModule; begin // Load binary. writeln('Loading binary...'); var binary := TWasmByteVec.NewEmpty; {$ifdef USE_WASMFILE} if not (+binary).LoadFromFile('callback.wasm') then begin writeln('> Error loading module!'); exit(false); end; {$else} var wat := '(module'+ ' (func $print (import "" "print") (param i32) (result i32))'+ ' (func $closure (import "" "closure") (result i32))'+ ' (func (export "run") (param $x i32) (param $y i32) (result i32)'+ ' (i32.add'+ ' (call $print (i32.add (local.get $x) (local.get $y)))'+ ' (call $closure)'+ ' )'+ ' )'+ ')'; {$ifndef USE_WASMER} if (+binary).Wat2Wasm(wat).IsError( procedure(e : PWasmtimeError) begin writeln(e.GetMessage()); end) then begin writeln('> Error loading wat!'); exit(false); end; {$else} (+binary).Wat2Wasm(wat); {$ifend} {$ifend} // Compile. writeln('Compiling module...'); module := TWasmModule.New(+store, +binary); if module.IsNone then begin writeln('> Error compiling module!'); exit(false); end; end; // Create external print functions. writeln('Creating callback...'); var print_func := TWasmFunc.New(+store, +TWasmFunctype.New([WASM_I32], [WASM_I32]), print_callback); var i := 42; var closure_func := TWasmFunc.NewWithEnv(+store, +TWasmFunctype.New([], [WASM_I32]), closure_callback, @i, nil); // Instantiate. Writeln('Instantiating module...'); var externs := [ (+print_func).AsExtern, (+closure_func).AsExtern ]; var instance := TWasmInstance.New(+store, +module, externs); if instance.IsNone then begin writeln('> Error instantiating module!'); exit(false); end; // Extract export. writeln('Extracting export...'); var exportfns := (+instance).GetExports; if (+exportfns).size = 0 then begin writeln('> Error accessing exports!'); exit(false); end; var run_func := (+exportfns).Items[0].AsFunc; if run_func = nil then begin writeln('> Error accessing export!'); exit(false); end; // Call. writeln('Calling export...'); var args := TWasmValVec.Create([ 3, 4 ]); var results := TWasmValVec.Create([nil]); if run_func.Call(@args, @results).IsError then begin writeln('> Error calling function!'); exit(false); end; // Print result. writeln('Printing result...'); writeln('> '+IntToStr(results.Items[0].i32)); // Shut down. writeln('Shutting down...'); // All done. writeln('Done.'); exit(true); end; end.
unit class_8; interface implementation uses system; type TC1 = class FData: Int32; function GetData: Int32; end; TC2 = class FC: TC1; constructor Create; end; function TC1.GetData: Int32; begin Result := FData; end; constructor TC2.Create; begin FC := TC1.Create(); FC.FData := 51; end; var C: TC2; G: Int32; procedure Test; begin C := TC2.Create(); G := C.FC.GetData(); end; initialization Test(); finalization Assert(G = 51); end.
PROGRAM Prime(INPUT, OUTPUT); CONST Min = 2; Max = 100; VAR Sieve: SET OF Min .. Max; Count, CountMax, CheckNumber: Min .. Max; BEGIN {Prime} Count := Min; CountMax := Max; Sieve := [Min .. Max]; WRITE('Простые числа от 2 до ', Max, ': ', Min, ' '); WHILE (Count < CountMax) DO BEGIN CheckNumber := Count; WHILE CheckNumber <= CountMax DO BEGIN IF (CheckNumber MOD Count = 0) THEN Sieve := Sieve - [CheckNumber]; CheckNumber := CheckNumber + 1 END; WHILE NOT (CountMax IN Sieve) DO CountMax := CountMax - 1; WHILE NOT (Count IN Sieve) DO Count := Count + 1; WRITE(Count, ' ') END; WRITELN END.{Prime}
{ Routines for sending CAN frames. } module can_send; define can_send; %include 'can2.ins.pas'; { ******************************************************************************** * * Subroutine CAN_SEND (CL, FRAME, STAT) * * Send the CAN frame described by FRAME. The CAN frame may be transmitted * after this routine returns. } procedure can_send ( {send a CAN frame} in out cl: can_t; {state for this use of the library} in frame: can_frame_t; {the CAN frame to send} out stat: sys_err_t); {completion status} val_param; begin sys_error_none (stat); {init to no error encountered} if cl.send_p <> nil then begin {send routine supplied ?} sys_thread_lock_enter (cl.lk_send); {acquire exclusive lock on sending} cl.send_p^ (addr(cl), cl.dat_p, frame, stat); {send the frame} sys_thread_lock_leave (cl.lk_send); {release sending lock} end; end;
unit ToolsU; interface uses ComObj, Windows, Messages, SysUtils, Classes, VCL.Controls, VCL.Forms, VCL.Dialogs, ShellAPI, SHFolder, DB, Variants, Printers, WinSpool, System.UITypes, VCL.Graphics; function IsEmptyString(AValue: string): boolean; function StripExtraSpaces(AValue: string; ARemoveTab: boolean = False; ARemoveCRLF: boolean = False): string; function StripCharsInSet(const AValue: string; ACharset: TSysCharSet): string; function GetUserAppDataDir: string; function GetShellFolderPath(AFolder: integer): string; function CheckDirectoryExists(ADirectory: string; ACreate: boolean): boolean; function ExecuteFile(const Operation, FileName, Params, DefaultDir: string; ShowCmd: word): integer; function ValidateFileName(AFileName: TFileName): TFileName; function GetFileSize(const AFileName: string): int64; procedure GetNetworkIPList(AList: TStrings); function IsFontInstalled(const AFontName: string): boolean; implementation uses IdStack, Winapi.ShlObj; function IsFontInstalled(const AFontName: string): boolean; begin Result := Screen.Fonts.IndexOf(AFontName) <> -1; end; function IsEmptyString(AValue: string): boolean; begin Result := Trim(AValue) = ''; end; function StripExtraSpaces(AValue: string; ARemoveTab: boolean = False; ARemoveCRLF: boolean = False): string; var i: integer; Source: string; begin Source := Trim(AValue); Source := StringReplace(Source, #160, ' ', [rfReplaceAll]); if ARemoveTab then Source := StringReplace(Source, #9, ' ', [rfReplaceAll]); if ARemoveCRLF then begin Source := StringReplace(Source, #10, ' ', [rfReplaceAll]); Source := StringReplace(Source, #13, ' ', [rfReplaceAll]); end; if Length(Source) > 1 then begin Result := Source[1]; for i := 2 to Length(Source) do begin if Source[i] = ' ' then begin if not(Source[i - 1] = ' ') then Result := Result + ' '; end else begin Result := Result + Source[i]; end; end; end else begin Result := Source; end; Result := Trim(Result); end; function GetShellFolderPath(AFolder: integer): string; const SHGFP_TYPE_CURRENT = 0; var path: array [0 .. MAX_PATH] of char; begin if SUCCEEDED(SHGetFolderPath(0, AFolder, 0, SHGFP_TYPE_CURRENT, @path[0])) then Result := path else Result := ''; end; function CheckDirectoryExists(ADirectory: string; ACreate: boolean): boolean; begin try if ACreate then begin if not DirectoryExists(ADirectory) then begin ForceDirectories(ADirectory); end; end; finally Result := DirectoryExists(ADirectory); end; end; function GetUserAppDataDir: string; begin Result := IncludeTrailingPathDelimiter (IncludeTrailingPathDelimiter(GetShellFolderPath(CSIDL_APPDATA)) + Application.Title); CheckDirectoryExists(Result, true); end; function ExecuteFile(const Operation, FileName, Params, DefaultDir: string; ShowCmd: word): integer; var zFileName, zParams, zDir: array [0 .. 255] of char; begin Result := ShellExecute(Application.Handle, PChar(Operation), StrPCopy(zFileName, FileName), StrPCopy(zParams, Params), StrPCopy(zDir, DefaultDir), ShowCmd); end; function StripCharsInSet(const AValue: string; ACharset: TSysCharSet): string; var i: integer; begin for i := 1 to Length(AValue) do begin if not CharInSet(AValue[i], ACharset) then Result := Result + AValue[i]; end; end; function ValidateFileName(AFileName: TFileName): TFileName; begin Result := AFileName; Result := StripExtraSpaces(Result, true, true); Result := StripCharsInSet(Result, ['\', '/', ':', '*', '?', '"', '<', '>', '|']); end; function GetFileSize(const AFileName: string): int64; var Handle: THandle; FindData: TWin32FindData; begin Handle := FindFirstFile(PChar(AFileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(Handle); if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then begin Int64Rec(Result).Lo := FindData.nFileSizeLow; Int64Rec(Result).Hi := FindData.nFileSizeHigh; Exit; end; end; Result := -1; end; procedure GetNetworkIPList(AList: TStrings); var Lidx: integer; LAddress: string; begin TIdStack.IncUsage; try if Assigned(GStack) then begin for Lidx := 0 to Pred(GStack.LocalAddresses.Count) do begin LAddress := StripExtraSpaces(GStack.LocalAddresses[Lidx], true, true); if not IsEmptyString(LAddress) then AList.Add(LAddress); end; end; finally TIdStack.DecUsage; AList.Add('127.0.0.1'); end; end; end.
UNIT huffman; INTERFACE CONST END_OF_INPUT=256; TYPE T_symbolFrequency=array[0..255] of longint; T_modelEntry=record previousSymbol:byte; followerFrequency:T_symbolFrequency end; T_arrayOfBoolean=array of boolean; HuffmanModel=(hm_DEFAULT,hm_LUCKY,hm_NUMBERS,hm_WIKIPEDIA,hm_MNH); CONST DEFAULT_PREV_SYMBOL=32; TYPE T_bitArray=object private datFill:longint; data:array of byte; trashBits:byte; cursorIndex:longint; FUNCTION getBit(CONST index:longint):boolean; public CONSTRUCTOR create; CONSTRUCTOR create(CONST rawData:ansistring); CONSTRUCTOR create(CONST prevArray:T_bitArray; CONST nextBit:boolean); DESTRUCTOR destroy; PROCEDURE append(CONST nextBit:boolean); inline; PROCEDURE append(CONST arr:T_bitArray; CONST finalAppend:boolean=false); PROCEDURE parseString(CONST stringOfZeroesAndOnes:ansistring); FUNCTION size:longint; PROPERTY bit[CONST index:longint]:boolean read getBit; default; FUNCTION getRawDataAsString:ansistring; FUNCTION getBitString:ansistring; FUNCTION bits:T_arrayOfBoolean; FUNCTION nextBit:boolean; FUNCTION hasNextBit:boolean; end; P_huffmanNode=^T_huffmanNode; T_huffmanNode=record symbol:word; frequency:longint; children:array[false..true] of P_huffmanNode; end; T_arrayOfHuffmanNode=array of P_huffmanNode; P_huffmanCode=^T_huffmanCode; T_huffmanCode=object private table:array [0..256] of T_bitArray; tree:P_huffmanNode; public CONSTRUCTOR create; CONSTRUCTOR create(CONST conservative:boolean; frequency: T_symbolFrequency); DESTRUCTOR destroy; PROCEDURE encodeNextSymbol(CONST c:char; VAR output:T_bitArray); PROCEDURE encodeEndOfInput(VAR output:T_bitArray); FUNCTION decodeNextSymbol(VAR input:T_bitArray):word; end; T_twoLevelHuffmanCode=object private subCodes:array[-1..255] of P_huffmanCode; initialized:boolean; myModel :HuffmanModel; busy :longint; codeCs :TRTLCriticalSection; PROCEDURE initialize(CONST conservative:boolean); PROCEDURE initialize(CONST model:array of T_modelEntry); PROCEDURE initialize; PROCEDURE clean; public CONSTRUCTOR create(CONST model:HuffmanModel); DESTRUCTOR destroy; FUNCTION encode(CONST s:ansistring):ansistring; FUNCTION decode(CONST s:ansistring):ansistring; end; FUNCTION huffyDecode(CONST s:ansistring; CONST model:HuffmanModel):ansistring; FUNCTION huffyEncode(CONST s:ansistring; CONST model:HuffmanModel):ansistring; IMPLEMENTATION USES mySys,sysutils; VAR huffmanCode:array[HuffmanModel] of T_twoLevelHuffmanCode; OPERATOR +(CONST x,y:T_symbolFrequency):T_symbolFrequency; VAR i:longint; k:int64; begin for i:=0 to 255 do begin k:=int64(x[i])+int64(y[i]); if (k>=0) and (k<maxLongint) then result[i]:=k else result[i]:=0; end; end; FUNCTION huffyDecode(CONST s: ansistring; CONST model:HuffmanModel): ansistring; begin result:=huffmanCode[model].decode(s); end; FUNCTION huffyEncode(CONST s: ansistring; CONST model:HuffmanModel): ansistring; begin result:=huffmanCode[model].encode(s); end; CONSTRUCTOR T_twoLevelHuffmanCode.create(CONST model:HuffmanModel); begin initCriticalSection(codeCs); initialized:=false; myModel:=model; busy:=0; memoryCleaner.registerObjectForCleanup(1,@clean); end; CONST DEFAULT_MODEL:{$i huffman_model_default.inc} PROCEDURE T_twoLevelHuffmanCode.initialize; CONST NUMERIC_MODEL:{$i huffman_model_numeric.inc} CONST WIKI_MODEL :{$i huffman_model_wiki.inc} CONST MNH_MODEL :{$i huffman_model_mnh.inc} begin enterCriticalSection(codeCs); try if not(initialized) then case myModel of hm_DEFAULT : initialize(true); hm_LUCKY : initialize(false); hm_NUMBERS : initialize(NUMERIC_MODEL); hm_WIKIPEDIA: initialize(WIKI_MODEL); hm_MNH : initialize(MNH_MODEL); end; finally leaveCriticalSection(codeCs); end; end; PROCEDURE T_twoLevelHuffmanCode.initialize(CONST conservative:boolean); VAR i:longint; begin new(subCodes[-1],create); for i:=0 to 255 do subCodes[i]:=nil; for i:=0 to length(DEFAULT_MODEL)-1 do new(subCodes[DEFAULT_MODEL[i].previousSymbol],create(conservative,DEFAULT_MODEL[i].followerFrequency)); for i:=0 to 255 do if (subCodes[i]=nil) then subCodes[i]:=subCodes[-1]; initialized:=true; end; PROCEDURE T_twoLevelHuffmanCode.initialize(CONST model:array of T_modelEntry); VAR fallbackModel:T_symbolFrequency; m:T_modelEntry; k:longint; i:longint; initCount:longint=0; begin for i:= 0 to 255 do fallbackModel[i]:=0; for i:=-1 to 255 do subCodes [i]:=nil; for i:=0 to 255 do if subCodes[i]=nil then for k:=0 to length(model)-1 do if model[k].previousSymbol=i then begin m:=model[k]; if subCodes[i]=nil then begin new(subCodes[i],create(false,m.followerFrequency)); inc(initCount); fallbackModel+=m.followerFrequency; end else writeln('DUPLICATE MODEL ENTRY FOR previousSymbol=',i,' at index ',k); end; //All initialized, no fallback needed if initCount>=256 then exit; //Fill gaps by using default model: for i:=0 to 255 do if subCodes[i]=nil then for k:=0 to length(DEFAULT_MODEL)-1 do if DEFAULT_MODEL[k].previousSymbol=i then begin m:=DEFAULT_MODEL[k]; new(subCodes[i],create(true,m.followerFrequency)); inc(initCount); fallbackModel+=m.followerFrequency; end; //All initialized, no further fallback needed if initCount>=256 then exit; //Fill gaps by using fallback model new(subCodes[-1],create(true,fallbackModel)); for i:=0 to 255 do if subCodes[i]=nil then begin subCodes[i]:=subCodes[-1]; end; initialized:=true; end; PROCEDURE T_twoLevelHuffmanCode.clean; VAR i:longint; begin if busy>0 then exit; enterCriticalSection(codeCs); try if initialized then begin for i:= 0 to 255 do if subCodes[i]=subCodes[-1] then subCodes[i]:=nil; for i:=-1 to 255 do if subCodes[i]<>nil then dispose(subCodes[i],destroy); end; initialized:=false; finally leaveCriticalSection(codeCs); end; end; DESTRUCTOR T_twoLevelHuffmanCode.destroy; begin memoryCleaner.unregisterObjectForCleanup(@clean); while busy>0 do sleep(1); clean; doneCriticalSection(codeCs); end; FUNCTION T_twoLevelHuffmanCode.encode(CONST s: ansistring): ansistring; VAR resultArr:T_bitArray; i:longint; prevSymbol:word=DEFAULT_PREV_SYMBOL; begin interLockedIncrement(busy); initialize; try resultArr.create; for i:=1 to length(s) do begin subCodes[prevSymbol]^.encodeNextSymbol(s[i],resultArr); prevSymbol:=ord(s[i]); end; subCodes[prevSymbol]^.encodeEndOfInput(resultArr); result:=resultArr.getRawDataAsString; resultArr.destroy; finally interlockedDecrement(busy); end; end; FUNCTION T_twoLevelHuffmanCode.decode(CONST s: ansistring): ansistring; VAR inputArr:T_bitArray; prevSymbol:word=DEFAULT_PREV_SYMBOL; nextSymbol:word; begin interLockedIncrement(busy); initialize; try result:=''; inputArr.create(s); while (inputArr.hasNextBit) and (prevSymbol<>END_OF_INPUT) do begin nextSymbol:=subCodes[prevSymbol]^.decodeNextSymbol(inputArr); if nextSymbol<>END_OF_INPUT then result:=result+chr(nextSymbol); prevSymbol:=nextSymbol; end; inputArr.destroy; finally interlockedDecrement(busy); end; end; CONSTRUCTOR T_huffmanCode.create; VAR symbolFrequency:T_symbolFrequency; entry:T_modelEntry; i:longint; begin for i:=0 to 255 do symbolFrequency[i]:=0; for entry in DEFAULT_MODEL do symbolFrequency+=entry.followerFrequency; create(true,symbolFrequency); end; PROCEDURE disposeTree(VAR root:P_huffmanNode); begin if root=nil then exit; if root^.children[false]<>nil then disposeTree(root^.children[false]); if root^.children[true ]<>nil then disposeTree(root^.children[true ]); freeMem(root,sizeOf(T_huffmanNode)); end; CONSTRUCTOR T_huffmanCode.create(CONST conservative:boolean; frequency: T_symbolFrequency); PROCEDURE buildTreeFromLeafs(L: T_arrayOfHuffmanNode); VAR i,i0,i1,j:longint; newNode:P_huffmanNode; PROCEDURE traverseTree(CONST prefix:ansistring; VAR root:P_huffmanNode); begin if root^.symbol<=256 then table[root^.symbol].parseString(prefix) else begin traverseTree(prefix+'0',root^.children[false]); traverseTree(prefix+'1',root^.children[true ]); end; end; begin //Build binary tree while length(L)>1 do begin i0:=0; i1:=1; for i:=2 to length(L)-1 do if (L[i]^.frequency<L[i0]^.frequency) then i0:=i else if (L[i]^.frequency<L[i1]^.frequency) then i1:=i; getMem(newNode,sizeOf(T_huffmanNode)); newNode^.symbol:=65535; //no leaf-> no symbol newNode^.frequency:=L[i0]^.frequency+L[i1]^.frequency; newNode^.children[false]:=L[i0]; newNode^.children[true ]:=L[i1]; j:=0; for i:=0 to length(L)-1 do if (i<>i0) and (i<>i1) then begin L[j]:=L[i]; inc(j); end; setLength(L,length(L)-1); L[length(L)-1]:=newNode; end; //parse tree: tree:=L[0]; traverseTree('',tree); end; PROCEDURE initModel; VAR parentNodes:array of P_huffmanNode=(); i:longint; begin setLength(parentNodes,END_OF_INPUT+1); for i:=0 to length(frequency)-1 do begin getMem(parentNodes[i],sizeOf(T_huffmanNode)); parentNodes[i]^.frequency:=frequency[i]; parentNodes[i]^.symbol:=i; parentNodes[i]^.children[false]:=nil; parentNodes[i]^.children[true ]:=nil; end; getMem(parentNodes[END_OF_INPUT],sizeOf(T_huffmanNode)); parentNodes[END_OF_INPUT]^.frequency:=1; parentNodes[END_OF_INPUT]^.symbol:=END_OF_INPUT; parentNodes[END_OF_INPUT]^.children[false]:=nil; parentNodes[END_OF_INPUT]^.children[true ]:=nil; buildTreeFromLeafs(parentNodes); end; VAR i:longint; k:longint=0; tot:int64=0; begin //Fix frequencies:---------------------- for i:=0 to 255 do inc(tot,frequency[i]); while tot>(maxLongint shr 2) do begin tot:=tot shr 1; inc(k); end; if k>0 then for i:=0 to 255 do frequency[i]:=frequency[i] shr k; //----------------------:Fix frequencies for i:=0 to length(table)-1 do table[i].create; tree:=nil; if conservative or (k>0) then begin for i:=0 to length(frequency)-1 do if frequency[i]<=0 then frequency[i]:=1; end else begin for i:=0 to length(frequency)-1 do if frequency[i]<=0 then frequency[i]:=0; end; initModel; end; DESTRUCTOR T_huffmanCode.destroy; VAR i:longint; begin disposeTree(tree); for i:=0 to length(table)-1 do table[i].destroy; end; PROCEDURE T_huffmanCode.encodeNextSymbol(CONST c: char; VAR output: T_bitArray); begin output.append(table[ord(c)]); end; PROCEDURE T_huffmanCode.encodeEndOfInput(VAR output: T_bitArray); begin output.append(table[END_OF_INPUT],true); end; FUNCTION T_huffmanCode.decodeNextSymbol(VAR input:T_bitArray): word; VAR currentNode:P_huffmanNode; begin currentNode:=tree; while input.hasNextBit do begin currentNode:=currentNode^.children[input.nextBit]; if currentNode^.symbol<=END_OF_INPUT then exit(currentNode^.symbol); end; result:=END_OF_INPUT; end; FUNCTION T_bitArray.getBit(CONST index: longint): boolean; VAR byteIndex:longint; bitMask:byte; begin if index<size then begin byteIndex:=index shr 3; bitMask:=1 shl (7-(index and 7)); result:=data[byteIndex] and bitMask=bitMask; end else result:=false; end; CONSTRUCTOR T_bitArray.create; begin setLength(data,0); datFill:=0; trashBits:=0; cursorIndex:=0; end; CONSTRUCTOR T_bitArray.create(CONST rawData: ansistring); VAR i:longint; begin setLength(data,length(rawData)); for i:=0 to length(data)-1 do data[i]:=ord(rawData[i+1]); datFill:=length(data); trashBits:=0; cursorIndex:=0; end; CONSTRUCTOR T_bitArray.create(CONST prevArray: T_bitArray; CONST nextBit: boolean); VAR i:longint; begin setLength(data,length(prevArray.data)); for i:=0 to length(data)-1 do data[i]:=prevArray.data[i]; trashBits:=prevArray.trashBits; datFill:=prevArray.datFill; append(nextBit); cursorIndex:=0; end; DESTRUCTOR T_bitArray.destroy; begin setLength(data,0); trashBits:=0; end; PROCEDURE T_bitArray.append(CONST nextBit: boolean); begin if trashBits=0 then begin if datFill>=length(data) then setLength(data,1+round(1.1*datFill)); inc(datFill); data[datFill-1]:=0; trashBits:=7; if nextBit then data[datFill-1]:=data[datFill-1] or (1 shl trashBits); end else begin dec(trashBits); if nextBit then data[datFill-1]:=data[datFill-1] or (1 shl trashBits); end; end; PROCEDURE T_bitArray.append(CONST arr: T_bitArray; CONST finalAppend: boolean); VAR i:longint; b:boolean; begin if finalAppend then begin i:=0; while (trashBits<>0) and (i<arr.size) do begin append(arr[i]); inc(i); end; end else for b in arr.bits do append(b); end; PROCEDURE T_bitArray.parseString(CONST stringOfZeroesAndOnes: ansistring); VAR i:longint; begin setLength(data,0); trashBits:=0; for i:=1 to length(stringOfZeroesAndOnes) do append(stringOfZeroesAndOnes[i]='1'); end; FUNCTION T_bitArray.size: longint; begin result:=datFill shl 3-trashBits; end; FUNCTION T_bitArray.getRawDataAsString: ansistring; VAR i:longint; begin result:=''; for i:=0 to datFill-1 do result:=result+chr(data[i]); end; FUNCTION T_bitArray.getBitString: ansistring; VAR i:longint; begin result:=''; for i:=0 to size-1 do if bit[i] then result:=result+'1' else result:=result+'0'; end; FUNCTION T_bitArray.bits:T_arrayOfBoolean; CONST M:array[0..7] of byte=(1, 2, 4, 8, 16,32,64,128); VAR i:longint; k:longint=0; begin initialize(result); setLength(result,datFill shl 3); for i:=0 to datFill-1 do begin result[k]:=(data[i] and M[7])>0; inc(k); result[k]:=(data[i] and M[6])>0; inc(k); result[k]:=(data[i] and M[5])>0; inc(k); result[k]:=(data[i] and M[4])>0; inc(k); result[k]:=(data[i] and M[3])>0; inc(k); result[k]:=(data[i] and M[2])>0; inc(k); result[k]:=(data[i] and M[1])>0; inc(k); result[k]:=(data[i] and M[0])>0; inc(k); end; setLength(result,size); end; FUNCTION T_bitArray.nextBit: boolean; begin result:=getBit(cursorIndex); inc(cursorIndex); end; FUNCTION T_bitArray.hasNextBit: boolean; begin result:=cursorIndex<size; end; INITIALIZATION huffmanCode[hm_DEFAULT ].create(hm_DEFAULT ); huffmanCode[hm_LUCKY ].create(hm_LUCKY ); huffmanCode[hm_NUMBERS ].create(hm_NUMBERS ); huffmanCode[hm_WIKIPEDIA].create(hm_WIKIPEDIA); huffmanCode[hm_MNH ].create(hm_MNH ); FINALIZATION huffmanCode[hm_DEFAULT ].destroy; huffmanCode[hm_LUCKY ].destroy; huffmanCode[hm_NUMBERS ].destroy; huffmanCode[hm_WIKIPEDIA].destroy; huffmanCode[hm_MNH ].destroy; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConfig.PackagesFrame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, Data.Bind.Controls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.Bind.Navigator, FMX.Platform, System.StrUtils, RSConfig.NameValueFrame, FMX.ListBox, RSConfig.ListControlFrame; type TPackagesFrame = class(TFrame) ListControlFrame1: TListControlFrame; ListBox1: TListBox; private { Private declarations } public { Public declarations } ActiveFrame: TNameValueFrame; constructor Create(AOwner: TComponent); override; procedure Callback(Sender: TObject); procedure LoadSectionList; procedure SaveSectionList; end; implementation {$R *.fmx} uses RSConsole.FormConfig, RSConfig.ConfigDM, RSConfig.Consts; constructor TPackagesFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); ListControlFrame1.HelpButton.Hint := strPackagesHelp; end; procedure TPackagesFrame.Callback(Sender: TObject); var LOpenDialog: TOpenDialog; begin ActiveFrame := TNameValueFrame(Sender); LOpenDialog := TOpenDialog.Create(Self); try LOpenDialog.DefaultExt := 'bpl'; LOpenDialog.Filter := strResModuleFiles + '|*.bpl'; LOpenDialog.FileName := ExtractFileName(ActiveFrame.NameEdit.Text); LOpenDialog.InitialDir := IfThen(ActiveFrame.NameEdit.Text <> '', ExtractFilePath(ActiveFrame.NameEdit.Text), GetCurrentDir); if LOpenDialog.Execute then ActiveFrame.NameEdit.Text := LOpenDialog.FileName; finally LOpenDialog.Free; end; ActiveFrame := nil; end; procedure TPackagesFrame.LoadSectionList; begin ListControlFrame1.SetFrameType(PACKAGES_FRAME); ListControlFrame1.SetListBox(ListBox1); ListControlFrame1.SetCallback(Callback); ConfigDM.LoadSectionList(strServerPackages, ListBox1, Callback); end; procedure TPackagesFrame.SaveSectionList; begin ConfigDM.SaveSectionList(strServerPackages, ListBox1); end; end.
{ /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.net/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HproseIO.pas * * * * hprose io unit for delphi. * * * * LastModified: Feb 8, 2014 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ } unit HproseIO; {$I Hprose.inc} interface uses Classes, HproseCommon {$IFDEF Supports_Generics}, Generics.Collections {$ENDIF}, TypInfo; const { Hprose Serialize Tags } HproseTagInteger :AnsiChar = 'i'; HproseTagLong :AnsiChar = 'l'; HproseTagDouble :AnsiChar = 'd'; HproseTagNull :AnsiChar = 'n'; HproseTagEmpty :AnsiChar = 'e'; HproseTagTrue :AnsiChar = 't'; HproseTagFalse :AnsiChar = 'f'; HproseTagNaN :AnsiChar = 'N'; HproseTagInfinity :AnsiChar = 'I'; HproseTagDate :AnsiChar = 'D'; HproseTagTime :AnsiChar = 'T'; HproseTagUTC :AnsiChar = 'Z'; HproseTagBytes :AnsiChar = 'b'; HproseTagUTF8Char :AnsiChar = 'u'; HproseTagString :AnsiChar = 's'; HproseTagGuid :AnsiChar = 'g'; HproseTagList :AnsiChar = 'a'; HproseTagMap :AnsiChar = 'm'; HproseTagClass :AnsiChar = 'c'; HproseTagObject :AnsiChar = 'o'; HproseTagRef :AnsiChar = 'r'; { Hprose Serialize Marks } HproseTagPos :AnsiChar = '+'; HproseTagNeg :AnsiChar = '-'; HproseTagSemicolon :AnsiChar = ';'; HproseTagOpenbrace :AnsiChar = '{'; HproseTagClosebrace :AnsiChar = '}'; HproseTagQuote :AnsiChar = '"'; HproseTagPoint :AnsiChar = '.'; { Hprose Protocol Tags } HproseTagFunctions :AnsiChar = 'F'; HproseTagCall :AnsiChar = 'C'; HproseTagResult :AnsiChar = 'R'; HproseTagArgument :AnsiChar = 'A'; HproseTagError :AnsiChar = 'E'; HproseTagEnd :AnsiChar = 'z'; type THproseReader = class private FStream: TStream; FRefList: IList; FClassRefList: IList; FAttrRefMap: IMap; function UnexpectedTag(Tag: AnsiChar; const ExpectTags: string = ''): EHproseException; function TagToString(Tag: AnsiChar): string; function ReadByte: Byte; function ReadInt64(Tag: AnsiChar): Int64; overload; {$IFDEF Supports_UInt64} function ReadUInt64(Tag: AnsiChar): UInt64; overload; {$ENDIF} function ReadStringAsWideString: WideString; function ReadBooleanArray(Count: Integer): Variant; function ReadShortIntArray(Count: Integer): Variant; function ReadByteArray(Count: Integer): Variant; function ReadSmallIntArray(Count: Integer): Variant; function ReadWordArray(Count: Integer): Variant; function ReadIntegerArray(Count: Integer): Variant; function ReadLongWordArray(Count: Integer): Variant; function ReadSingleArray(Count: Integer): Variant; function ReadDoubleArray(Count: Integer): Variant; function ReadCurrencyArray(Count: Integer): Variant; function ReadDateTimeArray(Count: Integer): Variant; function ReadWideStringArray(Count: Integer): Variant; function ReadVariantArray(Count: Integer): Variant; overload; function ReadInterfaceArray(Count: Integer): Variant; function ReadDynArrayWithoutTag(varType: Integer): Variant; function ReadIList(AClass: TClass): IList; function ReadList(AClass: TClass): TAbstractList; function ReadListAsIMap(AClass: TClass): IMap; function ReadListAsMap(AClass: TClass): TAbstractMap; function ReadIMap(AClass: TClass): IMap; function ReadMap(AClass: TClass): TAbstractMap; function ReadMapAsInterface(AClass: TClass; const IID: TGUID): IInterface; function ReadMapAsObject(AClass: TClass): TObject; function ReadObjectAsIMap(AClass: TMapClass): IMap; function ReadObjectAsMap(AClass: TMapClass): TAbstractMap; function ReadObjectAsInterface(AClass: TClass; const IID: TGUID): IInterface; function ReadObjectWithoutTag(AClass: TClass): TObject; overload; procedure ReadClass; function ReadRef: Variant; {$IFDEF Supports_Generics} procedure ReadArray<T>(var DynArray: TArray<T>; TypeInfo: PTypeInfo); overload; procedure ReadArray(TypeInfo: PTypeInfo; out DynArray); overload; procedure ReadDynArray(TypeInfo: PTypeInfo; out DynArray); overload; {$IFDEF Supports_Rtti} function ReadTList<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TList<T>; overload; function ReadTList(TypeInfo: PTypeInfo): TObject; overload; function ReadTQueue<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TQueue<T>; overload; function ReadTQueue(TypeInfo: PTypeInfo): TObject; overload; function ReadTStack<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TStack<T>; overload; function ReadTStack(TypeInfo: PTypeInfo): TObject; overload; function ReadTDictionary2<TKey, TValue>( TypeInfo, KeyTypeInfo, ValueTypeInfo: PTypeInfo): TDictionary<TKey, TValue>; function ReadTDictionary1<TKey>(TypeInfo, KeyTypeInfo, ValueTypeInfo: PTypeInfo; ValueSize: Integer): TObject; function ReadTDictionary(TypeInfo: PTypeInfo): TObject; function UnserializeTypeAsT<T>(TypeInfo: PTypeInfo): T; {$ENDIF} function ReadSmartObject(TypeInfo: PTypeInfo): ISmartObject; {$ENDIF} procedure ReadRaw(const OStream: TStream; Tag: AnsiChar); overload; procedure ReadInfinityRaw(const OStream: TStream); procedure ReadNumberRaw(const OStream: TStream); procedure ReadDateTimeRaw(const OStream: TStream); procedure ReadUTF8CharRaw(const OStream: TStream); procedure ReadStringRaw(const OStream: TStream); procedure ReadBytesRaw(const OStream: TStream); procedure ReadGuidRaw(const OStream: TStream); procedure ReadComplexRaw(const OStream: TStream); public constructor Create(AStream: TStream); procedure CheckTag(expectTag: AnsiChar); function CheckTags(const expectTags: RawByteString): AnsiChar; function ReadUntil(Tag: AnsiChar): string; function ReadInt(Tag: AnsiChar): Integer; function ReadIntegerWithoutTag: Integer; function ReadLongWithoutTag: string; function ReadInfinityWithoutTag: Extended; function ReadDoubleWithoutTag: Extended; function ReadDateWithoutTag: TDateTime; function ReadTimeWithoutTag: TDateTime; function ReadUTF8CharWithoutTag: WideChar; function ReadStringWithoutTag: WideString; function ReadBytesWithoutTag: Variant; function ReadGuidWithoutTag: string; function ReadListWithoutTag: Variant; function ReadMapWithoutTag: Variant; function ReadObjectWithoutTag: Variant; overload; function ReadInteger: Integer; function ReadInt64: Int64; overload; {$IFDEF Supports_UInt64} function ReadUInt64: UInt64; overload; {$ENDIF} function ReadExtended: Extended; function ReadCurrency: Currency; function ReadBoolean: Boolean; function ReadDateTime: TDateTime; function ReadUTF8Char: WideChar; function ReadString: WideString; function ReadBytes: Variant; function ReadGuid: string; function ReadDynArray(varType: Integer): Variant; overload; function ReadVariantArray: TVariants; overload; function ReadInterface(AClass: TClass; const IID: TGUID): IInterface; function ReadObject(AClass: TClass): TObject; {$IFDEF Supports_Generics} procedure Unserialize(TypeInfo: PTypeInfo; out Value); overload; function Unserialize<T>: T; overload; {$ENDIF} function Unserialize: Variant; overload; function Unserialize(TypeInfo: PTypeInfo): Variant; overload; function ReadRaw: TMemoryStream; overload; procedure ReadRaw(const OStream: TStream); overload; procedure Reset; property Stream: TStream read FStream; end; THproseWriter = class private FStream: TStream; FRefList: IList; FClassRefList: IList; procedure WriteRef(Value: Integer); function WriteClass(const Instance: TObject): Integer; procedure WriteRawByteString(const S: RawByteString); procedure WriteShortIntArray(var P; Count: Integer); procedure WriteSmallIntArray(var P; Count: Integer); procedure WriteWordArray(var P; Count: Integer); procedure WriteIntegerArray(var P; Count: Integer); procedure WriteCurrencyArray(var P; Count: Integer); procedure WriteLongWordArray(var P; Count: Integer); procedure WriteSingleArray(var P; Count: Integer); procedure WriteDoubleArray(var P; Count: Integer); procedure WriteBooleanArray(var P; Count: Integer); procedure WriteWideStringArray(var P; Count: Integer); procedure WriteDateTimeArray(var P; Count: Integer); procedure WriteVariantArray(var P; Count: Integer); procedure WriteWideString(const Str: WideString); procedure WriteStrings(const SS: TStrings); procedure WriteList(const AList: TAbstractList); overload; procedure WriteMap(const AMap: TAbstractMap); overload; {$IFDEF Supports_Generics} procedure Serialize(const Value; TypeInfo: Pointer); overload; procedure WriteArray(const DynArray; const Name: string); overload; procedure WriteArrayWithRef(const DynArray; TypeInfo: Pointer); overload; procedure WriteList(const AList: TObject); overload; procedure WriteObjectList(const AList: TObject); procedure WriteQueue(const AQueue: TObject); procedure WriteObjectQueue(const AQueue: TObject); procedure WriteStack(const AStack: TObject); procedure WriteObjectStack(const AStack: TObject); procedure WriteDictionary(const ADict: TObject); procedure WriteObjectDictionary(const ADict: TObject); procedure WriteTDictionary1<TKey>(const ADict: TObject; ValueSize: Integer; KeyTypeInfo, ValueTypeInfo: Pointer); procedure WriteTDictionary2<TKey, TValue>(const ADict: TDictionary<TKey, TValue>; KeyTypeInfo, ValueTypeInfo: Pointer); {$ENDIF} public constructor Create(AStream: TStream); procedure Serialize(const Value: Variant); overload; procedure Serialize(const Value: array of const); overload; procedure WriteInteger(I: Integer); procedure WriteLong(L: Int64); overload; {$IFDEF DELPHI2009_UP} procedure WriteLong(L: UInt64); overload; {$ENDIF} {$IFDEF FPC} procedure WriteLong(L: QWord); overload; {$ENDIF} procedure WriteLong(const L: RawByteString); overload; procedure WriteDouble(D: Extended); procedure WriteCurrency(C: Currency); procedure WriteNull(); procedure WriteEmpty(); procedure WriteBoolean(B: Boolean); procedure WriteNaN(); procedure WriteInfinity(Positive: Boolean); procedure WriteUTF8Char(C: WideChar); procedure WriteDateTime(const ADateTime: TDateTime); procedure WriteDateTimeWithRef(const ADateTime: TDateTime); procedure WriteBytes(const Bytes: Variant); procedure WriteBytesWithRef(const Bytes: Variant); procedure WriteString(const S: WideString); procedure WriteStringWithRef(const S: WideString); procedure WriteArray(const Value: Variant); overload; procedure WriteArrayWithRef(const Value: Variant); overload; procedure WriteArray(const Value: array of const); overload; procedure WriteList(const AList: IList); overload; procedure WriteListWithRef(const AList: IList); overload; procedure WriteMap(const AMap: IMap); overload; procedure WriteMapWithRef(const AMap: IMap); {$IFDEF Supports_Generics} procedure Serialize<T>(const Value: T); overload; procedure WriteArray<T>(const DynArray: array of T); overload; procedure WriteDynArray<T>(const DynArray: TArray<T>); procedure WriteDynArrayWithRef<T>(const DynArray: TArray<T>); overload; procedure WriteTList<T>(const AList: TList<T>); overload; procedure WriteTListWithRef<T>(const AList: TList<T>); overload; procedure WriteTQueue<T>(const AQueue: TQueue<T>); overload; procedure WriteTQueueWithRef<T>(const AQueue: TQueue<T>); procedure WriteTStack<T>(const AStack: TStack<T>); overload; procedure WriteTStackWithRef<T>(const AStack: TStack<T>); procedure WriteTDictionary<TKey, TValue>(const ADict: TDictionary<TKey, TValue>); overload; procedure WriteTDictionaryWithRef<TKey, TValue>(const ADict: TDictionary<TKey, TValue>); {$ELSE} procedure Serialize(const Value: TObject); overload; {$ENDIF} procedure WriteObject(const AObject: TObject); procedure WriteObjectWithRef(const AObject: TObject); procedure WriteInterface(const Intf: IInterface); procedure WriteInterfaceWithRef(const Intf: IInterface); procedure WriteSmartObject(const SmartObject: ISmartObject); procedure WriteSmartObjectWithRef(const SmartObject: ISmartObject); procedure Reset; property Stream: TStream read FStream; end; THproseFormatter = class public class function Serialize(const Value: Variant): RawByteString; overload; class function Serialize(const Value: array of const): RawByteString; overload; {$IFDEF Supports_Generics} class function Serialize<T>(const Value: T): RawByteString; overload; class function Unserialize<T>(const Data:RawByteString): T; overload; {$ELSE} class function Serialize(const Value: TObject): RawByteString; overload; {$ENDIF} class function Unserialize(const Data:RawByteString): Variant; overload; class function Unserialize(const Data:RawByteString; TypeInfo: Pointer): Variant; overload; end; function HproseSerialize(const Value: TObject): RawByteString; overload; function HproseSerialize(const Value: Variant): RawByteString; overload; function HproseSerialize(const Value: array of const): RawByteString; overload; function HproseUnserialize(const Data:RawByteString; TypeInfo: Pointer = nil): Variant; implementation uses DateUtils, Math, RTLConsts, {$IFNDEF FPC}StrUtils, SysConst, {$ENDIF} {$IFDEF Supports_Rtti}Rtti, {$ENDIF} SysUtils, Variants; type PSmallIntArray = ^TSmallIntArray; TSmallIntArray = array[0..MaxInt div Sizeof(SmallInt) - 1] of SmallInt; PShortIntArray = ^TShortIntArray; TShortIntArray = array[0..MaxInt div Sizeof(ShortInt) - 1] of ShortInt; PLongWordArray = ^TLongWordArray; TLongWordArray = array[0..MaxInt div Sizeof(LongWord) - 1] of LongWord; PSingleArray = ^TSingleArray; TSingleArray = array[0..MaxInt div Sizeof(Single) - 1] of Single; PDoubleArray = ^TDoubleArray; TDoubleArray = array[0..MaxInt div Sizeof(Double) - 1] of Double; PCurrencyArray = ^TCurrencyArray; TCurrencyArray = array[0..MaxInt div Sizeof(Currency) - 1] of Currency; PWordBoolArray = ^TWordBoolArray; TWordBoolArray = array[0..MaxInt div Sizeof(WordBool) - 1] of WordBool; PWideStringArray = ^TWideStringArray; TWideStringArray = array[0..MaxInt div Sizeof(WideString) - 1] of WideString; PDateTimeArray = ^TDateTimeArray; TDateTimeArray = array[0..MaxInt div Sizeof(TDateTime) - 1] of TDateTime; PVariantArray = ^TVariantArray; TVariantArray = array[0..MaxInt div Sizeof(Variant) - 1] of Variant; PInterfaceArray = ^TInterfaceArray; TInterfaceArray = array[0..MaxInt div Sizeof(Variant) - 1] of IInterface; SerializeCache = record RefCount: Integer; Data: RawByteString; end; PSerializeCache = ^SerializeCache; var PropertiesCache: IMap; const htInteger = 'i'; htLong = 'l'; htDouble = 'd'; htNull = 'n'; htEmpty = 'e'; htTrue = 't'; htFalse = 'f'; htNaN = 'N'; htInfinity = 'I'; htDate = 'D'; htTime = 'T'; htBytes = 'b'; htUTF8Char = 'u'; htString = 's'; htGuid = 'g'; htList = 'a'; htMap = 'm'; htClass = 'c'; htObject = 'o'; htRef = 'r'; htError = 'E'; HproseTagBoolean :array[Boolean] of AnsiChar = ('f', 't'); HproseTagSign :array[Boolean] of AnsiChar = ('-', '+'); {$IFDEF Supports_Generics} type TB1 = Byte; TB2 = Word; TB4 = LongWord; TB8 = UInt64; function IsSmartObject(const Name: string): Boolean; inline; begin Result := AnsiStartsText('ISmartObject<', Name) or AnsiStartsText('HproseCommon.ISmartObject<', Name); end; function GetElementName(const Name: string): string; var I, L: Integer; begin L := Length(Name); for I := 1 to L do if Name[I] = '<' then begin Result := AnsiMidStr(Name, I + 1, L - I - 1); Break; end; end; procedure SplitKeyValueTypeName(const Name: string; var KeyName, ValueName: string); var I, N, P, L: Integer; begin L := Length(Name); N := 0; P := 0; for I := 1 to L do begin case Name[I] of '<': Inc(N); '>': Dec(N); ',': if N = 0 then begin P := I; Break; end; end; end; if P > 0 then begin KeyName := AnsiMidStr(Name, 1, P - 1); ValueName := AnsiMidStr(Name, P + 1, L - P); end; end; {$ENDIF} function GetStoredPropList(Instance: TObject; out PropList: PPropList): Integer; var I, Count: Integer; TempList: PPropList; begin Count := GetPropList(PTypeInfo(Instance.ClassInfo), TempList); PropList := nil; Result := 0; if Count > 0 then try for I := 0 to Count - 1 do if IsStoredProp(Instance, TempList^[I]) then Inc(Result); GetMem(PropList, Result * SizeOf(Pointer)); for I := 0 to Result - 1 do if IsStoredProp(Instance, TempList^[I]) then PropList^[I] := TempList^[I]; finally FreeMem(TempList); end; end; { GetPropValue/SetPropValue } procedure PropertyNotFound(const Name: string); begin raise EPropertyError.CreateResFmt(@SUnknownProperty, [Name]); end; procedure PropertyConvertError(const Name: AnsiString); begin raise EPropertyConvertError.CreateResFmt(@SInvalidPropertyType, [Name]); end; {$IFNDEF FPC} {$IFNDEF DELPHI2007_UP} type TAccessStyle = (asFieldData, asAccessor, asIndexedAccessor); function GetAccessToProperty(Instance: TObject; PropInfo: PPropInfo; AccessorProc: Longint; out FieldData: Pointer; out Accessor: TMethod): TAccessStyle; begin if (AccessorProc and $FF000000) = $FF000000 then begin // field - Getter is the field's offset in the instance data FieldData := Pointer(Integer(Instance) + (AccessorProc and $00FFFFFF)); Result := asFieldData; end else begin if (AccessorProc and $FF000000) = $FE000000 then // virtual method - Getter is a signed 2 byte integer VMT offset Accessor.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(AccessorProc))^) else // static method - Getter is the actual address Accessor.Code := Pointer(AccessorProc); Accessor.Data := Instance; if PropInfo^.Index = Integer($80000000) then // no index Result := asAccessor else Result := asIndexedAccessor; end; end; function GetDynArrayProp(Instance: TObject; PropInfo: PPropInfo): Pointer; type { Need a(ny) dynamic array type to force correct call setup. (Address of result passed in EDX) } TDynamicArray = array of Byte; type TDynArrayGetProc = function: TDynamicArray of object; TDynArrayIndexedGetProc = function (Index: Integer): TDynamicArray of object; var M: TMethod; begin case GetAccessToProperty(Instance, PropInfo, Longint(PropInfo^.GetProc), Result, M) of asFieldData: Result := PPointer(Result)^; asAccessor: Result := Pointer(TDynArrayGetProc(M)()); asIndexedAccessor: Result := Pointer(TDynArrayIndexedGetProc(M)(PropInfo^.Index)); end; end; procedure SetDynArrayProp(Instance: TObject; PropInfo: PPropInfo; const Value: Pointer); type TDynArraySetProc = procedure (const Value: Pointer) of object; TDynArrayIndexedSetProc = procedure (Index: Integer; const Value: Pointer) of object; var P: Pointer; M: TMethod; begin case GetAccessToProperty(Instance, PropInfo, Longint(PropInfo^.SetProc), P, M) of asFieldData: asm MOV ECX, PropInfo MOV ECX, [ECX].TPropInfo.PropType MOV ECX, [ECX] MOV EAX, [P] MOV EDX, Value CALL System.@DynArrayAsg end; asAccessor: TDynArraySetProc(M)(Value); asIndexedAccessor: TDynArrayIndexedSetProc(M)(PropInfo^.Index, Value); end; end; {$ENDIF} {$ELSE} function GetDynArrayProp(Instance: TObject; PropInfo: PPropInfo): Pointer; type { Need a(ny) dynamic array type to force correct call setup. (Address of result passed in EDX) } TDynamicArray = array of Byte; type TDynArrayGetProc = function: TDynamicArray of object; TDynArrayIndexedGetProc = function (Index: Integer): TDynamicArray of object; var AMethod: TMethod; begin case (PropInfo^.PropProcs) and 3 of ptfield: Result := PPointer(Pointer(Instance) + PtrUInt(PropInfo^.GetProc))^; ptstatic, ptvirtual: begin if (PropInfo^.PropProcs and 3) = ptStatic then AMethod.Code := PropInfo^.GetProc else AMethod.Code := PPointer(Pointer(Instance.ClassType) + PtrUInt(PropInfo^.GetProc))^; AMethod.Data := Instance; if ((PropInfo^.PropProcs shr 6) and 1) <> 0 then Result := TDynArrayIndexedGetProc(AMethod)(PropInfo^.Index) else Result := TDynArrayGetProc(AMethod)(); end; end; end; procedure SetDynArrayProp(Instance: TObject; PropInfo: PPropInfo; const Value: Pointer); type TDynArraySetProc = procedure (const Value: Pointer) of object; TDynArrayIndexedSetProc = procedure (Index: Integer; const Value: Pointer) of object; var AMethod: TMethod; begin case (PropInfo^.PropProcs shr 2) and 3 of ptfield: PPointer(Pointer(Instance) + PtrUInt(PropInfo^.SetProc))^ := Value; ptstatic, ptvirtual: begin if ((PropInfo^.PropProcs shr 2) and 3) = ptStatic then AMethod.Code := PropInfo^.SetProc else AMethod.Code := PPointer(Pointer(Instance.ClassType) + PtrUInt(PropInfo^.SetProc))^; AMethod.Data := Instance; if ((PropInfo^.PropProcs shr 6) and 1) <> 0 then TDynArrayIndexedSetProc(AMethod)(PropInfo^.Index, Value) else TDynArraySetProc(AMethod)(Value); end; end; end; function GetInterfaceProp(Instance: TObject; PropInfo: PPropInfo): IInterface; type TInterfaceGetProc = function: IInterface of object; TInterfaceIndexedGetProc = function (Index: Integer): IInterface of object; var P: ^IInterface; AMethod: TMethod; begin case (PropInfo^.PropProcs) and 3 of ptfield: begin P := Pointer(Pointer(Instance) + PtrUInt(PropInfo^.GetProc)); Result := P^; // auto ref count end; ptstatic, ptvirtual: begin if (PropInfo^.PropProcs and 3) = ptStatic then AMethod.Code := PropInfo^.GetProc else AMethod.Code := PPointer(Pointer(Instance.ClassType) + PtrUInt(PropInfo^.GetProc))^; AMethod.Data := Instance; if ((PropInfo^.PropProcs shr 6) and 1) <> 0 then Result := TInterfaceIndexedGetProc(AMethod)(PropInfo^.Index) else Result := TInterfaceGetProc(AMethod)(); end; end; end; procedure SetInterfaceProp(Instance: TObject; PropInfo: PPropInfo; const Value: IInterface); type TInterfaceSetProc = procedure (const Value: IInterface) of object; TInterfaceIndexedSetProc = procedure (Index: Integer; const Value: IInterface) of object; var P: ^IInterface; AMethod: TMethod; begin case (PropInfo^.PropProcs shr 2) and 3 of ptfield: begin P := Pointer(Pointer(Instance) + PtrUInt(PropInfo^.SetProc)); P^ := Value; // auto ref count end; ptstatic, ptvirtual: begin if ((PropInfo^.PropProcs shr 2) and 3) = ptStatic then AMethod.Code := PropInfo^.SetProc else AMethod.Code := PPointer(Pointer(Instance.ClassType) + PtrUInt(PropInfo^.SetProc))^; AMethod.Data := Instance; if ((PropInfo^.PropProcs shr 6) and 1) <> 0 then TInterfaceIndexedSetProc(AMethod)(PropInfo^.Index, Value) else TInterfaceSetProc(AMethod)(Value); end; end; end; {$ENDIF} function GetPropValue(Instance: TObject; PropInfo: PPropInfo): Variant; var PropType: PTypeInfo; DynArray: Pointer; begin // assume failure Result := Null; PropType := PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF}; case PropType^.Kind of tkInteger: Result := GetOrdProp(Instance, PropInfo); tkWChar: Result := WideString(WideChar(GetOrdProp(Instance, PropInfo))); tkChar: Result := AnsiChar(GetOrdProp(Instance, PropInfo)); tkEnumeration: if GetTypeData(PropType)^.BaseType{$IFNDEF FPC}^{$ENDIF} = TypeInfo(Boolean) then Result := Boolean(GetOrdProp(Instance, PropInfo)) else Result := GetOrdProp(Instance, PropInfo); tkSet: Result := GetOrdProp(Instance, PropInfo); tkFloat: if ((GetTypeName(PropType) = 'TDateTime') or (GetTypeName(PropType) = 'TDate') or (GetTypeName(PropType) = 'TTime')) then Result := VarAsType(GetFloatProp(Instance, PropInfo), varDate) else Result := GetFloatProp(Instance, PropInfo); tkString, {$IFDEF FPC}tkAString, {$ENDIF}tkLString: Result := GetStrProp(Instance, PropInfo); tkWString: Result := GetWideStrProp(Instance, PropInfo); {$IFDEF DELPHI2009_UP} tkUString: Result := GetUnicodeStrProp(Instance, PropInfo); {$ENDIF} tkVariant: Result := GetVariantProp(Instance, PropInfo); tkInt64: {$IFDEF DELPHI2009_UP} if (GetTypeName(PropType) = 'UInt64') then Result := UInt64(GetInt64Prop(Instance, PropInfo)) else {$ENDIF} Result := GetInt64Prop(Instance, PropInfo); {$IFDEF FPC} tkBool: Result := Boolean(GetOrdProp(Instance, PropInfo)); tkQWord: Result := QWord(GetInt64Prop(Instance, PropInfo)); {$ENDIF} tkInterface: Result := GetInterfaceProp(Instance, PropInfo); tkDynArray: begin DynArray := GetDynArrayProp(Instance, PropInfo); DynArrayToVariant(Result, DynArray, PropType); end; tkClass: Result := ObjToVar(GetObjectProp(Instance, PropInfo)); else PropertyConvertError(PropType^.Name); end; end; procedure SetPropValue(Instance: TObject; PropInfo: PPropInfo; const Value: Variant); var PropType: PTypeInfo; TypeData: PTypeData; Obj: TObject; DynArray: Pointer; begin PropType := PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF}; TypeData := GetTypeData(PropType); // set the right type case PropType^.Kind of tkInteger, tkChar, tkWChar, tkEnumeration, tkSet: SetOrdProp(Instance, PropInfo, Value); {$IFDEF FPC} tkBool: SetOrdProp(Instance, PropInfo, Value); tkQWord: SetInt64Prop(Instance, PropInfo, QWord(Value)); {$ENDIF} tkFloat: SetFloatProp(Instance, PropInfo, Value); tkString, {$IFDEF FPC}tkAString, {$ENDIF}tkLString: SetStrProp(Instance, PropInfo, VarToStr(Value)); tkWString: SetWideStrProp(Instance, PropInfo, VarToWideStr(Value)); {$IFDEF DELPHI2009_UP} tkUString: SetUnicodeStrProp(Instance, PropInfo, VarToStr(Value)); //SB: ?? tkInt64: SetInt64Prop(Instance, PropInfo, Value); {$ELSE} tkInt64: SetInt64Prop(Instance, PropInfo, TVarData(VarAsType(Value, varInt64)).VInt64); {$ENDIF} tkVariant: SetVariantProp(Instance, PropInfo, Value); tkInterface: begin SetInterfaceProp(Instance, PropInfo, Value); end; tkDynArray: begin DynArray := nil; // "nil array" if VarIsNull(Value) or (VarArrayHighBound(Value, 1) >= 0) then begin DynArrayFromVariant(DynArray, Value, PropType); end; SetDynArrayProp(Instance, PropInfo, DynArray); {$IFNDEF FPC} DynArrayClear(DynArray, PropType); {$ENDIF} end; tkClass: if VarIsNull(Value) then SetOrdProp(Instance, PropInfo, 0) else if VarIsObj(Value) then begin Obj := VarToObj(Value); if (Obj.ClassType.InheritsFrom(TypeData^.ClassType)) then SetObjectProp(Instance, PropInfo, Obj) else PropertyConvertError(PropType^.Name); end else PropertyConvertError(PropType^.Name); else PropertyConvertError(PropType^.Name); end; end; function GetVarTypeAndClass(TypeInfo: PTypeInfo; out AClass: TClass): TVarType; var TypeData: PTypeData; TypeName: string; begin Result := varVariant; AClass := nil; TypeName := GetTypeName(TypeInfo); if TypeName = 'Boolean' then Result := varBoolean else if (TypeName = 'TDateTime') or (TypeName = 'TDate') or (TypeName = 'TTime') then Result := varDate {$IFDEF DELPHI2009_UP} else if TypeName = 'UInt64' then Result := varUInt64 {$ENDIF} else begin TypeData := GetTypeData(TypeInfo); case TypeInfo^.Kind of tkInteger, tkEnumeration, tkSet: case TypeData^.OrdType of otSByte: Result := varShortInt; otUByte: Result := varByte; otSWord: Result := varSmallInt; otUWord: Result := varWord; otSLong: Result := varInteger; otULong: Result := varLongWord; end; tkChar: begin AClass := TObject; Result := varByte; end; tkWChar: begin AClass := TObject; Result := varWord; end; {$IFDEF FPC} tkBool: Result := varBoolean; tkQWord: Result := varQWord; {$ENDIF} tkFloat: case TypeData^.FloatType of ftSingle: Result := varSingle; ftDouble, ftExtended: Result := varDouble; ftComp: Result := varInt64; ftCurr: Result := varCurrency; end; tkString, {$IFDEF FPC}tkAString, {$ENDIF}tkLString: Result := varString; tkWString: Result := varOleStr; {$IFDEF DELPHI2009_UP} tkUString: Result := varUString; {$ENDIF} tkInt64: Result := varInt64; tkInterface: begin Result := varUnknown; AClass := GetClassByInterface(TypeData.Guid); end; tkDynArray: Result := TypeData.varType; tkClass: AClass := TypeData.ClassType; end; end; end; function StrToByte(const S:string): Byte; overload; begin if Length(S) = 1 then Result := Ord(S[1]) else Result := Byte(StrToInt(S)); end; function OleStrToWord(const S:WideString): Word; overload; begin if Length(S) = 1 then Result := Ord(S[1]) else Result := Word(StrToInt(S)); end; type TAnsiCharSet = set of AnsiChar; function CharInSet(C: WideChar; const CharSet: TAnsiCharSet): Boolean; begin Result := (C < #$0100) and (AnsiChar(C) in CharSet); end; { THproseReader } constructor THproseReader.Create(AStream: TStream); begin FStream := AStream; FRefList := TArrayList.Create(False); FClassRefList := TArrayList.Create(False); FAttrRefMap := THashMap.Create(False); end; function THproseReader.UnexpectedTag(Tag: AnsiChar; const ExpectTags: string): EHproseException; begin if ExpectTags = '' then Result := EHproseException.Create('Unexpected serialize tag "' + string(Tag) + '" in stream') else Result := EHproseException.Create('Tag "' + ExpectTags + '" expected, but "' + string(Tag) + '" found in stream'); end; function THproseReader.TagToString(Tag: AnsiChar): string; begin case Tag of '0'..'9', htInteger: Result := 'Integer'; htLong: Result := 'BigInteger'; htDouble: Result := 'Double'; htNull: Result := 'Null'; htEmpty: Result := 'Empty String'; htTrue: Result := 'Boolean True'; htFalse: Result := 'Boolean False'; htNaN: Result := 'NaN'; htInfinity: Result := 'Infinity'; htDate: Result := 'DateTime'; htTime: Result := 'DateTime'; htBytes: Result := 'Binary Data'; htUTF8Char: Result := 'Char'; htString: Result := 'String'; htGuid: Result := 'Guid'; htList: Result := 'List'; htMap: Result := 'Map'; htClass: Result := 'Class'; htObject: Result := 'Object'; htRef: Result := 'Object Reference'; htError: raise EHproseException.Create(ReadString()); else raise UnexpectedTag(Tag); end; end; procedure THproseReader.CheckTag(ExpectTag: AnsiChar); var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); if Tag <> expectTag then raise UnexpectedTag(Tag, string(ExpectTag)); end; function THproseReader.CheckTags(const ExpectTags: RawByteString): AnsiChar; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); if Pos(Tag, ExpectTags) = 0 then raise UnexpectedTag(Tag, string(ExpectTags)); Result := Tag; end; function THproseReader.ReadByte: Byte; begin FStream.ReadBuffer(Result, 1); end; function THproseReader.ReadUntil(Tag: AnsiChar): string; var S: TStringBuffer; C: AnsiChar; begin S := TStringBuffer.Create(); try while (FStream.Read(C, 1) = 1) and (C <> Tag) do S.Write(C, 1); Result := S.ToString; finally S.Free; end; end; function THproseReader.ReadInt(Tag: AnsiChar): Integer; var S: Integer; I: Integer; C: AnsiChar; begin Result := 0; S := 1; I := FStream.Read(C, 1); if I = 1 then if C = '+' then I := FStream.Read(C, 1) else if C = '-' then begin S := -1; I := FStream.Read(C, 1); end; while (I = 1) and (C <> Tag) do begin Result := Result * 10 + (Ord(C) - Ord('0')) * S; I := FStream.Read(C, 1); end; end; function THproseReader.ReadInt64(Tag: AnsiChar): Int64; var S: Int64; I: Integer; C: AnsiChar; begin Result := 0; S := 1; I := FStream.Read(C, 1); if I = 1 then if C = '+' then I := FStream.Read(C, 1) else if C = '-' then begin S := -1; I := FStream.Read(C, 1); end; while (I = 1) and (C <> Tag) do begin Result := Result * 10 + Int64(Ord(C) - Ord('0')) * S; I := FStream.Read(C, 1); end; end; {$IFDEF Supports_UInt64} function THproseReader.ReadUInt64(Tag: AnsiChar): UInt64; var I: Integer; C: AnsiChar; begin Result := 0; I := FStream.Read(C, 1); if (I = 1) and (C = '+') then I := FStream.Read(C, 1); while (I = 1) and (C <> Tag) do begin Result := Result * 10 + UInt64(Ord(C) - Ord('0')); I := FStream.Read(C, 1); end; end; {$ENDIF} function THproseReader.ReadIntegerWithoutTag: Integer; begin Result := ReadInt(HproseTagSemicolon); end; function THproseReader.ReadLongWithoutTag: string; begin Result := ReadUntil(HproseTagSemicolon); end; function THproseReader.ReadInfinityWithoutTag: Extended; begin if ReadByte = Ord(HproseTagNeg) then Result := NegInfinity else Result := Infinity; end; function THproseReader.ReadDoubleWithoutTag: Extended; begin Result := StrToFloat(ReadUntil(HproseTagSemicolon)); end; function THproseReader.ReadDateWithoutTag: TDateTime; var Tag, Year, Month, Day, Hour, Minute, Second, Millisecond: Integer; begin Year := ReadByte - Ord('0'); Year := Year * 10 + ReadByte - Ord('0'); Year := Year * 10 + ReadByte - Ord('0'); Year := Year * 10 + ReadByte - Ord('0'); Month := ReadByte - Ord('0'); Month := Month * 10 + ReadByte - Ord('0'); Day := ReadByte - Ord('0'); Day := Day * 10 + ReadByte - Ord('0'); Tag := ReadByte; if Tag = Ord(HproseTagTime) then begin Hour := ReadByte - Ord('0'); Hour := Hour * 10 + ReadByte - Ord('0'); Minute := ReadByte - Ord('0'); Minute := Minute * 10 + ReadByte - Ord('0'); Second := ReadByte - Ord('0'); Second := Second * 10 + ReadByte - Ord('0'); Millisecond := 0; if ReadByte = Ord(HproseTagPoint) then begin Millisecond := ReadByte - Ord('0'); Millisecond := Millisecond * 10 + ReadByte - Ord('0'); Millisecond := Millisecond * 10 + ReadByte - Ord('0'); Tag := ReadByte; if (Tag >= Ord('0')) and (Tag <= Ord('9')) then begin ReadByte; ReadByte; Tag := ReadByte; if (Tag >= Ord('0')) and (Tag <= Ord('9')) then begin ReadByte; ReadByte; ReadByte; end; end; end; Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); end else Result := EncodeDate(Year, Month, Day); FRefList.Add(Result); end; function THproseReader.ReadTimeWithoutTag: TDateTime; var Tag, Hour, Minute, Second, Millisecond: Integer; begin Hour := ReadByte - Ord('0'); Hour := Hour * 10 + ReadByte - Ord('0'); Minute := ReadByte - Ord('0'); Minute := Minute * 10 + ReadByte - Ord('0'); Second := ReadByte - Ord('0'); Second := Second * 10 + ReadByte - Ord('0'); Millisecond := 0; if ReadByte = Ord(HproseTagPoint) then begin Millisecond := ReadByte - Ord('0'); Millisecond := Millisecond * 10 + ReadByte - Ord('0'); Millisecond := Millisecond * 10 + ReadByte - Ord('0'); Tag := ReadByte; if (Tag >= Ord('0')) and (Tag <= Ord('9')) then begin ReadByte; ReadByte; Tag := ReadByte; if (Tag >= Ord('0')) and (Tag <= Ord('9')) then begin ReadByte; ReadByte; ReadByte; end; end; end; Result := EncodeTime(Hour, Minute, Second, Millisecond); FRefList.Add(Result); end; function THproseReader.ReadUTF8CharWithoutTag: WideChar; var C, C2, C3: LongWord; begin C := ReadByte; case C shr 4 of 0..7: { 0xxx xxxx } Result := WideChar(C); 12,13: begin { 110x xxxx 10xx xxxx } C2 := ReadByte; Result := WideChar(((C and $1F) shl 6) or (C2 and $3F)); end; 14: begin { 1110 xxxx 10xx xxxx 10xx xxxx } C2 := ReadByte; C3 := ReadByte; Result := WideChar(((C and $0F) shl 12) or ((C2 and $3F) shl 6) or (C3 and $3F)); end; else raise EHproseException.Create('bad unicode encoding at $' + IntToHex(C, 4)); end; end; function THproseReader.ReadStringAsWideString: WideString; var Count, I: Integer; C, C2, C3, C4: LongWord; begin Count := ReadInt(HproseTagQuote); SetLength(Result, Count); I := 0; while I < Count do begin Inc(I); C := ReadByte; case C shr 4 of 0..7: { 0xxx xxxx } Result[I] := WideChar(C); 12,13: begin { 110x xxxx 10xx xxxx } C2 := ReadByte; Result[I] := WideChar(((C and $1F) shl 6) or (C2 and $3F)); end; 14: begin { 1110 xxxx 10xx xxxx 10xx xxxx } C2 := ReadByte; C3 := ReadByte; Result[I] := WideChar(((C and $0F) shl 12) or ((C2 and $3F) shl 6) or (C3 and $3F)); end; 15: begin { 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx } if (C and $F) <= 4 then begin C2 := ReadByte; C3 := ReadByte; C4 := ReadByte; C := ((C and $07) shl 18) or ((C2 and $3F) shl 12) or ((C3 and $3F) shl 6) or (C4 and $3F) - $10000; if C <= $FFFFF then begin Result[I] := WideChar(((C shr 10) and $03FF) or $D800); Inc(I); Result[I] := WideChar((C and $03FF) or $DC00); Continue; end; end; raise EHproseException.Create('bad unicode encoding at $' + IntToHex(C, 4)); end; else raise EHproseException.Create('bad unicode encoding at $' + IntToHex(C, 4)); end; end; CheckTag(HproseTagQuote); end; function THproseReader.ReadStringWithoutTag: WideString; begin Result := ReadStringAsWideString; FRefList.Add(Result); end; function THproseReader.ReadBytesWithoutTag: Variant; var Len: Integer; P: PByteArray; begin Len := ReadInt(HproseTagQuote); Result := VarArrayCreate([0, Len - 1], varByte); P := VarArrayLock(Result); FStream.ReadBuffer(P^[0], Len); VarArrayUnLock(Result); CheckTag(HproseTagQuote); FRefList.Add(VarArrayRef(Result)); end; function THproseReader.ReadGuidWithoutTag: string; begin SetLength(Result, 38); FStream.ReadBuffer(Result[1], 38); FRefList.Add(Result); end; function THproseReader.ReadBooleanArray(Count: Integer): Variant; var P: PWordBoolArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varBoolean); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadBoolean; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadShortIntArray(Count: Integer): Variant; var P: PShortIntArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varShortInt); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ShortInt(ReadInteger); VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadByteArray(Count: Integer): Variant; var P: PShortIntArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varByte); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := Byte(ReadInteger); VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadSmallIntArray(Count: Integer): Variant; var P: PSmallIntArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varSmallInt); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := SmallInt(ReadInteger); VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadWordArray(Count: Integer): Variant; var P: PWordArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varWord); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := Word(ReadInteger); VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadIntegerArray(Count: Integer): Variant; var P: PIntegerArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varInteger); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadInteger; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadLongWordArray(Count: Integer): Variant; var P: PLongWordArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varLongWord); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := LongWord(ReadInt64); VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadSingleArray(Count: Integer): Variant; var P: PSingleArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varSingle); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadExtended; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadDoubleArray(Count: Integer): Variant; var P: PDoubleArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varDouble); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadExtended; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadCurrencyArray(Count: Integer): Variant; var P: PCurrencyArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varCurrency); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadCurrency; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadDateTimeArray(Count: Integer): Variant; var P: PDateTimeArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varDate); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadDateTime; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadWideStringArray(Count: Integer): Variant; var P: PWideStringArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varOleStr); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := ReadString; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadVariantArray(Count: Integer): Variant; var P: PVariantArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varVariant); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := Unserialize; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadInterfaceArray(Count: Integer): Variant; var P: PInterfaceArray; I, N: Integer; begin Result := VarArrayCreate([0, Count - 1], varVariant); N := FRefList.Add(Null); P := VarArrayLock(Result); for I := 0 to Count - 1 do P^[I] := Unserialize; VarArrayUnlock(Result); FRefList[N] := VarArrayRef(Result); end; function THproseReader.ReadDynArrayWithoutTag(varType: Integer): Variant; var Count: Integer; begin Count := ReadInt(HproseTagOpenbrace); case varType of varBoolean: Result := ReadBooleanArray(Count); varShortInt: Result := ReadShortIntArray(Count); varByte: Result := ReadByteArray(Count); varSmallint: Result := ReadSmallintArray(Count); varWord: Result := ReadWordArray(Count); varInteger: Result := ReadIntegerArray(Count); varLongWord: Result := ReadLongWordArray(Count); varSingle: Result := ReadSingleArray(Count); varDouble: Result := ReadDoubleArray(Count); varCurrency: Result := ReadCurrencyArray(Count); varOleStr: Result := ReadWideStringArray(Count); varDate: Result := ReadDateTimeArray(Count); varVariant: Result := ReadVariantArray(Count); varUnknown: Result := ReadInterfaceArray(Count); end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadIList(AClass: TClass): IList; var Count, I: Integer; begin Count := ReadInt(HproseTagOpenbrace); Result := TListClass(AClass).Create(Count) as IList; FRefList.Add(Result); for I := 0 to Count - 1 do Result[I] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadList(AClass: TClass): TAbstractList; var Count, I: Integer; begin Count := ReadInt(HproseTagOpenbrace); Result := TListClass(AClass).Create(Count); FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do Result[I] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadListWithoutTag: Variant; begin Result := ReadIList(TArrayList); end; function THproseReader.ReadListAsIMap(AClass: TClass): IMap; var Count, I: Integer; begin Count := ReadInt(HproseTagOpenbrace); Result := TMapClass(AClass).Create(Count) as IMap; FRefList.Add(Result); for I := 0 to Count - 1 do Result[I] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadListAsMap(AClass: TClass): TAbstractMap; var Count, I: Integer; begin Count := ReadInt(HproseTagOpenbrace); Result := TMapClass(AClass).Create(Count); FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do Result[I] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadIMap(AClass: TClass): IMap; var Count, I: Integer; Key: Variant; begin Count := ReadInt(HproseTagOpenbrace); Result := TMapClass(AClass).Create(Count) as IMap; FRefList.Add(Result); for I := 0 to Count - 1 do begin Key := Unserialize; Result[Key] := Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadMap(AClass: TClass): TAbstractMap; var Count, I: Integer; Key: Variant; begin Count := ReadInt(HproseTagOpenbrace); Result := TMapClass(AClass).Create(Count); FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do begin Key := Unserialize; Result[Key] := Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadMapAsInterface(AClass: TClass; const IID: TGUID): IInterface; var Count, I: Integer; Instance: TObject; PropInfo: PPropInfo; begin Count := ReadInt(HproseTagOpenbrace); Instance := AClass.Create; Supports(Instance, IID, Result); FRefList.Add(Result); for I := 0 to Count - 1 do begin PropInfo := GetPropInfo(AClass, ReadString); if (PropInfo <> nil) then SetPropValue(Instance, PropInfo, Unserialize(PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF})) else Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadMapAsObject(AClass: TClass): TObject; var Count, I: Integer; PropInfo: PPropInfo; begin Count := ReadInt(HproseTagOpenbrace); Result := AClass.Create; FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do begin PropInfo := GetPropInfo(AClass, ReadString); if (PropInfo <> nil) then SetPropValue(Result, PropInfo, Unserialize(PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF})) else Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadMapWithoutTag: Variant; begin Result := ReadIMap(THashMap); end; procedure THproseReader.ReadClass; var ClassName: string; I, Count: Integer; AttrNames: IList; AClass: TClass; Key: Variant; begin ClassName := ReadStringAsWideString; Count := ReadInt(HproseTagOpenbrace); AttrNames := TArrayList.Create(Count, False) as IList; for I := 0 to Count - 1 do AttrNames[I] := ReadString; CheckTag(HproseTagClosebrace); AClass := GetClassByAlias(ClassName); if AClass = nil then begin Key := IInterface(TInterfacedObject.Create); FClassRefList.Add(Key); FAttrRefMap[Key] := AttrNames; end else begin Key := NativeInt(AClass); FClassRefList.Add(Key); FAttrRefMap[Key] := AttrNames; end; end; function THproseReader.ReadObjectAsIMap(AClass: TMapClass): IMap; var C: Variant; AttrNames: IList; I, Count: Integer; begin C := FClassRefList[ReadInt(HproseTagOpenbrace)]; AttrNames := VarToList(FAttrRefMap[C]); Count := AttrNames.Count; Result := AClass.Create(Count) as IMap; FRefList.Add(Result); for I := 0 to Count - 1 do Result[AttrNames[I]] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadObjectAsMap(AClass: TMapClass): TAbstractMap; var C: Variant; AttrNames: IList; I, Count: Integer; begin C := FClassRefList[ReadInt(HproseTagOpenbrace)]; AttrNames := VarToList(FAttrRefMap[C]); Count := AttrNames.Count; Result := AClass.Create(Count); FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do Result[AttrNames[I]] := Unserialize; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadObjectAsInterface(AClass: TClass; const IID: TGUID): IInterface; var C: Variant; RegisteredClass: TClass; AttrNames: IList; I, Count: Integer; Instance: TObject; PropInfo: PPropInfo; begin C := FClassRefList[ReadInt(HproseTagOpenbrace)]; if VarType(C) = varNativeInt then begin RegisteredClass := TClass(NativeInt(C)); if (AClass = nil) or RegisteredClass.InheritsFrom(AClass) then AClass := RegisteredClass; end; AttrNames := VarToList(FAttrRefMap[C]); Count := AttrNames.Count; Instance := AClass.Create; Supports(Instance, IID, Result); FRefList.Add(Result); for I := 0 to Count - 1 do begin PropInfo := GetPropInfo(Instance, AttrNames[I]); if (PropInfo <> nil) then SetPropValue(Instance, PropInfo, Unserialize(PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF})) else Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadObjectWithoutTag(AClass: TClass): TObject; var C: Variant; RegisteredClass: TClass; AttrNames: IList; I, Count: Integer; PropInfo: PPropInfo; begin C := FClassRefList[ReadInt(HproseTagOpenbrace)]; if VarType(C) = varNativeInt then begin RegisteredClass := TClass(NativeInt(C)); if (AClass = nil) or RegisteredClass.InheritsFrom(AClass) then AClass := RegisteredClass; end; AttrNames := VarToList(FAttrRefMap[C]); Count := AttrNames.Count; Result := AClass.Create; FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do begin PropInfo := GetPropInfo(Result, AttrNames[I]); if (PropInfo <> nil) then SetPropValue(Result, PropInfo, Unserialize(PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF})) else Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadObjectWithoutTag: Variant; var C: Variant; AttrNames: IList; I, Count: Integer; AClass: TClass; AMap: IMap; Intf: IInterface; Instance: TObject; Map: TAbstractMap; PropInfo: PPropInfo; begin C := FClassRefList[ReadInt(HproseTagOpenbrace)]; AttrNames := VarToList(FAttrRefMap[C]); Count := AttrNames.Count; if VarType(C) = varNativeInt then begin AClass := TClass(NativeInt(C)); if AClass.InheritsFrom(TInterfacedObject) and HasRegisterWithInterface(TInterfacedClass(AClass)) then begin Instance := AClass.Create; Supports(Instance, GetInterfaceByClass(TInterfacedClass(AClass)), Intf); Result := Intf; end else begin Instance := AClass.Create; Result := ObjToVar(Instance); end; FRefList.Add(Result); if Instance is TAbstractMap then begin Map := TAbstractMap(Instance); for I := 0 to Count - 1 do Map[AttrNames[I]] := Unserialize; end else for I := 0 to Count - 1 do begin PropInfo := GetPropInfo(Instance, AttrNames[I]); if (PropInfo <> nil) then SetPropValue(Instance, PropInfo, Unserialize(PropInfo^.PropType{$IFNDEF FPC}^{$ENDIF})) else Unserialize; end; end else begin AMap := TCaseInsensitiveHashMap.Create(Count) as IMap; Result := AMap; FRefList.Add(Result); for I := 0 to Count - 1 do AMap[AttrNames[I]] := Unserialize; end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadRef: Variant; begin Result := FRefList[ReadInt(HproseTagSemicolon)]; end; function CastError(const SrcType, DestType: string): EHproseException; begin Result := EHproseException.Create(SrcType + ' can''t change to ' + DestType); end; function THproseReader.ReadInteger: Integer; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := 0; '1': Result := 1; '2': Result := 2; '3': Result := 3; '4': Result := 4; '5': Result := 5; '6': Result := 6; '7': Result := 7; '8': Result := 8; '9': Result := 9; htInteger, htLong: Result := ReadIntegerWithoutTag; htDouble: Result := Integer(Trunc(ReadDoubleWithoutTag)); htNull, htEmpty, htFalse: Result := 0; htTrue: Result := 1; htUTF8Char: Result := StrToInt(string(ReadUTF8CharWithoutTag)); htString: Result := StrToInt(ReadStringWithoutTag); else raise CastError(TagToString(Tag), 'Integer'); end; end; function THproseReader.ReadInt64: Int64; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := 0; '1': Result := 1; '2': Result := 2; '3': Result := 3; '4': Result := 4; '5': Result := 5; '6': Result := 6; '7': Result := 7; '8': Result := 8; '9': Result := 9; htInteger, htLong: Result := ReadInt64(HproseTagSemicolon); htDouble: Result := Trunc(ReadDoubleWithoutTag); htNull, htEmpty, htFalse: Result := 0; htTrue: Result := 1; htUTF8Char: Result := StrToInt64(string(ReadUTF8CharWithoutTag)); htString: Result := StrToInt64(ReadStringWithoutTag); else raise CastError(TagToString(Tag), 'Int64'); end; end; {$IFDEF Supports_UInt64} function THproseReader.ReadUInt64: UInt64; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := 0; '1': Result := 1; '2': Result := 2; '3': Result := 3; '4': Result := 4; '5': Result := 5; '6': Result := 6; '7': Result := 7; '8': Result := 8; '9': Result := 9; htInteger, htLong: Result := ReadUInt64(HproseTagSemicolon); htDouble: Result := Trunc(ReadDoubleWithoutTag); htNull, htEmpty, htFalse: Result := 0; htTrue: Result := 1; {$IFDEF FPC} htUTF8Char: Result := StrToQWord(string(ReadUTF8CharWithoutTag)); htString: Result := StrToQWord(ReadStringWithoutTag); {$ELSE} htUTF8Char: Result := StrToInt64(string(ReadUTF8CharWithoutTag)); htString: Result := StrToInt64(ReadStringWithoutTag); {$ENDIF} else raise CastError(TagToString(Tag), 'UInt64'); end; end; {$ENDIF} function THproseReader.ReadExtended: Extended; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := 0; '1': Result := 1; '2': Result := 2; '3': Result := 3; '4': Result := 4; '5': Result := 5; '6': Result := 6; '7': Result := 7; '8': Result := 8; '9': Result := 9; htInteger, htLong, htDouble: Result := ReadDoubleWithoutTag; htNull, htEmpty, htFalse: Result := 0; htTrue: Result := 1; htNaN: Result := NaN; htInfinity: Result := ReadInfinityWithoutTag; htUTF8Char: Result := StrToFloat(string(ReadUTF8CharWithoutTag)); htString: Result := StrToFloat(ReadStringWithoutTag); else raise CastError(TagToString(Tag), 'Extended'); end; end; function THproseReader.ReadCurrency: Currency; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := 0; '1': Result := 1; '2': Result := 2; '3': Result := 3; '4': Result := 4; '5': Result := 5; '6': Result := 6; '7': Result := 7; '8': Result := 8; '9': Result := 9; htInteger, htLong, htDouble: Result := StrToCurr(ReadUntil(HproseTagSemicolon)); htNull, htEmpty, htFalse: Result := 0; htTrue: Result := 1; htUTF8Char: Result := StrToCurr(string(ReadUTF8CharWithoutTag)); htString: Result := StrToCurr(ReadStringWithoutTag); else raise CastError(TagToString(Tag), 'Currency'); end; end; function THproseReader.ReadBoolean: Boolean; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0': Result := False; '1'..'9': Result := True; htInteger, htLong, htDouble: Result := ReadDoubleWithoutTag <> 0; htNull, htEmpty, htFalse: Result := False; htTrue: Result := True; htUTF8Char: Result := StrToBool(string(ReadUTF8CharWithoutTag)); htString: Result := StrToBool(ReadStringWithoutTag); else raise CastError(TagToString(Tag), 'Boolean'); end; end; function THproseReader.ReadDateTime: TDateTime; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0'..'9': Result := TimeStampToDateTime(MSecsToTimeStamp(Ord(Tag) - Ord('0'))); htInteger: Result := TimeStampToDateTime(MSecsToTimeStamp(ReadIntegerWithoutTag)); htLong: Result := TimeStampToDateTime(MSecsToTimeStamp(ReadInt64(HproseTagSemicolon))); htDouble: Result := TimeStampToDateTime(MSecsToTimeStamp(Trunc(ReadDoubleWithoutTag))); htDate: Result := ReadDateWithoutTag; htTime: Result := ReadTimeWithoutTag; htString: Result := StrToDateTime(ReadStringWithoutTag); htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'TDateTime'); end; end; function THproseReader.ReadUTF8Char: WideChar; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0'..'9': Result := WideChar(Tag); htInteger, htLong: Result := WideChar(ReadIntegerWithoutTag); htDouble: Result := WideChar(Trunc(ReadDoubleWithoutTag)); htNull: Result := #0; htUTF8Char: Result := ReadUTF8CharWithoutTag; htString: Result := ReadStringWithoutTag[1]; else raise CastError(TagToString(Tag), 'WideChar'); end; end; function THproseReader.ReadString: WideString; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0'..'9': Result := WideString(Tag); htInteger, htLong, htDouble: Result := ReadUntil(HproseTagSemicolon); htNull, htEmpty: Result := ''; htFalse: Result := 'False'; htTrue: Result := 'True'; htNaN: Result := FloatToStr(NaN); htInfinity: Result := FloatToStr(ReadInfinityWithoutTag); htDate: Result := DateTimeToStr(ReadDateWithoutTag); htTime: Result := DateTimeToStr(ReadTimeWithoutTag); htUTF8Char: Result := WideString(ReadUTF8CharWithoutTag); htString: Result := ReadStringWithoutTag; htGuid: Result := WideString(ReadGuidWithoutTag); htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'String'); end; end; function THproseReader.ReadBytes: Variant; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := Null; htBytes: Result := ReadBytesWithoutTag; htList: Result := ReadDynArrayWithoutTag(varByte); htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'Byte'); end; end; function THproseReader.ReadGuid: string; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := ''; htString: Result := GuidToString(StringToGuid(ReadStringWithoutTag)); htGuid: Result := ReadGuidWithoutTag; htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'TGUID'); end; end; function THproseReader.ReadDynArray(varType: Integer): Variant; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := Null; htList: Result := ReadDynArrayWithoutTag(varType); htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'DynArray'); end; end; function THproseReader.ReadVariantArray: TVariants; var Tag: AnsiChar; I, Count: Integer; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := Null; htList: begin Count := ReadInt(HproseTagOpenbrace); SetLength(Result, Count); FRefList.Add(Null); for I := 0 to Count - 1 do Result[I] := Unserialize; CheckTag(HproseTagClosebrace); end; else raise CastError(TagToString(Tag), 'TVariants'); end; end; function THproseReader.ReadInterface(AClass: TClass; const IID: TGUID): IInterface; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := nil; htList: if AClass.InheritsFrom(TAbstractList) then Result := ReadIList(AClass) else if AClass.InheritsFrom(TAbstractMap) then Result := ReadListAsIMap(AClass) else Result := nil; htMap: if AClass.InheritsFrom(TAbstractMap) then Result := ReadIMap(AClass) else Result := ReadMapAsInterface(AClass, IID); htClass: begin ReadClass; Result := ReadInterface(AClass, IID); end; htObject: begin if AClass.InheritsFrom(TAbstractMap) then Result := ReadObjectAsIMap(TMapClass(AClass)) else Result := ReadObjectAsInterface(AClass, IID); end; htRef: Result := ReadRef; else raise CastError(TagToString(Tag), 'Interface'); end; end; function THproseReader.ReadObject(AClass: TClass): TObject; var {$IFDEF Supports_Rtti} ClassName: string; TypeInfo: PTypeInfo; {$ENDIF} Tag: AnsiChar; begin {$IFDEF Supports_Rtti} ClassName := AClass.ClassName; TypeInfo := PTypeInfo(AClass.ClassInfo); {$ENDIF} FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Result := nil; htList: if AClass.InheritsFrom(TAbstractList) then Result := ReadList(AClass) else if AClass.InheritsFrom(TAbstractMap) then Result := ReadListAsMap(AClass) {$IFDEF Supports_Rtti} else if AnsiStartsText('TList<', ClassName) or AnsiStartsText('TObjectList<', ClassName) then Result := ReadTList(TypeInfo) else if AnsiStartsText('TQueue<', ClassName) or AnsiStartsText('TObjectQueue<', ClassName) then Result := ReadTQueue(TypeInfo) else if AnsiStartsText('TStack<', ClassName) or AnsiStartsText('TObjectStack<', ClassName) then Result := ReadTStack(TypeInfo) {$ENDIF} else Result := nil; htMap: if AClass.InheritsFrom(TAbstractMap) then Result := ReadMap(AClass) {$IFDEF Supports_Rtti} else if AnsiStartsText('TDictionary<', ClassName) or AnsiStartsText('TObjectDictionary<', ClassName) then Result := ReadTDictionary(TypeInfo) {$ENDIF} else Result := ReadMapAsObject(AClass); htClass: begin ReadClass; Result := ReadObject(AClass); end; htObject: begin if AClass.InheritsFrom(TAbstractMap) then Result := ReadObjectAsMap(TMapClass(AClass)) else Result := ReadObjectWithoutTag(AClass); end; htRef: Result := VarToObj(ReadRef); else raise CastError(TagToString(Tag), 'Object'); end; end; {$IFDEF Supports_Generics} procedure THproseReader.ReadArray<T>(var DynArray: TArray<T>; TypeInfo: PTypeInfo); var Count, I: Integer; begin Count := ReadInt(HproseTagOpenbrace); SetLength(DynArray, Count); FRefList.Add(NativeInt(Pointer(DynArray))); for I := 0 to Count - 1 do Unserialize(TypeInfo, DynArray[I]); CheckTag(HproseTagClosebrace); end; procedure THproseReader.ReadArray(TypeInfo: PTypeInfo; out DynArray); var TypeName, ElementName: string; ElementTypeInfo: PTypeInfo; Size: Integer; begin TypeName := GetTypeName(TypeInfo); ElementName := GetElementName(TypeName); ElementTypeInfo := GetTypeInfo(ElementName, Size); if ElementTypeInfo = nil then raise EHproseException.Create(ElementName + 'is not registered'); case ElementTypeInfo^.Kind of tkString: ReadArray<ShortString>(TArray<ShortString>(DynArray), ElementTypeInfo); tkLString: ReadArray<AnsiString>(TArray<AnsiString>(DynArray), ElementTypeInfo); tkWString: ReadArray<WideString>(TArray<WideString>(DynArray), ElementTypeInfo); tkUString: ReadArray<UnicodeString>(TArray<UnicodeString>(DynArray), ElementTypeInfo); tkVariant: ReadArray<Variant>(TArray<Variant>(DynArray), ElementTypeInfo); tkDynArray: ReadArray<TArray<Pointer>>(TArray<TArray<Pointer>>(DynArray), ElementTypeInfo); tkInterface: ReadArray<IInterface>(TArray<IInterface>(DynArray), ElementTypeInfo); tkClass: ReadArray<TObject>(TArray<TObject>(DynArray), ElementTypeInfo); else case Size of 1: ReadArray<TB1>(TArray<TB1>(DynArray), ElementTypeInfo); 2: ReadArray<TB2>(TArray<TB2>(DynArray), ElementTypeInfo); 4: ReadArray<TB4>(TArray<TB4>(DynArray), ElementTypeInfo); 8: ReadArray<TB8>(TArray<TB8>(DynArray), ElementTypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then ReadArray<Extended>(TArray<Extended>(DynArray), ElementTypeInfo) else raise EHproseException.Create('Can not unserialize ' + TypeName); end; end; end; type PDynArrayRec = ^TDynArrayRec; TDynArrayRec = packed record {$IFDEF CPUX64} _Padding: LongInt; // Make 16 byte align for payload.. {$ENDIF} RefCnt: LongInt; Length: NativeInt; end; procedure DynArrayAddRef(P: Pointer); begin if P <> nil then Inc(PDynArrayRec(PByte(P) - SizeOf(TDynArrayRec))^.RefCnt); end; procedure THproseReader.ReadDynArray(TypeInfo: PTypeInfo; out DynArray); var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of htNull, htEmpty: Pointer(DynArray) := nil; htList: ReadArray(TypeInfo, DynArray); htRef: begin Pointer(DynArray) := Pointer(NativeInt(ReadRef)); DynArrayAddRef(Pointer(DynArray)); end; else raise CastError(TagToString(Tag), 'DynArray'); end; end; {$IFDEF Supports_Rtti} function THproseReader.ReadTList<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TList<T>; var Count, I: Integer; AClass: TClass; Context: TRttiContext; RttiType: TRttiType; RttiMethod: TRttiMethod; begin Count := ReadInt(HproseTagOpenbrace); AClass := GetTypeData(TypeInfo)^.ClassType; Context := TRttiContext.Create; RttiType := Context.GetType(AClass); RttiMethod := RttiType.GetMethod('Create'); Result := TList<T>(RttiMethod.Invoke(AClass, []).AsObject); RttiMethod.Free; RttiType.Free; Context.Free; Result.Count := Count; FRefList.Add(ObjToVar(Result)); for I := 0 to Count - 1 do Result[I] := UnserializeTypeAsT<T>(ElementTypeInfo); CheckTag(HproseTagClosebrace); end; function THproseReader.ReadTList(TypeInfo: PTypeInfo): TObject; var TypeName, ElementName: string; ElementTypeInfo: PTypeInfo; Size: Integer; begin TypeName := GetTypeName(TypeInfo); ElementName := GetElementName(TypeName); ElementTypeInfo := GetTypeInfo(ElementName, Size); if ElementTypeInfo = nil then raise EHproseException.Create(ElementName + 'is not registered'); case ElementTypeInfo^.Kind of tkString: Result := ReadTList<ShortString>(TypeInfo, ElementTypeInfo); tkLString: Result := ReadTList<AnsiString>(TypeInfo, ElementTypeInfo); tkWString: Result := ReadTList<WideString>(TypeInfo, ElementTypeInfo); tkUString: Result := ReadTList<UnicodeString>(TypeInfo, ElementTypeInfo); tkVariant: Result := ReadTList<Variant>(TypeInfo, ElementTypeInfo); tkDynArray: Result := ReadTList<TArray<Pointer>>(TypeInfo, ElementTypeInfo); tkInterface: Result := ReadTList<IInterface>(TypeInfo, ElementTypeInfo); tkClass: Result := ReadTList<TObject>(TypeInfo, ElementTypeInfo); else case Size of 1: Result := ReadTList<TB1>(TypeInfo, ElementTypeInfo); 2: Result := ReadTList<TB2>(TypeInfo, ElementTypeInfo); 4: Result := ReadTList<TB4>(TypeInfo, ElementTypeInfo); 8: Result := ReadTList<TB8>(TypeInfo, ElementTypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then Result := ReadTList<Extended>(TypeInfo, ElementTypeInfo) else raise EHproseException.Create('Can not unserialize ' + TypeName); end; end; end; function THproseReader.ReadTQueue<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TQueue<T>; var Count, I: Integer; AClass: TClass; Context: TRttiContext; RttiType: TRttiType; RttiMethod: TRttiMethod; begin Count := ReadInt(HproseTagOpenbrace); AClass := GetTypeData(TypeInfo)^.ClassType; Context := TRttiContext.Create; RttiType := Context.GetType(AClass); RttiMethod := RttiType.GetMethod('Create'); Result := TQueue<T>(RttiMethod.Invoke(AClass, []).AsObject); RttiMethod.Free; RttiType.Free; Context.Free; FRefList.Add(ObjToVar(Result)); for I := 1 to Count do Result.Enqueue(UnserializeTypeAsT<T>(ElementTypeInfo)); CheckTag(HproseTagClosebrace); end; function THproseReader.ReadTQueue(TypeInfo: PTypeInfo): TObject; var TypeName, ElementName: string; ElementTypeInfo: PTypeInfo; Size: Integer; begin TypeName := GetTypeName(TypeInfo); ElementName := GetElementName(TypeName); ElementTypeInfo := GetTypeInfo(ElementName, Size); if ElementTypeInfo = nil then raise EHproseException.Create(ElementName + 'is not registered'); case ElementTypeInfo^.Kind of tkString: Result := ReadTQueue<ShortString>(TypeInfo, ElementTypeInfo); tkLString: Result := ReadTQueue<AnsiString>(TypeInfo, ElementTypeInfo); tkWString: Result := ReadTQueue<WideString>(TypeInfo, ElementTypeInfo); tkUString: Result := ReadTQueue<UnicodeString>(TypeInfo, ElementTypeInfo); tkVariant: Result := ReadTQueue<Variant>(TypeInfo, ElementTypeInfo); tkDynArray: Result := ReadTQueue<TArray<Pointer>>(TypeInfo, ElementTypeInfo); tkInterface: Result := ReadTQueue<IInterface>(TypeInfo, ElementTypeInfo); tkClass: Result := ReadTQueue<TObject>(TypeInfo, ElementTypeInfo); else case Size of 1: Result := ReadTQueue<TB1>(TypeInfo, ElementTypeInfo); 2: Result := ReadTQueue<TB2>(TypeInfo, ElementTypeInfo); 4: Result := ReadTQueue<TB4>(TypeInfo, ElementTypeInfo); 8: Result := ReadTQueue<TB8>(TypeInfo, ElementTypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then Result := ReadTQueue<Extended>(TypeInfo, ElementTypeInfo) else raise EHproseException.Create('Can not unserialize ' + TypeName); end; end; end; function THproseReader.ReadTStack<T>(TypeInfo, ElementTypeInfo: PTypeInfo): TStack<T>; var Count, I: Integer; AClass: TClass; begin Count := ReadInt(HproseTagOpenbrace); AClass := GetTypeData(TypeInfo)^.ClassType; Result := TStack<T>(AClass.Create); FRefList.Add(ObjToVar(Result)); for I := 1 to Count do Result.Push(UnserializeTypeAsT<T>(ElementTypeInfo)); CheckTag(HproseTagClosebrace); end; function THproseReader.ReadTStack(TypeInfo: PTypeInfo): TObject; var TypeName, ElementName: string; ElementTypeInfo: PTypeInfo; Size: Integer; begin TypeName := GetTypeName(TypeInfo); ElementName := GetElementName(TypeName); ElementTypeInfo := GetTypeInfo(ElementName, Size); if ElementTypeInfo = nil then raise EHproseException.Create(ElementName + 'is not registered'); case ElementTypeInfo^.Kind of tkString: Result := ReadTStack<ShortString>(TypeInfo, ElementTypeInfo); tkLString: Result := ReadTStack<AnsiString>(TypeInfo, ElementTypeInfo); tkWString: Result := ReadTStack<WideString>(TypeInfo, ElementTypeInfo); tkUString: Result := ReadTStack<UnicodeString>(TypeInfo, ElementTypeInfo); tkVariant: Result := ReadTStack<Variant>(TypeInfo, ElementTypeInfo); tkDynArray: Result := ReadTStack<TArray<Pointer>>(TypeInfo, ElementTypeInfo); tkInterface: Result := ReadTStack<IInterface>(TypeInfo, ElementTypeInfo); tkClass: Result := ReadTStack<TObject>(TypeInfo, ElementTypeInfo); else case Size of 1: Result := ReadTStack<TB1>(TypeInfo, ElementTypeInfo); 2: Result := ReadTStack<TB2>(TypeInfo, ElementTypeInfo); 4: Result := ReadTStack<TB4>(TypeInfo, ElementTypeInfo); 8: Result := ReadTStack<TB8>(TypeInfo, ElementTypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then Result := ReadTStack<Extended>(TypeInfo, ElementTypeInfo) else raise EHproseException.Create('Can not unserialize ' + TypeName); end; end; end; function THproseReader.ReadTDictionary2<TKey, TValue>( TypeInfo, KeyTypeInfo, ValueTypeInfo: PTypeInfo): TDictionary<TKey, TValue>; var Count, I: Integer; Key: TKey; Value: TValue; AClass: TClass; Context: TRttiContext; RttiType: TRttiType; RttiMethod: TRttiMethod; begin Count := ReadInt(HproseTagOpenbrace); AClass := GetTypeData(TypeInfo)^.ClassType; Context := TRttiContext.Create; RttiType := Context.GetType(AClass); RttiMethod := RttiType.GetMethod('Create'); Result := TDictionary<TKey, TValue>(RttiMethod.Invoke(AClass, [Count]).AsObject); RttiMethod.Free; RttiType.Free; Context.Free; FRefList.Add(ObjToVar(Result)); for I := 1 to Count do begin Unserialize(KeyTypeInfo, Key); Unserialize(ValueTypeInfo, Value); Result.Add(Key, Value); end; CheckTag(HproseTagClosebrace); end; function THproseReader.ReadTDictionary1<TKey>(TypeInfo, KeyTypeInfo, ValueTypeInfo: PTypeInfo; ValueSize: Integer): TObject; begin case ValueTypeInfo^.Kind of tkString: Result := ReadTDictionary2<TKey, ShortString>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkLString: Result := ReadTDictionary2<TKey, AnsiString>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkWString: Result := ReadTDictionary2<TKey, WideString>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkUString: Result := ReadTDictionary2<TKey, UnicodeString>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkVariant: Result := ReadTDictionary2<TKey, Variant>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkDynArray: Result := ReadTDictionary2<TKey, TArray<Pointer>>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkInterface: Result := ReadTDictionary2<TKey, IInterface>( TypeInfo, KeyTypeInfo, ValueTypeInfo); tkClass: Result := ReadTDictionary2<TKey, TObject>( TypeInfo, KeyTypeInfo, ValueTypeInfo); else case ValueSize of 1: Result := ReadTDictionary2<TKey, TB1>( TypeInfo, KeyTypeInfo, ValueTypeInfo); 2: Result := ReadTDictionary2<TKey, TB2>( TypeInfo, KeyTypeInfo, ValueTypeInfo); 4: Result := ReadTDictionary2<TKey, TB4>( TypeInfo, KeyTypeInfo, ValueTypeInfo); 8: Result := ReadTDictionary2<TKey, TB8>( TypeInfo, KeyTypeInfo, ValueTypeInfo); else if GetTypeName(ValueTypeInfo) = 'Extended' then Result := ReadTDictionary2<TKey, Extended>( TypeInfo, KeyTypeInfo, ValueTypeInfo) else raise EHproseException.Create('Can not unserialize ' + GetTypeName(TypeInfo)); end; end; end; function THproseReader.ReadTDictionary(TypeInfo: PTypeInfo): TObject; var TypeName, KeyName, ValueName: string; KeyTypeInfo, ValueTypeInfo: PTypeInfo; KeySize, ValueSize: Integer; begin TypeName := GetTypeName(TypeInfo); SplitKeyValueTypeName(GetElementName(TypeName), KeyName, ValueName); KeyTypeInfo := GetTypeInfo(KeyName, KeySize); ValueTypeInfo := GetTypeInfo(ValueName, ValueSize); if KeyTypeInfo = nil then raise EHproseException.Create(KeyName + 'is not registered'); if ValueTypeInfo = nil then raise EHproseException.Create(ValueName + 'is not registered'); case KeyTypeInfo^.Kind of tkString: Result := ReadTDictionary1<ShortString>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkLString: Result := ReadTDictionary1<AnsiString>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkWString: Result := ReadTDictionary1<WideString>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkUString: Result := ReadTDictionary1<UnicodeString>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkVariant: Result := ReadTDictionary1<Variant>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkDynArray: Result := ReadTDictionary1<TArray<Pointer>>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkInterface: Result := ReadTDictionary1<IInterface>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); tkClass: Result := ReadTDictionary1<TObject>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); else case KeySize of 1: Result := ReadTDictionary1<TB1>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); 2: Result := ReadTDictionary1<TB2>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); 4: Result := ReadTDictionary1<TB4>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); 8: Result := ReadTDictionary1<TB8>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize); else if GetTypeName(KeyTypeInfo) = 'Extended' then Result := ReadTDictionary1<Extended>(TypeInfo, KeyTypeInfo, ValueTypeInfo, ValueSize) else raise EHproseException.Create('Can not unserialize ' + TypeName); end; end; end; function THproseReader.UnserializeTypeAsT<T>(TypeInfo: PTypeInfo): T; begin Unserialize(TypeInfo, Result); end; {$ENDIF} function THproseReader.ReadSmartObject(TypeInfo: PTypeInfo): ISmartObject; var TypeName, ElementName: string; ElementTypeInfo: PTypeInfo; AObject: TObject; begin TypeName := GetTypeName(TypeInfo); if not IsSmartObject(TypeName) then raise EHproseException.Create(TypeName + ' is not a ISmartObject interface'); ElementName := GetElementName(TypeName); TypeName := 'TSmartObject<' + ElementName + '>'; TypeInfo := TTypeManager.TypeInfo(TypeName); ElementTypeInfo := TTypeManager.TypeInfo(ElementName); if (TypeInfo = nil) or (ElementTypeInfo = nil) then raise EHproseException.Create(ElementName + 'is not registered'); if ElementTypeInfo^.Kind <> tkClass then raise EHproseException.Create(ElementName + 'is not a Class'); AObject := ReadObject(GetTypeData(ElementTypeInfo)^.ClassType); Result := TSmartClass(GetTypeData(TypeInfo)^.ClassType).Create(AObject) as ISmartObject; end; procedure THproseReader.Unserialize(TypeInfo: PTypeInfo; out Value); var TypeData: PTypeData; TypeName: string; AClass: TClass; begin TypeName := GetTypeName(TypeInfo); if TypeName = 'Boolean' then Boolean(Value) := ReadBoolean else if (TypeName = 'TDateTime') or (TypeName = 'TDate') or (TypeName = 'TTime') then TDateTime(Value) := ReadDateTime {$IFDEF DELPHI2009_UP} else if TypeName = 'UInt64' then UInt64(Value) := ReadUInt64 {$ENDIF} else begin TypeData := GetTypeData(TypeInfo); case TypeInfo^.Kind of tkInteger, tkEnumeration, tkSet: case TypeData^.OrdType of otSByte: ShortInt(Value) := ShortInt(ReadInteger); otUByte: Byte(Value) := Byte(ReadInteger); otSWord: SmallInt(Value) := SmallInt(ReadInteger); otUWord: Word(Value) := Word(ReadInteger); otSLong: Integer(Value) := ReadInteger; otULong: LongWord(Value) := LongWord(ReadInt64); end; tkChar: AnsiChar(Value) := AnsiChar(ReadUTF8Char); tkWChar: WideChar(Value) := ReadUTF8Char; {$IFDEF FPC} tkBool: Boolean(Value) := ReadBoolean; tkQWord: QWord(Value) := ReadUInt64; {$ENDIF} tkFloat: case TypeData^.FloatType of ftSingle: Single(Value) := ReadExtended; ftDouble: Double(Value) := ReadExtended; ftExtended: Extended(Value) := ReadExtended; ftComp: Comp(Value) := ReadInt64; ftCurr: Currency(Value) := ReadCurrency; end; tkString: ShortString(Value) := ShortString(ReadString()); tkLString{$IFDEF FPC}, tkAString{$ENDIF}: AnsiString(Value) := AnsiString(ReadString); tkWString: WideString(Value) := ReadString; {$IFDEF DELPHI2009_UP} tkUString: UnicodeString(Value) := UnicodeString(ReadString); {$ENDIF} tkInt64: Int64(Value) := ReadInt64; tkInterface: begin AClass := GetClassByInterface(TypeData^.Guid); if AClass = nil then raise EHproseException.Create(GetTypeName(TypeInfo) + ' is not registered') else if Supports(AClass, ISmartObject) then ISmartObject(Value) := ReadSmartObject(TypeInfo) else IInterface(Value) := ReadInterface(AClass, TypeData^.Guid); end; tkDynArray: ReadDynArray(TypeInfo, Value); tkClass: begin AClass := TypeData^.ClassType; TObject(Value) := ReadObject(AClass); end; end; end; end; function THproseReader.Unserialize<T>: T; begin Unserialize(TypeInfo(T), Result); end; {$ENDIF} function THproseReader.Unserialize: Variant; var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Tag of '0'..'9': Result := Ord(Tag) - Ord('0'); htInteger: Result := ReadIntegerWithoutTag; htLong: Result := ReadLongWithoutTag; htDouble: Result := ReadDoubleWithoutTag; htNaN: Result := NaN; htInfinity: Result := ReadInfinityWithoutTag; htTrue: Result := True; htFalse: Result := False; htNull: Result := Null; htEmpty: Result := ''; htDate: Result := ReadDateWithoutTag; htTime: Result := ReadTimeWithoutTag; htBytes: Result := ReadBytesWithoutTag; htUTF8Char: Result := ReadUTF8CharWithoutTag; htString: Result := ReadStringWithoutTag; htGuid: Result := ReadGuidWithoutTag; htList: Result := ReadListWithoutTag; htMap: Result := ReadMapWithoutTag; htClass: begin ReadClass; Result := Unserialize; end; htObject: Result := ReadObjectWithoutTag; htRef: Result := ReadRef; else raise EHproseException.Create(TagToString(Tag) + 'can''t unserialize'); end; end; function THproseReader.Unserialize(TypeInfo: PTypeInfo): Variant; var TypeData: PTypeData; TypeName: string; AClass: TClass; begin if TypeInfo = nil then Result := Unserialize else begin Result := Unassigned; TypeName := GetTypeName(TypeInfo); if TypeName = 'Boolean' then Result := ReadBoolean else if (TypeName = 'TDateTime') or (TypeName = 'TDate') or (TypeName = 'TTime') then Result := ReadDateTime {$IFDEF DELPHI2009_UP} else if TypeName = 'UInt64' then Result := ReadUInt64 {$ENDIF} else begin TypeData := GetTypeData(TypeInfo); case TypeInfo^.Kind of tkInteger, tkEnumeration, tkSet: case TypeData^.OrdType of otSByte: Result := ShortInt(ReadInteger); otUByte: Result := Byte(ReadInteger); otSWord: Result := SmallInt(ReadInteger); otUWord: Result := Word(ReadInteger); otSLong: Result := ReadInteger; otULong: Result := LongWord(ReadInt64); end; tkChar: begin Result := AnsiChar(ReadUTF8Char); end; tkWChar: begin Result := ReadUTF8Char; end; {$IFDEF FPC} tkBool: Result := ReadBoolean; tkQWord: Result := ReadUInt64; {$ENDIF} tkFloat: case TypeData^.FloatType of ftSingle: Result := VarAsType(ReadExtended, varSingle); ftDouble, ftExtended: Result := ReadExtended; ftComp: Result := ReadInt64; ftCurr: Result := ReadCurrency; end; tkString: Result := ShortString(ReadString()); tkLString{$IFDEF FPC}, tkAString{$ENDIF}: Result := AnsiString(ReadString); tkWString: Result := ReadString; {$IFDEF DELPHI2009_UP} tkUString: Result := UnicodeString(ReadString); {$ENDIF} tkInt64: Result := ReadInt64; tkInterface: begin AClass := GetClassByInterface(TypeData^.Guid); if AClass = nil then raise EHproseException.Create(GetTypeName(TypeInfo) + ' is not registered'); Result := ReadInterface(AClass, TypeData^.Guid); end; tkDynArray: Result := ReadDynArray(TypeData^.varType and not varArray); tkClass: begin AClass := TypeData^.ClassType; Result := ObjToVar(ReadObject(AClass)); end; end; end; end; end; function THproseReader.ReadRaw: TMemoryStream; begin Result := TMemoryStream.Create; ReadRaw(Result); end; procedure THproseReader.ReadRaw(const OStream: TStream); var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); ReadRaw(OStream, Tag); end; procedure THproseReader.ReadRaw(const OStream: TStream; Tag: AnsiChar); begin OStream.WriteBuffer(Tag, 1); case Tag of '0'..'9', htNull, htEmpty, htTrue, htFalse, htNaN: begin end; htInfinity: ReadInfinityRaw(OStream); htInteger, htLong, htDouble, htRef: ReadNumberRaw(OStream); htDate, htTime: ReadDateTimeRaw(OStream); htUTF8Char: ReadUTF8CharRaw(OStream); htBytes: ReadBytesRaw(OStream); htString: ReadStringRaw(OStream); htGuid: ReadGuidRaw(OStream); htList, htMap, htObject: ReadComplexRaw(OStream); htClass: begin ReadComplexRaw(OStream); ReadRaw(OStream); end; htError: begin ReadRaw(OStream); end; else raise EHproseException.Create('Unexpected serialize tag "' + Tag + '" in stream'); end; end; procedure THproseReader.ReadInfinityRaw(const OStream: TStream); var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); end; procedure THproseReader.ReadNumberRaw(const OStream: TStream); var Tag: AnsiChar; begin repeat FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); until (Tag = HproseTagSemicolon); end; procedure THproseReader.ReadDateTimeRaw(const OStream: TStream); var Tag: AnsiChar; begin repeat FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); until (Tag = HproseTagSemicolon) or (Tag = HproseTagUTC); end; procedure THproseReader.ReadUTF8CharRaw(const OStream: TStream); var Tag: AnsiChar; begin FStream.ReadBuffer(Tag, 1); case Ord(Tag) shr 4 of 0..7: OStream.WriteBuffer(Tag, 1); 12,13: begin OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); end; 14: begin OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); end; else raise EHproseException.Create('bad unicode encoding at $' + IntToHex(Ord(Tag), 4)); end; end; procedure THproseReader.ReadBytesRaw(const OStream: TStream); var Tag: AnsiChar; Len: Integer; begin Len := 0; Tag := '0'; repeat Len := Len * 10 + (Ord(Tag) - Ord('0')); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); until (Tag = HproseTagQuote); OStream.CopyFrom(FStream, Len + 1); end; procedure THproseReader.ReadStringRaw(const OStream: TStream); var Tag: AnsiChar; Len, I: Integer; begin Len := 0; Tag := '0'; repeat Len := Len * 10 + (Ord(Tag) - Ord('0')); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); until (Tag = HproseTagQuote); { When I = Len, Read & Write HproseTagQuote } for I := 0 to Len do begin FStream.ReadBuffer(Tag, 1); case Ord(Tag) shr 4 of 0..7: OStream.WriteBuffer(Tag, 1); 12,13: begin OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); end; 14: begin OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); end; 15: begin if (Ord(Tag) and $F) <= 4 then begin OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); Continue; end; raise EHproseException.Create('bad unicode encoding at $' + IntToHex(Ord(Tag), 4)); end; else raise EHproseException.Create('bad unicode encoding at $' + IntToHex(Ord(Tag), 4)); end; end; end; procedure THproseReader.ReadGuidRaw(const OStream: TStream); begin OStream.CopyFrom(FStream, 38); end; procedure THproseReader.ReadComplexRaw(const OStream: TStream); var Tag: AnsiChar; begin repeat FStream.ReadBuffer(Tag, 1); OStream.WriteBuffer(Tag, 1); until (Tag = HproseTagOpenbrace); FStream.ReadBuffer(Tag, 1); while (Tag <> HproseTagClosebrace) do begin ReadRaw(OStream, Tag); FStream.ReadBuffer(Tag, 1); end; OStream.WriteBuffer(Tag, 1); end; procedure THproseReader.Reset; begin FRefList.Clear; FClassRefList.Clear; FAttrRefMap.Clear; end; { THproseWriter } constructor THproseWriter.Create(AStream: TStream); begin FStream := AStream; FRefList := THashedList.Create(False); FClassRefList := THashedList.Create(False); end; procedure THproseWriter.Serialize(const Value: Variant); var AList: IList; AMap: IMap; ASmartObject: ISmartObject; Obj: TObject; begin with FindVarData(Value)^ do begin case VType and not varByRef of varEmpty, varNull : WriteNull; varBoolean : WriteBoolean(Value); varByte, varWord, varShortInt, varSmallint, varInteger: WriteInteger(Value); {$IFDEF DELPHI2009_UP} varUInt64: WriteLong(RawByteString(UIntToStr(Value))); {$ENDIF} {$IFDEF FPC}varQWord, {$ENDIF} varLongWord, varInt64: WriteLong(RawByteString(VarToStr(Value))); varSingle, varDouble: WriteDouble(Value); varCurrency: WriteCurrency(Value); varString, {$IFDEF DELPHI2009_UP}varUString, {$ENDIF}varOleStr: WriteWideString(Value); varDate: WriteDateTimeWithRef(Value); varUnknown: if (IInterface(Value) = nil) then WriteNull else if Supports(IInterface(Value), IList, AList) then WriteListWithRef(AList) else if Supports(IInterface(Value), IMap, AMap) then WriteMapWithRef(AMap) else if Supports(IInterface(Value), ISmartObject, ASmartObject) then WriteSmartObjectWithRef(ASmartObject) else WriteInterfaceWithRef(IInterface(Value)); else if VType and varArray = varArray then if (VType and varTypeMask = varByte) and (VarArrayDimCount(Value) = 1) then WriteBytesWithRef(Value) else WriteArrayWithRef(Value) else if VType and not varByRef = varObject then begin Obj := VarToObj(Value); if Obj = nil then WriteNull else WriteObjectWithRef(Obj); end end; end; end; procedure THproseWriter.Serialize(const Value: array of const); begin WriteArray(Value); end; procedure THproseWriter.WriteRawByteString(const S: RawByteString); begin FStream.WriteBuffer(S[1], Length(S)); end; procedure THproseWriter.WriteArray(const Value: array of const); var I, N: Integer; AList: IList; AMap: IMap; ASmartObject: ISmartObject; begin FRefList.Add(Null); N := Length(Value); FStream.WriteBuffer(HproseTagList, 1); if N > 0 then WriteRawByteString(RawByteString(IntToStr(N))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to N - 1 do with Value[I] do case VType of vtInteger: WriteInteger(VInteger); vtBoolean: WriteBoolean(VBoolean); vtChar: WriteUTF8Char(WideString(VChar)[1]); vtExtended: WriteDouble(VExtended^); vtString: WriteStringWithRef(WideString(VString^)); vtPChar: WriteStringWithRef(WideString(AnsiString(VPChar))); vtObject: if VObject = nil then WriteNull else WriteObjectWithRef(VObject); vtWideChar: WriteUTF8Char(VWideChar); vtPWideChar: WriteStringWithRef(WideString(VPWideChar)); vtAnsiString: WriteStringWithRef(WideString(AnsiString(VAnsiString))); vtCurrency: WriteCurrency(VCurrency^); vtVariant: Serialize(VVariant^); vtInterface: if IInterface(VInterface) = nil then WriteNull else if Supports(IInterface(VInterface), IList, AList) then WriteListWithRef(AList) else if Supports(IInterface(VInterface), IMap, AMap) then WriteMapWithRef(AMap) else if Supports(IInterface(VInterface), ISmartObject, ASmartObject) then WriteSmartObjectWithRef(ASmartObject) else WriteInterfaceWithRef(IInterface(VInterface)); vtWideString: WriteStringWithRef(WideString(VWideString)); vtInt64: WriteLong(VInt64^); {$IFDEF FPC} vtQWord: WriteLong(VQWord^); {$ENDIF} {$IFDEF DELPHI2009_UP} vtUnicodeString: WriteStringWithRef(UnicodeString(VUnicodeString)); {$ENDIF} else WriteNull; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteArray(const Value: Variant); var PVar: PVarData; P: Pointer; Rank, Count, MaxRank, I, N: Integer; Des: array of array[0..1] of Integer; Loc, Len: array of Integer; begin FRefList.Add(Value); PVar := FindVarData(Value); Rank := VarArrayDimCount(Value); if Rank = 1 then begin Count := VarArrayHighBound(Value, 1) - VarArrayLowBound(Value, 1) + 1; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); P := VarArrayLock(Value); case PVar.VType and varTypeMask of varInteger: WriteIntegerArray(P, Count); varShortInt: WriteShortIntArray(P, Count); varWord: WriteWordArray(P, Count); varSmallint: WriteSmallintArray(P, Count); varLongWord: WriteLongWordArray(P, Count); varSingle: WriteSingleArray(P, Count); varDouble: WriteDoubleArray(P, Count); varCurrency: WriteCurrencyArray(P, Count); varOleStr: WriteWideStringArray(P, Count); varBoolean: WriteBooleanArray(P, Count); varDate: WriteDateTimeArray(P, Count); varVariant: WriteVariantArray(P, Count); end; VarArrayUnLock(Value); FStream.WriteBuffer(HproseTagClosebrace, 1); end else begin SetLength(Des, Rank); SetLength(Loc, Rank); SetLength(Len, Rank); MaxRank := Rank - 1; for I := 0 to MaxRank do begin Des[I, 0] := VarArrayLowBound(Value, I + 1); Des[I, 1] := VarArrayHighBound(Value, I + 1); Loc[I] := Des[I, 0]; Len[I] := Des[I, 1] - Des[I, 0] + 1; end; FStream.WriteBuffer(HproseTagList, 1); if Len[0] > 0 then WriteRawByteString(RawByteString(IntToStr(Len[0]))); FStream.WriteBuffer(HproseTagOpenbrace, 1); while Loc[0] <= Des[0, 1] do begin N := 0; for I := Maxrank downto 1 do if Loc[I] = Des[I, 0] then Inc(N) else Break; for I := Rank - N to MaxRank do begin FRefList.Add(Null); FStream.WriteBuffer(HproseTagList, 1); if Len[I] > 0 then WriteRawByteString(RawByteString(IntToStr(Len[I]))); FStream.WriteBuffer(HproseTagOpenbrace, 1); end; for I := Des[MaxRank, 0] to Des[MaxRank, 1] do begin Loc[MaxRank] := I; Serialize(VarArrayGet(Value, Loc)); end; Inc(Loc[MaxRank]); for I := MaxRank downto 1 do if Loc[I] > Des[I, 1] then begin Loc[I] := Des[I, 0]; Inc(Loc[I - 1]); FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteArrayWithRef(const Value: Variant); var Ref: Integer; begin Ref := FRefList.IndexOf(Value); if Ref > -1 then WriteRef(Ref) else WriteArray(Value); end; procedure THproseWriter.WriteBoolean(B: Boolean); begin FStream.WriteBuffer(HproseTagBoolean[B], 1); end; procedure THproseWriter.WriteBooleanArray(var P; Count: Integer); var AP: PWordBoolArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteBoolean(AP^[I]); end; procedure THproseWriter.WriteBytes(const Bytes: Variant); var N: Integer; begin FRefList.Add(Bytes); N := VarArrayHighBound(Bytes, 1) - VarArrayLowBound(Bytes, 1) + 1; FStream.WriteBuffer(HproseTagBytes, 1); WriteRawByteString(RawByteString(IntToStr(N))); FStream.WriteBuffer(HproseTagQuote, 1); FStream.WriteBuffer(VarArrayLock(Bytes)^, N); VarArrayUnLock(Bytes); FStream.WriteBuffer(HproseTagQuote, 1); end; procedure THproseWriter.WriteBytesWithRef(const Bytes: Variant); var Ref: Integer; begin Ref := FRefList.IndexOf(Bytes); if Ref > -1 then WriteRef(Ref) else WriteBytes(Bytes); end; function THproseWriter.WriteClass(const Instance: TObject): Integer; var ClassAlias: string; PropName: ShortString; PropList: PPropList; PropCount, I: Integer; CachePointer: PSerializeCache; CacheStream: TMemoryStream; TempData: RawByteString; TempWStr: WideString; begin ClassAlias := GetClassAlias(Instance.ClassType); if ClassAlias = '' then raise EHproseException.Create(Instance.ClassName + ' has not registered'); PropertiesCache.Lock; try CachePointer := PSerializeCache(NativeInt(PropertiesCache[ClassAlias])); if CachePointer = nil then begin New(CachePointer); try CachePointer^.RefCount := 0; CachePointer^.Data := ''; CacheStream := TMemoryStream.Create; try PropCount := GetStoredPropList(Instance, PropList); try CacheStream.WriteBuffer(HproseTagClass, 1); TempData := RawByteString(IntToStr(Length(ClassAlias))); CacheStream.WriteBuffer(TempData[1], Length(TempData)); CacheStream.WriteBuffer(HproseTagQuote, 1); Tempdata := RawByteString(ClassAlias); CacheStream.WriteBuffer(TempData[1], Length(TempData)); CacheStream.WriteBuffer(HproseTagQuote, 1); if PropCount > 0 then begin Tempdata := RawByteString(IntToStr(PropCount)); CacheStream.WriteBuffer(TempData[1], Length(TempData)); end; CacheStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to PropCount - 1 do begin PropName := PropList^[I]^.Name; if PropName[1] in ['A'..'Z'] then PropName[1] := AnsiChar(Integer(PropName[1]) + 32); TempWStr := WideString(PropName); CacheStream.WriteBuffer(HproseTagString, 1); Tempdata := RawByteString(IntToStr(Length(TempWStr))); CacheStream.WriteBuffer(TempData[1], Length(TempData)); CacheStream.WriteBuffer(HproseTagQuote, 1); Tempdata := UTF8Encode(TempWStr); CacheStream.WriteBuffer(TempData[1], Length(TempData)); CacheStream.WriteBuffer(HproseTagQuote, 1); Inc(CachePointer^.RefCount); end; CacheStream.WriteBuffer(HproseTagClosebrace, 1); finally FreeMem(PropList); end; CacheStream.Position := 0; SetLength(CachePointer^.Data, CacheStream.Size); Move(CacheStream.Memory^, PAnsiChar(CachePointer^.Data)^, CacheStream.Size); finally CacheStream.Free; end; except Dispose(CachePointer); end; PropertiesCache[ClassAlias] := NativeInt(CachePointer); end; finally PropertiesCache.UnLock; end; FStream.WriteBuffer(CachePointer^.Data[1], Length(CachePointer^.Data)); if CachePointer^.RefCount > 0 then FRefList.Count := FRefList.Count + CachePointer^.RefCount; Result := FClassRefList.Add(Instance.ClassName); end; procedure THproseWriter.WriteCurrency(C: Currency); begin stream.WriteBuffer(HproseTagDouble, 1); WriteRawByteString(RawByteString(CurrToStr(C))); stream.WriteBuffer(HproseTagSemicolon, 1); end; procedure THproseWriter.WriteCurrencyArray(var P; Count: Integer); var AP: PCurrencyArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteCurrency(AP^[I]); end; procedure THproseWriter.WriteDateTimeArray(var P; Count: Integer); var AP: PDateTimeArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteDateTimeWithRef(AP^[I]); end; procedure THproseWriter.WriteDateTime(const ADateTime: TDateTime); var ADate, ATime, AMillisecond: RawByteString; begin FRefList.Add(ADateTime); ADate := RawByteString(FormatDateTime('yyyymmdd', ADateTime)); ATime := RawByteString(FormatDateTime('hhnnss', ADateTime)); AMillisecond := RawByteString(FormatDateTime('zzz', ADateTime)); if (ATime = '000000') and (AMillisecond = '000') then begin FStream.WriteBuffer(HproseTagDate, 1); WriteRawByteString(ADate); end else if ADate = '18991230' then begin FStream.WriteBuffer(HproseTagTime, 1); WriteRawByteString(ATime); if AMillisecond <> '000' then begin FStream.WriteBuffer(HproseTagPoint, 1); WriteRawByteString(AMillisecond); end; end else begin FStream.WriteBuffer(HproseTagDate, 1); WriteRawByteString(ADate); FStream.WriteBuffer(HproseTagTime, 1); WriteRawByteString(ATime); if AMillisecond <> '000' then begin FStream.WriteBuffer(HproseTagPoint, 1); WriteRawByteString(AMillisecond); end; end; FStream.WriteBuffer(HproseTagSemicolon, 1); end; procedure THproseWriter.WriteDateTimeWithRef(const ADateTime: TDateTime); var Ref: Integer; begin Ref := FRefList.IndexOf(ADateTime); if Ref > -1 then WriteRef(Ref) else WriteDateTime(ADateTime); end; procedure THproseWriter.WriteDouble(D: Extended); begin if IsNaN(D) then WriteNaN else if IsInfinite(D) then WriteInfinity(Sign(D) = 1) else begin stream.WriteBuffer(HproseTagDouble, 1); WriteRawByteString(RawByteString(FloatToStr(D))); stream.WriteBuffer(HproseTagSemicolon, 1); end; end; procedure THproseWriter.WriteDoubleArray(var P; Count: Integer); var AP: PDoubleArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteDouble(AP^[I]); end; procedure THproseWriter.WriteInfinity(Positive: Boolean); begin FStream.WriteBuffer(HproseTagInfinity, 1); FStream.WriteBuffer(HproseTagSign[Positive], 1); end; procedure THproseWriter.WriteInteger(I: Integer); var C: AnsiChar; begin if (I >= 0) and (I <= 9) then begin C := AnsiChar(I + Ord('0')); FStream.WriteBuffer(C, 1); end else begin FStream.WriteBuffer(HproseTagInteger, 1); WriteRawByteString(RawByteString(IntToStr(I))); FStream.WriteBuffer(HproseTagSemicolon, 1); end; end; procedure THproseWriter.WriteIntegerArray(var P; Count: Integer); var AP: PIntegerArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteInteger(AP^[I]); end; procedure THproseWriter.WriteList(const AList: IList); var Count, I: Integer; begin FRefList.Add(AList); Count := AList.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do Serialize(AList[I]); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteListWithRef(const AList: IList); var Ref: Integer; begin Ref := FRefList.IndexOf(AList); if Ref > -1 then WriteRef(Ref) else WriteList(AList); end; procedure THproseWriter.WriteList(const AList: TAbstractList); var Count, I: Integer; begin FRefList.Add(ObjToVar(AList)); Count := AList.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do Serialize(AList[I]); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteLong(const L: RawByteString); begin if (Length(L) = 1) and (L[1] in ['0'..'9']) then FStream.WriteBuffer(L[1], 1) else begin FStream.WriteBuffer(HproseTagLong, 1); WriteRawByteString(L); FStream.WriteBuffer(HproseTagSemicolon, 1); end; end; procedure THproseWriter.WriteLong(L: Int64); var C: AnsiChar; begin if (L >= 0) and (L <= 9) then begin C := AnsiChar(L + Ord('0')); FStream.WriteBuffer(C, 1); end else begin FStream.WriteBuffer(HproseTagLong, 1); WriteRawByteString(RawByteString(IntToStr(L))); FStream.WriteBuffer(HproseTagSemicolon, 1); end; end; {$IFDEF DELPHI2009_UP} procedure THproseWriter.WriteLong(L: UInt64); var C: AnsiChar; begin if L <= 9 then begin C := AnsiChar(L + Ord('0')); FStream.WriteBuffer(C, 1); end else begin FStream.WriteBuffer(HproseTagLong, 1); WriteRawByteString(RawByteString(UIntToStr(L))); FStream.WriteBuffer(HproseTagSemicolon, 1); end; end; {$ENDIF} {$IFDEF FPC} procedure THproseWriter.WriteLong(L: QWord); var C: AnsiChar; begin if L <= 9 then begin C := AnsiChar(L + Ord('0')); FStream.WriteBuffer(C, 1); end else begin FStream.WriteBuffer(HproseTagLong, 1); WriteRawByteString(RawByteString(IntToStr(L))); FStream.WriteBuffer(HproseTagSemicolon, 1); end; end; {$ENDIF} procedure THproseWriter.WriteLongWordArray(var P; Count: Integer); var AP: PLongWordArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteLong(AP^[I]); end; procedure THproseWriter.WriteMap(const AMap: IMap); var Count, I: Integer; begin FRefList.Add(AMap); Count := AMap.Count; FStream.WriteBuffer(HproseTagMap, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do begin Serialize(AMap.Keys[I]); Serialize(AMap.Values[I]); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteMapWithRef(const AMap: IMap); var Ref: Integer; begin Ref := FRefList.IndexOf(AMap); if Ref > -1 then WriteRef(Ref) else WriteMap(AMap); end; procedure THproseWriter.WriteMap(const AMap: TAbstractMap); var Count, I: Integer; begin FRefList.Add(ObjToVar(AMap)); Count := AMap.Count; FStream.WriteBuffer(HproseTagMap, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do begin Serialize(AMap.Keys[I]); Serialize(AMap.Values[I]); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteNaN; begin FStream.WriteBuffer(HproseTagNaN, 1); end; procedure THproseWriter.WriteNull; begin FStream.WriteBuffer(HproseTagNull, 1); end; procedure THproseWriter.WriteEmpty; begin FStream.WriteBuffer(HproseTagEmpty, 1); end; procedure THproseWriter.WriteObject(const AObject: TObject); var ClassRef: Integer; Value: Variant; PropList: PPropList; PropCount, I: Integer; ClassName: string; begin ClassName := AObject.ClassName; if AObject is TAbstractList then WriteList(TAbstractList(AObject)) else if AObject is TAbstractMap then WriteMap(TAbstractMap(AObject)) else if AObject is TStrings then WriteStrings(TStrings(AObject)) else {$IFDEF Supports_Generics} if AnsiStartsText('TList<', ClassName) then WriteList(AObject) else if AnsiStartsText('TQueue<', ClassName) then WriteQueue(AObject) else if AnsiStartsText('TStack<', ClassName) then WriteStack(AObject) else if AnsiStartsText('TDictionary<', ClassName) then WriteDictionary(AObject) else if AnsiStartsText('TObjectList<', ClassName) then WriteObjectList(AObject) else if AnsiStartsText('TObjectQueue<', ClassName) then WriteObjectQueue(AObject) else if AnsiStartsText('TObjectStack<', ClassName) then WriteObjectStack(AObject) else if AnsiStartsText('TObjectDictionary<', ClassName) then WriteObjectDictionary(AObject) else {$ENDIF} begin Value := ObjToVar(AObject); ClassRef := FClassRefList.IndexOf(ClassName); if ClassRef < 0 then ClassRef := WriteClass(AObject); FRefList.Add(Value); FStream.WriteBuffer(HproseTagObject, 1); WriteRawByteString(RawByteString(IntToStr(ClassRef))); FStream.WriteBuffer(HproseTagOpenbrace, 1); PropCount := GetStoredPropList(AObject, PropList); try for I := 0 to PropCount - 1 do Serialize(GetPropValue(AObject, PropList^[I])); finally FreeMem(PropList); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteObjectWithRef(const AObject: TObject); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(AObject)); if Ref > -1 then WriteRef(Ref) else WriteObject(AObject); end; procedure THproseWriter.WriteInterface(const Intf: IInterface); var ClassRef: Integer; AObject: TObject; PropList: PPropList; PropCount, I: Integer; begin AObject := IntfToObj(Intf); ClassRef := FClassRefList.IndexOf(AObject.ClassName); if ClassRef < 0 then ClassRef := WriteClass(AObject); FRefList.Add(Intf); FStream.WriteBuffer(HproseTagObject, 1); WriteRawByteString(RawByteString(IntToStr(ClassRef))); FStream.WriteBuffer(HproseTagOpenbrace, 1); PropCount := GetStoredPropList(AObject, PropList); try for I := 0 to PropCount - 1 do Serialize(GetPropValue(AObject, PropList^[I])); finally FreeMem(PropList); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteInterfaceWithRef(const Intf: IInterface); var Ref: Integer; begin Ref := FRefList.IndexOf(Intf); if Ref > -1 then WriteRef(Ref) else WriteInterface(Intf); end; procedure THproseWriter.WriteSmartObject(const SmartObject: ISmartObject); begin WriteObject(SmartObject.Value); end; procedure THproseWriter.WriteSmartObjectWithRef(const SmartObject: ISmartObject); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(SmartObject.Value)); if Ref > -1 then WriteRef(Ref) else if SmartObject.Value is TStrings then WriteStrings(TStrings(SmartObject.Value)) else WriteObject(SmartObject.Value); end; procedure THproseWriter.WriteRef(Value: Integer); begin FStream.WriteBuffer(HproseTagRef, 1); WriteRawByteString(RawByteString(IntToStr(Value))); FStream.WriteBuffer(HproseTagSemicolon, 1); end; procedure THproseWriter.WriteShortIntArray(var P; Count: Integer); var AP: PShortIntArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteInteger(AP^[I]); end; procedure THproseWriter.WriteSingleArray(var P; Count: Integer); var AP: PSingleArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteDouble(AP^[I]); end; procedure THproseWriter.WriteSmallIntArray(var P; Count: Integer); var AP: PSmallIntArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteInteger(AP^[I]); end; procedure THproseWriter.WriteUTF8Char(C: WideChar); begin FStream.WriteBuffer(HproseTagUTF8Char, 1); WriteRawByteString(UTF8Encode(WideString(C))); end; procedure THproseWriter.WriteString(const S: WideString); begin FRefList.Add(S); FStream.WriteBuffer(HproseTagString, 1); WriteRawByteString(RawByteString(IntToStr(Length(S)))); FStream.WriteBuffer(HproseTagQuote, 1); WriteRawByteString(UTF8Encode(S)); FStream.WriteBuffer(HproseTagQuote, 1); end; procedure THproseWriter.WriteStringWithRef(const S: WideString); var Ref: Integer; begin Ref := FRefList.IndexOf(S); if Ref > -1 then WriteRef(Ref) else WriteString(S); end; procedure THproseWriter.WriteStrings(const SS: TStrings); var Count, I: Integer; begin FRefList.Add(ObjToVar(SS)); Count := SS.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do WriteStringWithRef(SS[I]); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteVariantArray(var P; Count: Integer); var AP: PVariantArray absolute P; I: Integer; begin for I := 0 to Count - 1 do Serialize(AP^[I]); end; procedure THproseWriter.WriteWideString(const Str: WideString); begin case Length(Str) of 0: WriteEmpty; 1: WriteUTF8Char(Str[1]); else WriteStringWithRef(Str); end; end; procedure THproseWriter.WriteWideStringArray(var P; Count: Integer); var AP: PWideStringArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteWideString(AP^[I]); end; procedure THproseWriter.WriteWordArray(var P; Count: Integer); var AP: PWordArray absolute P; I: Integer; begin for I := 0 to Count - 1 do WriteInteger(AP^[I]); end; procedure THproseWriter.Reset; begin FRefList.Clear; FClassRefList.Clear; end; {$IFDEF Supports_Generics} procedure THproseWriter.Serialize(const Value; TypeInfo: Pointer); var TypeData: PTypeData; TypeName: string; AList: IList; AMap: IMap; ASmartObject: ISmartObject; Obj: TObject; begin TypeName := GetTypeName(TypeInfo); if TypeName = 'Boolean' then WriteBoolean(Boolean(Value)) else if (TypeName = 'TDateTime') or (TypeName = 'TDate') or (TypeName = 'TTime') then WriteDateTimeWithRef(TDateTime(Value)) else if TypeName = 'UInt64' then WriteLong(RawByteString(UIntToStr(UInt64(Value)))) else begin TypeData := GetTypeData(TypeInfo); case PTypeInfo(TypeInfo)^.Kind of tkVariant: Serialize(Variant(Value)); tkInteger, tkEnumeration, tkSet: case TypeData^.OrdType of otSByte: WriteInteger(ShortInt(Value)); otUByte: WriteInteger(Byte(Value)); otSWord: WriteInteger(SmallInt(Value)); otUWord: WriteInteger(Word(Value)); otSLong: WriteInteger(Integer(Value)); otULong: WriteLong(RawByteString(UIntToStr(LongWord(Value)))); end; tkChar: WriteUTF8Char(WideString(AnsiChar(Value))[1]); tkWChar: WriteUTF8Char(WideChar(Value)); tkFloat: case TypeData^.FloatType of ftSingle: WriteDouble(Single(Value)); ftDouble: WriteDouble(Double(Value)); ftExtended: WriteDouble(Extended(Value)); ftComp: WriteLong(RawByteString(IntToStr(Int64(Value)))); ftCurr: WriteCurrency(Currency(Value)); end; tkString: WriteWideString(WideString(ShortString(Value))); tkLString: WriteWideString(WideString(AnsiString(Value))); tkWString: WriteWideString(WideString(Value)); tkUString: WriteWideString(WideString(UnicodeString(Value))); tkInt64: WriteLong(RawByteString(IntToStr(Int64(Value)))); tkDynArray: WriteArrayWithRef(Value, TypeInfo); tkInterface: begin if IInterface(Value) = nil then WriteNull else if Supports(IInterface(Value), IList, AList) then WriteListWithRef(AList) else if Supports(IInterface(Value), IMap, AMap) then WriteMapWithRef(AMap) else if Supports(IInterface(Value), ISmartObject, ASmartObject) then WriteSmartObjectWithRef(ASmartObject) else WriteInterfaceWithRef(IInterface(Value)); end; tkClass: begin Obj := TObject(Value); if Obj = nil then WriteNull else WriteObjectWithRef(Obj); end; end; end; end; procedure THproseWriter.WriteArray(const DynArray; const Name: string); var TypeName: string; Size: Integer; TypeInfo: PTypeInfo; B1Array: TArray<TB1> absolute DynArray; B2Array: TArray<TB2> absolute DynArray; B4Array: TArray<TB4> absolute DynArray; B8Array: TArray<TB8> absolute DynArray; EArray: TArray<Extended> absolute DynArray; SArray: TArray<ShortString> absolute DynArray; LArray: TArray<AnsiString> absolute DynArray; WArray: TArray<WideString> absolute DynArray; UArray: TArray<UnicodeString> absolute DynArray; VArray: TArray<Variant> absolute DynArray; DArray: TArray<TArray<Pointer>> absolute DynArray; IArray: TArray<IInterface> absolute DynArray; OArray: TArray<TObject> absolute DynArray; Count, I: Integer; begin TypeName := GetElementName(Name); if IsSmartObject(TypeName) then TypeName := 'ISmartObject'; TypeInfo := GetTypeInfo(TypeName, Size); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + Name) else begin FRefList.Add(NativeInt(Pointer(DynArray))); Count := Length(B1Array); FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); case PTypeInfo(TypeInfo)^.Kind of tkString: for I := 0 to Count - 1 do WriteWideString(WideString(SArray[I])); tkLString: for I := 0 to Count - 1 do WriteWideString(WideString(LArray[I])); tkWString: for I := 0 to Count - 1 do WriteWideString(WArray[I]); tkUString: for I := 0 to Count - 1 do WriteWideString(WideString(UArray[I])); tkVariant: for I := 0 to Count - 1 do Serialize(VArray[I]); tkDynArray: for I := 0 to Count - 1 do WriteArrayWithRef(DArray[I], TypeInfo); tkInterface: for I := 0 to Count - 1 do Serialize(IArray[I], TypeInfo); tkClass: for I := 0 to Count - 1 do Serialize(OArray[I], TypeInfo); else case Size of 1: for I := 0 to Count - 1 do Serialize(B1Array[I], TypeInfo); 2: for I := 0 to Count - 1 do Serialize(B2Array[I], TypeInfo); 4: for I := 0 to Count - 1 do Serialize(B4Array[I], TypeInfo); 8: for I := 0 to Count - 1 do Serialize(B8Array[I], TypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then for I := 0 to Count - 1 do WriteDouble(EArray[I]) else raise EHproseException.Create('Can not serialize ' + Name); end; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteArrayWithRef(const DynArray; TypeInfo: Pointer); var Name: string; Ref: Integer; Value: Variant; TypeData: PTypeData; begin Name := GetTypeName(TypeInfo); if AnsiStartsText('TArray<', Name) then begin Ref := FRefList.IndexOf(NativeInt(Pointer(DynArray))); if Ref > -1 then WriteRef(Ref) else WriteArray(DynArray, Name); end else begin DynArrayToVariant(Value, Pointer(DynArray), TypeInfo); TypeData := GetTypeData(TypeInfo); if (TypeData^.varType and varTypeMask = varByte) and (VarArrayDimCount(Value) = 1) then WriteBytesWithRef(Value) else WriteArrayWithRef(Value); end; end; procedure THproseWriter.WriteList(const AList: TObject); var ClassName: string; TypeName: string; Size: Integer; TypeInfo: PTypeInfo; B1List: TList<TB1> absolute AList; B2List: TList<TB2> absolute AList; B4List: TList<TB4> absolute AList; B8List: TList<TB8> absolute AList; EList: TList<Extended> absolute AList; SList: TList<ShortString> absolute AList; LList: TList<AnsiString> absolute AList; WList: TList<WideString> absolute AList; UList: TList<UnicodeString> absolute AList; VList: TList<Variant> absolute AList; DList: TList<TArray<Pointer>> absolute AList; IList: TList<IInterface> absolute AList; OList: TList<TObject> absolute AList; B1: TB1; B2: TB2; B4: TB4; B8: TB8; SS: ShortString; LS: AnsiString; WS: WideString; US: UnicodeString; V: Variant; E: Extended; D: TArray<Pointer>; I: IInterface; O: TObject; Count: Integer; begin ClassName := AList.ClassName; TypeName := GetElementName(ClassName); if IsSmartObject(TypeName) then TypeName := 'ISmartObject'; TypeInfo := GetTypeInfo(TypeName, Size); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AList)); Count := B1List.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); case PTypeInfo(TypeInfo)^.Kind of tkString: for SS in SList do WriteWideString(WideString(SS)); tkLString: for LS in LList do WriteWideString(WideString(LS)); tkWString: for WS in WList do WriteWideString(WS); tkUString: for US in UList do WriteWideString(WideString(US)); tkVariant: for V in VList do Serialize(V); tkDynArray: for D in DList do WriteArrayWithRef(D, TypeInfo); tkInterface: for I in IList do Serialize(I, TypeInfo); tkClass: for O in OList do Serialize(O, TypeInfo); else case Size of 1: for B1 in B1List do Serialize(B1, TypeInfo); 2: for B2 in B2List do Serialize(B2, TypeInfo); 4: for B4 in B4List do Serialize(B4, TypeInfo); 8: for B8 in B8List do Serialize(B8, TypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then for E in EList do WriteDouble(E) else raise EHproseException.Create('Can not serialize ' + ClassName); end; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteObjectList(const AList: TObject); var ClassName: string; TypeInfo: PTypeInfo; OList: TObjectList<TObject> absolute AList; O: TObject; Count: Integer; begin ClassName := AList.ClassName; TypeInfo := TTypeManager.TypeInfo(GetElementName(ClassName)); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AList)); Count := OList.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for O in OList do Serialize(O, TypeInfo); FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteQueue(const AQueue: TObject); var ClassName: string; TypeName: string; Size: Integer; TypeInfo: PTypeInfo; B1Queue: TQueue<TB1> absolute AQueue; B2Queue: TQueue<TB2> absolute AQueue; B4Queue: TQueue<TB4> absolute AQueue; B8Queue: TQueue<TB8> absolute AQueue; EQueue: TQueue<Extended> absolute AQueue; SQueue: TQueue<ShortString> absolute AQueue; LQueue: TQueue<AnsiString> absolute AQueue; WQueue: TQueue<WideString> absolute AQueue; UQueue: TQueue<UnicodeString> absolute AQueue; VQueue: TQueue<Variant> absolute AQueue; DQueue: TQueue<TArray<Pointer>> absolute AQueue; IQueue: TQueue<IInterface> absolute AQueue; OQueue: TQueue<TObject> absolute AQueue; B1: TB1; B2: TB2; B4: TB4; B8: TB8; SS: ShortString; LS: AnsiString; WS: WideString; US: UnicodeString; V: Variant; E: Extended; D: TArray<Pointer>; I: IInterface; O: TObject; Count: Integer; begin ClassName := AQueue.ClassName; TypeName := GetElementName(ClassName); if IsSmartObject(TypeName) then TypeName := 'ISmartObject'; TypeInfo := GetTypeInfo(TypeName, Size); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AQueue)); Count := B1Queue.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); case PTypeInfo(TypeInfo)^.Kind of tkString: for SS in SQueue do WriteWideString(WideString(SS)); tkLString: for LS in LQueue do WriteWideString(WideString(LS)); tkWString: for WS in WQueue do WriteWideString(WS); tkUString: for US in UQueue do WriteWideString(WideString(US)); tkVariant: for V in VQueue do Serialize(V); tkDynArray: for D in DQueue do WriteArrayWithRef(D, TypeInfo); tkInterface: for I in IQueue do Serialize(I, TypeInfo); tkClass: for O in OQueue do Serialize(O, TypeInfo); else case Size of 1: for B1 in B1Queue do Serialize(B1, TypeInfo); 2: for B2 in B2Queue do Serialize(B2, TypeInfo); 4: for B4 in B4Queue do Serialize(B4, TypeInfo); 8: for B8 in B8Queue do Serialize(B8, TypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then for E in EQueue do WriteDouble(E) else raise EHproseException.Create('Can not serialize ' + ClassName); end; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteObjectQueue(const AQueue: TObject); var ClassName: string; TypeInfo: PTypeInfo; OQueue: TObjectQueue<TObject> absolute AQueue; O: TObject; Count: Integer; begin ClassName := AQueue.ClassName; TypeInfo := TTypeManager.TypeInfo(GetElementName(ClassName)); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AQueue)); Count := OQueue.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for O in OQueue do Serialize(O, TypeInfo); FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteStack(const AStack: TObject); var ClassName: string; TypeName: string; Size: Integer; TypeInfo: PTypeInfo; B1Stack: TStack<TB1> absolute AStack; B2Stack: TStack<TB2> absolute AStack; B4Stack: TStack<TB4> absolute AStack; B8Stack: TStack<TB8> absolute AStack; EStack: TStack<Extended> absolute AStack; SStack: TStack<ShortString> absolute AStack; LStack: TStack<AnsiString> absolute AStack; WStack: TStack<WideString> absolute AStack; UStack: TStack<UnicodeString> absolute AStack; VStack: TStack<Variant> absolute AStack; DStack: TStack<TArray<Pointer>> absolute AStack; IStack: TStack<IInterface> absolute AStack; OStack: TStack<TObject> absolute AStack; B1: TB1; B2: TB2; B4: TB4; B8: TB8; SS: ShortString; LS: AnsiString; WS: WideString; US: UnicodeString; V: Variant; E: Extended; D: TArray<Pointer>; I: IInterface; O: TObject; Count: Integer; begin ClassName := AStack.ClassName; TypeName := GetElementName(ClassName); if IsSmartObject(TypeName) then TypeName := 'ISmartObject'; TypeInfo := GetTypeInfo(TypeName, Size); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AStack)); Count := B1Stack.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); case PTypeInfo(TypeInfo)^.Kind of tkString: for SS in SStack do WriteWideString(WideString(SS)); tkLString: for LS in LStack do WriteWideString(WideString(LS)); tkWString: for WS in WStack do WriteWideString(WS); tkUString: for US in UStack do WriteWideString(WideString(US)); tkVariant: for V in VStack do Serialize(V); tkDynArray: for D in DStack do WriteArrayWithRef(D, TypeInfo); tkInterface: for I in IStack do Serialize(I, TypeInfo); tkClass: for O in OStack do Serialize(O, TypeInfo); else case Size of 1: for B1 in B1Stack do Serialize(B1, TypeInfo); 2: for B2 in B2Stack do Serialize(B2, TypeInfo); 4: for B4 in B4Stack do Serialize(B4, TypeInfo); 8: for B8 in B8Stack do Serialize(B8, TypeInfo); else if GetTypeName(TypeInfo) = 'Extended' then for E in EStack do WriteDouble(E) else raise EHproseException.Create('Can not serialize ' + ClassName); end; end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteObjectStack(const AStack: TObject); var ClassName: string; TypeInfo: PTypeInfo; OStack: TObjectStack<TObject> absolute AStack; O: TObject; Count: Integer; begin ClassName := AStack.ClassName; TypeInfo := TTypeManager.TypeInfo(GetElementName(ClassName)); if TypeInfo = nil then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(AStack)); Count := OStack.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for O in OStack do Serialize(O, TypeInfo); FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.WriteTDictionary1<TKey>(const ADict: TObject; ValueSize: Integer; KeyTypeInfo, ValueTypeInfo: Pointer); begin case PTypeInfo(ValueTypeInfo)^.Kind of tkString: WriteTDictionary2<TKey, ShortString>( TDictionary<TKey, ShortString>(ADict), KeyTypeInfo, ValueTypeInfo); tkLString: WriteTDictionary2<TKey, AnsiString>( TDictionary<TKey, AnsiString>(ADict), KeyTypeInfo, ValueTypeInfo); tkWString: WriteTDictionary2<TKey, WideString>( TDictionary<TKey, WideString>(ADict), KeyTypeInfo, ValueTypeInfo); tkUString: WriteTDictionary2<TKey, UnicodeString>( TDictionary<TKey, UnicodeString>(ADict), KeyTypeInfo, ValueTypeInfo); tkVariant: WriteTDictionary2<TKey, Variant>( TDictionary<TKey, Variant>(ADict), KeyTypeInfo, ValueTypeInfo); tkDynArray: WriteTDictionary2<TKey, TArray<Pointer>>( TDictionary<TKey, TArray<Pointer>>(ADict), KeyTypeInfo, ValueTypeInfo); tkInterface: WriteTDictionary2<TKey, IInterface>( TDictionary<TKey, IInterface>(ADict), KeyTypeInfo, ValueTypeInfo); tkClass: WriteTDictionary2<TKey, TObject>( TDictionary<TKey, TObject>(ADict), KeyTypeInfo, ValueTypeInfo); else case ValueSize of 1: WriteTDictionary2<TKey, TB1>( TDictionary<TKey, TB1>(ADict), KeyTypeInfo, ValueTypeInfo); 2: WriteTDictionary2<TKey, TB2>( TDictionary<TKey, TB2>(ADict), KeyTypeInfo, ValueTypeInfo); 4: WriteTDictionary2<TKey, TB4>( TDictionary<TKey, TB4>(ADict), KeyTypeInfo, ValueTypeInfo); 8: WriteTDictionary2<TKey, TB8>( TDictionary<TKey, TB8>(ADict), KeyTypeInfo, ValueTypeInfo); else if GetTypeName(ValueTypeInfo) = 'Extended' then WriteTDictionary2<TKey, Extended>( TDictionary<TKey, Extended>(ADict), KeyTypeInfo, ValueTypeInfo) else raise EHproseException.Create('Can not serialize ' + ClassName); end; end; end; procedure THproseWriter.WriteDictionary(const ADict: TObject); var ClassName: string; KeyTypeName: string; KeySize: Integer; KeyTypeInfo: PTypeInfo; ValueTypeName: string; ValueSize: Integer; ValueTypeInfo: PTypeInfo; begin ClassName := ADict.ClassName; SplitKeyValueTypeName(GetElementName(ClassName), KeyTypeName, ValueTypeName); if IsSmartObject(KeyTypeName) then KeyTypeName := 'ISmartObject'; if IsSmartObject(ValueTypeName) then ValueTypeName := 'ISmartObject'; KeyTypeInfo := GetTypeInfo(KeyTypeName, KeySize); ValueTypeInfo := GetTypeInfo(ValueTypeName, ValueSize); if (KeyTypeInfo = nil) or (ValueTypeInfo = nil) then raise EHproseException.Create('Can not serialize ' + ClassName) else begin case PTypeInfo(KeyTypeInfo)^.Kind of tkString: WriteTDictionary1<ShortString>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkLString: WriteTDictionary1<AnsiString>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkWString: WriteTDictionary1<WideString>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkUString: WriteTDictionary1<UnicodeString>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkVariant: WriteTDictionary1<Variant>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkDynArray: WriteTDictionary1<TArray<Pointer>>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkInterface: WriteTDictionary1<IInterface>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); tkClass: WriteTDictionary1<TObject>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); else case KeySize of 1: WriteTDictionary1<TB1>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); 2: WriteTDictionary1<TB2>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); 4: WriteTDictionary1<TB4>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); 8: WriteTDictionary1<TB8>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo); else if GetTypeName(KeyTypeInfo) = 'Extended' then WriteTDictionary1<Extended>(ADict, ValueSize, KeyTypeInfo, ValueTypeInfo) else raise EHproseException.Create('Can not serialize ' + ClassName); end; end; end; end; procedure THproseWriter.WriteObjectDictionary(const ADict: TObject); var ClassName, KeyTypeName, ValueTypeName: string; KeyTypeInfo, ValueTypeInfo: PTypeInfo; ODict: TObjectDictionary<TObject, TObject> absolute ADict; O: TPair<TObject, TObject>; Count: Integer; begin ClassName := ADict.ClassName; SplitKeyValueTypeName(GetElementName(ClassName), KeyTypeName, ValueTypeName); KeyTypeInfo := TTypeManager.TypeInfo(KeyTypeName); ValueTypeInfo := TTypeManager.TypeInfo(ValueTypeName); if (KeyTypeInfo = nil) or (ValueTypeInfo = nil) then raise EHproseException.Create('Can not serialize ' + ClassName) else begin FRefList.Add(ObjToVar(ADict)); Count := ODict.Count; FStream.WriteBuffer(HproseTagMap, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for O in ODict do begin Serialize(O.Key, KeyTypeInfo); Serialize(O.Value, ValueTypeInfo); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; end; procedure THproseWriter.Serialize<T>(const Value: T); begin Serialize(Value, TypeInfo(T)); end; procedure THproseWriter.WriteArray<T>(const DynArray: array of T); var Count, I: Integer; begin FRefList.Add(Null); Count := Length(DynArray); FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do Serialize(DynArray[I], TypeInfo(T)); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteDynArray<T>(const DynArray: TArray<T>); var Count, I: Integer; begin FRefList.Add(NativeInt(Pointer(DynArray))); Count := Length(DynArray); FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do Serialize(DynArray[I], TypeInfo(T)); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteDynArrayWithRef<T>(const DynArray: TArray<T>); var Ref: Integer; begin Ref := FRefList.IndexOf(NativeInt(Pointer(DynArray))); if Ref > -1 then WriteRef(Ref) else WriteDynArray<T>(DynArray); end; procedure THproseWriter.WriteTList<T>(const AList: TList<T>); var Count, I: Integer; Element: T; begin FRefList.Add(ObjToVar(AList)); Count := AList.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for I := 0 to Count - 1 do begin Element := AList[I]; Serialize(Element, TypeInfo(T)); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteTListWithRef<T>(const AList: TList<T>); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(AList)); if Ref > -1 then WriteRef(Ref) else WriteTList<T>(AList); end; procedure THproseWriter.WriteTQueue<T>(const AQueue: TQueue<T>); var Count, I: Integer; Element: T; begin FRefList.Add(ObjToVar(AQueue)); Count := AQueue.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for Element in AQueue do Serialize(Element, TypeInfo(T)); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteTQueueWithRef<T>(const AQueue: TQueue<T>); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(AQueue)); if Ref > -1 then WriteRef(Ref) else WriteTQueue<T>(AQueue); end; procedure THproseWriter.WriteTStack<T>(const AStack: TStack<T>); var Count, I: Integer; Element: T; begin FRefList.Add(ObjToVar(AStack)); Count := AStack.Count; FStream.WriteBuffer(HproseTagList, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for Element in AStack do Serialize(Element, TypeInfo(T)); FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteTStackWithRef<T>(const AStack: TStack<T>); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(AStack)); if Ref > -1 then WriteRef(Ref) else WriteTStack<T>(AStack); end; procedure THproseWriter.WriteTDictionary2<TKey, TValue>( const ADict: TDictionary<TKey, TValue>; KeyTypeInfo, ValueTypeInfo: Pointer); var Count, I: Integer; Pair: TPair<TKey, TValue>; begin FRefList.Add(ObjToVar(ADict)); Count := ADict.Count; FStream.WriteBuffer(HproseTagMap, 1); if Count > 0 then WriteRawByteString(RawByteString(IntToStr(Count))); FStream.WriteBuffer(HproseTagOpenbrace, 1); for Pair in ADict do begin Serialize(Pair.Key, KeyTypeInfo); Serialize(Pair.Value, ValueTypeInfo); end; FStream.WriteBuffer(HproseTagClosebrace, 1); end; procedure THproseWriter.WriteTDictionary<TKey, TValue>( const ADict: TDictionary<TKey, TValue>); begin WriteTDictionary2<TKey, TValue>(ADict, TypeInfo(TKey), TypeInfo(TValue)); end; procedure THproseWriter.WriteTDictionaryWithRef<TKey, TValue>( const ADict: TDictionary<TKey, TValue>); var Ref: Integer; begin Ref := FRefList.IndexOf(ObjToVar(ADict)); if Ref > -1 then WriteRef(Ref) else WriteTDictionary<TKey, TValue>(ADict); end; {$ELSE} procedure THproseWriter.Serialize(const Value: TObject); begin Serialize(ObjToVar(Value)); end; {$ENDIF} { HproseSerialize } function HproseSerialize(const Value: TObject): RawByteString; begin Result := HproseSerialize(ObjToVar(Value)); end; function HproseSerialize(const Value: Variant): RawByteString; var Writer: THproseWriter; Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Writer := THproseWriter.Create(Stream); try Writer.Serialize(Value); Stream.Position := 0; SetLength(Result, Stream.Size); Move(Stream.Memory^, PAnsiChar(Result)^, Stream.Size); finally Writer.Free; end; finally Stream.Free; end; end; function HproseSerialize(const Value: array of const): RawByteString; var Writer: THproseWriter; Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Writer := THproseWriter.Create(Stream); try Writer.Serialize(Value); Stream.Position := 0; SetLength(Result, Stream.Size); Move(Stream.Memory^, PAnsiChar(Result)^, Stream.Size); finally Writer.Free; end; finally Stream.Free; end; end; { HproseUnserialize } function HproseUnserialize(const Data: RawByteString; TypeInfo: Pointer): Variant; var Reader: THproseReader; Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Stream.SetSize(Length(Data)); Move(PAnsiChar(Data)^, Stream.Memory^, Stream.Size); Reader := THproseReader.Create(Stream); try Result := Reader.Unserialize(TypeInfo); finally Reader.Free; end; finally Stream.Free; end; end; { THproseFormatter } class function THproseFormatter.Serialize( const Value: Variant): RawByteString; begin Result := HproseSerialize(Value); end; class function THproseFormatter.Serialize( const Value: array of const): RawByteString; begin Result := HproseSerialize(Value); end; {$IFDEF Supports_Generics} class function THproseFormatter.Serialize<T>(const Value: T): RawByteString; var Writer: THproseWriter; Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Writer := THproseWriter.Create(Stream); try Writer.Serialize<T>(Value); Stream.Position := 0; SetLength(Result, Stream.Size); Move(Stream.Memory^, PAnsiChar(Result)^, Stream.Size); finally Writer.Free; end; finally Stream.Free; end; end; class function THproseFormatter.Unserialize<T>(const Data:RawByteString): T; var Reader: THproseReader; Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Stream.SetSize(Length(Data)); Move(PAnsiChar(Data)^, Stream.Memory^, Stream.Size); Reader := THproseReader.Create(Stream); try Result := Reader.Unserialize<T>; finally Reader.Free; end; finally Stream.Free; end; end; {$ELSE} class function THproseFormatter.Serialize(const Value: TObject): RawByteString; begin Result := HproseSerialize(Value); end; {$ENDIF} class function THproseFormatter.Unserialize(const Data: RawByteString; TypeInfo: Pointer): Variant; begin Result := HproseUnserialize(Data, TypeInfo); end; class function THproseFormatter.Unserialize(const Data:RawByteString): Variant; begin Result := HproseUnserialize(Data, nil); end; procedure FreePropertiesCache; var I: Integer; CacheValues: IList; CachePointer: PSerializeCache; begin PropertiesCache.Lock; try CacheValues := PropertiesCache.Values; for I := 0 to CacheValues.Count - 1 do begin CachePointer := PSerializeCache(NativeInt(CacheValues[I])); Dispose(CachePointer); end; finally PropertiesCache.Unlock; end; end; initialization PropertiesCache := THashMap.Create; finalization FreePropertiesCache; end.
unit Vcl.TCustomEditHelper; interface uses Winapi.Windows, Vcl.StdCtrls, Vcl.Mask; const ECM_FIRST = $1500; EM_SETCUEBANNER = ECM_FIRST + 1; EM_GETCUEBANNER = ECM_FIRST + 2; type TCustomEditHelper = class helper for TCustomEdit private function GetOldValue: String; procedure SetOldValue(InVal: String); published property OldValue: String read GetOldValue write SetOldValue; end; TEdit = class(Vcl.StdCtrls.TEdit) protected procedure DoEnter; override; end; TMaskEdit = class(Vcl.Mask.TMaskEdit) protected procedure DoEnter; override; end; implementation { TCustomEditHelper } function TCustomEditHelper.GetOldValue: String; const Buf_Size = 512; var w: PWideChar; begin result := ''; w := AllocMem(Buf_Size); try SendMessage(Self.handle, EM_GETCUEBANNER, WParam(w), LParam(Buf_Size)); result := WideCharToString(w); finally FreeMem(w); end; end; procedure TCustomEditHelper.SetOldValue(InVal: String); var w: WideString; begin w := InVal; SendMessage(Self.handle, EM_SETCUEBANNER, 1, LParam(PWideChar(w))); Self.Refresh; end; { TEdit } procedure TEdit.DoEnter; begin inherited; OldValue := Text; end; { TMaskEdit } procedure TMaskEdit.DoEnter; begin inherited; OldValue := Text; end; end.
{******************************************************************************* * * * TksImageViewer - Enhanced image viewer component * * * * https://bitbucket.org/gmurt/kscomponents * * * * Copyright 2017 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksImageViewer; interface {$I ksComponents.inc} uses Classes, Types, ksTypes, FMX.InertialMovement, System.UITypes, FMX.Graphics, FMX.Layouts, FMX.Types; //const // C_BORDER = 20; type [ComponentPlatformsAttribute( pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or {$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or {$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF} )] TksImageViewer = class(TksControl) private FAniCalc: TksAniCalc; FBitmap: TBitmap; FZoom: single; FStartZoom: single; FStartDistance: single; FOnZoom: TNotifyEvent; FMaxXPos: single; FMaxYPos: single; FZooming: Boolean; procedure AniCalcStart(Sender: TObject); procedure AniCalcStop(Sender: TObject); procedure AniCalcChange(Sender: TObject); procedure SetBitmap(const Value: TBitmap); procedure UpdateScrollLimits; procedure SetZoom(const Value: single); protected procedure DblClick; override; procedure DoMouseLeave; override; procedure Paint; override; procedure Resize; override; procedure CMGesture(var EventInfo: TGestureEventInfo); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure DoDoubleTap; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DownloadFile(AUrl: string); function GetFitHeightWidthZoom: integer; procedure FitHeight; procedure FitWidth; procedure FitHeightAndWidth; published property Align; property Bitmap: TBitmap read FBitmap write SetBitmap; property Zoom: single read FZoom write SetZoom; property Position; property Padding; property Margins; property Size; property Width; property Height; property Visible; property Touch; property OnGesture; property OnDblClick; property OnZoom: TNotifyEvent read FOnZoom write FOnZoom; end; procedure Register; implementation uses System.UIConsts, SysUtils, Math, FMX.Controls, System.Net.HttpClientComponent, ksCommon; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksImageViewer]); end; { TksImageViewer } procedure TksImageViewer.AniCalcStart(Sender: TObject); begin if Scene <> nil then Scene.ChangeScrollingState(Self, True); end; procedure TksImageViewer.AniCalcStop(Sender: TObject); begin if Scene <> nil then Scene.ChangeScrollingState(nil, False); end; constructor TksImageViewer.Create(AOwner: TComponent); begin inherited; FBitmap := TBitmap.Create; Touch.InteractiveGestures := [TInteractiveGesture.Zoom, TInteractiveGesture.Pan]; FAniCalc := TksAniCalc.Create(nil); FAniCalc.OnChanged := AniCalcChange; FAniCalc.ViewportPositionF := PointF(0, 0); FAniCalc.Animation := True; FAniCalc.Averaging := True; FAniCalc.Interval := 8; FAniCalc.BoundsAnimation := True; FAniCalc.TouchTracking := [ttHorizontal, ttVertical]; FAniCalc.OnChanged := AniCalcChange; FAniCalc.OnStart := AniCalcStart; FAniCalc.OnStop := AniCalcStop; Width := 100; Height := 100; FZoom := 100; FMaxXPos := 0; FMaxYPos := 0; FZooming := False; Touch.InteractiveGestures := [TInteractiveGesture.Zoom, TInteractiveGesture.Pan]; //FTouchCount := 0; end; procedure TksImageViewer.DblClick; begin inherited; end; destructor TksImageViewer.Destroy; begin FreeAndNil(FBitmap); FreeAndNil(FAniCalc); inherited; end; procedure TksImageViewer.DoDoubleTap; begin if Assigned(OnDblClick) then OnDblClick(Self); end; procedure TksImageViewer.DoMouseLeave; begin inherited; if (FAniCalc <> nil) then FAniCalc.MouseLeave; //FTouchCount := 0; FStartDistance := 0; FStartZoom := 0; end; procedure TksImageViewer.DownloadFile(AUrl: string); var AHttp: TNetHTTPClient; AStream: TStream; ABmp: TBitmap; begin AHttp := TNetHTTPClient.Create(nil); ABmp := TBitmap.Create; try AStream := AHttp.Get(AUrl).ContentStream; AStream.Position := 0; ABmp.LoadFromStream(AStream); Bitmap := ABmp; FitHeightAndWidth; finally AHttp.DisposeOf; FreeAndNil(ABmp); end; InvalidateRect(ClipRect); end; procedure TksImageViewer.FitHeight; begin Zoom := (Height / FBitmap.Height) * 100; end; procedure TksImageViewer.FitHeightAndWidth; begin Zoom := GetFitHeightWidthZoom; end; procedure TksImageViewer.FitWidth; begin Zoom := (Width / FBitmap.Width) * 100; end; function TksImageViewer.GetFitHeightWidthZoom: integer; var z1, z2: single; begin z1 := (Height / FBitmap.Height) * 100; z2 := (Width / FBitmap.Width) * 100; Result := Trunc(Min(z1, z2)); end; procedure TksImageViewer.CMGesture(var EventInfo: TGestureEventInfo); {$IFDEF IOS} var ADistance: integer; ANewZoom: single; {$ENDIF} begin inherited; {$IFDEF IOS} if EventInfo.GestureID = igiDoubleTap then DoDoubleTap; if EventInfo.GestureID = igiZoom then begin if TInteractiveGestureFlag.gfEnd in EventInfo.Flags then begin FZooming := False; FStartDistance := 0; Exit; end; //if TInteractiveGestureFlag.gfBegin in EventInfo.Flags then if FStartDistance = 0 then begin FStartDistance := Round(EventInfo.Distance);//EventInfo.Distance; FStartZoom := FZoom; FZooming := True; Exit; end; ADistance := Round(EventInfo.Distance-FStartDistance) * Round(GetScreenScale(True)); //if FStartZoom + Round(EventInfo.Distance-FStartDistance) > 10 then ANewZoom := FStartZoom + (ADistance / 10); ANewZoom := Min(ANewZoom, 200); ANewZoom := Max(ANewZoom, 10); Zoom := ANewZoom; end; {$ENDIF} end; procedure TksImageViewer.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FStartDistance := 0; FAniCalc.MouseDown(x, y); end; procedure TksImageViewer.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; FAniCalc.MouseMove(x, y); end; procedure TksImageViewer.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FZooming := False; FAniCalc.MouseUp(x, y); FStartDistance := 0; end; procedure TksImageViewer.Paint; var ADestRect: TRectF; ASaveState: TCanvasSaveState; AScale: single; begin inherited; if Locked then Exit; ASaveState := Canvas.SaveState; try Canvas.IntersectClipRect(RectF(0, 0, Width, Height)); Canvas.Clear(claLightgray); AScale := FZoom / 100; ADestRect := RectF(0,0, (FBitmap.Width * AScale), (FBitmap.Height * AScale)); OffsetRect(ADestRect, 0-(FAniCalc.ViewportPosition.X), 0-(FAniCalc.ViewportPosition.Y)); if ADestRect.Width < Width then OffsetRect(ADestRect, (Width-ADestRect.Width) / 2, 0); if ADestRect.Height < Height then OffsetRect(ADestRect, 0, (Height-ADestRect.Height) / 2); InflateRect(ADestRect, -10, -10); Canvas.DrawBitmap(FBitmap, RectF(0, 0, FBitmap.Width, FBitmap.Height), ADestRect, 1, True); finally Canvas.RestoreState(ASaveState); end; end; procedure TksImageViewer.Resize; begin inherited; UpdateScrollLimits; end; procedure TksImageViewer.SetBitmap(const Value: TBitmap); begin FBitmap.Assign(Value); UpdateScrollLimits; Repaint; end; procedure TksImageViewer.SetZoom(const Value: single); var xpercent, ypercent: single; ANewX, ANewY: single; begin if FZoom <> Value then begin if Value < GetFitHeightWidthZoom then Exit; xPercent := 0; yPercent := 0; if (FAniCalc.ViewportPosition.X > 0) and (FMaxXPos > 0) then xPercent := (FAniCalc.ViewportPosition.X / FMaxXPos) * 100; if (FAniCalc.ViewportPosition.Y > 0) and (FMaxYPos > 0) then yPercent := (FAniCalc.ViewportPosition.Y / FMaxYPos) * 100; FZoom := Value; UpdateScrollLimits; ANewX := 0; ANewY := 0; if (FMaxXPos > 0) and (xpercent > 0) then ANewX := (FMaxXPos/100) * xpercent; if (FMaxYPos > 0) and (ypercent > 0) then ANewY := (FMaxYPos/100) * ypercent; FAniCalc.ViewportPositionF := PointF(ANewX, ANewY); InvalidateRect(ClipRect); if Assigned(FOnZoom) then FOnZoom(Self); end; end; procedure TksImageViewer.AniCalcChange(Sender: TObject); begin InvalidateRect(ClipRect); end; procedure TksImageViewer.UpdateScrollLimits; var Targets: array of TAniCalculations.TTarget; AScale: single; begin if FAniCalc <> nil then begin AScale := FZoom / 100; SetLength(Targets, 2); Targets[0].TargetType := TAniCalculations.TTargetType.Min; Targets[0].Point := TPointD.Create(0, 0); Targets[1].TargetType := TAniCalculations.TTargetType.Max; Targets[1].Point := TPointD.Create(Max(0,((FBitmap.Width*AScale))-Width), Max(0, ((FBitmap.Height*AScale))-Height)); FAniCalc.SetTargets(Targets); FMaxXPos := Targets[1].Point.X; FMaxYPos := Targets[1].Point.Y; end; end; end.
unit BenchmarkForm; {$mode delphi} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, BenchmarkClassUnit, Math, CheckLst, Grids, Buttons, ExtCtrls, ComCtrls, Clipbrd, MMValidation, ToolWin, ImgList, Menus; {$I FASTCODE_MM.INC} const WM_POSTPROCESSING = WM_USER + 1; type {The benchmark form} TfBenchmark = class(TForm) gbBenchmarks: TGroupBox; bRunSelectedBenchmark: TBitBtn; bRunAllCheckedBenchmarks: TBitBtn; mBenchmarkDescription: TMemo; ValidateButton: TBitBtn; BitBtn1: TBitBtn; RunTimeEdit: TEdit; ExtraValidateButton: TBitBtn; bGraph: TBitBtn; PageControl1: TPageControl; TabSheetBenchmarkResults: TTabSheet; ListViewResults: TListView; TabSheetProgress: TTabSheet; TabSheetValidation: TTabSheet; MemoValidation: TMemo; mResults: TMemo; ToolBar1: TToolBar; ToolButtonCopyResults: TToolButton; TabSheetScores: TTabSheet; MemoScores: TMemo; ImageList1: TImageList; ToolButtonDeleteResults: TToolButton; btnCopySummary: TBitBtn; bRenameMM: TToolButton; ToolButton1: TToolButton; ListViewBenchmarks: TListView; TabSheetCPU: TTabSheet; MemoCPU: TMemo; PopupMenuBenchmarks: TPopupMenu; PopupClearAllCheckMarks: TMenuItem; PopupSelectAllCheckMarks: TMenuItem; N1: TMenuItem; PopupCheckAllDefaultBenchmarks: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCopySummaryClick(Sender: TObject); procedure ValidateButtonClick(Sender: TObject); procedure bRunSelectedBenchmarkClick(Sender: TObject); procedure bRunAllCheckedBenchmarksClick(Sender: TObject); procedure bGraphClick(Sender: TObject); procedure ToolButtonCopyResultsClick(Sender: TObject); procedure ToolButtonDeleteResultsClick(Sender: TObject); procedure ListViewResultsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure bRenameMMClick(Sender: TObject); procedure ToolButton1Click(Sender: TObject); procedure ListViewBenchmarksSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure PopupClearAllCheckMarksClick(Sender: TObject); procedure PopupSelectAllCheckMarksClick(Sender: TObject); procedure PopupCheckAllDefaultBenchmarksClick(Sender: TObject); private FRanBenchmarkCount: Integer; FMMValidation: TMMValidation; FValidationHasBeenRun: Boolean; FValidationFailures: string; FExtraValidationHasBeenRun: Boolean; FExtraValidationFailures: string; FBenchmarkHasBeenRun: Boolean; FXMLResultList: TStringList; procedure LoadXMLResults; procedure SaveXMLResults; procedure AddValidationToLog; procedure UpdateValidationInLog; procedure AddBenchmark; procedure UpdateBenchmark; procedure SaveSummary; procedure ValidationProgress(const CurrentValidation, Failed: string); procedure WMPOSTPROCESSING(var msg: TMessage); message WM_POSTPROCESSING; {Runs a benchmark and returns its relative speed} procedure RunBenchmark(ABenchmarkClass: TFastcodeMMBenchmarkClass); procedure InitResultsDisplay; procedure AddResultsToDisplay(const BenchName, MMName, TimeRan: String; Ticks, Peak: Cardinal; CurrentSession: string= 'T'; InitialLoad: Boolean = False); procedure LoadResultsToDisplay; procedure SaveResults; procedure CalculateScores; public CSVResultsFileName: AnsiString; end; var fBenchmark: TfBenchmark; const CSV_RESULT_PREFIX = 'MMBench'; SUMMARY_FILE_PREFIX = 'BVSummary'; XML_RESULT_BACKUP_FILENAME = 'MMChallenge_Backup.xml'; XML_RESULT_FILENAME = 'MMChallenge.xml'; //Column indices for the ListView LVCOL_BENCH = 0; LVCOL_MM = 1; LVCOL_TIME = 2; LVCOL_TICKS = 3; LVCOL_MEM = 4; //ListView Subitem Indices LVSI_MM = 0; LVSI_TIME = 1; LVSI_TICKS = 2; LVSI_MEM = 3; //Order of columns in the Results File RESULTS_BENCH = 0; RESULTS_MM = 1; RESULTS_TICKS = 2; RESULTS_MEM = 3; RESULTS_TIME = 4; { PassValidations indicates whether the MM passes all normal validations FastCodeQualityLabel indicates whether the MM passes the normal AND the extra validations If you execute a validation run and the results do not match the hardcoded values, you'll get a message that you should change the source code. } {$IFDEF MM_BUCKETMM} {Robert Houdart's BucketMM} MemoryManager_Name = 'BucketMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'BUC'; {$ENDIF} {$IFDEF MM_BUCKETMM_ASM} {Robert Houdart's BucketBasmMM} MemoryManager_Name = 'BucketMM_Asm'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'BCA'; {$ENDIF} {$IFDEF MM_BUCKETMMDKC_ASM} {Robert Houdart's BucketBasmMM} MemoryManager_Name = 'BucketMMDKC_Asm'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'BCA'; {$ENDIF} {$IFDEF MM_DKCIA32MM} {Dennis Kjaer Christensen Slowcode challenge entry v0.12} MemoryManager_Name = 'DKCIA32MM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'DKC'; {$ENDIF} {$IFDEF MM_EWCMM} {Eric Carman's EWCMM} MemoryManager_Name = 'EWCMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'EWC'; {$ENDIF} {$IFDEF MM_FASTMM2} {Pierre le Riche's FastMM v2.xx} MemoryManager_Name = 'FastMM2'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'FA2'; {$ENDIF} {$IFDEF MM_FASTMM3} {Pierre le Riche's FastMM v3.xx} MemoryManager_Name = 'FastMM3'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'FA3'; {$ENDIF} {$IFDEF MM_FASTMM4} {Pierre le Riche's FastMM v4.xx} MemoryManager_Name = 'FastMM4'; PassValidations = True; FastCodeQualityLabel = True; DllExtension = 'FA4'; {$ENDIF} {$IFDEF MM_FASTMM4_16} {Pierre le Riche's FastMM v4.xx} MemoryManager_Name = 'FastMM4_16'; PassValidations = True; FastCodeQualityLabel = True; DllExtension = 'FA4_16'; {$ENDIF} {$IFDEF MM_HEAPMM} {Vladimir Kladov's HeapMM} { disabled... identical to WINMEM } MemoryManager_Name = 'HeapMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'HPM'; {$ENDIF} {$IFDEF MM_LOCALHEAP} {Carsten Zeumer's LocalHeapMM (Uses the windows heap)} { disabled... identical to WINMEM } MemoryManager_Name = 'LocalHeapMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'LHM'; {$ENDIF} {$IFDEF MM_MULTIMM} {Robert Lee's HPMM} MemoryManager_Name = 'MultiMM'; PassValidations = False; FastCodeQualityLabel = False; DllExtension = 'MMM'; {$ENDIF} {$IFDEF MM_NEXUSMM} {NexusDB Memory Manager} MemoryManager_Name = 'NexusMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'NEX'; {$ENDIF} {$IFDEF MM_PSDMM} {PSDMemoryManager v1.0} MemoryManager_Name = 'PSDMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'PSD'; {$ENDIF} {$IFDEF MM_QMEMORY} {Andrew Driazgov's QMemory} MemoryManager_Name = 'QMemory'; PassValidations = False; FastCodeQualityLabel = False; DllExtension = 'QMM'; {$ENDIF} {$IFDEF MM_RECYCLERMM} {Eric Grange's RecyclerMM} MemoryManager_Name = 'RecyclerMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'REC'; {$ENDIF} {$IFDEF MM_RTLMM} { Borland Delphi RTL Memory Manager } MemoryManager_Name = 'RTLMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'RTL'; {$ENDIF} {$IFDEF MM_TOPMM} {Ivo Top's TopMM} MemoryManager_Name = 'TopMM'; PassValidations = True; // warning: in its current version TopMM fails the DLL Validation FastCodeQualityLabel = False; DllExtension = 'TOP'; {$ENDIF} {$IFDEF MM_WINMEM} {Mike Lischke's WinMem (Uses the windows heap)} MemoryManager_Name = 'WinMem'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'WIN'; {$ENDIF} {$IFDEF MM_QMM} {Martok's QMM} MemoryManager_Name = 'QuickMM'; PassValidations = True; FastCodeQualityLabel = False; DllExtension = 'QuMM'; {$ENDIF} implementation uses FragmentationTestUnit, NexusDBBenchmarkUnit, ReallocMemBenchmark, DownsizeTestUnit, ReplayBenchmarkUnit, WildThreadsBenchmarkUnit, GraphsForm, BlockSizeSpreadBenchmark, SmallDownsizeBenchmark, SmallUpsizeBenchmark, RawPerformanceSingleThread, RawPerformanceMultiThread, AddressSpaceCreepBenchmark, LargeBlockSpreadBenchmark, StringThreadTestUnit, ArrayUpsizeSingleThread, DoubleFPBenchmark1Unit, DoubleFPBenchmark2Unit, DoubleFPBenchmark3Unit, SingleFPBenchmark1Unit, SingleFPBenchmark2Unit, MoveBenchmark1Unit, MoveBenchmark2Unit, AddressSpaceCreepBenchmarkLarge, LinkedListBenchmark, RenameMMForm, BenchmarkUtilities, GeneralFunctions, SystemInfoUnit; {$R *.lfm} {Disables the window ghosting feature for the calling graphical user interface (GUI) process. Window ghosting is a Windows Manager feature that lets the user minimize, move, or close the main window of an application that is not responding. (This "feature" causes problems with form z-order and also modal forms not showing as modal after long periods of non-responsiveness)} procedure DisableProcessWindowsGhosting; var DisableProcessWindowsGhostingProc: procedure; begin DisableProcessWindowsGhostingProc := GetProcAddress( GetModuleHandle('user32.dll'), 'DisableProcessWindowsGhosting'); if Assigned(DisableProcessWindowsGhostingProc) then DisableProcessWindowsGhostingProc; end; procedure TfBenchmark.FormCreate(Sender: TObject); //From FastcodeBenchmarkTool091 - Per Dennis C. Suggestion procedure ShowCPUInfo; var CPUID : TCPUID; I : Integer; begin MemoCPU.Lines.Clear; for I := Low(CPUID) to High(CPUID) do CPUID[I] := -1; if IsCPUID_Available then begin CPUID := GetCPUID; MemoCPU.Lines.Add('Processor Type: ' + IntToStr(CPUID[1] shr 12 and 3)); MemoCPU.Lines.Add('Family: ' + IntToStr(CPUID[1] shr 8 and $f)); MemoCPU.Lines.Add('Model: ' + IntToStr(CPUID[1] shr 4 and $f)); MemoCPU.Lines.Add('Stepping: ' + IntToStr(CPUID[1] and $f)); MemoCPU.Lines.Add('Name: ' + DetectCPUType(Integer(CPUID[1] shr 8 and $f), Integer(CPUID[1] shr 4 and $f))); MemoCPU.Lines.Add('Frequency: ' + IntToStr(GetCPUFrequencyMHz) + ' MHz'); MemoCPU.Lines.Add('Vendor: ' + GetCPUVendor); end; end; var i: integer; Item: TListItem; LWeight: Double; CopiedExeFileName: string; begin Caption := Format('%s %s - %s %s', [Caption, GetFormattedVersion, GetMMName, GetCompilerName]); // ShowCPUInfo; MemoCPU.Lines.Clear; MemoCPU.Lines.Add(SystemInfoCPU); MemoCPU.Lines.Add(''); MemoCPU.Lines.Add(SystemInfoWindows); fGraphs := TfGraphs.Create(Self); CSVResultsFileName := Format('%s%s_%s.csv', [ExtractFilePath(GetModuleName(HInstance)), CSV_RESULT_PREFIX, GetCompilerAbbr]); FValidationHasBeenRun := False; FValidationFailures := ''; FExtraValidationHasBeenRun := False; FExtraValidationFailures := ''; FBenchmarkHasBeenRun := False; FXMLResultList := TStringList.Create; LoadXMLResults; // make a copy of the application's Exe for later use //Skip copy if this is the MM specific exe. if Pos('_' + GetMMName, GetModuleName(HInstance)) = 0 then begin CopiedExeFileName := Format('%s_%s_%s.exe', [ChangeFileExt(Application.ExeName, ''), GetCompilerAbbr, GetMMName]); CopyFile(PChar(GetModuleName(HInstance)), PChar(CopiedExeFileName), False); end; {List the benchmarks} for i := 0 to high(Benchmarks) do begin Item := ListViewBenchmarks.Items.Add; Item.Data := Pointer(i); Item.Checked := Benchmarks[i].RunByDefault; Item.Caption := Benchmarks[i].GetBenchmarkName; LWeight := Benchmarks[i].GetSpeedWeight; Item.SubItems.Add(BenchmarkCategoryNames[Benchmarks[i].GetCategory]); Item.SubItems.Add(FormatFloat('0.## %', LWeight * 100)); Item.SubItems.Add(FormatFloat('0.## %', 100 - LWeight * 100)); Item.SubItems.Add(FormatFloat('0.## %', Benchmarks[i].GetBenchmarkWeight * 100)); Item.SubItems.Add(FormatFloat('0.## %', GlobalBenchmarkWeights[i] * 100)); end; if ListViewBenchmarks.Items.Count > 0 then begin //Select the first benchmark ListViewBenchmarks.Items[0].Selected := True; ListViewBenchmarks.Items[0].Focused := True; //Set the benchmark description. ListViewBenchmarksSelectItem(nil, ListViewBenchmarks.Selected, ListViewBenchmarks.Selected <> nil); end; InitResultsDisplay; FMMValidation := TMMValidation.Create(Self); FMMValidation.OnProgress := ValidationProgress; MemoValidation.Lines.Clear; PageControl1.ActivePage := TabSheetBenchmarkResults; if FastCodeQualityLabel then begin ExtraValidateButton.Font.Color := clGreen; ExtraValidateButton.Caption := 'FastCode Quality Label'; end else begin ExtraValidateButton.Font.Color := clRed; ExtraValidateButton.Caption := 'No FastCode Quality Label'; end; if PassValidations then begin ValidateButton.Font.Color := clGreen; ValidateButton.Caption := 'Passes Validations'; end else begin ValidateButton.Font.Color := clRed; ValidateButton.Caption := 'Does not Pass Validations'; end; if ParamCount > 0 then PostMessage(Handle, WM_POSTPROCESSING, 0, 0) end; procedure TfBenchmark.FormClose(Sender: TObject; var Action: TCloseAction); begin if FRanBenchmarkCount > 0 then SaveResults; FreeAndNil(FXMLResultList); end; procedure TfBenchmark.bRunSelectedBenchmarkClick(Sender: TObject); var StartTime, RunTime : TDateTime; begin StartTime := Time; Screen.Cursor := crHourglass; RuntimeEdit.Text := 'Running'; RuntimeEdit.Color := clLime; if ListViewBenchmarks.Selected = nil then Exit; bRunSelectedBenchmark.Caption := 'Running'; Enabled := False; Application.ProcessMessages; Enabled := True; RunBenchmark(Benchmarks[Integer(ListViewBenchmarks.Selected.Data)]); if FRanBenchmarkCount > 0 then SaveResults; CalculateScores; SaveSummary; bRunSelectedBenchmark.Caption := 'Run Selected Benchmark'; Enabled := False; Application.ProcessMessages; Enabled := True; Screen.Cursor := crDefault; RuntimeEdit.Color := clWindow; RunTime := Time - StartTime; RunTimeEdit.Text := 'Benchmark Time: ' + TimeToStr(RunTime); end; procedure TfBenchmark.RunBenchmark(ABenchmarkClass: TFastcodeMMBenchmarkClass); var LBenchmark: TFastcodeMMBenchmark; LStartTicks, LUsedTicks: Int64; begin PageControl1.ActivePage := TabSheetProgress; mResults.Lines.Add(FormatDateTime('HH:nn:ss', time) + ' Running Benchmark: ' + ABenchmarkClass.GetBenchmarkName + '...'); {Create the benchmark} LBenchmark := ABenchmarkClass.CreateBenchmark; try if LBenchmark.CanRunBenchmark then begin {Do the getmem test} LStartTicks := GetCPUTicks; LBenchmark.RunBenchmark; LUsedTicks := GetCPUTicks - LStartTicks; {Add a line} mResults.Lines[mResults.Lines.Count - 1] := FormatDateTime('HH:nn:ss', time) + ' ' + Format('%-45s MTicks = %6d Mem = %7d', [ ABenchmarkClass.GetBenchmarkName, LUsedTicks shr 20, LBenchmark.PeakAddressSpaceUsage ]); Enabled := False; Application.ProcessMessages; Enabled := True; AddResultsToDisplay(ABenchmarkClass.GetBenchmarkName, MemoryManager_Name, FormatDateTime('YYYYMMDD HH:NN:SS.ZZZ', Now), LUsedTicks shr 20, LBenchmark.PeakAddressSpaceUsage); if not FBenchmarkHasBeenRun then begin AddBenchmark; FBenchmarkHasBeenRun := True; end; UpdateBenchmark; end else begin mResults.Lines[mResults.Lines.Count - 1] := ABenchmarkClass.GetBenchmarkName + ': Skipped'; Enabled := False; Application.ProcessMessages; Enabled := True; end; finally {Free the benchmark} LBenchmark.Free; end; end; procedure TfBenchmark.bRunAllCheckedBenchmarksClick(Sender: TObject); var i: integer; StartTime, RunTime : TDateTime; begin StartTime := Time; Screen.Cursor := crHourglass; RuntimeEdit.Text := 'Running'; RuntimeEdit.Color := clLime; bRunAllCheckedBenchmarks.Caption := 'Running'; Enabled := False; Application.ProcessMessages; Enabled := True; mResults.Lines.Add('***Running All Checked Benchmarks***'); for i := 0 to high(BenchMarks) do begin {Must this benchmark be run?} if ListViewBenchmarks.Items[i].Checked then begin {Show progress in checkboxlist} ListViewBenchmarks.Items[i].Selected := True; ListViewBenchmarks.Items[i].Focused := True; ListViewBenchmarks.Selected.MakeVisible(False); ListViewBenchmarksSelectItem(nil, ListViewBenchmarks.Selected, ListViewBenchmarks.Selected <> nil); Enabled := False; Application.ProcessMessages; Enabled := True; {Run the benchmark} RunBenchmark(BenchMarks[i]); {Wait one second} Sleep(1000); end; end; mResults.Lines.Add('***All Checked Benchmarks Done***'); bRunAllCheckedBenchmarks.Caption := 'Run All Checked Benchmarks'; if FRanBenchmarkCount > 0 then SaveResults; CalculateScores; SaveSummary; Screen.Cursor := crDefault; RuntimeEdit.Color := clWindow; RunTime := Time - StartTime; RunTimeEdit.Text := 'Benchmark Time: ' + TimeToStr(RunTime); end; procedure TfBenchmark.ValidateButtonClick(Sender: TObject); var StartTime, RunTime : TDateTime; FailedValidation, OriginalCaption: string; begin StartTime := Time; Screen.Cursor := crHourglass; try OriginalCaption := (Sender as TBitBtn).Caption; TBitBtn(Sender).Caption := 'Running'; RuntimeEdit.Text := 'Running'; RuntimeEdit.Color := clLime; MemoValidation.Color := clLime; MemoValidation.Lines.Clear; PageControl1.ActivePage := TabSheetValidation; Enabled := False; Application.ProcessMessages; Enabled := True; // execute Validation if not (FValidationHasBeenRun or FExtraValidationHasBeenRun)then AddValidationToLog; if Sender = ExtraValidateButton then begin FailedValidation := FMMValidation.ExtraValidate; FExtraValidationFailures := FailedValidation; FExtraValidationHasBeenRun := True; // Application.ProcessMessages; UpdateValidationInLog; end else begin FailedValidation := FMMValidation.Validate; FValidationFailures := FailedValidation; FValidationHasBeenRun := True; // Application.ProcessMessages; UpdateValidationInLog; end; // show result if FailedValidation = '' then begin MemoValidation.Color := clGreen; end else begin MemoValidation.Color := clRed; MemoValidation.Lines.Add('Failed Validations: ' + FailedValidation); end; RunTime := Time - StartTime; RunTimeEdit.Text := 'Validation Time: ' + TimeToStr(RunTime); // check FastCode Quality Label // if Sender = ExtraValidateButton then begin // if FastCodeQualityLabel xor (PassValidations and (FailedValidation = '')) then // ShowMessage(Format('Constant FastCodeQualityLabel for "%s" should be updated in the source code !', // [MemoryManager_Name])); // end // else begin // if PassValidations xor (FailedValidation = '') then // ShowMessage(Format('Constant PassValidations for "%s" should be updated in the source code !', // [MemoryManager_Name])); // end; finally Screen.Cursor := crDefault; RuntimeEdit.Color := clWindow; (Sender as TBitBtn).Caption := OriginalCaption; end; end; procedure TfBenchmark.bGraphClick(Sender: TObject); begin fGraphs.LoadResultsFromFile(CSVResultsFileName); fGraphs.BuildGraphs; fGraphs.Show; end; procedure TfBenchmark.ValidationProgress(const CurrentValidation, Failed: string); begin if Failed = '' then begin MemoValidation.Color := clGreen; RunTimeEdit.Text := Format('Running %s...', [CurrentValidation]); MemoValidation.Lines.Add(Format('Running %s...', [CurrentValidation])) end else begin MemoValidation.Color := clRed; RunTimeEdit.Text := Format('Running %s... - Failed: %s', [CurrentValidation, Failed]); MemoValidation.Lines.Add(Format('Running %s... - Failed: %s', [CurrentValidation, Failed])); end; Enabled := False; Application.ProcessMessages; Enabled := True; Sleep(250); // slow down a bit so you can see what's happening end; procedure TfBenchmark.InitResultsDisplay; begin ListViewResults.Items.BeginUpdate; try ListViewResults.Items.Clear; finally ListViewResults.Items.EndUpdate; end; FRanBenchmarkCount := 0; LoadResultsToDisplay; ListViewResults.Column[LVCOL_BENCH].Width := -2; ListViewResults.Column[LVCOL_MM].Width := -2; ListViewResults.Column[LVCOL_TIME].Width := -2; ListViewResults.Column[LVCOL_TICKS].Width := -2; ListViewResults.Column[LVCOL_MEM].Width := 120; CalculateScores; end; procedure TfBenchmark.AddResultsToDisplay(const BenchName, MMName, TimeRan: String; Ticks, Peak: Cardinal; CurrentSession: string = 'T'; InitialLoad: Boolean = False); var Item: TListItem; begin Inc(FRanBenchmarkCount); Item := ListViewResults.Items.Add; Item.Caption := BenchName; Item.SubItems.Add(MMName); Item.SubItems.Add(TimeRan); Item.SubItems.Add(IntToStr(Ticks)); Item.SubItems.Add(IntToStr(Peak)); Item.SubItems.Add(CurrentSession); // if not InitialLoad then // ListViewResults.AlphaSort; end; procedure TfBenchmark.LoadResultsToDisplay; var CSV, Bench: TStringList; l: Integer; BenchName, MMName, TimeRan: string; Ticks, Peak: Integer; begin if not FileExists(CSVResultsFileName) then Exit; CSV := TStringList.Create; Bench := TStringList.Create; try Bench.Delimiter := ';'; CSV.LoadFromFile(CSVResultsFileName); ListViewResults.Items.BeginUpdate; try for l := 0 to CSV.Count - 1 do begin Bench.DelimitedText := CSV[l]; if Bench.Count < 4 then Continue; BenchName := Bench[RESULTS_BENCH]; if Trim(BenchName) = '' then Continue; MMName := Bench[RESULTS_MM]; if Bench.Count > RESULTS_TIME then // Available from B&V 0.25 on TimeRan := Bench[RESULTS_TIME] else TimeRan := ''; Ticks := StrToInt(Bench[RESULTS_TICKS]); Peak := StrToInt(Bench[RESULTS_MEM]); AddResultsToDisplay(BenchName, MMName, TimeRan, Ticks, Peak, 'F'); end; finally ListViewResults.Items.EndUpdate; end; // ListViewResults.AlphaSort; if ListViewResults.Items.Count > 0 then begin ListViewResults.Items[0].Selected := True; ListViewResults.Items[0].Focused := True; end; finally Bench.Free; CSV.Free; end; end; procedure TfBenchmark.SaveResults; var CSV, Bench: TStringList; i: Integer; begin CSV := TStringList.Create; Bench := TStringList.Create; try Bench.Delimiter := ';'; for i := 0 to ListViewResults.Items.Count - 1 do begin Bench.Clear; Bench.Add(ListViewResults.Items[i].Caption); Bench.Add(ListViewResults.Items[i].SubItems[LVSI_MM]); Bench.Add(ListViewResults.Items[i].SubItems[LVSI_TICKS]); Bench.Add(ListViewResults.Items[i].SubItems[LVSI_MEM]); Bench.Add(ListViewResults.Items[i].SubItems[LVSI_TIME]); CSV.Add(Bench.DelimitedText); end; CSV.SaveToFile(CSVResultsFileName); finally Bench.Free; CSV.Free; end; end; procedure TfBenchmark.ToolButtonCopyResultsClick(Sender: TObject); var iRow: Integer; iCol: Integer; StringList: TStringList; s: string; Item: TListItem; begin //The tab-delimited data dropped to the clipboard can be pasted into // Excel and will generally auto-separate itself into columns. StringList := TStringList.Create; try //Header s := ''; for iCol := 0 to ListViewResults.Columns.Count - 1 do s := s + #9 + ListViewResults.Column[iCol].Caption; Delete(s, 1, 1); // delete initial #9 character StringList.Add(s); //Body for iRow := 0 to ListViewResults.Items.Count - 1 do begin Item := ListViewResults.Items[iRow]; s := Item.Caption; for iCol := 0 to Item.SubItems.Count - 1 do s := s + #9 + Item.SubItems[iCol]; StringList.Add(s); end; Clipboard.AsText := StringList.Text; finally StringList.Free; end; end; procedure TfBenchmark.CalculateScores; begin if not FileExists(CSVResultsFileName) then begin MemoScores.Lines.Clear; Exit; end; fGraphs.LoadResultsFromFile(CSVResultsFileName); {load score in memo} MemoScores.Lines.BeginUpdate; try MemoScores.Lines.Clear; fGraphs.ShowSummary(MemoScores.Lines); finally MemoScores.Lines.EndUpdate; end; end; procedure TfBenchmark.ToolButtonDeleteResultsClick(Sender: TObject); begin // if (Application.MessageBox('Are you sure you want to delete all results?', // 'Confirm Results Clear', MB_ICONQUESTION or MB_YesNo or MB_DefButton2) = mrYes) then begin ListViewResults.Items.BeginUpdate; try ListViewResults.Items.Clear; finally ListViewResults.Items.EndUpdate; end; DeleteFile(CSVResultsFileName); FRanBenchmarkCount := 0; CalculateScores; end; end; procedure TfBenchmark.ListViewResultsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin //Sort list by Benchmark Name, MM Name, Time Ran Compare := AnsiCompareText(Item1.Caption, Item2.Caption); if Compare = 0 then Compare := AnsiCompareText(Item1.SubItems[0], Item2.SubItems[0]); if Compare = 0 then Compare := AnsiCompareText(Item1.SubItems[1], Item2.SubItems[1]); end; procedure TfBenchmark.btnCopySummaryClick(Sender: TObject); var StringList: TStringList; begin if not FileExists(CSVResultsFileName) then Exit; fGraphs.LoadResultsFromFile(CSVResultsFileName); StringList := TStringList.Create; try fGraphs.ExportTabbedSummary(StringList); Clipboard.AsText := StringList.Text; finally StringList.Free; end; end; procedure TfBenchmark.bRenameMMClick(Sender: TObject); var LInd: integer; LOldName, LNewName: String; begin if ListViewResults.ItemIndex >= 0 then begin Application.CreateForm(TfRenameMM, fRenameMM); try LOldName := ListViewResults.Items[ListViewResults.ItemIndex].SubItems[0]; fRenameMM.eMMName.Text := LOldName; if (fRenameMM.ShowModal = mrOK) and (fRenameMM.eMMName.Text <> '') then begin LNewName := fRenameMM.eMMName.Text; for LInd := 0 to ListViewResults.Items.Count - 1 do begin if ListViewResults.Items[LInd].SubItems[0] = LOldName then ListViewResults.Items[LInd].SubItems[0] := LNewName; end; SaveResults; CalculateScores; end; finally FreeAndNil(fRenameMM); end; end; end; procedure TfBenchmark.ToolButton1Click(Sender: TObject); var LMMName: string; LInd: integer; begin if ListViewResults.ItemIndex < 0 then exit; LMMName := ListViewResults.Items[ListViewResults.ItemIndex].SubItems[0]; // if (Application.MessageBox(PChar('Are you sure you want to delete results for ' + LMMName + '?'), // 'Confirm Results Delete', MB_ICONQUESTION or MB_YesNo or MB_DefButton2) = mrYes) then begin for LInd := ListViewResults.Items.Count - 1 downto 0 do begin if ListViewResults.Items[LInd].SubItems[0] = LMMName then begin ListViewResults.Items[LInd].Delete; Dec(FRanBenchmarkCount); end; end; SaveResults; CalculateScores; end; end; procedure TfBenchmark.ListViewBenchmarksSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin //Set the benchmark description if (Item <> nil) and Selected then mBenchmarkDescription.Text := Benchmarks[Integer(Item.Data)].GetBenchmarkDescription; end; procedure TfBenchmark.PopupClearAllCheckMarksClick(Sender: TObject); var i: Integer; begin for i := 0 to ListViewBenchmarks.Items.Count - 1 do ListViewBenchmarks.Items[i].Checked := False; end; procedure TfBenchmark.PopupSelectAllCheckMarksClick(Sender: TObject); var i: Integer; begin for i := 0 to ListViewBenchmarks.Items.Count - 1 do ListViewBenchmarks.Items[i].Checked := True; end; procedure TfBenchmark.PopupCheckAllDefaultBenchmarksClick(Sender: TObject); var i: Integer; begin for i := 0 to ListViewBenchmarks.Items.Count - 1 do ListViewBenchmarks.Items[i].Checked := Benchmarks[i].RunByDefault; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.LoadXMLResults; var InsertionPoint: Integer; begin if FileExists(XML_RESULT_FILENAME) then begin FXMLResultList.LoadFromFile(XML_RESULT_FILENAME); InsertionPoint := FXMLResultList.IndexOf('</mmbench>'); if InsertionPoint = -1 then begin InsertionPoint := FXMLResultList.Count - 1; FXMLResultList.Insert(InsertionPoint, '<mmbench>'); FXMLResultList.Insert(InsertionPoint+1, '</mmbench>'); end; end else begin FXMLResultList.Add('<mmchallenge>'); FXMLResultList.Add('<mmbench>'); FXMLResultList.Add('</mmbench>'); FXMLResultList.Add('</mmchallenge>'); end; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.AddValidationToLog; var InsertionPoint: Integer; BenchmarksIndex: Integer; begin InsertionPoint := FXMLResultList.IndexOf('</validations>'); if InsertionPoint = -1 then begin BenchmarksIndex := FXMLResultList.IndexOf('<benchmarks>'); if BenchmarksIndex > -1 then InsertionPoint := BenchmarksIndex else InsertionPoint := FXMLResultList.Count - 1; FXMLResultList.Insert(InsertionPoint-1, '<validations>'); FXMLResultList.Insert(InsertionPoint, '</validations>'); end; FXMLResultList.Insert(InsertionPoint, Format('<validation version="%s" compiler="%s" MM="%s">', [GetFormattedVersion, GetCompilerAbbr, GetMMName])); // FXMLResultList.Insert(InsertionPoint, '<validation compiler="' + GetCompilerName + '" MM="' + GetMMName + '" >'); // FXMLResultList.Insert(InsertionPoint+1, Format('<cpu>%s</cpu>', [SystemInfoCPU])); FXMLResultList.Insert(InsertionPoint+1, SystemInfoCPUAsXML); FXMLResultList.Insert(InsertionPoint+2, Format('<os>%s</os>', [SystemInfoWindows])); FXMLResultList.Insert(InsertionPoint+3, '<result> </result>'); FXMLResultList.Insert(InsertionPoint+4, '<extraresult> </extraresult>'); FXMLResultList.Insert(InsertionPoint+5, '</validation>'); end; // ---------------------------------------------------------------------------- procedure TfBenchmark.UpdateValidationInLog; var s: string; ResultIndex: Integer; begin s := ''; ResultIndex := FXMLResultList.IndexOf('</validations>') - 3; if FValidationHasBeenRun then begin if FValidationFailures = '' then s := 'PASS' else s := 'FAILED: ' + FValidationFailures; FXMLResultList[ResultIndex] := Format('<result>%s</result>', [s]); end; if FExtraValidationHasBeenRun then begin s := FExtraValidationFailures; if FExtraValidationFailures = '' then s := 'PASS' else s := 'FAILED: ' + FExtraValidationFailures; FXMLResultList[ResultIndex+1] := Format('<extraresult>%s</extraresult>', [s]); end; SaveXMLResults; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.AddBenchmark; var InsertionPoint: Integer; begin InsertionPoint := FXMLResultList.IndexOf('</benchmarks>'); if InsertionPoint = -1 then begin InsertionPoint := FXMLResultList.Count - 1; FXMLResultList.Insert(InsertionPoint-1, '<benchmarks>'); FXMLResultList.Insert(InsertionPoint, '</benchmarks>'); end; FXMLResultList.Insert(InsertionPoint, Format('<benchmark version="%s" compiler="%s" MM="%s">', [GetFormattedVersion, GetCompilerAbbr, GetMMName])); // FXMLResultList.Insert(InsertionPoint, '<benchmark compiler="' + GetCompilerName + '" MM="' + GetMMName + '" >'); // FXMLResultList.Insert(InsertionPoint+1, Format('<cpu>%s</cpu>', [SystemInfoCPU])); FXMLResultList.Insert(InsertionPoint+1, SystemInfoCPUAsXML); FXMLResultList.Insert(InsertionPoint+2, Format('<os>%s</os>', [SystemInfoWindows])); FXMLResultList.Insert(InsertionPoint+3, '<result> </result>'); FXMLResultList.Insert(InsertionPoint+4, '</benchmark>'); end; // ---------------------------------------------------------------------------- procedure TfBenchmark.UpdateBenchmark; var i: Integer; s: string; Item: TListItem; ResultIndex: Integer; begin ResultIndex := FXMLResultList.IndexOf('</benchmarks>')-1; while SameText(Copy(FXMLResultList[ResultIndex-1], 1, 7), '<result') do begin FXMLResultList.Delete(ResultIndex-1); Dec(ResultIndex); end; for i := ListViewResults.Items.Count -1 downto 0 do begin Item := ListViewResults.Items[i]; if SameText('T', Item.SubItems[4]) then begin s := Format('<result name="%s" time="%s" mticks="%s" mem="%s" />', [Item.Caption, Item.SubItems[1], Item.SubItems[2], Item.SubItems[3]]); FXMLResultList.Insert(ResultIndex, s); end; end; SaveXMLResults; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.WMPOSTPROCESSING(var msg: TMessage); begin if FindCmdLineSwitch('SmokeTest', ['-', '/'], True) then begin Application.ProcessMessages; Close; Exit; end; if FindCmdLineSwitch('C', ['-', '/'], True) then begin // clear CSV results; ToolButtonDeleteResults.Click; end; // All benchmarks if FindCmdLineSwitch('B', ['-', '/'], True) then begin // run all benchmarks Show; Enabled := False; Application.ProcessMessages; Enabled := True; bRunAllCheckedBenchmarks.Click; Halt; end; // All validations if FindCmdLineSwitch('V', ['-', '/'], True) then begin // perform all validations Show; Enabled := False; Application.ProcessMessages; Enabled := True; ValidateButton.Click; ExtraValidateButton.Click; Halt; end; // Regular validations if FindCmdLineSwitch('RV', ['-', '/'], True) then begin // perform all validations Show; Enabled := False; Application.ProcessMessages; Enabled := True; ValidateButton.Click; Halt; end; // Extra validations if FindCmdLineSwitch('EV', ['-', '/'], True) then begin // perform only extra validations Show; Enabled := False; Application.ProcessMessages; Enabled := True; ExtraValidateButton.Click; Halt; end; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.SaveSummary; var FileName: string; F: TextFile; i: Integer; begin FileName := Format('%s%s_%s.txt', [ExtractFilePath(GetModuleName(HInstance)), SUMMARY_FILE_PREFIX, GetCompilerAbbr]); if FileExists(FileName) then DeleteFile(FileName); AssignFile(F, FileName); Rewrite(F); try Writeln(F, 'Summary report for Memory Manager challenge ' + GetFormattedVersion + FormatDateTime(' yyyy-mmm-dd hh:nn:ss', NOW)); Writeln(F, ''); Writeln(F, 'Compiler: ' + GetCompilerName); Writeln(F, SystemInfoCPU); Writeln(F, SystemInfoWindows); Writeln(F, ''); Writeln(F, ''); for i := 0 to MemoScores.Lines.Count - 1 do Writeln(F, MemoScores.Lines[i]); Flush(F); finally CloseFile(F); end; end; // ---------------------------------------------------------------------------- procedure TfBenchmark.SaveXMLResults; var F: TextFile; i: Integer; begin if FileExists(XML_RESULT_FILENAME) then DeleteFile(XML_RESULT_FILENAME); AssignFile(F, XML_RESULT_FILENAME); Rewrite(F); try for i := 0 to FXMLResultList.Count - 1 do Writeln(F, FXMLResultList[i]); Flush(F); finally CloseFile(F); end; // Sometimes forcing an out of memory error causes you to lose the previous // results leaving you with an empty file. This is kind of a backup plan. if FileExists(XML_RESULT_BACKUP_FILENAME) then DeleteFile(XML_RESULT_BACKUP_FILENAME); CopyFile(XML_RESULT_FILENAME, XML_RESULT_BACKUP_FILENAME, False); // FXMLResultList.SaveToFile(XML_RESULT_FILENAME); // Application.ProcessMessages; end; initialization {We want the main form repainted while it's busy running} DisableProcessWindowsGhosting; end.
unit FC.StockChart.UnitTask.Calendar.Navigator; 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.Calendar.NavigatorDialog; type //Специальный Unit Task для автоматического подбора размеров грани и длины периода. //Подюор оусщестьвляется прямым перебором. TStockUnitTaskCalendarNavigator = 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; { TStockUnitTaskCalendarNavigator } function TStockUnitTaskCalendarNavigator.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorCalendar); if result then aOperationName:='Calendar: Navigate'; end; procedure TStockUnitTaskCalendarNavigator.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmCalendarNavigatorDialog.Run(aIndicator as ISCIndicatorCalendar,aStockChart); end; initialization //Регистрируем Unit Task StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskCalendarNavigator.Create); end.
unit ItemsDef; {$DEFINE DEBUG} {$DEFINE DEBUG_SQL} interface uses SysUtils, Types, Graphics, Contnrs, Classes, ItemsSerialize, DateUtils, MkSqLite3, Variants; const STATE_ARRAY : array[0..2] of string = ('продано', 'сободно', 'неисправно'); type TDbItemField = record Name: string; Value: string; ValueType: AnsiChar; // I-Integer, N-Numeric (n.m), S-String end; TDbItemFields = array of TDbItemField; // Базовый класс объекта, хранимого в базе данных TDbItem = class(TObject) protected procedure WriteSL(sl: TStrings; TableName: string); virtual; procedure WriteFields(fl: TDbItemFields; TableName: string); virtual; //procedure ReadFromDataset(ds: TDataSet); virtual; procedure ReadFromDatasetMk(ds: IMkSqlStmt); //function ExecSQL(SQL: string): TDataSet; virtual; function ExecSqlMk(SQL: string): IMkSqlStmt; public ID: Integer; SubItemsLoaded: Boolean; function GetFields(var fl: TDbItemFields): Boolean; virtual; function SetFields(var fl: TDbItemFields): Boolean; virtual; function GetTableName(): string; virtual; procedure Write(WriteSubitems: Boolean = False); virtual; procedure Read(ReadSubitems: Boolean = False); virtual; procedure Delete(DeleteSubitems: Boolean = False); virtual; function Assign(Item: TDbItem): boolean; virtual; procedure Serialize(var Stream: TItemSerialize); virtual; procedure Deserialize(var Stream: TItemSerialize); virtual; end; // Базовый класс списка однотипных объектов, хранимых в базе данных TDbItemsList = class(TObjectList) public SQL_Load: string; SQL_Delete: string; ItemsLoaded: boolean; function AGetItemByID(ItemID: integer): TDbItem; virtual; procedure SaveToBase(); function LoadFromBase(): Boolean; virtual; function CreateItem(): TDbItem; virtual; procedure DeleteFromBase(DeleteSubitems: Boolean = False); virtual; procedure Serialize(var Stream: TItemSerialize);virtual; procedure Deserialize(var Stream: TItemSerialize);virtual; end; TNumLabelTplList = class; TNumLabelList = class; TNumLabelDataList = class; TTicketTplList = class; TTicketList = class; TTicketTpl = class; TNumProject = class; TNumPlanItem = class; TNumPageTpl = class; // Шаблон нумератора TNumLabelTpl = class(TDbItem) public Project: TNumProject; Name: string; // Название BaseValue: string; // Начальное значение ValueType: string; // Тип значения Action: string; // Действие ActionTrigger: AnsiChar; // На чем срабатывает действие (P-лист, T-билет) Prefix: string; // Префикс Suffix: string; // Суффикс constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; //procedure Write(WriteSubitems: Boolean = False); override; //procedure Read(ReadSubitems: Boolean = False); override; //procedure ReadFromDataset(ds: TDataSet); override; //procedure Delete(DeleteSubitems: Boolean = False); override; end; // Нумератор - число или строка, располагающаяся на шаблоне билета // Подчинен шаблону билета // Подчинен шаблону листа // Ссылается на шаблон нумератора TNumLabel = class(TDbItem) private FTicketTpl: TTicketTpl; FNumPageTpl: TNumPageTpl; FNumLabelTpl: TNumLabelTpl; function GetTicketTpl(): TTicketTpl; function GetNumPageTpl(): TNumPageTpl; function GetNumLabelTpl(): TNumLabelTpl; public Project: TNumProject; Name: string; // Название Position: TPoint; // Положение внутри билета/листа Size: Integer; // Размер (высота) надписи Angle: Integer; // Угол наклона Font: TFont; // Шрифт Color: TColor; // Цвет constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; // Fields property TicketTpl: TTicketTpl read GetTicketTpl write FTicketTpl; property NumPageTpl: TNumPageTpl read GetNumPageTpl write FNumPageTpl; property NumLabelTpl: TNumLabelTpl read GetNumLabelTpl write FNumLabelTpl; end; // Данные нумератора // Подчинен элементу плана нумерации // Ссылается на шаблон нумератора TNumLabelData = class(TDbItem) private FNumPlanItem: TNumPlanItem; FNumLabelTpl: TNumLabelTpl; function GetNumPlanItem(): TNumPlanItem; function GetNumLabelTpl(): TNumLabelTpl; public Project: TNumProject; Value: string; // Значение ValueType: string; // Тип значения Action: string; // Действие constructor Create(AProject: TNumProject); function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; //procedure ReadFromDataset(ds: TDataSet); override; // Fields property NumPlanItem: TNumPlanItem read GetNumPlanItem write FNumPlanItem; property NumLabelTpl: TNumLabelTpl read GetNumLabelTpl write FNumLabelTpl; end; // Шаблон листа // Содержит список билетов // Содержит список нумераторов TNumPageTpl = class(TDbItem) private FTickets: TTicketList; FNumLabels: TNumLabelList; function GetTickets(): TTicketList; function GetNumLabels(): TNumLabelList; public Project: TNumProject; Name: string; // Название Size: TPoint; // Размер //Orientation: constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; procedure Delete(DeleteSubitems: Boolean = False); override; procedure Serialize(var Stream: TItemSerialize);override; procedure Deserialize(var Stream: TItemSerialize);override; // Subitems property Tickets: TTicketList read GetTickets; property NumLabels: TNumLabelList read GetNumLabels; // Extra function Assign(Item: TDbItem): boolean; override; end; // Шаблон билета // Содержит список нумераторов TTicketTpl = class(TDbItem) private FNumLabels: TNumLabelList; function GetNumLabels(): TNumLabelList; public Project: TNumProject; Name: string; // Название Size: TPoint; // Размер constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; //procedure ReadFromDataset(ds: TDataSet); override; procedure Delete(DeleteSubitems: Boolean = False); override; procedure Serialize(var Stream: TItemSerialize);override; procedure Deserialize(var Stream: TItemSerialize);override; // Subitems property NumLabels: TNumLabelList read GetNumLabels; // Extra /// Копирует свойства элемента и подчиненные элементы. Старые значения удаляются. function Assign(Item: TDbItem): boolean; override; end; // Билет шаблона листа // Подчинен шаблону листа // Ссылается на шаблон билета TTicket = class(TDbItem) private FTpl: TTicketTpl; FNumPageTpl: TNumPageTpl; function GetTpl(): TTicketTpl; function GetNumPageTpl(): TNumPageTpl; public Project: TNumProject; Name: string; // Название Position: TPoint; // Положение на листе //NumDataList: TObjectList; constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; procedure Read(ReadSubitems: Boolean = False); override; // Fields property Tpl: TTicketTpl read GetTpl write FTpl; property NumPageTpl: TNumPageTpl read GetNumPageTpl write FNumPageTpl; end; /// Лист билетной книги /// Ссылается на шаблон листа TNumPage = class(TDbItem) private FNumPageTpl: TNumPageTpl; public Order: integer; // Порядковый номер State: string; // Состояние Project: TNumProject; constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; //procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; //procedure ReadFromDataset(ds: TDataSet); override; //procedure Delete(DeleteSubitems: Boolean = False); override; // Fields function GetNumPageTpl(): TNumPageTpl; property NumPageTpl: TNumPageTpl read GetNumPageTpl write FNumPageTpl; end; // Элемент плана нумерации // Ссылается на билет, лист с билетами // Содержит список данных нумераторов TNumPlanItem = class(TDbItem) private FTicket: TTicket; FNumPage: TNumPage; FNumLabelDataList: TNumLabelDataList; function GetTicket(): TTicket; function GetNumPage(): TNumPage; function GetNumLabelDataList(): TNumLabelDataList; function GetDataValue(const AName: string): string; procedure SetDataValue(const AName, AValue: string); public Order: integer; // Порядковый номер State: string; // Состояние Project: TNumProject; constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; procedure Delete(DeleteSubitems: Boolean = False); override; procedure Serialize(var Stream: TItemSerialize);override; procedure Deserialize(var Stream: TItemSerialize);override; // Fields property Ticket: TTicket read GetTicket write FTicket; property NumPage: TNumPage read GetNumPage write FNumPage; // Subitems property NumLabelDataList: TNumLabelDataList read GetNumLabelDataList; // Extra property DataValue[const AName: string]: string read GetDataValue write SetDataValue; end; //THallItemKind = (hikSeat, hikScreen, ); THallItemState = (hisBusy, hikFree); // Элемент зала // Ссылается на элемент плана нумерации THallItem = class(TDbItem) private FNumPlanItem: TNumPlanItem; function GetNumPlanItem(): TNumPlanItem; public Project: TNumProject; Position: TPoint; // Положение на плане // S-место, O-настройка, F-фигура, T-текст Kind: AnsiChar; // Вид элемента ParamsText: string; // Строка параметров Color: TColor; // Цвет Row: integer; // Номер ряда Place: integer; // Номер места Sector: integer; // Номер сектора State: string; // Состояние // not for DB Selected: Boolean; Moved: Boolean; Order: integer; constructor Create(AProject: TNumProject); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; //procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; //procedure ReadFromDataset(ds: TDataSet); override; //procedure Delete(DeleteSubitems: Boolean = False); override; // Fields property NumPlanItem: TNumPlanItem read GetNumPlanItem write FNumPlanItem; end; // Элемент настроек проекта TProjectOption = class(TDbItem) public Project: TNumProject; Name: string; Value: string; constructor Create(AProject: TNumProject); //destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; end; TNumProjectList = class(TDbItemsList) private function GetItem(Index: Integer): TNumProject; procedure SetItem(Index: Integer; Value: TNumProject); public property Items[Index: Integer]: TNumProject read GetItem write SetItem; default; function GetProjectByID(ProjectID: integer): TNumProject; procedure SaveToFile(Filename: string); function LoadFromFile(Filename: string): Boolean; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; end; TTicketTplList = class(TDbItemsList) private function GetItem(Index: Integer): TTicketTpl; procedure SetItem(Index: Integer; Value: TTicketTpl); public NumProject: TNumProject; property Items[Index: Integer]: TTicketTpl read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TTicketTpl; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; end; TTicketList = class(TDbItemsList) private function GetItem(Index: Integer): TTicket; procedure SetItem(Index: Integer; Value: TTicket); public NumProject: TNumProject; NumPageTPL: TNumPageTpl; property Items[Index: Integer]: TTicket read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TTicket; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; end; TNumPageTplList = class(TDbItemsList) private function GetItem(Index: Integer): TNumPageTpl; procedure SetItem(Index: Integer; Value: TNumPageTpl); public NumProject: TNumProject; constructor Create(AProject: TNumProject; OwnsItems: Boolean=true); property Items[Index: Integer]: TNumPageTpl read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumPageTpl; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; end; TNumPageList = class(TDbItemsList) private function GetItem(Index: Integer): TNumPage; procedure SetItem(Index: Integer; Value: TNumPage); public NumProject: TNumProject; constructor Create(AProject: TNumProject; OwnsItems: Boolean=true); property Items[Index: Integer]: TNumPage read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumPage; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; procedure DeleteFromBase(DeleteSubitems: Boolean = False); override; function CreateItem(): TDbItem; override; procedure SortByOrder(); end; TNumLabelTplList = class(TDbItemsList) private function GetItem(Index: Integer): TNumLabelTpl; procedure SetItem(Index: Integer; Value: TNumLabelTpl); public NumProject: TNumProject; property Items[Index: Integer]: TNumLabelTpl read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumLabelTpl; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; end; /// Список нумерторов шаблона билета или листа // TNumLabelList = class(TDbItemsList) private function GetItem(Index: Integer): TNumLabel; procedure SetItem(Index: Integer; Value: TNumLabel); public NumProject: TNumProject; TicketTpl: TTicketTpl; NumPageTpl: TNumPageTpl; property Items[Index: Integer]: TNumLabel read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumLabel; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; procedure DeleteFromBase(DeleteSubitems: Boolean = False); override; function CreateItem(): TDbItem; override; end; TNumLabelDataList = class(TDbItemsList) private function GetItem(Index: Integer): TNumLabelData; procedure SetItem(Index: Integer; Value: TNumLabelData); public NumProject: TNumProject; NumPlanItem: TNumPlanItem; property Items[Index: Integer]: TNumLabelData read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumLabelData; //procedure SaveToBase(); function LoadFromBase(): Boolean; override; procedure DeleteFromBase(DeleteSubitems: Boolean = False); override; function CreateItem(): TDbItem; override; end; TNumPlan = class(TDbItemsList) private function GetItem(Index: Integer): TNumPlanItem; procedure SetItem(Index: Integer; Value: TNumPlanItem); public NumProject: TNumProject; property Items[Index: Integer]: TNumPlanItem read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TNumPlanItem; //procedure SaveToBase(SaveSubitems: Boolean = false); reintroduce; function LoadFromBase(): Boolean; override; procedure DeleteFromBase(DeleteSubitems: Boolean = False); override; function CreateItem(): TDbItem; override; procedure SortByOrder(); function GetItemByOrder(AOrder: integer): TNumPlanItem; end; THallPlan = class(TDbItemsList) private function GetItem(Index: Integer): THallItem; procedure SetItem(Index: Integer; Value: THallItem); public NumProject: TNumProject; property Items[Index: Integer]: THallItem read GetItem write SetItem; default; function GetItemByID(ItemID: integer): THallItem; //procedure SaveToBase(SaveSubitems: Boolean = false); reintroduce; function LoadFromBase(): Boolean; override; procedure DeleteFromBase(DeleteSubitems: Boolean = False); override; function CreateItem(): TDbItem; override; end; TProjectOptionList = class(TDbItemsList) private function GetItem(Index: Integer): TProjectOption; procedure SetItem(Index: Integer; Value: TProjectOption); function FGetOption(const Name: string): string; procedure FSetOption(const Name: string; Value: string); public NumProject: TNumProject; property Items[Index: Integer]: TProjectOption read GetItem write SetItem; default; function GetItemByID(ItemID: integer): TProjectOption; //procedure SaveToBase(SaveSubitems: Boolean = false); reintroduce; function LoadFromBase(): Boolean; override; function CreateItem(): TDbItem; override; property Params[const Name: string]: string read FGetOption write FSetOption; end; // Проект нумерации // Содержит шаблоны, страницы, билеты, план нумерации, план зала TNumProject = class(TDbItem) private FPagesTpl: TNumPageTplList; FPages: TNumPageList; FTickets: TTicketList; FTicketTplList: TTicketTplList; FNumLabelsTpl: TNumLabelTplList; FHallPlan: THallPlan; FNumPlanItems: TNumPlan; FOptions: TProjectOptionList; function GetPagesTpl(): TNumPageTplList; function GetPages(): TNumPageList; function GetTickets(): TTicketList; function GetTicketTplList(): TTicketTplList; function GetNumLabelsTpl(): TNumLabelTplList; function GetHallPlan(): THallPlan; function GetNumPlanItems(): TNumPlan; function GetOptions(): TProjectOptionList; public ParentID: Integer; // ID вышестоящего проекта Name: string; // Название Desc: string; // Описание // Not for DB Loaded: Boolean; // Загружен TreeNode: Pointer; // Ссылка на узел визуального дерева проектов CurNumPlanItem: TNumPlanItem; // Текущий билет constructor Create(); destructor Destroy(); override; function GetTableName(): string; override; function GetFields(var fl: TDbItemFields): Boolean; override; function SetFields(var fl: TDbItemFields): Boolean; override; procedure Write(WriteSubitems: Boolean = False); override; procedure Read(ReadSubitems: Boolean = False); override; //procedure ReadFromDataset(ds: TDataSet); override; procedure Delete(DeleteSubitems: Boolean = False); override; procedure Serialize(var Stream: TItemSerialize);override; procedure Deserialize(var Stream: TItemSerialize);override; // Subitems property PagesTpl: TNumPageTplList read GetPagesTpl; property Pages: TNumPageList read GetPages; property Tickets: TTicketList read GetTickets; property TicketTplList: TTicketTplList read GetTicketTplList; property NumLabelsTpl: TNumLabelTplList read GetNumLabelsTpl; property HallPlan: THallPlan read GetHallPlan; property NumPlanItems: TNumPlan read GetNumPlanItems; property Options: TProjectOptionList read GetOptions; end; function CheckAllTables(): Boolean; function PosToStr(Pos: TPoint): string; function StrToPos(const val : string):TPoint; function ApplyAction(Value, Action: string): string; function StartTransaction(): Boolean; function CloseTransaction(): Boolean; function AbortTransaction(): Boolean; procedure DebugMsg(sMsg, sMode: string); const sTableNumLabelData = 'num_data'; sTableNumLabelTpl = 'num_label_tpl'; sTableNumLabels = 'num_labels'; sTableTicketsTpl = 'tickets_tpl'; sTableTickets = 'tickets'; sTableNumPagesTpl = 'pages_tpl'; sTableNumPages = 'pages'; sTableProjects = 'projects'; sTableNumPlanItems = 'num_plan_items'; sTableHallItems = 'hall_items'; sTableProjectOptions= 'project_options'; var TransactionActive: Boolean; DT: TDateTime; db: TMkSqlite; sTicketTplErr: string = 'Не назначен макет билета'; sNumLabelTplErr: string = 'Не назначен шаблон нумератора'; implementation uses MainForm; procedure DebugMsg(sMsg, sMode: string); begin MainForm.frmMain.DebugMsg(sMsg, sMode); end; function Disarm(s: string): string; var DoDisarm: Boolean; begin DoDisarm:=false; if Pos(' ', s)>-1 then DoDisarm:=true else if Pos(',', s)>-1 then DoDisarm:=true else if Pos('"', s)>-1 then DoDisarm:=true; if DoDisarm then begin Result:=StringReplace(s, '"', '""', [rfReplaceAll]); Result:='"'+Result+'"'; Exit; end; Result:=s; end; function PosToStr(Pos: TPoint): string; begin Result:=IntToStr(Pos.X)+' x '+IntToStr(Pos.Y); end; function StrToPos(const val : string):TPoint; const FIND_STR = ' x '; var strVal : string; ps : integer; begin ps:= pos(FIND_STR, val); if ps>0 then begin strVal := copy(val,1,ps-1); Result.X := StrToIntDef(strVal, -1); strVal := copy(val,ps+length(FIND_STR),length(val)-ps); Result.Y := StrToIntDef(strVal, -1); end else Result := Point(-1, -1); end; function ApplyAction2(Value, Action: string): string; var i, n: integer; Cmd, Param: string; begin Cmd:=Copy(Action, 1, 1); Param:=Copy(Action, 2, MaxInt); if Cmd='=' then begin if Param='' then Result:=Value else Result:=Param; Exit; end; i:=StrToIntDef(Value, 0); n:=StrToIntDef(Param, 1); if Cmd='+' then begin Result:=IntToStr(i+n); end else if Cmd='-' then begin Result:=IntToStr(i-n); end; end; function ApplyAction(Value, Action: string): string; var i, n, l, ln: integer; Cmd, Param: string; begin Cmd:=Copy(Action, 1, 1); if Pos(Cmd, '+-=')=0 then begin Result:=''; Exit; end; Param:=Copy(Action, 2, MaxInt); if Cmd='=' then begin if Param='' then Result:=Value else Result:=Param; Exit; end; l:=Length(Value); if l=0 then begin Result:=''; Exit; end; Result:=Copy(Value, 1, l); ln:=l; //n:=StrToIntDef(Param, 1); n:=1; while ln>0 do begin i:=StrToIntDef(Result[ln], 0); if Cmd='+' then begin i:=i+n; if i > 9 then i:=0; Result[ln]:=IntToStr(i)[1]; if i=0 then Dec(ln) else ln:=0; if (i=0) and (ln=0) then Result:='1'+Result; end else if Cmd='-' then begin i:=i-n; if i < 0 then i:=9; Result[ln]:=IntToStr(i)[1]; if i=9 then Dec(ln) else ln:=0; end; end; end; function FontToStr(font: TFont): string; begin Result:=font.Name+', '+IntToStr(font.Size); if (fsBold in font.Style) then Result:=Result+', bold'; if (fsItalic in font.Style) then Result:=Result+', italic'; if (fsUnderline in font.Style) then Result:=Result+', underline'; end; function StrToFont(s: string; font: TFont): Boolean; var ss, sn: string; function GetParam(var sr: string): string; var i: integer; begin Result:=''; i:=Pos(',', sr); if i=0 then i := maxint-1; Result:=Trim(Copy(sr, 1, i-1)); Delete(sr, 1, i); sr:=Trim(sr); end; begin Result:=False; if not Assigned(font) then Exit; ss:=s; font.Name:=GetParam(ss); font.Size:=StrToIntDef(GetParam(ss), font.Size); while ss<>'' do begin sn:=GetParam(ss); if sn='bold' then font.Style:=font.Style + [fsBold]; if sn='italic' then font.Style:=font.Style + [fsItalic]; if sn='underline' then font.Style:=font.Style + [fsUnderline]; end; Result:=True; end; procedure CreateTable(sTableName: string; sl: TStringList); var SQL: string; i: Integer; ds: IMkSqlStmt; begin SQL:='CREATE TABLE '+sTableName+' ('; for i:=0 to sl.Count-1 do begin if i>0 then SQL:=SQL+','; SQL:=SQL+sl.Names[i]+' '+sl.ValueFromIndex[i]; end; SQL:=SQL+');'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} ds:=db.exec(SQL); end; procedure RebuildTable(sTableName: string; sl: TStringList); var i: integer; sTmpTableName: string; //rs: IMkSqlStmt; ds: IMkSqlStmt; s, sn, st, sql: string; begin if not Assigned(db) then Exit; // old table info sn:=''; //rs:=db.SchemaTableInfo(sTableName); SQL:='SELECT * FROM '+sTableName+' LIMIT 1;'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} try ds:=db.exec(SQL); except Exit; end; for i:=0 to ds.fieldCount-1 do begin if sl.IndexOfName(ds.Field[i].name)<0 then Continue; if Length(sn)>0 then sn:=sn+','; sn:=sn+ds.Field[i].name; end; // rename table to temp sTmpTableName:=sTableName+'_tmp'; sql:='ALTER TABLE '+sTableName+' RENAME TO '+sTmpTableName+';'; {$IFDEF DEBUG_SQL} DebugMsg(sql, 'SQL'); {$ENDIF} db.Exec(sql); // create new table CreateTable(sTableName, sl); // refill new table sql:='INSERT INTO '+sTableName+' ('+sn+') ' +'SELECT '+sn+' FROM '+sTmpTableName+';'; {$IFDEF DEBUG_SQL} DebugMsg(sql, 'SQL'); {$ENDIF} db.Exec(sql); // drop temp table sql:='DROP TABLE '+sTmpTableName+';'; {$IFDEF DEBUG_SQL} DebugMsg(sql, 'SQL'); {$ENDIF} db.Exec(sql); end; function CheckTable(sTableName: string; sl: TStringList): Boolean; var SQL: string; i: Integer; ds: IMkSqlStmt; begin Result:=True; //sTableProjects SQL:='SELECT * FROM '+sTableName+' LIMIT 1;'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} try ds:=db.exec(SQL); except CreateTable(sTableName, sl); Exit; end; ds.First(); if ds.fieldCount=0 then begin CreateTable(sTableName, sl); Exit; end; for i:=0 to sl.Count-1 do begin if ds.fieldIndex(sl.Names[i])<0 then begin RebuildTable(sTableName, sl); Exit; end; end; //Result:=False; end; function StartTransaction(): Boolean; begin Result:=False; if TransactionActive then Exit; //DataModule1.DataBase.StartTransaction(); db.beginTransaction(); TransactionActive:=True; Result:=True; end; function CloseTransaction(): Boolean; begin Result:=False; if not TransactionActive then Exit; //DataModule1.DataBase.Commit(); db.Commit(); TransactionActive:=False; Result:=True; end; function AbortTransaction(): Boolean; begin Result:=False; if not TransactionActive then Exit; //DataModule1.DataBase.RollBack(); db.RollBack(); TransactionActive:=False; Result:=True; end; procedure SetDbItemField(var f: TDbItemField; Name, Value: string; ValueType: AnsiChar); begin f.Name:=Name; f.Value:=Value; f.ValueType:=ValueType; end; procedure AddDbItemField(var fl: TDbItemFields; Name, Value: string; ValueType: AnsiChar); var i: Integer; begin i:=Length(fl); SetLength(fl, i+1); fl[i].Name:=Name; fl[i].Value:=Value; fl[i].ValueType:=ValueType; end; function GetDbItemFieldValue(var fl: TDbItemFields; Name: string): string; var i, flCount: Integer; begin flCount:=Length(fl); for i:=0 to flCount-1 do begin if fl[i].Name=Name then begin Result:=fl[i].Value; Exit; end; end; Result:=''; end; // === TDbItem === procedure TDbItem.WriteSL(sl: TStrings; TableName: string); var SQL: string; i: Integer; begin SQL:=''; if self.ID = 0 then begin SQL:='INSERT INTO '+TableName+' ('; for i:=1 to sl.Count-1 do begin if i>1 then SQL:=SQL+','; SQL:=SQL+sl.Names[i]; end; SQL:=SQL+') VALUES ('; for i:=1 to sl.Count-1 do begin if i>1 then SQL:=SQL+','; SQL:=SQL+sl.ValueFromIndex[i]; end; SQL:=SQL+');'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); ID:=db.LastInsertRowId(); //DataModule1.Query1.SQL.Text:=SQL; //DataModule1.Query1.ExecSQL(); //ID:=DataModule1.Query1.GetLastInsertRow(); end else begin SQL:='UPDATE '+TableName+' SET '; for i:=1 to sl.Count-1 do begin if i>1 then SQL:=SQL+','; SQL:=SQL+sl[i]; end; SQL:=SQL+' WHERE id='+IntToStr(ID)+';'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); //DataModule1.Query1.SQL.Text:=SQL; //DataModule1.Query1.ExecSQL(); end; end; procedure TDbItem.WriteFields(fl: TDbItemFields; TableName: string); var SQL: string; i, flCount: Integer; begin SQL:=''; flCount:=Length(fl); if self.ID = 0 then begin SQL:='INSERT INTO '+TableName+' ('; for i:=1 to flCount-1 do begin if i>1 then SQL:=SQL+','; SQL:=SQL+fl[i].Name; end; SQL:=SQL+') VALUES ('; for i:=1 to flCount-1 do begin if i>1 then SQL:=SQL+','; if fl[i].ValueType='S' then SQL:=SQL+Disarm(fl[i].Value) else SQL:=SQL+fl[i].Value; end; SQL:=SQL+');'; //DataModule1.Query1.SQL.Text:=SQL; //DataModule1.Query1.ExecSQL(); //ID:=DataModule1.Query1.GetLastInsertRow(); {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); ID:=db.LastInsertRowId(); end else begin SQL:='UPDATE '+TableName+' SET '; for i:=1 to flCount-1 do begin if i>1 then SQL:=SQL+','; SQL:=SQL+fl[i].Name+'='; if fl[i].ValueType='S' then SQL:=SQL+Disarm(fl[i].Value) else SQL:=SQL+fl[i].Value; end; SQL:=SQL+' WHERE id='+IntToStr(ID)+';'; //DataModule1.Query1.SQL.Text:=SQL; //DataModule1.Query1.ExecSQL(); {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); end; end; procedure TDbItem.Write(WriteSubitems: Boolean = False); var fl: TDbItemFields; begin if GetFields(fl) then WriteFields(fl, GetTableName()); end; procedure TDbItem.Read(ReadSubitems: Boolean = False); var SQL: string; begin if ID=0 then Exit; SQL:='SELECT * FROM '+GetTableName()+' WHERE id='+IntToStr(ID)+';'; //ReadFromDataset(ExecSQL(SQL)); ReadFromDatasetMk(ExecSqlMk(SQL)); end; procedure TDbItem.Delete(DeleteSubitems: Boolean = False); begin //ExecSQL('DELETE FROM '+GetTableName()+' WHERE id='+IntToStr(ID)); if ID <> 0 then ExecSqlMk('DELETE FROM '+GetTableName()+' WHERE id='+IntToStr(ID)); end; //function TDbItem.ExecSQL(SQL: string): TDataSet; //begin // Result:=DataModule1.Query1; // {$IFDEF DEBUG_SQL} // DebugMsg(SQL, 'SQL'); // {$ENDIF} // DataModule1.Query1.SQL.Text:=SQL; // DataModule1.Query1.ExecSQL(); // if Result.RecordCount=0 then Exit; // Result.First(); // //ReadFromDataset(DataModule1.Query1); //end; function TDbItem.ExecSqlMk(SQL: string): IMkSqlStmt; begin {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} Result:=db.exec(SQL); end; //procedure TDbItem.ReadFromDataset(ds: TDataSet); //var // sl: TStringList; // i: Integer; // s: string; //begin // sl:=TStringList.Create(); // ds.GetFieldNames(sl); // for i:=0 to sl.Count-1 do // begin // s:=sl[i]; // sl[i]:=s+'='+ds.Fields[i].AsString; // end; // SetFields(sl); // sl.Free(); //end; //procedure TDbItem.ReadFromDataset(ds: TDataSet); //var // fl: TDbItemFields; // i: Integer; //begin // //ds.GetFieldNames(sl); // SetLength(fl, ds.FieldCount); // for i:=0 to ds.FieldCount-1 do // begin // fl[i].Name:=ds.Fields[i].FieldName; // fl[i].Value:=ds.Fields[i].AsString; // end; // SetFields(fl); //end; procedure TDbItem.ReadFromDatasetMk(ds: IMkSqlStmt); var fl: TDbItemFields; i: Integer; begin //ds.GetFieldNames(sl); SetLength(fl, ds.FieldCount); for i:=0 to ds.FieldCount-1 do begin fl[i].Name:=ds.Field[i].name; fl[i].Value:=ds.value[i]; end; SetFields(fl); end; function TDbItem.GetFields(var fl: TDbItemFields): Boolean; begin SetLength(fl, 1); SetDbItemField(fl[0], 'id', IntToStr(ID), 'I'); Result:=True; end; function TDbItem.SetFields(var fl: TDbItemFields): Boolean; var i, flCount: Integer; begin flCount:=Length(fl); for i:=0 to flCount-1 do begin if fl[i].Name='id' then ID:=StrToIntDef(fl[i].Value, ID); end; Result:=True; end; function TDbItem.GetTableName(): string; begin Result:=''; end; procedure TDbItem.Serialize(var Stream: TItemSerialize); var fl: TDbItemFields; i, flCount: Integer; begin if not GetFields(fl) then Exit; try flCount:=Length(fl); //Stream.StartItem(GetTableName()); for i:=0 to flCount-1 do Stream.AddAttribute(fl[i].Name, fl[i].Value); //Stream.CloseItem(GetTableName()); finally end; end; procedure TDbItem.Deserialize(var Stream: TItemSerialize); var fl: TDbItemFields; i, flCount: Integer; s: string; begin if not GetFields(fl) then Exit; flCount:=Length(fl); try for i:=0 to flCount-1 do begin s:=Stream.GetAttrValue(fl[i].Name); if (s <> '') then fl[i].Value:=s; end; SetFields(fl); finally end; end; function TDbItem.Assign(Item: TDbItem): boolean; var fl: TDbItemFields; OldID: Integer; begin Result:=False; if not Assigned(Item) then Exit; OldID:=self.ID; if Item.GetFields(fl) then Result:=Self.SetFields(fl); Self.ID:=OldID; end; // === TNumLabelTpl === constructor TNumLabelTpl.Create(AProject: TNumProject); begin self.Project:=AProject; ActionTrigger:='T'; end; destructor TNumLabelTpl.Destroy(); begin // end; function TNumLabelTpl.GetTableName(): string; begin Result:=sTableNumLabelTpl; end; function TNumLabelTpl.GetFields(var fl: TDbItemFields): Boolean; begin inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'base_value', BaseValue, 'S'); AddDbItemField(fl, 'value_type', ValueType, 'S'); AddDbItemField(fl, 'action', Action, 'S'); AddDbItemField(fl, 'action_trigger', ActionTrigger, 'S'); AddDbItemField(fl, 'prefix', Prefix, 'S'); AddDbItemField(fl, 'suffix', Suffix, 'S'); Result:=True; end; function TNumLabelTpl.SetFields(var fl: TDbItemFields): Boolean; var i, flCount: Integer; s: string; begin Result:=inherited SetFields(fl); flCount:=Length(fl); for i:=0 to flCount-1 do begin if fl[i].Name='name' then Name:=fl[i].Value else if fl[i].Name='base_value' then BaseValue:=fl[i].Value else if fl[i].Name='value_type' then ValueType:=fl[i].Value else if fl[i].Name='action' then Action:=fl[i].Value else if fl[i].Name='action_trigger' then begin s:=fl[i].Value; if Length(s)>0 then ActionTrigger:=s[1]; end else if fl[i].Name='prefix' then Prefix:=fl[i].Value else if fl[i].Name='suffix' then Suffix:=fl[i].Value; end; Result:=True; end; // === TNumLabel === constructor TNumLabel.Create(AProject: TNumProject); begin Self.Font:=TFont.Create(); self.Project:=AProject; Self.TicketTpl:=nil; self.NumPageTpl:=nil; self.NumLabelTpl:=nil; end; destructor TNumLabel.Destroy(); begin FreeAndNil(Font); end; function TNumLabel.GetTableName(): string; begin Result:=sTableNumLabels; end; function TNumLabel.GetFields(var fl: TDbItemFields): Boolean; var TicketTplID: integer; NumPageTplID: integer; NumLabelTplID: integer; begin TicketTplID:=0; NumPageTplID:=0; NumLabelTplID:=0; if Assigned(TicketTpl) then TicketTplID:=TicketTpl.ID; if Assigned(NumPageTpl) then NumPageTplID:=NumPageTpl.ID; if Assigned(NumLabelTpl) then NumLabelTplID:=NumLabelTpl.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'ticket_tpl_id', IntToStr(TicketTplID), 'I'); AddDbItemField(fl, 'numpage_tpl_id', IntToStr(NumPageTplID), 'I'); AddDbItemField(fl, 'numlabel_tpl_id', IntToStr(NumLabelTplID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'pos_x', IntToStr(Position.X), 'I'); AddDbItemField(fl, 'pos_y', IntToStr(Position.Y), 'I'); AddDbItemField(fl, 'size', IntToStr(Size), 'I'); AddDbItemField(fl, 'angle', IntToStr(Angle), 'I'); AddDbItemField(fl, 'color', IntToStr(Color), 'I'); AddDbItemField(fl, 'font', FontToStr(Font), 'S'); Result:=True; end; function TNumLabel.SetFields(var fl: TDbItemFields): Boolean; begin Result:= inherited SetFields(fl); Name:=GetDbItemFieldValue(fl, 'name'); FTicketTpl:=Project.TicketTplList.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'ticket_tpl_id'), 0)); FNumPageTpl:=Project.PagesTpl.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'numpage_tpl_id'), 0)); FNumLabelTpl:=Project.NumLabelsTpl.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'numlabel_tpl_id'), 0)); Position.X:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_x'), Position.X); Position.Y:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_y'), Position.Y); Size:=StrToIntDef(GetDbItemFieldValue(fl, 'size'), Size); Angle:=StrToIntDef(GetDbItemFieldValue(fl, 'angle'), Angle); Color:=StrToIntDef(GetDbItemFieldValue(fl, 'color'), Color); StrToFont(GetDbItemFieldValue(fl, 'font'), Font); Result:=True; end; function TNumLabel.GetTicketTpl(): TTicketTpl; begin if (not Assigned(FNumPageTpl)) and (not Assigned(FTicketTpl)) then Read(); Result:=FTicketTpl; end; function TNumLabel.GetNumPageTpl(): TNumPageTpl; begin if (not Assigned(FNumPageTpl)) and (not Assigned(FTicketTpl)) then Read(); Result:=FNumPageTpl; end; function TNumLabel.GetNumLabelTpl(): TNumLabelTpl; begin if not Assigned(FNumLabelTpl) then Read(); Result:=FNumLabelTpl; end; // === TNumLabelData === constructor TNumLabelData.Create(AProject: TNumProject); begin inherited Create(); Self.Project:=AProject; end; function TNumLabelData.GetTableName(): string; begin Result:=sTableNumLabelData; end; function TNumLabelData.GetFields(var fl: TDbItemFields): Boolean; var NumPlanItemID: integer; NumLabelTplID: integer; begin NumPlanItemID:=0; NumLabelTplID:=0; if Assigned(NumPlanItem) then NumPlanItemID:=NumPlanItem.ID; if Assigned(NumLabelTpl) then NumLabelTplID:=NumLabelTpl.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); // * AddDbItemField(fl, 'numplan_item_id', IntToStr(NumPlanItemID), 'I'); AddDbItemField(fl, 'numlabel_tpl_id', IntToStr(NumLabelTplID), 'I'); AddDbItemField(fl, 'value', Value, 'S'); AddDbItemField(fl, 'action', Action, 'S'); Result:=True; end; function TNumLabelData.SetFields(var fl: TDbItemFields): Boolean; begin Result:= inherited SetFields(fl); FNumPlanItem:=Project.NumPlanItems.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'numplan_item_id'), 0)); FNumLabelTpl:=Project.NumLabelsTpl.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'numlabel_tpl_id'), 0)); Value:=GetDbItemFieldValue(fl, 'value'); Action:=GetDbItemFieldValue(fl, 'action'); Result:=True; end; // Optimisation for speed (epic fail) //procedure TNumLabelData.ReadFromDataset(ds: TDataSet); //var // i: Integer; //begin // i:=ds.FieldValues['numplan_item_id']; // if (FNumPlanItem = nil) or (FNumPlanItem.ID <> i) then // begin // FNumPlanItem:=Project.NumPlanItems.GetItemByID(i); // end; // i:=ds.FieldValues['numlabel_tpl_id']; // if (FNumLabelTpl = nil) or (FNumLabelTpl.ID <> i) then // begin // FNumLabelTpl:=Project.NumLabelsTpl.GetItemByID(i); // end; // Value:=ds.FieldValues['value']; // Action:=ds.FieldValues['action']; //end; function TNumLabelData.GetNumPlanItem(): TNumPlanItem; begin if not Assigned(FNumPlanItem) then Read(); Result:=FNumPlanItem; end; function TNumLabelData.GetNumLabelTpl(): TNumLabelTpl; begin if not Assigned(FNumLabelTpl) then Read(); Result:=FNumLabelTpl; end; // === TNumPageTpl === constructor TNumPageTpl.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; Self.FTickets:=TTicketList.Create(true); Self.FTickets.NumProject:=AProject; Self.FTickets.NumPageTpl:=Self; Self.FNumLabels:=TNumLabelList.Create(true); Self.FNumLabels.NumProject:=AProject; Self.FNumLabels.NumPageTpl:=Self; end; destructor TNumPageTpl.Destroy(); begin FreeAndNil(FTickets); FreeAndNil(FNumLabels); end; function TNumPageTpl.GetTableName(): string; begin Result:=sTableNumPagesTpl; end; function TNumPageTpl.GetFields(var fl: TDbItemFields): Boolean; begin inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'size_x', IntToStr(Size.X), 'I'); AddDbItemField(fl, 'size_y', IntToStr(Size.Y), 'I'); Result:=True; end; function TNumPageTpl.SetFields(var fl: TDbItemFields): Boolean; begin Result:= inherited SetFields(fl); Name:=GetDbItemFieldValue(fl, 'name'); Size.X:=StrToIntDef(GetDbItemFieldValue(fl, 'size_x'), Size.X); Size.Y:=StrToIntDef(GetDbItemFieldValue(fl, 'size_y'), Size.Y); Result:=True; end; procedure TNumPageTpl.Write(WriteSubitems: Boolean=false); begin inherited Write(WriteSubitems); // Write subitems if not WriteSubitems then Exit; Self.Tickets.SaveToBase(); Self.NumLabels.SaveToBase(); end; procedure TNumPageTpl.Read(ReadSubitems: Boolean = False); begin inherited Read(ReadSubitems); // Retrieve subitems if not ReadSubitems then Exit; Self.Tickets.LoadFromBase(); Self.NumLabels.LoadFromBase(); end; procedure TNumPageTpl.Delete(DeleteSubitems: Boolean = False); begin inherited Delete(DeleteSubitems); if not DeleteSubitems then Exit; Self.Tickets.DeleteFromBase(); //Self.NumLabels.DeleteFromBase(); // !!! end; procedure TNumPageTpl.Serialize(var Stream: TItemSerialize); begin inherited Serialize(Stream); Tickets.Serialize(Stream); NumLabels.Serialize(Stream); end; procedure TNumPageTpl.Deserialize(var Stream: TItemSerialize); begin inherited Deserialize(Stream); Tickets.Deserialize(Stream); NumLabels.Deserialize(Stream); end; function TNumPageTpl.GetTickets(): TTicketList; begin Result:=FTickets; if not FTickets.ItemsLoaded then FTickets.LoadFromBase(); end; function TNumPageTpl.GetNumLabels(): TNumLabelList; begin Result:=FNumLabels; if not FNumLabels.ItemsLoaded then FNumLabels.LoadFromBase(); end; function TNumPageTpl.Assign(Item: TDbItem): boolean; var i: Integer; t: TTicket; begin Result:=inherited Assign(Item); if not Result then Exit; self.Tickets.Clear(); for i:=0 to (Item as TNumPageTpl).Tickets.Count-1 do begin t:=TTicket.Create(self.Project); t.Assign((Item as TNumPageTpl).Tickets[i]); self.Tickets.Add(t); end; end; // === TTicketTpl === constructor TTicketTpl.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; Self.FNumLabels:=TNumLabelList.Create(false); Self.FNumLabels.NumProject:=AProject; Self.FNumLabels.TicketTpl:=Self; end; destructor TTicketTpl.Destroy(); begin FreeAndNil(FNumLabels); end; function TTicketTpl.GetTableName(): string; begin Result:=sTableTicketsTpl; end; function TTicketTpl.GetFields(var fl: TDbItemFields): Boolean; begin inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'width', IntToStr(Size.X), 'I'); AddDbItemField(fl, 'height', IntToStr(Size.Y), 'I'); Result:=True; end; function TTicketTpl.SetFields(var fl: TDbItemFields): Boolean; begin Result:= inherited SetFields(fl); Name:=GetDbItemFieldValue(fl, 'name'); Size.X:=StrToIntDef(GetDbItemFieldValue(fl, 'width'), Size.X); Size.Y:=StrToIntDef(GetDbItemFieldValue(fl, 'height'), Size.Y); Result:=True; end; procedure TTicketTpl.Write(WriteSubitems: Boolean = False); begin inherited Write(WriteSubitems); // Write subitems if not WriteSubitems then Exit; Self.NumLabels.SaveToBase(); end; procedure TTicketTpl.Read(ReadSubitems: Boolean = False); begin inherited Read(ReadSubitems); // Read subitems if not ReadSubitems then Exit; Self.NumLabels.LoadFromBase(); end; procedure TTicketTpl.Delete(DeleteSubitems: Boolean = False); begin inherited Delete(DeleteSubitems); // Delete subitems if not DeleteSubitems then Exit; //Self.NumLabels.DeleteFromBase(); // !!! end; procedure TTicketTpl.Serialize(var Stream: TItemSerialize); begin inherited Serialize(Stream); NumLabels.Serialize(Stream); end; procedure TTicketTpl.Deserialize(var Stream: TItemSerialize); begin inherited Deserialize(Stream); NumLabels.Deserialize(Stream); end; function TTicketTpl.GetNumLabels(): TNumLabelList; begin Result:=FNumLabels; if not FNumLabels.ItemsLoaded then FNumLabels.LoadFromBase(); end; function TTicketTpl.Assign(Item: TDbItem): boolean; var i: Integer; nl : TNumLabel; begin Result:=inherited Assign(Item); if not Result then Exit; self.NumLabels.Clear(); for i:=0 to (Item as TTicketTpl).NumLabels.Count-1 do begin nl:=TNumLabel.Create(self.Project); //if Self.NumLabels[i].GetFields(fl) then Item.SetFields(fl); nl.Assign((Item as TTicketTpl).NumLabels[i]); self.NumLabels.Add(nl); end; end; // === TTicket === constructor TTicket.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; Self.FTpl:=nil; Self.FNumPageTpl:=nil; end; destructor TTicket.Destroy(); begin end; function TTicket.GetTableName(): string; begin Result:=sTableTickets; end; function TTicket.GetFields(var fl: TDbItemFields): Boolean; var TicketTplID: integer; NumPageTplID: integer; begin TicketTplID:=0; NumPageTplID:=0; if Assigned(self.Tpl) then TicketTplID:=self.Tpl.ID; if Assigned(self.NumPageTpl) then NumPageTplID:=self.NumPageTpl.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'page_tpl_id', IntToStr(NumPageTplID), 'I'); AddDbItemField(fl, 'tpl_id', IntToStr(TicketTplID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'pos_x', IntToStr(Position.X), 'I'); AddDbItemField(fl, 'pos_y', IntToStr(Position.Y), 'I'); Result:=True; end; function TTicket.SetFields(var fl: TDbItemFields): Boolean; begin ID:=StrToIntDef(GetDbItemFieldValue(fl, 'id'), ID); FNumPageTpl:=Project.PagesTpl.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'page_tpl_id'), 0)); FTpl:=Project.TicketTplList.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'tpl_id'), 0)); Name:=GetDbItemFieldValue(fl, 'name'); Position.X:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_x'), Position.X); Position.Y:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_y'), Position.Y); Result:=True; end; procedure TTicket.Read(ReadSubitems: Boolean = False); begin if ID=0 then Exit; if not Project.PagesTpl.ItemsLoaded then Project.PagesTpl.LoadFromBase(); if not Project.TicketTplList.ItemsLoaded then Project.TicketTplList.LoadFromBase(); inherited Read(ReadSubitems); end; function TTicket.GetTpl(): TTicketTpl; begin if not Assigned(FTpl) then Read(); Result:=FTpl; end; function TTicket.GetNumPageTpl(): TNumPageTpl; begin if not Assigned(FNumPageTpl) then Read(); Result:=FNumPageTpl; end; // === TNumPage === constructor TNumPage.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; end; destructor TNumPage.Destroy(); begin end; function TNumPage.GetTableName(): string; begin Result:=sTableNumPages; end; function TNumPage.GetFields(var fl: TDbItemFields): Boolean; var NumPageTplID: integer; begin NumPageTplID:=0; if Assigned(NumPageTpl) then NumPageTplID:=NumPageTpl.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'page_tpl_id', IntToStr(NumPageTplID), 'I'); AddDbItemField(fl, 'num_order', IntToStr(Order), 'I'); AddDbItemField(fl, 'state', State, 'S'); Result:=True; end; function TNumPage.SetFields(var fl: TDbItemFields): Boolean; begin Result:=inherited SetFields(fl); FNumPageTpl:=Project.PagesTpl.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'page_tpl_id'), 0)); Order:=StrToIntDef(GetDbItemFieldValue(fl, 'num_order'), Order); State:=GetDbItemFieldValue(fl, 'state'); Result:=True; end; procedure TNumPage.Read(ReadSubitems: Boolean = False); var SQL: string; begin if ID=0 then Exit; if not Project.PagesTpl.ItemsLoaded then Project.PagesTpl.LoadFromBase(); inherited Read(ReadSubitems); end; function TNumPage.GetNumPageTpl(): TNumPageTpl; begin if not Assigned(FNumPageTpl) then Read(); Result:=FNumPageTpl; end; // === TNumPlanItem === constructor TNumPlanItem.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; self.FNumLabelDataList:=TNumLabelDataList.Create(true); self.FNumLabelDataList.NumProject:=AProject; self.FNumLabelDataList.NumPlanItem:=Self; end; destructor TNumPlanItem.Destroy(); begin FreeAndNil(FNumLabelDataList); end; function TNumPlanItem.GetTableName(): string; begin Result:=sTableNumPlanItems; end; function TNumPlanItem.GetFields(var fl: TDbItemFields): Boolean; var TicketTplID: integer; NumPageTplID: integer; begin TicketTplID:=0; NumPageTplID:=0; if Assigned(Ticket) then TicketTplID:=Ticket.ID; if Assigned(NumPage) then NumPageTplID:=NumPage.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'ticket_id', IntToStr(TicketTplID), 'I'); AddDbItemField(fl, 'page_id', IntToStr(NumPageTplID), 'I'); AddDbItemField(fl, 'num_order', IntToStr(Order), 'I'); AddDbItemField(fl, 'state', State, 'S'); Result:=True; end; function TNumPlanItem.SetFields(var fl: TDbItemFields): Boolean; begin Result:=inherited SetFields(fl); Ticket:=Project.Tickets.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'ticket_id'), 0)); NumPage:=Project.Pages.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'page_id'), 0)); Order:=StrToIntDef(GetDbItemFieldValue(fl, 'num_order'), Order); State:=GetDbItemFieldValue(fl, 'state'); Result:=True; end; procedure TNumPlanItem.Write(WriteSubitems: Boolean = False); var sl: TStringList; begin inherited Write(WriteSubitems); // Write subitems if not WriteSubitems then Exit; Self.NumLabelDataList.SaveToBase(); end; procedure TNumPlanItem.Read(ReadSubitems: Boolean = False); var SQL: string; begin if ID=0 then Exit; if not Project.Tickets.ItemsLoaded then Project.Tickets.LoadFromBase(); if not Project.Pages.ItemsLoaded then Project.Pages.LoadFromBase(); inherited Read(ReadSubitems); // Retrieve subitems if not ReadSubitems then Exit; Self.NumLabelDataList.LoadFromBase(); end; procedure TNumPlanItem.Delete(DeleteSubitems: Boolean = False); begin inherited Delete(DeleteSubitems); if not DeleteSubitems then Exit; Self.NumLabelDataList.DeleteFromBase(); end; procedure TNumPlanItem.Serialize(var Stream: TItemSerialize); begin inherited Serialize(Stream); NumLabelDataList.Serialize(Stream); end; procedure TNumPlanItem.Deserialize(var Stream: TItemSerialize); begin inherited Deserialize(Stream); NumLabelDataList.Deserialize(Stream); end; function TNumPlanItem.GetTicket(): TTicket; begin if not Assigned(FTicket) then Read(); Result:=FTicket; end; function TNumPlanItem.GetNumPage(): TNumPage; begin if not Assigned(FNumPage) then Read(); Result:=FNumPage; end; function TNumPlanItem.GetNumLabelDataList(): TNumLabelDataList; begin Result:=FNumLabelDataList; if not FNumLabelDataList.ItemsLoaded then FNumLabelDataList.LoadFromBase(); end; function TNumPlanItem.GetDataValue(const AName: string): string; var i: Integer; begin for i:=0 to NumLabelDataList.Count-1 do begin if AnsiSameText(NumLabelDataList[i].NumLabelTpl.Name, AName) then begin Result:=NumLabelDataList[i].Value; Exit; end; end; Result:=''; end; procedure TNumPlanItem.SetDataValue(const AName, AValue: string); var i: Integer; begin for i:=0 to NumLabelDataList.Count-1 do begin if AnsiSameText(NumLabelDataList[i].NumLabelTpl.Name, AName) then begin NumLabelDataList[i].Value:=AValue; Exit; end; end; end; // === THallItem === constructor THallItem.Create(AProject: TNumProject); begin inherited Create(); //Self.TreeNode:=nil; Self.Project:=AProject; end; destructor THallItem.Destroy(); begin end; function THallItem.GetTableName(): string; begin Result:=sTableHallItems; end; function THallItem.GetFields(var fl: TDbItemFields): Boolean; var NumPlanItemID: integer; begin NumPlanItemID:=0; if Assigned(NumPlanItem) then NumPlanItemID:=NumPlanItem.ID; inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); AddDbItemField(fl, 'numplan_item_id', IntToStr(NumPlanItemID), 'I'); AddDbItemField(fl, 'pos_x', IntToStr(Position.X), 'I'); AddDbItemField(fl, 'pos_y', IntToStr(Position.Y), 'I'); AddDbItemField(fl, 'color', IntToStr(Color), 'I'); AddDbItemField(fl, 'n_row', IntToStr(Row), 'I'); AddDbItemField(fl, 'n_place', IntToStr(Place), 'I'); AddDbItemField(fl, 'n_sector', IntToStr(Sector), 'I'); AddDbItemField(fl, 'state', State, 'S'); AddDbItemField(fl, 'kind', Kind, 'S'); AddDbItemField(fl, 'param_text', ParamsText, 'S'); Result:=True; end; function THallItem.SetFields(var fl: TDbItemFields): Boolean; var s: string; begin ID:=StrToIntDef(GetDbItemFieldValue(fl, 'id'), ID); FNumPlanItem:=Project.NumPlanItems.GetItemByID(StrToIntDef(GetDbItemFieldValue(fl, 'numplan_item_id'), 0)); Position.X:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_x'), Position.X); Position.Y:=StrToIntDef(GetDbItemFieldValue(fl, 'pos_y'), Position.Y); Color:=StrToIntDef(GetDbItemFieldValue(fl, 'color'), Color); Row:=StrToIntDef(GetDbItemFieldValue(fl, 'n_row'), Row); Place:=StrToIntDef(GetDbItemFieldValue(fl, 'n_place'), Place); Sector:=StrToIntDef(GetDbItemFieldValue(fl, 'n_sector'), Sector); State:=GetDbItemFieldValue(fl, 'state'); s:=GetDbItemFieldValue(fl, 'kind'); if Length(s)>0 then Kind:=s[1]; ParamsText:=GetDbItemFieldValue(fl, 'param_text'); Result:=True; end; procedure THallItem.Read(ReadSubitems: Boolean = False); begin if ID=0 then Exit; if not Project.NumPlanItems.ItemsLoaded then Project.NumPlanItems.LoadFromBase(); inherited Read(ReadSubitems); end; function THallItem.GetNumPlanItem(): TNumPlanItem; begin if not Assigned(FNumPlanItem) then Read(); Result:=FNumPlanItem; end; // === TProjectOption === constructor TProjectOption.Create(AProject: TNumProject); begin inherited Create(); Self.Project:=AProject; end; function TProjectOption.GetTableName(): string; begin Result:=sTableProjectOptions; end; function TProjectOption.GetFields(var fl: TDbItemFields): Boolean; begin inherited GetFields(fl); AddDbItemField(fl, 'project_id', IntToStr(Project.ID), 'I'); // * AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'value', Value, 'S'); Result:=True; end; function TProjectOption.SetFields(var fl: TDbItemFields): Boolean; begin Result:= inherited SetFields(fl); Name:=GetDbItemFieldValue(fl, 'name'); Value:=GetDbItemFieldValue(fl, 'value'); Result:=True; end; // === TNumProject === constructor TNumProject.Create(); begin inherited Create(); Self.TreeNode:=nil; self.Loaded:=false; self.FPages:=TNumPageList.Create(self, true); self.FPages.NumProject:=Self; self.FPagesTpl:=TNumPageTplList.Create(self, true); self.FPagesTpl.NumProject:=Self; self.FTickets:=TTicketList.Create(true); self.FTickets.NumProject:=Self; self.FTicketTplList:=TTicketTplList.Create(); self.FTicketTplList.NumProject:=Self; //self.FNumLabels:=TNumLabelList.Create(true); //self.FNumLabels.NumProject:=Self; self.FNumLabelsTpl:=TNumLabelTplList.Create(true); self.FNumLabelsTpl.NumProject:=Self; self.FNumPlanItems:=TNumPlan.Create(true); self.FNumPlanItems.NumProject:=Self; self.FHallPlan:=THallPlan.Create(true); self.FHallPlan.NumProject:=Self; self.FOptions:=TProjectOptionList.Create(true); self.FOptions.NumProject:=Self; end; destructor TNumProject.Destroy(); begin FreeAndNil(FOptions); FreeAndNil(FHallPlan); FreeAndNil(FNumPlanItems); FreeAndNil(FNumLabelsTpl); //FreeAndNil(FNumLabels); FreeAndNil(FTicketTplList); FreeAndNil(FTickets); FreeAndNil(FPagesTpl); FreeAndNil(FPages); end; function TNumProject.GetTableName(): string; begin Result:=sTableProjects; end; function TNumProject.GetFields(var fl: TDbItemFields): Boolean; begin inherited GetFields(fl); AddDbItemField(fl, 'parent_id', IntToStr(ParentID), 'I'); AddDbItemField(fl, 'name', Name, 'S'); AddDbItemField(fl, 'desc', Desc, 'S'); Result:=True; end; function TNumProject.SetFields(var fl: TDbItemFields): Boolean; begin Result:=inherited SetFields(fl); Name:=GetDbItemFieldValue(fl, 'name'); Desc:=GetDbItemFieldValue(fl, 'desc'); ParentID:=StrToIntDef(GetDbItemFieldValue(fl, 'parent_id'), ParentID); Result:=True; end; procedure TNumProject.Write(WriteSubitems: Boolean = False); begin inherited Write(WriteSubitems); // Write subitems if not WriteSubitems then Exit; StartTransaction(); Self.NumLabelsTpl.SaveToBase(); Self.TicketTplList.SaveToBase(); Self.PagesTpl.SaveToBase(); Self.Tickets.SaveToBase(); Self.Pages.SaveToBase(); Self.NumPlanItems.SaveToBase(); Self.HallPlan.SaveToBase(); CloseTransaction(); end; procedure TNumProject.Read(ReadSubitems: Boolean = False); begin if ID=0 then Exit; inherited Read(ReadSubitems); // Retrieve subitems if not ReadSubitems then Exit; StartTransaction(); Self.NumLabelsTpl.LoadFromBase(); Self.TicketTplList.LoadFromBase(); Self.PagesTpl.LoadFromBase(); Self.Tickets.LoadFromBase(); Self.Pages.LoadFromBase(); Self.NumPlanItems.LoadFromBase(); Self.HallPlan.LoadFromBase(); CloseTransaction(); end; procedure TNumProject.Delete(DeleteSubitems: Boolean = False); begin inherited Delete(DeleteSubitems); // Delete subitems if not DeleteSubitems then Exit; StartTransaction(); Self.HallPlan.DeleteFromBase(); Self.NumPlanItems.DeleteFromBase(); Self.Tickets.DeleteFromBase(); Self.Pages.DeleteFromBase(); Self.PagesTpl.DeleteFromBase(); Self.TicketTplList.DeleteFromBase(); Self.NumLabelsTpl.DeleteFromBase(); CloseTransaction(); end; procedure TNumProject.Serialize(var Stream: TItemSerialize); begin StartTransaction(); Stream.StartItem(GetTableName()); inherited Serialize(Stream); NumLabelsTpl.Serialize(Stream); TicketTplList.Serialize(Stream); PagesTpl.Serialize(Stream); Pages.Serialize(Stream); NumPlanItems.Serialize(Stream); HallPlan.Serialize(Stream); Stream.CloseItem(GetTableName()); CloseTransaction(); end; procedure TNumProject.Deserialize(var Stream: TItemSerialize); var ItemName: string; TempID: Integer; TempItem: TDbItem; begin StartTransaction(); //Stream.SetTag(GetTableName()); while Stream.GetItem do begin ItemName:=Stream.GetItemName(); TempID:=StrToIntDef(Stream.GetAttrValue('id'), 0); if ItemName = PagesTpl.ClassName then begin TempItem:=PagesTpl.GetItemByID(TempID); if not Assigned(TempItem) then TempItem:=PagesTpl.CreateItem(); TempItem.Deserialize(Stream); end; end; inherited Deserialize(Stream); PagesTpl.Deserialize(Stream); Pages.Deserialize(Stream); Tickets.Deserialize(Stream); TicketTplList.Deserialize(Stream); NumLabelsTpl.Deserialize(Stream); HallPlan.Deserialize(Stream); NumPlanItems.Deserialize(Stream); CloseTransaction(); end; function TNumProject.GetPagesTpl(): TNumPageTplList; begin Result:=FPagesTpl; if not FPagesTpl.ItemsLoaded then FPagesTpl.LoadFromBase(); end; function TNumProject.GetPages(): TNumPageList; begin Result:=FPages; if not FPages.ItemsLoaded then FPages.LoadFromBase(); end; function TNumProject.GetTickets(): TTicketList; begin Result:=FTickets; if not FTickets.ItemsLoaded then FTickets.LoadFromBase(); end; function TNumProject.GetTicketTplList(): TTicketTplList; begin Result:=FTicketTplList; if not FTicketTplList.ItemsLoaded then FTicketTplList.LoadFromBase(); end; function TNumProject.GetNumLabelsTpl(): TNumLabelTplList; begin Result:=FNumLabelsTpl; if not FNumLabelsTpl.ItemsLoaded then FNumLabelsTpl.LoadFromBase(); end; function TNumProject.GetHallPlan(): THallPlan; begin Result:=FHallPlan; if not FHallPlan.ItemsLoaded then FHallPlan.LoadFromBase(); end; function TNumProject.GetNumPlanItems(): TNumPlan; begin Result:=FNumPlanItems; if not FNumPlanItems.ItemsLoaded then FNumPlanItems.LoadFromBase(); end; function TNumProject.GetOptions(): TProjectOptionList; begin Result:=FOptions; if not FOptions.ItemsLoaded then FOptions.LoadFromBase(); end; // === TDbItemsList === function TDbItemsList.CreateItem(): TDbItem; begin Result:=TDbItem.Create(); end; function TDbItemsList.AGetItemByID(ItemID: integer): TDbItem; var i: Integer; begin Result:=nil; //if not ItemsLoaded then LoadFromBase(); for i:=0 to Count-1 do begin if (Items[i] as TDbItem).ID = ItemID then begin Result:=TDbItem(Items[i]); Exit; end; end; end; procedure TDbItemsList.SaveToBase(); var i: Integer; DoTransaction: Boolean; begin DoTransaction:=False; if not TransactionActive then begin DoTransaction:=True; StartTransaction(); end; for i:=0 to Self.Count-1 do begin (Items[i] as TDbItem).Write(); end; if DoTransaction then begin DoTransaction:=False; CloseTransaction(); end; end; //function TDbItemsList.LoadFromBase(): Boolean; //var // np: TDbItem; // ds: TDataSet; //begin // //Self.Clear(); // Result:=False; // DataModule1.Query1.SQL.Text:=SQL_Load; // try // DataModule1.Query1.ExecSQL(); // except // Exit; // end; // ds:=DataModule1.Query1; // // ItemsLoaded:=True; // ds.First(); // while not ds.Eof do // begin // np:=self.AGetItemByID(ds.FieldValues['id']); // if not Assigned(np) then // begin // np:=CreateItem(); // np.ID:=ds.FieldValues['id']; // self.Add(np); // end; // np.ReadFromDataset(ds); // ds.Next(); // end; // Result:=True; //end; function TDbItemsList.LoadFromBase(): Boolean; var np: TDbItem; ds: IMkSqlStmt; i: Integer; begin //Self.Clear(); Result:=False; //DataModule1.Query1.SQL.Text:=SQL_Load; {$IFDEF DEBUG_SQL} DebugMsg(SQL_Load, 'SQL'); {$ENDIF} try ds:=db.exec(SQL_Load); except Exit; end; //ds:=DataModule1.Query1; ItemsLoaded:=True; ds.First(); while not ds.Eof do begin //i:=ds.FieldValues['id']; i:=ds.valueof['id']; np:=self.AGetItemByID(i); if not Assigned(np) then begin np:=CreateItem(); np.ID:=i; self.Add(np); end; //np.ReadFromDataset(ds); np.ReadFromDatasetMk(ds); ds.Next(); end; Result:=True; end; procedure TDbItemsList.DeleteFromBase(DeleteSubitems: Boolean = False); var i, n: Integer; DoTransaction: Boolean; SQL, s, sTableName: string; procedure DelSQL(); begin s:=Copy(s, 1, Length(s)-1); SQL:='DELETE FROM "'+sTableName+'" WHERE id IN ('+s+');'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); SQL:=''; end; begin DoTransaction:=False; if not TransactionActive then begin DoTransaction:=True; StartTransaction(); end; if Length(SQL_Delete)>0 then begin {$IFDEF DEBUG_SQL} DebugMsg(SQL_Delete, 'SQL'); {$ENDIF} db.execCmd(SQL_Delete); end else begin s:=''; n:=Self.Count-1; for i:=n downto 0 do begin //(Items[i] as TDbItem).Delete(DeleteSubitems); s:=s+IntToStr((Items[i] as TDbItem).ID)+','; if i=n then sTableName:=(Items[i] as TDbItem).GetTableName(); Delete(i); if Length(s)>1024 then DelSQL(); end; if Length(s)>0 then DelSQL(); end; if DoTransaction then begin DoTransaction:=False; CloseTransaction(); end; self.Clear(); end; procedure TDbItemsList.Serialize(var Stream: TItemSerialize); var i: Integer; sName: string; begin sName := self.ClassName; Stream.StartItem(sName); for i:=0 to Self.Count-1 do begin Stream.StartItem((Self[i] as TDbItem).GetTableName()); (Self[i] as TDbItem).Serialize(Stream); Stream.CloseItem((Self[i] as TDbItem).GetTableName()); end; Stream.CloseItem(sName); end; procedure TDbItemsList.Deserialize(var Stream: TItemSerialize); var ItemName: string; TempID: Integer; TempItem: TDbItem; begin while Stream.GetItem() do begin ItemName:=Stream.GetItemName(); TempID:=StrToIntDef(Stream.GetAttrValue('id'), 0); if ItemName = self.ClassName then begin TempItem:=self.AGetItemByID(TempID); if not Assigned(TempItem) then TempItem:=self.CreateItem(); TempItem.Deserialize(Stream); end else Exit; end; end; // === TNumProjectList === function TNumProjectList.GetItem(Index: Integer): TNumProject; begin Result:=TNumProject(inherited Items[index]); end; procedure TNumProjectList.SetItem(Index: Integer; Value: TNumProject); begin inherited Items[Index]:=Value; end; function TNumProjectList.GetProjectByID(ProjectID: integer): TNumProject; begin Result:=TNumProject(AGetItemByID(ProjectID)); end; function TNumProjectList.CreateItem(): TDbItem; begin Result:=TNumProject.Create(); end; procedure TNumProjectList.SaveToFile(Filename: string); var sl: TStringList; i: Integer; begin if Count=0 then Exit; sl:=TStringList.Create(); for i:=0 to Count-1 do begin //sl.Add(Items[i].ToString); end; sl.SaveToFile(Filename); sl.Free(); end; function TNumProjectList.LoadFromFile(Filename: string): Boolean; var sl: TStringList; i: Integer; begin Result:=false; Self.Clear(); if not FileExists(Filename) then Exit; sl:=TStringList.Create(); try sl.LoadFromFile(Filename); except sl.Free(); Exit; end; for i:=0 to sl.Count-1 do begin //np:=TNumProject.Create(); //if np.FromString(sl[i]) then self.Add(li); end; sl.Free(); Result:=True; end; function TNumProjectList.LoadFromBase(): Boolean; begin self.SQL_Load:='SELECT * FROM '+sTableProjects+';'; Result:=inherited LoadFromBase(); end; // === TTicketTplList === function TTicketTplList.GetItem(Index: Integer): TTicketTpl; begin Result:=TTicketTpl(inherited Items[index]); end; procedure TTicketTplList.SetItem(Index: Integer; Value: TTicketTpl); begin inherited Items[Index]:=Value; end; function TTicketTplList.GetItemByID(ItemID: integer): TTicketTpl; begin Result:=TTicketTpl(AGetItemByID(ItemID)); end; function TTicketTplList.CreateItem(): TDbItem; begin Result:=TTicketTpl.Create(self.NumProject); end; function TTicketTplList.LoadFromBase(): Boolean; begin self.SQL_Load:='SELECT * FROM '+sTableTicketsTpl+' WHERE project_id='+IntToStr(NumProject.ID)+';'; Result:=inherited LoadFromBase(); end; // === TTicketlList === function TTicketList.GetItem(Index: Integer): TTicket; begin Result:=TTicket(inherited Items[index]); end; procedure TTicketList.SetItem(Index: Integer; Value: TTicket); begin inherited Items[Index]:=Value; end; function TTicketList.GetItemByID(ItemID: integer): TTicket; begin Result:=TTicket(AGetItemByID(ItemID)); end; function TTicketList.CreateItem(): TDbItem; begin Result:=TTicket.Create(self.NumProject); (Result as TTicket).NumPageTpl:=Self.NumPageTPL; end; function TTicketList.LoadFromBase(): Boolean; begin if Assigned(self.NumPageTPL) then begin SQL_Load:='SELECT * FROM '+sTableTickets+' WHERE project_id='+IntToStr(NumProject.ID) +' AND page_tpl_id='+IntToStr(NumPageTPL.ID)+';'; end else begin SQL_Load:='SELECT * FROM '+sTableTickets+' WHERE project_id='+IntToStr(NumProject.ID)+';'; end; //if not NumProject.PagesTpl.ItemsLoaded then NumProject.PagesTpl.LoadFromBase(); //if not NumProject.TicketTplList.ItemsLoaded then NumProject.TicketTplList.LoadFromBase(); Result:=inherited LoadFromBase(); end; // === TNumPageTplList === constructor TNumPageTplList.Create(AProject: TNumProject; OwnsItems: Boolean=true); begin inherited Create(OwnsItems); Self.NumProject:=AProject; end; function TNumPageTplList.GetItem(Index: Integer): TNumPageTpl; begin Result:=TNumPageTpl(inherited Items[index]); end; procedure TNumPageTplList.SetItem(Index: Integer; Value: TNumPageTpl); begin inherited Items[Index]:=Value; end; function TNumPageTplList.GetItemByID(ItemID: integer): TNumPageTpl; begin Result:=TNumPageTpl(AGetItemByID(ItemID)); end; function TNumPageTplList.CreateItem(): TDbItem; begin Result:=TNumPageTpl.Create(self.NumProject); end; function TNumPageTplList.LoadFromBase(): Boolean; begin self.SQL_Load:='SELECT * FROM '+sTableNumPagesTpl+' WHERE project_id='+IntToStr(NumProject.ID)+';'; Result:=inherited LoadFromBase(); end; // === TNumPageList === constructor TNumPageList.Create(AProject: TNumProject; OwnsItems: Boolean=true); begin inherited Create(OwnsItems); Self.NumProject:=AProject; end; function TNumPageList.GetItem(Index: Integer): TNumPage; begin Result:=TNumPage(inherited Items[index]); end; procedure TNumPageList.SetItem(Index: Integer; Value: TNumPage); begin inherited Items[Index]:=Value; end; function TNumPageList.GetItemByID(ItemID: integer): TNumPage; begin Result:=TNumPage(AGetItemByID(ItemID)); end; function TNumPageList.CreateItem(): TDbItem; begin Result:=TNumPage.Create(self.NumProject); end; function TNumPageList.LoadFromBase(): Boolean; begin self.SQL_Load:='SELECT * FROM '+sTableNumPages+' WHERE project_id='+IntToStr(NumProject.ID)+';'; if not NumProject.PagesTpl.ItemsLoaded then NumProject.PagesTpl.LoadFromBase(); Result:=inherited LoadFromBase(); end; procedure TNumPageList.DeleteFromBase(DeleteSubitems: Boolean = False); begin if not Assigned(NumProject) then Exit; self.SQL_Delete:='DELETE FROM '+sTableNumPages+' WHERE project_id='+IntToStr(NumProject.ID)+';'; inherited DeleteFromBase(DeleteSubitems); end; function NumPageListCompareFunction(Item1, Item2: Pointer): Integer; begin Result:=TNumPage(Item1).Order-TNumPage(Item2).Order; end; procedure TNumPageList.SortByOrder(); begin Sort(@NumPageListCompareFunction); end; // === TNumLabelTplList === function TNumLabelTplList.GetItem(Index: Integer): TNumLabelTpl; begin Result:=TNumLabelTpl(inherited Items[index]); end; procedure TNumLabelTplList.SetItem(Index: Integer; Value: TNumLabelTpl); begin inherited Items[Index]:=Value; end; function TNumLabelTplList.GetItemByID(ItemID: integer): TNumLabelTpl; begin Result:=TNumLabelTpl(AGetItemByID(ItemID)); end; function TNumLabelTplList.CreateItem(): TDbItem; begin Result:=TNumLabelTpl.Create(Self.NumProject); end; function TNumLabelTplList.LoadFromBase(): Boolean; begin //Self.Clear(); Result:=False; if not Assigned(NumProject) then Exit; self.SQL_Load:='SELECT * FROM '+sTableNumLabelTpl+' WHERE project_id='+IntToStr(NumProject.ID)+';'; Result:=inherited LoadFromBase(); end; // === TNumLabelList === function TNumLabelList.GetItem(Index: Integer): TNumLabel; begin Result:=TNumLabel(inherited Items[index]); end; procedure TNumLabelList.SetItem(Index: Integer; Value: TNumLabel); begin inherited Items[Index]:=Value; end; function TNumLabelList.GetItemByID(ItemID: integer): TNumLabel; begin Result:=TNumLabel(AGetItemByID(ItemID)); end; function TNumLabelList.CreateItem(): TDbItem; begin Result:=TNumLabel.Create(Self.NumProject); (Result as TNumLabel).TicketTpl:=Self.TicketTpl; end; function TNumLabelList.LoadFromBase(): Boolean; begin //Self.Clear(); Result:=False; if not Assigned(NumProject) then Exit; if Assigned(TicketTpl) then begin self.SQL_Load:='SELECT * FROM '+sTableNumLabels+' WHERE ticket_tpl_id='+IntToStr(TicketTpl.ID)+';'; end else if Assigned(NumPageTpl) then begin self.SQL_Load:='SELECT * FROM '+sTableNumLabels+' WHERE numpage_tpl_id='+IntToStr(NumPageTpl.ID)+';'; end else begin self.SQL_Load:='SELECT * FROM '+sTableNumLabels+' WHERE project_id='+IntToStr(NumProject.ID)+';'; end; Result:=inherited LoadFromBase(); end; procedure TNumLabelList.DeleteFromBase(DeleteSubitems: Boolean = False); begin if not Assigned(NumProject) then Exit; if Assigned(TicketTpl) then begin self.SQL_Delete:='DELETE FROM '+sTableNumLabels+' WHERE ticket_tpl_id='+IntToStr(TicketTpl.ID)+';'; end else if Assigned(NumPageTpl) then begin self.SQL_Delete:='DELETE FROM '+sTableNumLabels+' WHERE numpage_tpl_id='+IntToStr(NumPageTpl.ID)+';'; end else begin self.SQL_Delete:='DELETE FROM '+sTableNumLabels+' WHERE project_id='+IntToStr(NumProject.ID)+';'; end; inherited DeleteFromBase(DeleteSubitems); end; // === TNumLabelDataList === function TNumLabelDataList.GetItem(Index: Integer): TNumLabelData; begin Result:=TNumLabelData(inherited Items[index]); end; procedure TNumLabelDataList.SetItem(Index: Integer; Value: TNumLabelData); begin inherited Items[Index]:=Value; end; function TNumLabelDataList.GetItemByID(ItemID: integer): TNumLabelData; begin Result:=TNumLabelData(AGetItemByID(ItemID)); end; function TNumLabelDataList.CreateItem(): TDbItem; begin Result:=TNumLabelData.Create(Self.NumProject); (Result as TNumLabelData).NumPlanItem:=Self.NumPlanItem; end; function TNumLabelDataList.LoadFromBase(): Boolean; begin //Self.Clear(); Result:=False; if not Assigned(NumProject) then Exit; if Assigned(NumPlanItem) then begin self.SQL_Load:='SELECT * FROM '+sTableNumLabelData+' WHERE numplan_item_id='+IntToStr(NumPlanItem.ID)+';'; end else begin self.SQL_Load:='SELECT * FROM '+sTableNumLabelData+' WHERE project_id='+IntToStr(NumProject.ID)+';'; end; //if not NumProject.NumPlanItems.ItemsLoaded then NumProject.NumPlanItems.LoadFromBase(); //if not NumProject.NumLabelsTpl.ItemsLoaded then NumProject.NumLabelsTpl.LoadFromBase(); Result:=inherited LoadFromBase(); end; procedure TNumLabelDataList.DeleteFromBase(DeleteSubitems: Boolean = False); begin if not Assigned(NumProject) then Exit; if Assigned(NumPlanItem) then begin self.SQL_Delete:='DELETE FROM '+sTableNumLabelData+' WHERE numplan_item_id='+IntToStr(NumPlanItem.ID)+';'; end else begin self.SQL_Delete:='DELETE FROM '+sTableNumLabelData+' WHERE project_id='+IntToStr(NumProject.ID)+';'; end; inherited DeleteFromBase(DeleteSubitems); end; // === TNumPlan === function TNumPlan.GetItem(Index: Integer): TNumPlanItem; begin Result:=TNumPlanItem(inherited Items[index]); end; procedure TNumPlan.SetItem(Index: Integer; Value: TNumPlanItem); begin inherited Items[Index]:=Value; end; function TNumPlan.GetItemByID(ItemID: integer): TNumPlanItem; begin Result:=TNumPlanItem(AGetItemByID(ItemID)); end; function TNumPlan.CreateItem(): TDbItem; begin Result:=TNumPlanItem.Create(self.NumProject); end; {procedure TNumPlan.SaveToBase(SaveSubitems: Boolean = false); var i: Integer; begin DataModule1.Query1.StartTransaction(); for i:=0 to Self.Count-1 do begin (Items[i] as TDbItem).Write(SaveSubitems); end; DataModule1.Query1.Commit(); end;} function TNumPlan.LoadFromBase(): Boolean; var ds: IMkSqlStmt; StrSQL: string; i: Integer; NumPlanItem: TNumPlanItem; begin Result:=False; if not Assigned(NumProject) then Exit; {$IFDEF DEBUG} DT:=Now(); {$ENDIF} self.SQL_Load:='SELECT * FROM '+sTableNumPlanItems+' WHERE project_id='+IntToStr(NumProject.ID)+' ORDER BY num_order;'; //if not NumProject.Tickets.ItemsLoaded then NumProject.Tickets.LoadFromBase(); //if not NumProject.Pages.ItemsLoaded then NumProject.Pages.LoadFromBase(); Result:=inherited LoadFromBase(); {$IFDEF DEBUG} DebugMsg('Loaded '+IntToStr(Count)+' items in '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlan'); {$ENDIF} end; procedure TNumPlan.DeleteFromBase(DeleteSubitems: Boolean = False); begin if not Assigned(NumProject) then Exit; self.SQL_Delete:='DELETE FROM '+sTableNumPlanItems+' WHERE project_id='+IntToStr(NumProject.ID)+';'; inherited DeleteFromBase(DeleteSubitems); end; function NumPlanCompareFunction(Item1, Item2: Pointer): Integer; begin Result:=TNumPlanItem(Item1).Order-TNumPlanItem(Item2).Order; end; procedure TNumPlan.SortByOrder(); begin Sort(@NumPlanCompareFunction); end; function TNumPlan.GetItemByOrder(AOrder: integer): TNumPlanItem; var i: Integer; begin Result:=nil; for i:=0 to Count-1 do begin if Items[i].Order = AOrder then begin Result:=Items[i]; Break; end; end; end; // === THallPlan === function THallPlan.GetItem(Index: Integer): THallItem; begin Result:=THallItem(inherited Items[index]); end; procedure THallPlan.SetItem(Index: Integer; Value: THallItem); begin inherited Items[Index]:=Value; end; function THallPlan.GetItemByID(ItemID: integer): THallItem; begin Result:=THallItem(AGetItemByID(ItemID)); end; function THallPlan.CreateItem(): TDbItem; begin Result:=THallItem.Create(self.NumProject); end; function THallPlan.LoadFromBase(): Boolean; begin Result:=False; if not Assigned(NumProject) then Exit; {$IFDEF DEBUG} DT:=Now(); {$ENDIF} self.SQL_Load:='SELECT * FROM '+sTableHallItems+' WHERE project_id='+IntToStr(NumProject.ID)+';'; if not NumProject.NumPlanItems.ItemsLoaded then NumProject.NumPlanItems.LoadFromBase(); Result:=inherited LoadFromBase(); {$IFDEF DEBUG} DebugMsg('Loaded '+IntToStr(Count)+' items in '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'HallPlan'); {$ENDIF} end; procedure THallPlan.DeleteFromBase(DeleteSubitems: Boolean = False); begin if not Assigned(NumProject) then Exit; self.SQL_Delete:='DELETE FROM '+sTableHallItems+' WHERE project_id='+IntToStr(NumProject.ID)+';'; inherited DeleteFromBase(DeleteSubitems); end; // === TProjectOptionList === function TProjectOptionList.GetItem(Index: Integer): TProjectOption; begin Result:=TProjectOption(inherited Items[index]); end; procedure TProjectOptionList.SetItem(Index: Integer; Value: TProjectOption); begin inherited Items[Index]:=Value; end; function TProjectOptionList.GetItemByID(ItemID: integer): TProjectOption; begin Result:=TProjectOption(AGetItemByID(ItemID)); end; function TProjectOptionList.CreateItem(): TDbItem; begin Result:=TProjectOption.Create(self.NumProject); end; function TProjectOptionList.LoadFromBase(): Boolean; begin Result:=False; if not Assigned(NumProject) then Exit; self.SQL_Load:='SELECT * FROM '+sTableProjectOptions+' WHERE project_id='+IntToStr(NumProject.ID)+';'; Result:=inherited LoadFromBase(); end; function TProjectOptionList.FGetOption(const Name: string): string; var i: Integer; begin Result:=''; for i:=0 to self.Count-1 do begin if Self.Items[i].Name = Name then begin Result:=Self.Items[i].Value; Break; end; end; end; procedure TProjectOptionList.FSetOption(const Name: string; Value: string); var i: Integer; Item: TProjectOption; begin for i:=0 to self.Count-1 do begin if Self.Items[i].Name = Name then begin Self.Items[i].Value := Value; Exit; end; end; Item:=(self.CreateItem() as TProjectOption); Item.Name:=Name; Item.Value:=Value; Self.Add(Item); end; // ============== function CheckAllTables(): boolean; var sl: TStringList; SQL: string; begin sl:=TStringList.Create(); // Projects sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('parent_id=INTEGER'); sl.Add('name=VARCHAR(20)'); sl.Add('desc=TEXT'); Result:=ItemsDef.CheckTable(sTableProjects, sl); if not Result then Exit; // TicketTpl sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('name=VARCHAR(20)'); sl.Add('width=NUMERIC'); sl.Add('height=NUMERIC'); Result:=ItemsDef.CheckTable(sTableTicketsTpl, sl); if not Result then Exit; // Ticket sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER NOT NULL'); sl.Add('page_tpl_id=INTEGER NOT NULL'); sl.Add('tpl_id=INTEGER NOT NULL'); sl.Add('name=VARCHAR(20)'); sl.Add('pos_x=NUMERIC'); sl.Add('pos_y=NUMERIC'); Result:=ItemsDef.CheckTable(sTableTickets, sl); if not Result then Exit; // NumPageTpl sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('name=VARCHAR(20)'); sl.Add('size_x=NUMERIC'); sl.Add('size_y=NUMERIC'); Result:=ItemsDef.CheckTable(sTableNumPagesTpl, sl); if not Result then Exit; // NumLabelTpl sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('name=VARCHAR(20)'); sl.Add('base_value=TEXT'); sl.Add('value_type=TEXT'); sl.Add('action=TEXT'); sl.Add('action_trigger=VARCHAR(1)'); sl.Add('prefix=TEXT'); sl.Add('suffix=TEXT'); Result:=ItemsDef.CheckTable(sTableNumLabelTpl, sl); if not Result then Exit; // NumLabel sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('ticket_tpl_id=INTEGER'); sl.Add('numpage_tpl_id=INTEGER'); sl.Add('numlabel_tpl_id=INTEGER'); sl.Add('name=VARCHAR(20)'); sl.Add('pos_x=NUMERIC'); sl.Add('pos_y=NUMERIC'); sl.Add('size=NUMERIC'); sl.Add('angle=NUMERIC'); sl.Add('color=INTEGER'); sl.Add('font=TEXT'); Result:=ItemsDef.CheckTable(sTableNumLabels, sl); if not Result then Exit; // NumPage sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('page_tpl_id=INTEGER'); sl.Add('num_order=INTEGER'); sl.Add('state=VARCHAR(4)'); Result:=ItemsDef.CheckTable(sTableNumPages, sl); if not Result then Exit; // NumPlanItem sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('ticket_id=INTEGER'); sl.Add('page_id=INTEGER'); sl.Add('num_order=INTEGER'); sl.Add('state=VARCHAR(4)'); Result:=ItemsDef.CheckTable(sTableNumPlanItems, sl); if not Result then Exit; // HallItem sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('numplan_item_id=INTEGER'); sl.Add('pos_x=INTEGER'); sl.Add('pos_y=INTEGER'); sl.Add('color=INTEGER'); sl.Add('n_row=INTEGER'); sl.Add('n_place=INTEGER'); sl.Add('n_sector=INTEGER'); sl.Add('state=VARCHAR(4)'); sl.Add('kind=VARCHAR(4)'); sl.Add('param_text=TEXT'); Result:=ItemsDef.CheckTable(sTableHallItems, sl); if not Result then Exit; // NumLabelData sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('numplan_item_id=INTEGER'); sl.Add('numlabel_tpl_id=INTEGER'); sl.Add('value=TEXT'); sl.Add('action=TEXT'); Result:=ItemsDef.CheckTable(sTableNumLabelData, sl); if not Result then Exit; SQL:='CREATE INDEX IF NOT EXISTS numplan_item_id ON ' +sTableNumLabelData+'(numplan_item_id);'; {$IFDEF DEBUG_SQL} DebugMsg(SQL, 'SQL'); {$ENDIF} db.execCmd(SQL); // ProjectOptions sl.Clear(); sl.Add('id=INTEGER NOT NULL PRIMARY KEY'); sl.Add('project_id=INTEGER'); sl.Add('name=TEXT'); sl.Add('value=TEXT'); Result:=ItemsDef.CheckTable(sTableProjectOptions, sl); if not Result then Exit; sl.Free(); end; initialization begin NullStrictConvert:=False; // Null='' db:=TMkSqlite.Create(nil); db.dbName:='serial_print.sqb'; try db.open(); except FreeAndNil(db); end; end; finalization begin if Assigned(db) then begin db.close(); FreeAndNil(db); end; end; end.
unit xElecPower; interface uses xElecLine, xElecPoint; type TElecPower = class private FVolA: TElecLine; FVolB: TElecLine; FVolC: TElecLine; FVolN: TElecLine; FCurrAIn: TElecLine; FCurrAOut: TElecLine; FCurrBIn: TElecLine; FCurrBOut: TElecLine; FCurrCIn: TElecLine; FCurrCOut: TElecLine; public constructor Create; destructor Destroy; override; /// <summary> /// 电压A /// </summary> property VolA : TElecLine read FVolA write FVolA; /// <summary> /// 电压B /// </summary> property VolB : TElecLine read FVolB write FVolB; /// <summary> /// 电压C /// </summary> property VolC : TElecLine read FVolC write FVolC; /// <summary> /// 电压N /// </summary> property VolN : TElecLine read FVolN write FVolN; /// <summary> /// 电流A进 /// </summary> property CurrAIn : TElecLine read FCurrAIn write FCurrAIn; /// <summary> /// 电流A出 /// </summary> property CurrAOut : TElecLine read FCurrAOut write FCurrAOut; /// <summary> /// 电流B进 /// </summary> property CurrBIn : TElecLine read FCurrBIn write FCurrBIn; /// <summary> /// 电流B出 /// </summary> property CurrBOut : TElecLine read FCurrBOut write FCurrBOut; /// <summary> /// 电流C进 /// </summary> property CurrCIn : TElecLine read FCurrCIn write FCurrCIn; /// <summary> /// 电流C出 /// </summary> property CurrCOut : TElecLine read FCurrCOut write FCurrCOut; /// <summary> /// 初始化电源(三相四线) /// </summary> procedure INIPower4; /// <summary> /// 初始化电源(三相三线) /// </summary> procedure INIPower3; end; implementation { TElecPower } constructor TElecPower.Create; begin FVolA:= TElecLine.Create; FVolB:= TElecLine.Create; FVolC:= TElecLine.Create; FVolN:= TElecLine.Create; FCurrAIn:= TElecLine.Create; FCurrAOut:= TElecLine.Create; FCurrBIn:= TElecLine.Create; FCurrBOut:= TElecLine.Create; FCurrCIn:= TElecLine.Create; FCurrCOut:= TElecLine.Create; end; destructor TElecPower.Destroy; begin FVolA.Free; FVolB.Free; FVolC.Free; FVolN.Free; FCurrAIn.Free; FCurrAOut.Free; FCurrBIn.Free; FCurrBOut.Free; FCurrCIn.Free; FCurrCOut.Free; inherited; end; procedure TElecPower.INIPower3; procedure SetValue(AElecLine: TElecLine; sLineName: string; dVolValue, dVolAngle, dCurrValue, dCurrAngle : Double; bIsLowPoint, bIsHighPoint, bVolRoot : Boolean); begin AElecLine.LineName := sLineName; AElecLine.Voltage.Value := dVolValue; AElecLine.Voltage.Angle := dVolAngle; AElecLine.Current.Value := dCurrValue; AElecLine.Current.Angle := dCurrAngle; AElecLine.Current.IsLowPoint := bIsLowPoint; AElecLine.Current.IsHighPoint := bIsHighPoint; AElecLine.Current.ClearWValue; AElecLine.Voltage.ClearWValue; AElecLine.Voltage.IsVolRoot := bVolRoot; end; begin SetValue(FVolA, 'PowerUa', 57.7, 90, 0, 0, False, False, True); SetValue(FVolB, 'PowerUb', 57.7, 330, 0, 0, False, False, True); SetValue(FVolC, 'PowerUc', 57.7, 210, 0, 0, False, False, True); SetValue(FVolN, 'PowerUn', 0, 0, 0, 0, False, False, False); SetValue(FCurrAIn, 'PowerIa+', 0, 0, 5, 70, False, True, False); SetValue(FCurrAOut, 'PowerIa-', 0, 0, 0, 0, True, False, False); SetValue(FCurrBIn, 'PowerIb+', 0, 0, 0, 0, False, True, False); SetValue(FCurrBOut, 'PowerIb-', 0, 0, 0, 0, True, False, False); SetValue(FCurrCIn, 'PowerIc+', 0, 0, 5, 190, False, True, False); SetValue(FCurrCOut, 'PowerIc-', 0, 0, 0, 0, True, False, False); FCurrAOut.Current.WeightValue[100].WValue := 0; FCurrBOut.Current.WeightValue[101].WValue := 0; FCurrCOut.Current.WeightValue[102].WValue := 0; FCurrAIn.WID := 100; FCurrBIn.WID := 101; FCurrCIn.WID := 102; end; procedure TElecPower.INIPower4; procedure SetValue(AElecLine: TElecLine; sLineName: string; dVolValue, dVolAngle, dCurrValue, dCurrAngle : Double; bIsLowPoint, bIsHighPoint, bVolRoot : Boolean); begin AElecLine.LineName := sLineName; AElecLine.Voltage.Value := dVolValue; AElecLine.Voltage.Angle := dVolAngle; AElecLine.Current.Value := dCurrValue; AElecLine.Current.Angle := dCurrAngle; AElecLine.Current.IsLowPoint := bIsLowPoint; AElecLine.Current.IsHighPoint := bIsHighPoint; AElecLine.Current.ClearWValue; AElecLine.Voltage.ClearWValue; AElecLine.Voltage.IsVolRoot := bVolRoot; end; begin SetValue(FVolA, 'PowerUa', 220, 90, 0, 0, False, False, True); SetValue(FVolB, 'PowerUb', 220, 330, 0, 0, False, False, True); SetValue(FVolC, 'PowerUc', 220, 210, 0, 0, False, False, True); SetValue(FVolN, 'PowerUn', 0, 0, 0, 0, False, False, False); SetValue(FCurrAIn, 'PowerIa+', 0, 0, 5, 70, False, True, False); SetValue(FCurrAOut, 'PowerIa-', 0, 0, 0, 0, True, False, False); SetValue(FCurrBIn, 'PowerIb+', 0, 0, 5, 310, False, True, False); SetValue(FCurrBOut, 'PowerIb-', 0, 0, 0, 0, True, False, False); SetValue(FCurrCIn, 'PowerIc+', 0, 0, 5, 190, False, True, False); SetValue(FCurrCOut, 'PowerIc-', 0, 0, 0, 0, True, False, False); FCurrAOut.Current.WeightValue[100].WValue := 0; FCurrBOut.Current.WeightValue[101].WValue := 0; FCurrCOut.Current.WeightValue[102].WValue := 0; FCurrAIn.WID := 100; FCurrBIn.WID := 101; FCurrCIn.WID := 102; end; end.
unit dref_float_2; interface implementation var G1, G2: Float64; P: ^Float64; procedure Test; begin G1 := 5.1245789; P := @G1; G2 := P^; end; initialization Test(); finalization Assert(G2 = G1); end.
unit xVCL_FMX; interface uses System.Classes, System.SysUtils, VCL.Dialogs, Vcl.Forms, Vcl.ExtCtrls; type TMySaveDialog = class(TSaveDialog) end; type TMyOpenDialog = class(TOpenDialog) end; type TMyTimer = class(TTimer) end; /// <summary> /// 延时等待函数,等待时处理其它事件 /// </summary> /// <param name="nMSeconds">毫秒</param> procedure MyWaitForSeconds( nMSeconds : Cardinal ); /// <summary> /// 处理界面事件 /// </summary> procedure MyProcessMessages; implementation procedure MyProcessMessages; begin Application.ProcessMessages; end; procedure MyWaitForSeconds( nMSeconds : Cardinal ); var nTick : Cardinal; begin nTick := TThread.GetTickCount; repeat Application.ProcessMessages; Sleep(1); until TThread.GetTickCount - nTick > nMSeconds; end; end.
unit BmpToJpg; {-----------------------------------------------------------------------------} { TBmpToJpeg v 1.1 } { Copyright 1998,1999, Eric Pedrazzi. All Rights Reserved. } {-----------------------------------------------------------------------------} { A component to translate a bitmap (file or Timage) into a jpeg file } { } { This component can be freely used and distributed in commercial and private } { environments, provied this notice is not modified in any way and there is } { no charge for it other than nomial handling fees. Contact me directly for } { modifications to this agreement. } { } {-----------------------------------------------------------------------------} { Feel free to contact me if you have any questions, comments or suggestions } { at epedrazzi@chez.com } { The latest version will always be available on the web at: } { http://www.chez.com/epedrazzi } { See BmpToJpg.txt for notes, known issues, and revision history. } {-----------------------------------------------------------------------------} { Date last modified: April 1999 } {-----------------------------------------------------------------------------} { v1.0 : Initial release } { v1.1 : Rename of the methods } { Add Image property } { Add CopyImageToJpeg method } {-----------------------------------------------------------------------------} { This unit provides an invisible component to perform a copy of a Timage or a bitmap file to a jpeg file. Properties ---------- Image : Source Image (Timage) BmpFile : Source File in bitmap format JpegFile : Destination file in Jpeg format Methods ------- CopyBmpToJpeg : Start bmp file to jpg file translation CopyImageToJpeg : Start image to jpg file translation } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Jpeg, ExtCtrls; type TBmpToJpeg = class(TComponent) private { Déclarations privées } FStream : TStream; FImage : TImage; FJpeg : TJpegImage; FBmp : TPicture; FBmpFile : AnsiString; FJpegFile: AnsiString; protected { Déclarations protégées } procedure FCopyBmpToJpeg; procedure FCopyImageToJpeg; public { Déclarations publiques } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CopyBmpToJpeg; procedure CopyImageToJpeg; published { Déclarations publiées } property Image : TImage read FImage write FImage; property BmpFile : AnsiString read FBmpFile write FBmpFile; property JpegFile : AnsiString read FJpegFile write FJpegFile; end; procedure Register; implementation procedure TBmpToJpeg.FCopyBmpToJpeg; begin if FileExists(FJpegFile) then DeleteFile(FJpegFile); FStream := TFileStream.Create(FJpegFile,fmCreate); try FBmp.LoadFromFile(FBmpFile); FJpeg.Assign(FBmp.Bitmap); FJpeg.SaveToStream(FStream); finally FStream.Free; end; end; procedure TBmpToJpeg.FCopyImageToJpeg; begin FStream := TFileStream.Create(FJpegFile,fmCreate); try FJpeg.Assign(FImage.Picture.Bitmap); FJpeg.SaveToStream(FStream); finally FStream.Free; end; end; constructor TBmpToJpeg.Create(AOwner: TComponent); begin inherited Create(AOwner); FJpeg := TJpegImage.Create; FBmp := TPicture.Create; end; destructor TBmpToJpeg.Destroy; begin FJpeg.Free; FBmp.Free; inherited Destroy; end; procedure TBmpToJpeg.CopyBmpToJpeg; begin FCopyBmpToJpeg; end; procedure TBmpToJpeg.CopyImageToJpeg; begin FCopyImageToJpeg; end; procedure Register; begin RegisterComponents('Samples', [TBmpToJpeg]); end; end.
unit frm_estimacionAvances; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, sPageControl, frm_connection, global, ToolWin, ExtCtrls, DBCtrls, Mask, frm_barra, db, Menus, OleCtrls, frxClass, frxDBSet, Buttons, RxLookup, RxMemDS, utilerias, Newpanel, RXCtrls, DateUtils, math, strUtils, ImgList, frxPreview, frxChart, ZAbstractRODataset, ZDataset, sSkinProvider, Grids, DBGrids, rxToolEdit, RXDBCtrl, CheckLst, JvExControls, JvxCheckListBox, ZAbstractDataset; type TfrmEstimacionAvances = class(TForm) CmdCancel: TButton; OrdenesAnexos: TZReadOnlyQuery; ds_OrdenesAnexos: TDataSource; Label2: TLabel; tsOrdenes: TDBLookupComboBox; GrupoEstimacion: TGroupBox; Label9: TLabel; Label13: TLabel; Label14: TLabel; tFecha_I: TDBDateEdit; tFecha_F: TDBDateEdit; tNumeroEstimacion: TEdit; lblTipo: TLabel; DBGridAvances: TDBGrid; cmdOk: TBitBtn; ds_avances: TDataSource; QryAvances: TZQuery; QryAvancessContrato: TStringField; QryAvancesdIdFecha: TDateField; QryAvancesdAvanceProgramadoFisico: TFloatField; QryAvancesdAvanceRealFisico: TFloatField; QryAvancesdAvanceProgramadoFinanciero: TFloatField; QryAvancesdAvanceFisicoFinanciero: TFloatField; procedure FormShow(Sender: TObject); procedure tsOrdenesExit(Sender: TObject); procedure QryAvancesBeforePost(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var frmEstimacionAvances: TfrmEstimacionAvances; Bandera, Fecha : string; oper : integer ; Consecutivo : integer; implementation uses frm_EstimacionGeneral, frm_EstimacionDetalleAdicional; {$R *.dfm} procedure TfrmEstimacionAvances.FormShow(Sender: TObject); var Orden : string; begin OrdenesAnexos.Active; OrdenesAnexos.ParamByName('Contrato').AsString := global_contrato_barco; OrdenesAnexos.Open; if OrdenesAnexos.RecordCount > 0 then Orden := OrdenesAnexos.FieldValues['sContrato']; if OrdenesAnexos.RecordCount = 0 then messageDLG('No existe un códogo principal para las Ordenes / Anexos registradas!', mtInformation, [mbOk], 0); tFecha_I.Date := frmEstimacionGeneral.EstimacionGeneral.FieldValues['dFechaInicio']; tFecha_F.Date := frmEstimacionGeneral.EstimacionGeneral.FieldValues['dFechaFinal']; tNumeroEstimacion.Text := frmEstimacionGeneral.EstimacionGeneral.FieldValues['iNumeroEstimacion']; lblTipo.Caption := frmEstimacionGeneral.EstimacionGeneralsDescripcion.Text; tsOrdenes.KeyValue := Orden; tsOrdenes.SetFocus; DBGridAvances.SetFocus; end; procedure TfrmEstimacionAvances.QryAvancesBeforePost(DataSet: TDataSet); begin QryAvances.FieldValues['sContrato'] := tsOrdenes.Text; end; procedure TfrmEstimacionAvances.tsOrdenesExit(Sender: TObject); begin QryAvances.Active := False; QryAvances.ParamByName('Contrato').AsString := tsOrdenes.Text; QryAvances.Open; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSHTTPClient; interface uses System.SysUtils, System.Classes, System.Generics.Collections, Data.DBXCommon, System.Net.HTTPClient, System.Net.URLClient; type /// <summary>HTTP error information exception.</summary> EHTTPProtocolException = class(Exception) private FErrorMessage: string; FErrorCode: Integer; public /// <summary>Create an exception object</summary> constructor Create(AErrorCode: Integer; const AErrorMessage: string; const AMessage: string); /// <summary>The HTTP error code</summary> property ErrorCode: Integer read FErrorCode; /// <summary>The HTTP error message</summary> property ErrorMessage: string read FErrorMessage; end; TDSHTTPClass = class of TDSHTTP; /// <summary>TDSHTTP implements HTTP functionality on the client /// side.</summary> TDSHTTP = class(TComponent) public type TValidateCertificateEvent = System.Net.URLClient.TValidateCertificateEvent; TAuthEvent = System.Net.URLClient.TCredentialsStorage.TCredentialAuthEvent; /// <summary>Proxy server connection parameters</summary> IProxyConnectionInfo = interface /// <summary>Set the port of the proxy server</summary> procedure SetProxyPort(Val: Integer); /// <summary>Get the port of the proxy server</summary> function GetProxyPort: Integer; /// <summary>Get or set the port of the proxy server</summary> property ProxyPort: Integer read GetProxyPort write SetProxyPort; /// <summary>Get the proxy server host name</summary> function GetProxyServer: string; /// <summary>Set the proxy server host name</summary> procedure SetProxyServer(Val: string); /// <summary>Get or set the proxy server host name</summary> property ProxyServer: string read GetProxyServer write SetProxyServer; /// <summary>Get the proxy server scheme</summary> function GetProxyScheme: string; /// <summary>Set the proxy server scheme</summary> procedure SetProxyScheme(Val: string); /// <summary>Get or set the proxy server scheme</summary> property ProxyScheme: string read GetProxyScheme write SetProxyScheme; /// <summary>Get a the username used to access the proxy server</summary> function GetProxyUserName: string; /// <summary>Set a the username used to access the proxy server</summary> procedure SetProxyUserName(user: string); /// <summary>Get or set the username used to access the proxy server</summary> property ProxyUserName: string read GetProxyUserName write SetProxyUserName; /// <summary>Get the password used to access the proxy server</summary> function GetProxyPassword: string; /// <summary>Set the password used to access the proxy server</summary> procedure SetProxyPassword(pass: string); /// <summary>Get or set the passwor used to access the proxy server</summary> property ProxyPassword: string read GetProxyPassword write SetProxyPassword; end; /// <summary>List of HTTP headers</summary> IHeaderList = interface /// <summary>Get the count of header.</summary> function GetCount: Integer; /// <summary>Get the count of header.</summary> property Count: Integer read GetCount; /// <summary>Get the name of a header.</summary> function GetName(Index: Integer): string; /// <summary>Get the name of a header.</summary> property Names[Index: Integer]: string read GetName; /// <summary>Get the value of a header.</summary> function GetValue(const Name: string): string; /// <summary>Get the value of a header.</summary> property Values[const Name: string]: string read GetValue; end; /// <summary>List of HTTP headers that can be modified</summary> IRequestHeaderList = interface(IHeaderList) /// <summary>Clear all headers</summary> procedure Clear; /// <summary>Add or modify a header</summary> procedure SetValue(const AName, AValue: string); /// <summary>Get or set the value of a header</summary> property Values[const Name: string]: string read GetValue write SetValue; end; /// <summary>Properties of an HTTP request</summary> IRequest = interface /// <summary>Get the HTTP request accept string</summary> function GetAccept: string; /// <summary>Set the HTTP request accept string</summary> procedure SetAccept(const Val: string); /// <summary>Get or set the HTTP request accept string</summary> property Accept: string read GetAccept write SetAccept; /// <summary>Get the HTTP request charset string</summary> function GetAcceptCharSet: string; /// <summary>Set the HTTP request charset string</summary> procedure SetAcceptCharSet(const Val: string); /// <summary>Get or set the HTTP request charset string</summary> property AcceptCharSet: string read GetAcceptCharSet write SetAcceptCharSet; /// <summary>Get the HTTP request custom headers.</summary> function GetCustomHeaders: IRequestHeaderList; /// <summary>Get the HTTP request custom headers.</summary> property CustomHeaders: IRequestHeaderList read GetCustomHeaders; /// <summary>Get the HTTP request acceptencoding string</summary> function GetAcceptEncoding: string; /// <summary>Set the HTTP request acceptencoding string</summary> procedure SetAcceptEncoding(const Val: string); /// <summary>Get or set the HTTP request acceptencoding string</summary> property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding; /// <summary>Get the HTTP request contenttype string</summary> function GetContentType: string; /// <summary>Set the HTTP request contenttype string</summary> procedure SetContentType(LContentType: string); /// <summary>Get or set the HTTP request contenttype string</summary> property ContentType: string read GetContentType write SetContentType; /// <summary>Get the HTTP request useragent string</summary> function GetUserAgent: string; /// <summary>Set the HTTP request useragent string</summary> procedure SetUserAgent(const Val: string); /// <summary>Get or set the HTTP request useragent string</summary> property UserAgent: string read GetUserAgent write SetUserAgent; /// <summary>Get the HTTP request Username string</summary> function GetUserName: string; /// <summary>Get the HTTP request password string</summary> function GetPassword: string; /// <summary>Set the HTTP request username and password</summary> procedure SetAuthentication(const AUserName, APassword: string); end; /// <summary>Properties of an HTTP response</summary> IResponse = interface /// <summary>Get the HTTP response character set string</summary> function GetCharSet: string; /// <summary>Get the HTTP response character set string</summary> property CharSet: string read GetCharSet; /// <summary>Get the HTTP response content type string</summary> function GetContentType: string; /// <summary>Get the HTTP response content type string</summary> property ContentType: string read GetContentType; /// <summary>Get the HTTP response content encoding string</summary> function GetContentEncoding: string; /// <summary>Get the HTTP response content encoding string</summary> property ContentEncoding: string read GetContentEncoding; /// <summary>Get the HTTP response headers</summary> function GetHeaders: IHeaderList; /// <summary>Get the HTTP response headers</summary> property Headers: IHeaderList read GetHeaders; end; private FHTTPClient: THTTPClient; FHTTPResponse: IHTTPResponse; FIPHTTPRequestIntf: TDSHTTP.IRequest; FProxyConnectionInfo: IProxyConnectionInfo; FOnValidateCertificate: TValidateCertificateEvent; FOnValidatePeerCertificate: TValidateCertificate; FOnValidatePeerCertificateErr: TValidateCertificateErr; FOnAuthEvent: TCredentialsStorage.TCredentialAuthEvent; FIPImplementationID: string; FProtocol: string; function GetRequest: IRequest; function GetResponse: IResponse; function GetProxyParams: IProxyConnectionInfo; function GetResponseCode: Integer; function GetResponseText: string; function GetHandleRedirects: Boolean; procedure SetHandleRedirects(AValue: Boolean); function GetAllowCookies: Boolean; procedure SetAllowCookies(AValue: Boolean); function GetConnectTimeout: Integer; procedure SetConnectTimeout(const Value: Integer); function GetReadTimeout: Integer; procedure SetReadTimeout(const Value: Integer); procedure CheckResponse; procedure PrepareRequest(const ARequest: IHTTPRequest); procedure Execute(const AMethod: string; AURL: string; ASource, AResponseContent: TStream); overload; procedure Execute(const AMethod: string; AURL: string; AResponseContent: TStream); overload; procedure RaiseProtocolException(const AResponse: IHTTPResponse); procedure DoCustomAuthentication(const Sender: TObject; AnAuthTarget: TAuthTargetType; const ARealm, AURL: string; var AUserName, APassword: string; var AbortAuth: Boolean; var Persistence: TAuthPersistenceType); procedure DoValidateServerCertificate(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean); function GetProtocol: string; procedure SetProtocol(const protocol: string); function GetOnSelectClientCertificate: TNeedClientCertificateEvent; procedure SetOnSelectClientCertificate(const Value: TNeedClientCertificateEvent); function GetSecureProtocols: THTTPSecureProtocols; procedure SetSecureProtocols(const Value: THTTPSecureProtocols); public class constructor Create; class destructor Destroy; constructor Create; reintroduce; overload; virtual; constructor Create(AOwner: TComponent); overload; override; constructor Create(const AIPImplementationID: string); reintroduce; overload; virtual; constructor Create(AOwner: TComponent; const AIPImplementationID: string); reintroduce; overload; virtual; destructor Destroy; override; // For backwards compatibility class function HasPeerCertificate: Boolean; virtual; // For backwards compatibility class function RegisteredProtocolList: TArray<string>; static; // For backwards compatibility class function ProtocolClass(const AName: string): TDSHTTPClass; static; /// <summary>Execute HTTP DELETE</summary> procedure Delete(const AURL: string; AResponseStream: TStream = nil); /// <summary>Execute HTTP MERGE</summary> procedure Merge(const AURL: string; ARequestStream: TStream = nil); /// <summary>Execute HTTP HEAD</summary> procedure Head(const AURL: string); /// <summary>Execute HTTP PATCH</summary> procedure Patch(const AURL: string; ASource: TStream; AResponseContent: TStream = nil); /// <summary>Execute HTTP PUT</summary> procedure Put(const AURL: string; ASource: TStream; AResponseContent: TStream = nil); /// <summary>Execute HTTP POST</summary> procedure Post(const AURL: string; ASource: TStream; AResponseContent: TStream = nil); /// <summary>Execute HTTP GET</summary> procedure Get(const AURL: string; AResponseContent: TStream = nil); /// <summary>Uses HTTP standard authentication protocols with the given credentials.</summary> procedure SetAuthentication(const user: string; const password: string); /// <summary>clear all client credentials.</summary> procedure ClearClientCredentials; /// <summary>Get all Client credentials.</summary> function GetClientCredentials: TCredentialsStorage.TCredentialArray; /// <summary>Add a cookie that will be passed to the server with each request</summary> procedure AddServerCookie(const ACookie: string; const AURL: string); /// <summary>Get the HTTP request properties</summary> property Request: IRequest read GetRequest; property Response: IResponse read GetResponse; /// <summary>Get the proxy server connection properties</summary> property ProxyParams: IProxyConnectionInfo read GetProxyParams; /// <summary>Get the HTTP ResponseCode</summary> property ResponseCode: Integer read GetResponseCode; /// <summary>Get the HTTP Response text</summary> property ResponseText: string read GetResponseText; /// <summary>Indicate whether redirect responses are handled automatically by making an additional request.</summary> property HandleRedirects: Boolean read GetHandleRedirects write SetHandleRedirects; /// <summary>Allow the client to set server side cookies</summary> property AllowCookies: Boolean read GetAllowCookies write SetAllowCookies; /// <summary>Get or set the timeout when making an HTTP connection</summary> property ConnectTimeout: Integer read GetConnectTimeout write SetConnectTimeout; /// <summary>Get or set the timeout when reading a HTTP response</summary> property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout; property SecureProtocols: THTTPSecureProtocols read GetSecureProtocols write SetSecureProtocols; /// <summary>Event is fired when errors exist in the SSL certificates, that require user validation </summary> property OnValidateCertificate: TValidateCertificateEvent read FOnValidateCertificate write FOnValidateCertificate; /// <summary>Event is fired when Server requires the user to select the from OS installed certificates</summary> property OnSelectClientCertificate: TNeedClientCertificateEvent read GetOnSelectClientCertificate write SetOnSelectClientCertificate; // for backward compatibility /// <summary>Occurs when the peer SSL certificate is about to be validated.</summary> property OnValidatePeerCertificate: TValidateCertificate read FOnValidatePeerCertificate write FOnValidatePeerCertificate; /// <summary>Event is fired when errors exist in the SSL certificates, that require user validation </summary> property OnValidatePeerCertificateErr: TValidateCertificateErr read FOnValidatePeerCertificateErr write FOnValidatePeerCertificateErr; /// <summary>Method is called when Server fires an authentication event </summary> property OnCustomAuthentication: TCredentialsStorage.TCredentialAuthEvent read FOnAuthEvent write FOnAuthEvent; /// <summary>Implementation ID </summary> property IPImplementationID: string read FIPImplementationID; /// <summary>sets connection header to close </summary> procedure Disconnect; /// <summary>Get Protocol in use </summary> property protocol: string read GetProtocol write SetProtocol; end; TDSHTTPS = class(TDSHTTP) public // For backwards compatibility class function HasPeerCertificate: Boolean; override; end; implementation uses System.Hash, System.NetEncoding, Data.DBXClientResStrs, DataSnap.DSClientResStrs; type TIPHTTPRequest = class(TInterfacedObject, TDSHTTP.IRequest) private FAccept: string; FAcceptCharSet: string; FUserAgent: string; FContentType: string; FAcceptEncoding: string; FCustomHeaders: TStrings; FUserName: string; FPassword: string; function GetAccept: string; procedure SetAccept(const Val: string); function GetAcceptCharSet: string; procedure SetAcceptCharSet(const Val: string); function GetCustomHeaders: TDSHTTP.IRequestHeaderList; function GetAcceptEncoding: string; procedure SetAcceptEncoding(const Val: string); function GetContentType: string; procedure SetContentType(LContentType: string); function GetUserAgent: string; procedure SetUserAgent(const Val: string); function GetUserName: string; function GetPassword: string; procedure SetAuthentication(const AUserName, APassword: string); public constructor Create; destructor Destroy; override; end; TIPHTTPResponse = class(TInterfacedObject, TDSHTTP.IResponse) private FResponse: IHTTPResponse; function GetCharSet: string; function GetContentType: string; function GetContentEncoding: string; function GetHeaders: TDSHTTP.IHeaderList; public constructor Create(const AResponse: IHTTPResponse); end; TIPProxyConnectionInfo = class(TInterfacedObject, TDSHTTP.IProxyConnectionInfo) private FProxySettings: TProxySettings; procedure SetProxyPort(Val: Integer); function GetProxyPort: Integer; function GetProxyServer: string; procedure SetProxyServer(Val: string); function GetProxyScheme: string; procedure SetProxyScheme(Val: string); function GetProxyUserName: string; procedure SetProxyUserName(user: string); function GetProxyPassword: string; procedure SetProxyPassword(pass: string); end; TIPResponseHeaderList = class(TInterfacedObject, TDSHTTP.IHeaderList) private FStrings: TStrings; function GetCount: Integer; function GetName(Index: Integer): string; function GetValue(const Name: string): string; procedure Populate(const AResponse: IHTTPResponse); public constructor Create(const AResponse: IHTTPResponse); destructor Destroy; override; end; TIPRequestHeaderList = class(TInterfacedObject, TDSHTTP.IHeaderList, TDSHTTP.IRequestHeaderList) private FStrings: TStrings; function GetCount: Integer; function GetName(Index: Integer): string; function GetValue(const Name: string): string; procedure Clear; procedure SetValue(const AName, AValue: string); public constructor Create(const AStrings: TStrings); end; /// <summary> wrapper implementation of TX500Principal</summary> TX500NETPrincipal = class(TX500Principal) protected FName: string; public constructor Create(const AName: string); virtual; function GetName: string; override; function GetEncoded: Longint; override; end; TX509NETPublicKey = class(TPublicKey) private FAlgorithm: string; FFormat: string; public constructor Create(const PKAlgorithm, PKFormat: string); function GetAlgorithm: string; override; function GetFormat: string; override; function GetEncoded: TArray<Byte>; override; end; TX509NetWrapperCertificate = class(TX509Certificate) private FExpiry: TDateTime; /// <summary> Start date of the certificate</summary> FStart: TDateTime; /// <summary> Subject of the certificate</summary> FSubject: string; /// <summary> Issuer of the certificate</summary> FIssuer: string; /// <summary> ProtocolName of the certificate eg RSAEncryption</summary> FProtocolName: string; /// <summary> Algorithm Signature of the certificate eg. 00:d3:a4:50:6e:c8:ff:56:6b:e6:cf:5d:b6:... </summary> FAlgSignature: string; /// <summary> Algorithm Encryption of the certificate eg md5WithRSAEncryption</summary> FAlgEncryption: string; /// <summary> Encryption's KeySize of the certificate eg 128</summary> FKeySize: Integer; /// <summary> subject Principle information</summary> FSubjectPrincipal: TX500NETPrincipal; /// <summary> Issuer Principle information</summary> FIssuerPrincipal: TX500NETPrincipal; /// <summary> Public key information</summary> FPublicKey: TX509NETPublicKey; public constructor Create(const ACert: System.Net.URLClient.TCertificate); destructor Destroy; override; { Inherited from the base Certificate class } function GetEncoded: TArray<Byte>; override; function GetPublicKey: TPublicKey; override; function Verify(key: TPublicKey): Boolean; override; { Inherited from the X.509 Certificate class } procedure CheckValidity; overload; override; procedure CheckValidity(ADate: TDateTime); overload; override; function GetNotAfter: TDateTime; override; function GetNotBefore: TDateTime; override; function GetBasicConstraints: Integer; override; function GetSerialNumber: string; override; function GetVersion: Longint; override; function GetSigAlgName: string; override; function GetSignature: string; override; function GetIssuerX500Principal: TX500Principal; override; function GetSubjectX500Principal: TX500Principal; override; property Expiry: TDateTime read FExpiry; property Start: TDateTime read FStart; end; { TDSHTTPS } class function TDSHTTPS.HasPeerCertificate: Boolean; begin Result := True; end; { TDSHTTP } constructor TDSHTTP.Create; begin Create(nil); end; constructor TDSHTTP.Create(AOwner: TComponent); begin Create(AOwner, ''); end; constructor TDSHTTP.Create(const AIPImplementationID: string); begin Create(nil, AIPImplementationID); end; constructor TDSHTTP.Create(AOwner: TComponent; const AIPImplementationID: string); begin inherited Create(AOwner); FIPImplementationID := AIPImplementationID; FHTTPClient := THTTPClient.Create; FHTTPClient.AuthEvent := DoCustomAuthentication; FHTTPClient.OnValidateServerCertificate := DoValidateServerCertificate; FIPHTTPRequestIntf := TIPHTTPRequest.Create; // Reference count AllowCookies := True; end; destructor TDSHTTP.Destroy; begin FHTTPClient.Free; inherited; end; // public static class methods, for backward support class constructor TDSHTTP.Create; begin // FProtocols := TDictionary<string, TDSHTTPClass>.Create; end; class destructor TDSHTTP.Destroy; begin // FreeAndNil(FProtocols); end; class function TDSHTTP.HasPeerCertificate: Boolean; begin Result := False; end; class function TDSHTTP.RegisteredProtocolList: TArray<string>; begin SetLength(Result, 2); Result[0] := 'http'; Result[1] := 'https'; end; class function TDSHTTP.ProtocolClass(const AName: string): TDSHTTPClass; begin if SameText(AName, 'https') then Result := TDSHTTPS else Result := TDSHTTP; end; // public methods procedure TDSHTTP.Execute(const AMethod: string; AURL: string; ASource, AResponseContent: TStream); var LRequest: IHTTPRequest; LResponse: IHTTPResponse; begin LRequest := FHTTPClient.GetRequest(AMethod, AURL); PrepareRequest(LRequest); ASource.Seek(Longint(0), soFromBeginning); LRequest.SourceStream := ASource; LResponse := FHTTPClient.Execute(LRequest, AResponseContent); FHTTPResponse := LResponse; if LResponse.StatusCode >= 300 then RaiseProtocolException(LResponse); end; procedure TDSHTTP.Execute(const AMethod: string; AURL: string; AResponseContent: TStream); var LRequest: IHTTPRequest; LResponse: IHTTPResponse; begin LRequest := FHTTPClient.GetRequest(AMethod, AURL); PrepareRequest(LRequest); LResponse := FHTTPClient.Execute(LRequest, AResponseContent); FHTTPResponse := LResponse; if LResponse.StatusCode >= 300 then RaiseProtocolException(LResponse); end; procedure TDSHTTP.Delete(const AURL: string; AResponseStream: TStream); begin Execute('DELETE', AURL, AResponseStream); end; procedure TDSHTTP.Merge(const AURL: string; ARequestStream: TStream); begin Execute('MERGE', AURL, ARequestStream, nil); end; procedure TDSHTTP.Head(const AURL: string); begin Execute('HEAD', AURL, nil); end; procedure TDSHTTP.Patch(const AURL: string; ASource, AResponseContent: TStream); begin Execute('PATCH', AURL, ASource, AResponseContent); end; procedure TDSHTTP.Put(const AURL: string; ASource, AResponseContent: TStream); begin Execute('PUT', AURL, ASource, AResponseContent); end; procedure TDSHTTP.Post(const AURL: string; ASource, AResponseContent: TStream); begin Execute('POST', AURL, ASource, AResponseContent); end; procedure TDSHTTP.Get(const AURL: string; AResponseContent: TStream); begin Execute('GET', AURL, AResponseContent); end; procedure TDSHTTP.SetAuthentication(const user, password: string); begin FHTTPClient.CredentialsStorage.AddCredential(TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', '', user, password)) end; procedure TDSHTTP.DoCustomAuthentication(const Sender: TObject; AnAuthTarget: TAuthTargetType; const ARealm, AURL: string; var AUserName, APassword: string; var AbortAuth: Boolean; var Persistence: TAuthPersistenceType); var MyCredential: TCredentialsStorage.TCredential; begin if Assigned(FOnAuthEvent) then FOnAuthEvent(Sender, AnAuthTarget, ARealm, AURL, AUserName, APassword, AbortAuth, Persistence) else begin if AnAuthTarget = TAuthTargetType.Proxy then begin MyCredential := FHTTPClient.CredentialsStorage.FindAccurateCredential(AnAuthTarget, ''); AUserName := MyCredential.UserName; APassword := MyCredential.password; end; if AnAuthTarget = TAuthTargetType.Server then begin MyCredential := FHTTPClient.CredentialsStorage.FindAccurateCredential(AnAuthTarget, ''); AUserName := MyCredential.UserName; APassword := MyCredential.password; //Persistence := TAuthPersistenceType.Request; end; end; end; procedure TDSHTTP.DoValidateServerCertificate(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean); var X509cert: TX509Certificate; begin if Assigned(FOnValidateCertificate) then FOnValidateCertificate(Sender, ARequest, Certificate, Accepted) else if Assigned(FOnValidatePeerCertificate) then begin X509cert := TX509NetWrapperCertificate.Create(Certificate); try FOnValidatePeerCertificate(Sender, X509cert, 0, Accepted) finally X509cert.Free; end; end else if Assigned(FOnValidatePeerCertificateErr) then begin X509cert := TX509NetWrapperCertificate.Create(Certificate); try FOnValidatePeerCertificateErr(Sender, X509cert, 0, 0, Accepted) finally X509cert.Free; end; end else // Accept by default Accepted := True; end; // properties function TDSHTTP.GetRequest: IRequest; begin Result := FIPHTTPRequestIntf; end; function TDSHTTP.GetResponse: IResponse; begin CheckResponse; Result := TIPHTTPResponse.Create(FHTTPResponse); end; procedure TDSHTTP.CheckResponse; begin if FHTTPResponse = nil then raise Exception.Create(sResponseObjectNotFound); end; procedure TDSHTTP.ClearClientCredentials; begin FHTTPClient.CredentialsStorage.ClearCredentials; end; function TDSHTTP.GetClientCredentials; begin Result := FHTTPClient.CredentialsStorage.Credentials; end; function TDSHTTP.GetProxyParams: IProxyConnectionInfo; begin if FProxyConnectionInfo = nil then FProxyConnectionInfo := TIPProxyConnectionInfo.Create; Result := FProxyConnectionInfo; end; procedure TDSHTTP.AddServerCookie(const ACookie, AURL: string); begin if FHTTPClient.AllowCookies then FHTTPClient.CookieManager.AddServerCookie(ACookie, AURL); end; function TDSHTTP.GetAllowCookies: Boolean; begin Result := FHTTPClient.AllowCookies; end; function TDSHTTP.GetConnectTimeout: Integer; begin Result := FHTTPClient.ConnectionTimeout; end; function TDSHTTP.GetHandleRedirects: Boolean; begin Result := FHTTPClient.HandleRedirects; end; function TDSHTTP.GetReadTimeout: Integer; begin Result := FHTTPClient.ResponseTimeout; end; function TDSHTTP.GetResponseCode: Integer; begin CheckResponse; Result := FHTTPResponse.StatusCode; end; function TDSHTTP.GetResponseText: string; begin CheckResponse; Result := FHTTPResponse.StatusText; end; function TDSHTTP.GetSecureProtocols: THTTPSecureProtocols; begin Result := FHTTPClient.SecureProtocols; end; procedure TDSHTTP.SetAllowCookies(AValue: Boolean); begin FHTTPClient.AllowCookies := AValue; end; procedure TDSHTTP.SetConnectTimeout(const Value: Integer); begin FHTTPClient.ConnectionTimeout := Value; end; procedure TDSHTTP.SetHandleRedirects(AValue: Boolean); begin FHTTPClient.HandleRedirects := AValue; end; procedure TDSHTTP.SetReadTimeout(const Value: Integer); begin FHTTPClient.ResponseTimeout := Value; end; procedure TDSHTTP.SetSecureProtocols(const Value: THTTPSecureProtocols); begin FHTTPClient.SecureProtocols := Value; end; function TDSHTTP.GetOnSelectClientCertificate: TNeedClientCertificateEvent; begin Result := FHTTPClient.OnNeedClientCertificate; end; procedure TDSHTTP.SetOnSelectClientCertificate(const Value: TNeedClientCertificateEvent); begin FHTTPClient.OnNeedClientCertificate := Value; end; procedure TDSHTTP.PrepareRequest(const ARequest: IHTTPRequest); var LIPRequest: TIPHTTPRequest; I: Integer; begin if FProxyConnectionInfo <> nil then FHTTPClient.ProxySettings := TIPProxyConnectionInfo(FProxyConnectionInfo).FProxySettings; LIPRequest := TIPHTTPRequest(FIPHTTPRequestIntf); for I := 0 to LIPRequest.FCustomHeaders.Count - 1 do begin ARequest.AddHeader(LIPRequest.FCustomHeaders.Names[I], LIPRequest.FCustomHeaders.ValueFromIndex[I]); end; ARequest.Accept := LIPRequest.FAccept; if LIPRequest.FAcceptCharSet <> '' then ARequest.AcceptCharSet := LIPRequest.FAcceptCharSet; if LIPRequest.FUserAgent <> '' then ARequest.UserAgent := LIPRequest.FUserAgent; if LIPRequest.FAcceptEncoding <> '' then ARequest.AcceptEncoding := LIPRequest.FAcceptEncoding; if LIPRequest.FContentType <> '' then ARequest.AddHeader('Content-type', LIPRequest.FContentType); if LIPRequest.FUserName <> '' then begin ARequest.SetCredential(LIPRequest.FUserName, LIPRequest.FPassword); FHTTPClient.PreemptiveAuthentication := True; end; end; procedure TDSHTTP.RaiseProtocolException(const AResponse: IHTTPResponse); const sHTTP10 = 'HTTP/1.0'; sHTTP11 = 'HTTP/1.1'; sHTTP20 = 'HTTP/2.0'; var LMessage: string; begin case AResponse.Version of THTTPProtocolVersion.UNKNOWN_HTTP: LMessage := ''; THTTPProtocolVersion.HTTP_1_0: LMessage := sHTTP10 + ' '; THTTPProtocolVersion.HTTP_1_1: LMessage := sHTTP11 + ' '; THTTPProtocolVersion.HTTP_2_0: LMessage := sHTTP20 + ' '; end; LMessage := LMessage + Format('%d %s', [AResponse.StatusCode, AResponse.StatusText]); raise EHTTPProtocolException.Create(AResponse.StatusCode, AResponse.ContentAsString, LMessage); end; { TIPHTTPRequest } constructor TIPHTTPRequest.Create; begin FCustomHeaders := TStringList.Create; end; destructor TIPHTTPRequest.Destroy; begin FCustomHeaders.Free; inherited; end; function TIPHTTPRequest.GetAccept: string; begin Result := FAccept; end; function TIPHTTPRequest.GetAcceptCharSet: string; begin Result := FAcceptCharSet; end; function TIPHTTPRequest.GetAcceptEncoding: string; begin Result := FAcceptEncoding; end; function TIPHTTPRequest.GetContentType: string; begin Result := FContentType; end; function TIPHTTPRequest.GetCustomHeaders: TDSHTTP.IRequestHeaderList; begin Result := TIPRequestHeaderList.Create(FCustomHeaders); end; function TIPHTTPRequest.GetPassword: string; begin Result := FPassword; end; function TIPHTTPRequest.GetUserAgent: string; begin Result := FUserAgent; end; function TIPHTTPRequest.GetUserName: string; begin Result := FUserName; end; procedure TIPHTTPRequest.SetAccept(const Val: string); begin FAccept := Val; end; procedure TIPHTTPRequest.SetAcceptCharSet(const Val: string); begin FAcceptCharSet := Val; end; procedure TIPHTTPRequest.SetAcceptEncoding(const Val: string); begin FAcceptEncoding := Val; end; procedure TIPHTTPRequest.SetAuthentication(const AUserName, APassword: string); begin if AUserName <> emptystr then begin FUserName := AUserName; FPassword := APassword; end; end; procedure TIPHTTPRequest.SetContentType(LContentType: string); begin FContentType := LContentType; end; procedure TIPHTTPRequest.SetUserAgent(const Val: string); begin FUserAgent := Val; end; { TIPHTTPResponse } constructor TIPHTTPResponse.Create(const AResponse: IHTTPResponse); begin FResponse := AResponse; end; function TIPHTTPResponse.GetCharSet: string; begin Result := FResponse.ContentCharSet; end; function TIPHTTPResponse.GetContentEncoding: string; begin Result := FResponse.ContentEncoding; end; function TIPHTTPResponse.GetContentType: string; var LSplitted: TArray<string>; LResultValues: TArray<string>; S: string; begin Result := FResponse.MimeType; LSplitted := Result.Split([';']); // Remove charset for S in LSplitted do if not S.TrimLeft.StartsWith('charset', True) then // do not translate LResultValues := LResultValues + [S]; if Length(LResultValues) <> Length(LSplitted) then begin Result := ''; // Rebuild for S in LResultValues do begin if Result <> '' then Result := Result + ';'; Result := Result + S; end; end; end; function TIPHTTPResponse.GetHeaders: TDSHTTP.IHeaderList; begin Result := TIPResponseHeaderList.Create(FResponse); end; { TIPProxyConnectionInfo } function TIPProxyConnectionInfo.GetProxyPassword: string; begin Result := FProxySettings.password; end; function TIPProxyConnectionInfo.GetProxyPort: Integer; begin Result := FProxySettings.Port; end; function TIPProxyConnectionInfo.GetProxyServer: string; begin Result := FProxySettings.Host; end; function TIPProxyConnectionInfo.GetProxyScheme: string; begin Result := FProxySettings.Scheme; end; function TIPProxyConnectionInfo.GetProxyUserName: string; begin Result := FProxySettings.UserName; end; procedure TIPProxyConnectionInfo.SetProxyPassword(pass: string); begin FProxySettings.password := pass; end; procedure TIPProxyConnectionInfo.SetProxyPort(Val: Integer); begin FProxySettings.Port := Val; end; procedure TIPProxyConnectionInfo.SetProxyServer(Val: string); begin FProxySettings.Host := Val; end; procedure TIPProxyConnectionInfo.SetProxyScheme(Val: string); begin FProxySettings.Scheme := Val; end; procedure TIPProxyConnectionInfo.SetProxyUserName(user: string); begin FProxySettings.UserName := user; end; { TIPResponseHeaderList } destructor TIPResponseHeaderList.Destroy; begin FStrings.Free; inherited; end; function TIPResponseHeaderList.GetCount: Integer; begin Result := FStrings.Count; end; function TIPResponseHeaderList.GetName(Index: Integer): string; begin Result := FStrings.Names[Index]; end; function TIPResponseHeaderList.GetValue(const Name: string): string; begin Result := FStrings.Values[Name]; end; constructor TIPResponseHeaderList.Create(const AResponse: IHTTPResponse); begin FStrings := TStringList.Create; Populate(AResponse); end; procedure TIPResponseHeaderList.Populate(const AResponse: IHTTPResponse); var LHeader: TNetHeader; begin for LHeader in AResponse.Headers do FStrings.Values[LHeader.Name] := LHeader.Value; end; { TIPRequestHeaderList } function TIPRequestHeaderList.GetCount: Integer; begin Result := FStrings.Count; end; function TIPRequestHeaderList.GetName(Index: Integer): string; begin Result := FStrings.Names[Index]; end; function TIPRequestHeaderList.GetValue(const Name: string): string; begin Result := FStrings.Values[Name]; end; constructor TIPRequestHeaderList.Create(const AStrings: TStrings); begin FStrings := AStrings; end; procedure TIPRequestHeaderList.Clear; begin FStrings.Clear; end; procedure TIPRequestHeaderList.SetValue(const AName, AValue: string); begin FStrings.Values[AName] := AValue; end; function TDSHTTP.GetProtocol: string; begin Result := FProtocol; end; procedure TDSHTTP.SetProtocol(const protocol: string); begin FProtocol := protocol; end; procedure TDSHTTP.Disconnect; begin FIPHTTPRequestIntf.CustomHeaders.Values['Connection'] := 'close' end; { TX509NetAdaptorCertificate } procedure TX509NetWrapperCertificate.CheckValidity; begin CheckValidity(Now); end; procedure TX509NetWrapperCertificate.CheckValidity(ADate: TDateTime); begin if ADate > FExpiry then raise ECertificateExpiredException.Create(SCertExpired); if ADate < FStart then raise ECertificateNotYetValidException.Create(SCertNotYetValid); end; constructor TX509NetWrapperCertificate.Create(const ACert: System.Net.URLClient.TCertificate); begin FExpiry := ACert.Expiry; FStart := ACert.Start; FSubject := ACert.Subject; FIssuer := ACert.Issuer; FProtocolName := ACert.ProtocolName; FAlgSignature := ACert.AlgSignature; FAlgEncryption := ACert.AlgEncryption; FKeySize := ACert.KeySize; FSubjectPrincipal := TX500NETPrincipal.Create(ACert.Subject); FIssuerPrincipal := TX500NETPrincipal.Create(ACert.Issuer); FPublicKey := TX509NETPublicKey.Create(FProtocolName, ''); end; destructor TX509NetWrapperCertificate.Destroy; begin FIssuerPrincipal.Free; FSubjectPrincipal.Free; FPublicKey.Free; inherited; end; function TX509NetWrapperCertificate.GetBasicConstraints: Integer; begin Result := 0; end; function TX509NetWrapperCertificate.GetEncoded: TArray<Byte>; begin Result := TBytes.Create(); end; function TX509NetWrapperCertificate.GetIssuerX500Principal: TX500Principal; begin Result := FIssuerPrincipal; end; function TX509NetWrapperCertificate.GetNotAfter: TDateTime; begin Result := FExpiry; end; function TX509NetWrapperCertificate.GetNotBefore: TDateTime; begin Result := FStart; end; function TX509NetWrapperCertificate.GetPublicKey: TPublicKey; begin Result := FPublicKey; end; function TX509NetWrapperCertificate.GetSerialNumber: string; begin Result := 'not available'; end; function TX509NetWrapperCertificate.GetSigAlgName: string; begin Result := FAlgEncryption; end; function TX509NetWrapperCertificate.GetSignature: string; begin Result := FAlgSignature; end; function TX509NetWrapperCertificate.GetSubjectX500Principal: TX500Principal; begin Result := FSubjectPrincipal; end; function TX509NetWrapperCertificate.GetVersion: Longint; begin Result := 0; end; function TX509NetWrapperCertificate.Verify(key: TPublicKey): Boolean; begin Result := True; end; { TX500NETPrincipal } constructor TX500NETPrincipal.Create(const AName: string); begin FName := AName; end; function TX500NETPrincipal.GetEncoded: Longint; begin Result := 0; end; function TX500NETPrincipal.GetName: string; begin Result := FName; end; { TX509NETPublicKey } constructor TX509NETPublicKey.Create(const PKAlgorithm, PKFormat: string); begin FAlgorithm := PKAlgorithm; FFormat := PKFormat; end; function TX509NETPublicKey.GetAlgorithm: string; begin Result := FAlgorithm; end; function TX509NETPublicKey.GetEncoded: TArray<Byte>; begin Result := TBytes.Create(); // FIdX509.EncodedKey; end; function TX509NETPublicKey.GetFormat: string; begin Result := FFormat; end; { EHTTPProtocolException } constructor EHTTPProtocolException.Create(AErrorCode: Integer; const AErrorMessage: string; const AMessage: string); begin FErrorCode := AErrorCode; FErrorMessage := AErrorMessage; inherited Create(AMessage); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConfig.RedirectFrame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, Data.Bind.Controls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.TabControl, RSConfig.NameValueFrame, FMX.ListBox, RSConfig.ListControlFrame; type TRedirectFrame = class(TFrame) ListControlFrame1: TListControlFrame; TabControl: TTabControl; ListItem: TTabItem; EditItem: TTabItem; Layout72: TLayout; SaveButton: TButton; CancelButton: TButton; DestinationEdit: TEdit; Layout1: TLayout; Label1: TLabel; ListBox1: TListBox; procedure SaveButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } ActiveFrame: TNameValueFrame; constructor Create(AOwner: TComponent); override; procedure Callback(Sender: TObject); procedure LoadSectionList; procedure SaveSectionList; procedure ClearFields; procedure Reset; end; implementation {$R *.fmx} uses RSConsole.FormConfig, RSConfig.ConfigDM, RSConfig.Consts; constructor TRedirectFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); ListControlFrame1.HelpButton.Hint := strRedirectsHelp; end; procedure TRedirectFrame.Callback(Sender: TObject); var LRedirectItem: TRedirectItem; begin ActiveFrame := TNameValueFrame(Sender); if Assigned(ActiveFrame) then begin if ActiveFrame.ValueEdit.Text <> '' then begin LRedirectItem := TRedirectItem.FromJson(ActiveFrame.ValueEdit.Text); try DestinationEdit.Text := LRedirectItem.Destination; finally LRedirectItem.Free; end; end; TabControl.ActiveTab := EditItem; ConfigForm.SaveLayout.Visible := False; end; end; procedure TRedirectFrame.Reset; begin if TabControl.ActiveTab = EditItem then CancelButtonClick(Self); end; procedure TRedirectFrame.CancelButtonClick(Sender: TObject); begin ClearFields; TabControl.ActiveTab := ListItem; ConfigForm.SaveLayout.Visible := True; end; procedure TRedirectFrame.LoadSectionList; begin ListControlFrame1.SetFrameType(REDIRECT_FRAME); ListControlFrame1.SetListBox(ListBox1); ListControlFrame1.SetCallback(Callback); ConfigDM.LoadSectionList(strServerRedirect, ListBox1, Callback); end; procedure TRedirectFrame.SaveButtonClick(Sender: TObject); var LRedirectItem: TRedirectItem; begin if Assigned(ActiveFrame) then begin LRedirectItem := TRedirectItem.Create; try LRedirectItem.Destination := DestinationEdit.Text; ActiveFrame.ValueEdit.Text := LRedirectItem.ToJson; finally LRedirectItem.Free; end; ClearFields; ActiveFrame := nil; end; TabControl.ActiveTab := ListItem; ConfigForm.SaveLayout.Visible := True; end; procedure TRedirectFrame.ClearFields; begin DestinationEdit.Text := ''; end; procedure TRedirectFrame.SaveSectionList; begin ConfigDM.SaveSectionList(strServerRedirect, ListBox1); end; end.
{$R-} {$Q-} unit ncEncRc5; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers; const NUMROUNDS = 12; { number of rounds must be between 12-16 } type TncEnc_rc5 = class(TncEnc_blockcipher64) protected KeyData: array [0 .. ((NUMROUNDS * 2) + 1)] of DWord; procedure InitKey(const Key; Size: longword); override; public class function GetAlgorithm: string; override; class function GetMaxKeySize: integer; override; class function SelfTest: boolean; override; procedure Burn; override; procedure EncryptECB(const InData; var OutData); override; procedure DecryptECB(const InData; var OutData); override; end; { ****************************************************************************** } { ****************************************************************************** } implementation uses ncEncryption; const sBox: array [0 .. 33] of DWord = ($B7E15163, $5618CB1C, $F45044D5, $9287BE8E, $30BF3847, $CEF6B200, $6D2E2BB9, $0B65A572, $A99D1F2B, $47D498E4, $E60C129D, $84438C56, $227B060F, $C0B27FC8, $5EE9F981, $FD21733A, $9B58ECF3, $399066AC, $D7C7E065, $75FF5A1E, $1436D3D7, $B26E4D90, $50A5C749, $EEDD4102, $8D14BABB, $2B4C3474, $C983AE2D, $67BB27E6, $05F2A19F, $A42A1B58, $42619511, $E0990ECA, $7ED08883, $1D08023C); function LRot32(a, b: longword): longword; begin Result := (a shl b) or (a shr (32 - b)); end; function RRot32(a, b: longword): longword; begin Result := (a shr b) or (a shl (32 - b)); end; class function TncEnc_rc5.GetAlgorithm: string; begin Result := 'RC5'; end; class function TncEnc_rc5.GetMaxKeySize: integer; begin Result := 2048; end; class function TncEnc_rc5.SelfTest: boolean; const Key1: array [0 .. 15] of byte = ($DC, $49, $DB, $13, $75, $A5, $58, $4F, $64, $85, $B4, $13, $B5, $F1, $2B, $AF); Plain1: array [0 .. 1] of DWord = ($B7B3422F, $92FC6903); Cipher1: array [0 .. 1] of DWord = ($B278C165, $CC97D184); Key2: array [0 .. 15] of byte = ($52, $69, $F1, $49, $D4, $1B, $A0, $15, $24, $97, $57, $4D, $7F, $15, $31, $25); Plain2: array [0 .. 1] of DWord = ($B278C165, $CC97D184); Cipher2: array [0 .. 1] of DWord = ($15E444EB, $249831DA); var Cipher: TncEnc_rc5; Data: array [0 .. 1] of DWord; begin Cipher := TncEnc_rc5.Create(nil); Cipher.Init(Key1, Sizeof(Key1) * 8, nil); Cipher.EncryptECB(Plain1, Data); Result := boolean(CompareMem(@Data, @Cipher1, Sizeof(Data))); Cipher.DecryptECB(Data, Data); Result := Result and boolean(CompareMem(@Data, @Plain1, Sizeof(Data))); Cipher.Burn; Cipher.Init(Key2, Sizeof(Key2) * 8, nil); Cipher.EncryptECB(Plain2, Data); Result := Result and boolean(CompareMem(@Data, @Cipher2, Sizeof(Data))); Cipher.DecryptECB(Data, Data); Result := Result and boolean(CompareMem(@Data, @Plain2, Sizeof(Data))); Cipher.Burn; Cipher.Free; end; procedure TncEnc_rc5.InitKey(const Key; Size: longword); var xKeyD: array [0 .. 63] of DWord; i, j, k, xKeyLen: longword; a, b: DWord; begin FillChar(xKeyD, Sizeof(xKeyD), 0); Size := Size div 8; Move(Key, xKeyD, Size); xKeyLen := Size div 4; if (Size mod 4) <> 0 then Inc(xKeyLen); Move(sBox, KeyData, (NUMROUNDS + 1) * 8); i := 0; j := 0; a := 0; b := 0; if xKeyLen > ((NUMROUNDS + 1) * 2) then k := xKeyLen * 3 else k := (NUMROUNDS + 1) * 6; for k := k downto 1 do begin a := LRot32(KeyData[i] + a + b, 3); KeyData[i] := a; b := LRot32(xKeyD[j] + a + b, a + b); xKeyD[j] := b; i := (i + 1) mod ((NUMROUNDS + 1) * 2); j := (j + 1) mod xKeyLen; end; FillChar(xKeyD, Sizeof(xKeyD), 0); end; procedure TncEnc_rc5.Burn; begin FillChar(KeyData, Sizeof(KeyData), $FF); inherited Burn; end; procedure TncEnc_rc5.EncryptECB(const InData; var OutData); var a, b: DWord; i: longword; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); a := PDword(@InData)^ + KeyData[0]; b := PDword(longword(@InData) + 4)^ + KeyData[1]; for i := 1 to NUMROUNDS do begin a := a xor b; a := LRot32(a, b) + KeyData[2 * i]; b := b xor a; b := LRot32(b, a) + KeyData[(2 * i) + 1]; end; PDword(@OutData)^ := a; PDword(longword(@OutData) + 4)^ := b; end; procedure TncEnc_rc5.DecryptECB(const InData; var OutData); var a, b: DWord; i: longword; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); a := PDword(@InData)^; b := PDword(longword(@InData) + 4)^; for i := NUMROUNDS downto 1 do begin b := RRot32(b - KeyData[(2 * i) + 1], a); b := b xor a; a := RRot32(a - KeyData[2 * i], b); a := a xor b; end; PDword(@OutData)^ := a - KeyData[0]; PDword(longword(@OutData) + 4)^ := b - KeyData[1]; end; end.
namespace MetalExample; interface uses Metal, MetalKit; type mouseDownstate = enum(none, cmd, shift, alt, ctrl); [IBObject] Metal_View = public class(MTKView) private trackingArea: NSTrackingArea; fMousePos : NSPoint; fMouseDownPos : NSPoint; mState : mouseDownstate; fMousein : Boolean; fFilllayer : Boolean := true; method setTrackingAreas; private fMouseDelegate : nullable MetalMouseDelegate; public method awakeFromNib; override; method setFrameSize(newSize: NSSize); override; method mouseEntered(&event: not nullable NSEvent); override; method mouseExited(&event: not nullable NSEvent); override; method mouseDown(&event: not nullable NSEvent); override; method mouseUp(&event: not nullable NSEvent); override; method mouseMoved(&event: not nullable NSEvent); override; method mouseDragged(&event: not nullable NSEvent); override; property MouseDelegate : nullable MetalMouseDelegate read fMouseDelegate write fMouseDelegate; end; implementation method Metal_View.awakeFromNib; begin inherited; device := MTLCreateSystemDefaultDevice(); if device = nil then NSLog("Could not create a default MetalDevice!!"); setTrackingAreas; end; method Metal_View.mouseEntered(&event: not nullable NSEvent); begin fMousein := true; NSLog("mouseEntered"); if fMouseDelegate:DontShowCursor then begin NSCursor.hide; fMouseDelegate:showCrosshair := true; end; end; method Metal_View.mouseExited(&event: not nullable NSEvent); begin fMousein := false; NSLog("mouseExited"); // if fMouseDelegate:DontShowCursor then NSCursor.unhide; fMouseDelegate:showCrosshair := false; end; method Metal_View.mouseDown(&event: not nullable NSEvent); begin NSLog("mouseDown"); end; method Metal_View.mouseUp(&event: not nullable NSEvent); begin NSLog("mouseUp"); end; method Metal_View.mouseMoved(&event: not nullable NSEvent); begin fMousePos :=convertPointToBacking( convertPoint(&event.locationInWindow) fromView(nil)); fMouseDelegate:MouseMove(fMousePos.x, fMousePos.y); // NSLog("mouseMoved"); end; method Metal_View.mouseDragged(&event: not nullable NSEvent); begin fMousePos :=convertPointToBacking( convertPoint(&event.locationInWindow) fromView(nil)); fMouseDelegate:MouseMove(fMousePos.x, fMousePos.y); // NSLog("mouseDragged"); end; method Metal_View.setTrackingAreas; begin // Remove existing tracking area if necessary. if trackingArea <> nil then removeTrackingArea(trackingArea); // Create new tracking area. var options: NSTrackingAreaOptions := [ NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.MouseMoved, NSTrackingAreaOptions.ActiveInActiveApp, NSTrackingAreaOptions.NSTrackingInVisibleRect ,NSTrackingAreaOptions.EnabledDuringMouseDrag // NSTrackingAreaOptions.ActiveInActiveApp, ]; trackingArea := new NSTrackingArea() withRect(frame) options(options) owner(self) userInfo(nil); addTrackingArea(trackingArea); end; method Metal_View.setFrameSize(newSize: NSSize); begin inherited setFrameSize(newSize); setTrackingAreas; end; end.
unit PrnUtils; {PrnUtils Copyright (c) 1989-2000 by Joe C. Hecht All Rights Reserved} {License - Distribution of this souce code prohibited!} {For inclusion in compiled form in your application only!} {Version 3.1 - Use at your own risk - No liability accepted!} {TExcellentHomePage: www.code4sale.com/joehecht} {Author email: joehecht@code4sale.com} {Code4Sale.com - You place to buy and sell code! www.code4sale.com} interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, StdCtrls, Forms; type PPrnPageInfo = ^TPrnPageInfo; TPrnPageInfo = packed record Margin : TRect; { normal margins to printing area } PageSize : TPoint; { normal page (paper) size } PageArea : TPoint; { normal page image size } AdjustedMargin : TRect; { adjusted margins (equal on all sizes) } AdjustedPageArea : TPoint; { page image size adjusted for equal margins } AdjustedMarginOffset : TPoint; { amount to offset output for adjusted margins } DPI : TPoint; { pixels per inch } end; function GetPrnPageInfo(dc : HDC; lpPrnPageInfo : PPrnPageInfo) : BOOL; stdcall; type PScaleInfo = ^TScaleInfo; TScaleInfo = packed record OriginalSize_X : double; OriginalSize_Y : double; ScaledSize_X : double; ScaledSize_Y : double; ScaleFactor_X : double; ScaleFactor_Y : double; end; function ScaleToFitX(lpScaleInfo : PScaleInfo) : BOOL; stdcall; function ScaleToFitY(lpScaleInfo : PScaleInfo) : BOOL; stdcall; function ScaleToBestFit(lpScaleInfo : PScaleInfo) : BOOL; stdcall; type PPixelSizeInfo = ^TPixelSizeInfo; TPixelSizeInfo = packed record DotsPerInch_X : double; DotsPerInch_Y : double; DotsPerMillimeter_X : double; DotsPerMillimeter_Y : double; DotsPerPoint_X : double; DotsPerPoint_Y : double; end; function GetPixelSizeInfo(dc : HDC; lpPixelSizeInfo : PPixelSizeInfo) : BOOL; stdcall; function GetNumPagesRequired(PrinterPageSize : DWORD; ImageSize : DWORD) : DWORD; stdcall; function GetMemEx(size : DWORD) : pointer; stdcall; function FreeMemEx(p : pointer) : pointer; stdcall; function LoadDIBFromStream(TheStream : TStream; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; function LoadDIBFromFile(const FileName : string; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; function LoadDIBFromTBitmap(ABitmap : TBitmap; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; type TAbortDialog = class(TForm) btnCancel: TButton; procedure btnCancelClick(Sender: TObject); private { Private declarations } Canceled : BOOL; public { Public declarations } function Aborted : BOOL; end; function CreateAbortDialog(ApplicationHandle : THandle; AOwner: TComponent) : TAbortDialog; stdcall; procedure FreeAbortDialog(AbortDialog : TAbortDialog); stdcall; {Frees an abort dialog} procedure AbortDialogSetCaption(AbortDialog : TAbortDialog; s : pChar); stdcall; function AbortDialogUserHasCanceled(AbortDialog : TAbortDialog) : BOOL; stdcall; type TPrinterAbortDialog = TAbortDialog; function CreatePrinterAbortDialog(ApplicationHandle : THandle; AOwner: TComponent) : TPrinterAbortDialog; stdcall; procedure FreePrinterAbortDialog(AbortDialog : TPrinterAbortDialog); stdcall; procedure PrinterAbortDialogSetCaption(AbortDialog : TPrinterAbortDialog; ACaption : pChar); stdcall; function PrinterAbortDialogAborted(AbortDialog : TPrinterAbortDialog) : BOOL; stdcall; implementation {$R *.DFM} {$IFOPT Q+} {$DEFINE PrnUtils_CKOVERFLOW} {$Q-} {$ENDIF} {$IFOPT R+} {$DEFINE PrnUtils_CKRANGE} {$R-} {$ENDIF} function RoundWayUp(X: Extended): LongInt; begin if (Frac(X) > 0.0000001) then begin x := x + 1; end; Result := Trunc(X); end; function GetPrnPageInfo(dc : HDC; lpPrnPageInfo : PPrnPageInfo) : BOOL; stdcall; var Max : integer; begin result := FALSE; if (lpPrnPageInfo = nil) then begin exit; end; try lpPrnPageInfo^.Margin.Left := GetDeviceCaps(dc, PHYSICALOFFSETX); lpPrnPageInfo^.Margin.Top := GetDeviceCaps(dc, PHYSICALOFFSETY); lpPrnPageInfo^.PageSize.x := GetDeviceCaps(dc, PHYSICALWIDTH); lpPrnPageInfo^.PageSize.y := GetDeviceCaps(dc, PHYSICALHEIGHT); lpPrnPageInfo^.PageArea.x := GetDeviceCaps(dc, HORZRES); lpPrnPageInfo^.PageArea.y := GetDeviceCaps(dc, VERTRES); if (lpPrnPageInfo^.PageSize.x = 0) then begin lpPrnPageInfo^.PageSize.x := lpPrnPageInfo^.PageArea.x; end; if (lpPrnPageInfo^.PageSize.y = 0) then begin lpPrnPageInfo^.PageSize.y := lpPrnPageInfo^.PageArea.y; end; if (NOT Win32Platform = VER_PLATFORM_WIN32_NT) then begin while (lpPrnPageInfo^.PageArea.x > 32000) do begin Dec(lpPrnPageInfo^.PageArea.x); end; while (lpPrnPageInfo^.PageArea.y > 32000) do begin Dec(lpPrnPageInfo^.PageArea.y); end; end; lpPrnPageInfo^.Margin.Right := (lpPrnPageInfo^.PageSize.x - lpPrnPageInfo^.PageArea.x) - lpPrnPageInfo^.Margin.Left; lpPrnPageInfo^.Margin.Bottom := (lpPrnPageInfo^.PageSize.y - lpPrnPageInfo^.PageArea.y) - lpPrnPageInfo^.Margin.Top; if (lpPrnPageInfo^.Margin.Right > lpPrnPageInfo^.Margin.Left) then begin Max := lpPrnPageInfo^.Margin.Right; end else begin Max := lpPrnPageInfo^.Margin.Left; end; if (lpPrnPageInfo^.Margin.Top > Max) then begin Max := lpPrnPageInfo^.Margin.Top; end; if (lpPrnPageInfo^.Margin.Bottom > Max) then begin Max := lpPrnPageInfo^.Margin.Bottom; end; lpPrnPageInfo^.AdjustedMargin.Left := Max; lpPrnPageInfo^.AdjustedMargin.Top := Max; lpPrnPageInfo^.AdjustedMargin.Right := Max; lpPrnPageInfo^.AdjustedMargin.Bottom := Max; lpPrnPageInfo^.AdjustedMarginOffset.x := Max - lpPrnPageInfo^.Margin.Left; lpPrnPageInfo^.AdjustedMarginOffset.y := Max - lpPrnPageInfo^.Margin.Top; Max := Max * 2; lpPrnPageInfo^.AdjustedPageArea.x := lpPrnPageInfo^.PageSize.x - Max; lpPrnPageInfo^.AdjustedPageArea.y := lpPrnPageInfo^.PageSize.y - Max; lpPrnPageInfo^.DPI.x := GetDeviceCaps(dc, LOGPIXELSX); lpPrnPageInfo^.DPI.y := GetDeviceCaps(dc, LOGPIXELSY); except exit; end; result := TRUE; end; function ScaleToFitX(lpScaleInfo : PScaleInfo) : BOOL; stdcall; begin if ((lpScaleInfo = nil) OR (lpScaleInfo^.OriginalSize_X = 0)) then begin result := FALSE; exit; end; try lpScaleInfo^.ScaleFactor_X := lpScaleInfo^.ScaledSize_X / lpScaleInfo^.OriginalSize_X; lpScaleInfo^.ScaleFactor_Y := lpScaleInfo^.ScaleFactor_X; lpScaleInfo^.ScaledSize_Y := lpScaleInfo^.OriginalSize_Y * lpScaleInfo^.ScaleFactor_Y; except result := FALSE; exit; end; result := TRUE; end; function ScaleToFitY(lpScaleInfo : PScaleInfo) : BOOL; stdcall; begin if ((lpScaleInfo = nil) OR (lpScaleInfo^.OriginalSize_Y = 0)) then begin result := FALSE; exit; end; try lpScaleInfo^.ScaleFactor_Y := lpScaleInfo^.ScaledSize_Y / lpScaleInfo^.OriginalSize_Y; lpScaleInfo^.ScaleFactor_X := lpScaleInfo^.ScaleFactor_Y; lpScaleInfo^.ScaledSize_X := lpScaleInfo^.OriginalSize_X * lpScaleInfo^.ScaleFactor_Y; except result := FALSE; exit; end; result := TRUE; end; function ScaleToBestFit(lpScaleInfo : PScaleInfo) : BOOL; stdcall; begin if ((lpScaleInfo = nil) OR (lpScaleInfo^.OriginalSize_X = 0) OR (lpScaleInfo^.OriginalSize_Y = 0)) then begin result := FALSE; exit; end; try lpScaleInfo^.ScaleFactor_X := lpScaleInfo^.ScaledSize_X / lpScaleInfo^.OriginalSize_X; lpScaleInfo^.ScaleFactor_Y := lpScaleInfo^.ScaledSize_Y / lpScaleInfo^.OriginalSize_Y; if (lpScaleInfo^.ScaleFactor_X < lpScaleInfo^.ScaleFactor_Y) then begin lpScaleInfo^.ScaledSize_Y := lpScaleInfo^.OriginalSize_Y * lpScaleInfo^.ScaleFactor_X; end else begin lpScaleInfo^.ScaledSize_X := lpScaleInfo^.OriginalSize_X * lpScaleInfo^.ScaleFactor_Y; end; except result := FALSE; exit; end; result := TRUE; end; function GetPixelSizeInfo(dc : HDC; lpPixelSizeInfo : PPixelSizeInfo) : BOOL; stdcall; begin if (lpPixelSizeInfo = nil) then begin result := FALSE; exit; end; try if (dc = 0) then begin dc := GetDC(0); lpPixelSizeInfo^.DotsPerInch_X := GetDeviceCaps(dc, LOGPIXELSX); lpPixelSizeInfo^.DotsPerInch_Y := GetDeviceCaps(dc, LOGPIXELSY); ReleaseDc(0, dc); end else begin lpPixelSizeInfo^.DotsPerInch_X := GetDeviceCaps(dc, LOGPIXELSX); lpPixelSizeInfo^.DotsPerInch_Y := GetDeviceCaps(dc, LOGPIXELSY); end; lpPixelSizeInfo^.DotsPerMillimeter_X := lpPixelSizeInfo^.DotsPerInch_X / 25.4; lpPixelSizeInfo^.DotsPerMillimeter_Y := lpPixelSizeInfo^.DotsPerInch_Y / 25.4; lpPixelSizeInfo^.DotsPerPoint_X := lpPixelSizeInfo^.DotsPerInch_X / 72; lpPixelSizeInfo^.DotsPerPoint_Y := lpPixelSizeInfo^.DotsPerInch_Y / 72; except result := FALSE; exit; end; result := TRUE; end; function GetNumPagesRequired(PrinterPageSize : DWORD; ImageSize : DWORD) : DWORD; stdcall; begin if (PrinterPageSize = 0) then begin result := 0; exit; end; result := RoundWayUp(ImageSize / PrinterPageSize); end; {Allocates memory - zeros out block, returns null on failure} function GetMemEx(size : DWORD) : pointer; stdcall; begin try result := Pointer(GlobalAlloc(GPTR, size)); except result := nil; end; end; {Frees memory - returns null on success or returns pointer on failure} function FreeMemEx(p : pointer) : pointer; stdcall; begin try if (p = nil) then begin result := nil; end else begin result := Pointer(GlobalFree(THandle(p))); end; except result := nil; end; end; function LoadDIBFromStream(TheStream : TStream; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; var bmf : TBITMAPFILEHEADER; TheFileSize : integer; TheHeaderSize : integer; TheImageSize : integer; TheBitmapInfo : PBITMAPINFO; TheBitmapCoreInfo : PBITMAPCOREINFO; begin lpBitmapInfo := nil; lpBits := nil; BitmapWidth := 0; BitmapHeight := 0; if (TheStream = nil) then begin result := FALSE; exit; end; try TheFileSize := TheStream.Size - TheStream.Position; TheStream.ReadBuffer(bmf, sizeof(TBITMAPFILEHEADER)); except result := FALSE; exit; end; TheHeaderSize := bmf.bfOffBits - sizeof(TBITMAPFILEHEADER); TheImageSize := TheFileSize - integer(bmf.bfOffBits); if ((bmf.bfType <> $4D42) OR (integer(bmf.bfOffBits) < 1) OR (TheFileSize < 1) OR (TheHeaderSize < 1) OR (TheImageSize < 1) OR (TheFileSize < (sizeof(TBITMAPFILEHEADER) + TheHeaderSize + TheImageSize))) then begin result := FALSE; exit; end; try lpBitmapInfo := GetMemEx(TheHeaderSize); except lpBitmapInfo := nil; result := FALSE; exit; end; if (lpBitmapInfo = nil) then begin try FreeMemEx(lpBitmapInfo); except end; lpBitmapInfo := nil; result := FALSE; exit; end; try TheStream.ReadBuffer(lpBitmapInfo^, TheHeaderSize); except try FreeMemEx(lpBitmapInfo); except end; lpBitmapInfo := nil; result := FALSE; exit; end; try TheBitmapInfo := lpBitmapInfo; case (TheBitmapInfo^.bmiHeader.biSize) of sizeof(TBITMAPINFOHEADER) : begin BitmapWidth := TheBitmapInfo^.bmiHeader.biWidth; BitmapHeight := abs(TheBitmapInfo^.bmiHeader.biHeight); if (TheBitmapInfo^.bmiHeader.biSizeImage <> 0) then begin TheImageSize := TheBitmapInfo^.bmiHeader.biSizeImage; end else begin TheImageSize := (((((TheBitmapInfo^.bmiHeader.biWidth * TheBitmapInfo^.bmiHeader.biBitCount) + 31) AND NOT 31) div 8) * ABS(TheBitmapInfo^.bmiHeader.biHeight)); end; end; sizeof(TBITMAPCOREHEADER) : begin TheBitmapCoreInfo := PBITMAPCOREINFO(lpBitmapInfo); BitmapWidth := TheBitmapCoreInfo^.bmciHeader.bcWidth; BitmapHeight := TheBitmapCoreInfo^.bmciHeader.bcHeight; TheImageSize := (((((TheBitmapCoreInfo^.bmciHeader.bcWidth * TheBitmapCoreInfo^.bmciHeader.bcBitCount) + 31) AND NOT 31) div 8) * ABS(TheBitmapCoreInfo^.bmciHeader.bcHeight)); end; else begin try FreeMemEx(lpBitmapInfo); except end; lpBits := nil; lpBitmapInfo := nil; BitmapWidth := 0; BitmapHeight := 0; result := FALSE; exit; end; end; except try FreeMemEx(lpBitmapInfo); except end; lpBitmapInfo := nil; BitmapWidth := 0; BitmapHeight := 0; result := FALSE; exit; end; if ((BitmapWidth < 1) OR (BitmapHeight < 1) OR (TheImageSize < 32)) then begin try FreeMemEx(lpBitmapInfo); except end; lpBitmapInfo := nil; BitmapWidth := 0; BitmapHeight := 0; result := FALSE; exit; end; try lpBits := GetMemEx(TheImageSize); except try FreeMemEx(lpBitmapInfo); except end; lpBits := nil; lpBitmapInfo := nil; result := FALSE; exit; end; try TheStream.ReadBuffer(lpBits^, TheImageSize); except try FreeMemEx(lpBits); except end; try FreeMemEx(lpBitmapInfo); except end; lpBits := nil; lpBitmapInfo := nil; result := FALSE; exit; end; result := TRUE; end; function LoadDIBFromFile(const FileName : string; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; var TheFileStream : TFileStream; begin lpBitmapInfo := nil; lpBits := nil; BitmapWidth := 0; BitmapHeight := 0; try TheFileStream := TFileStream.Create(FileName, fmOpenRead OR fmShareDenyWrite); except result := FALSE; exit; end; if (TheFileStream = nil) then begin result := FALSE; exit; end; result := LoadDIBFromStream(TheFileStream, lpBitmapInfo, lpBits, BitmapWidth, BitmapHeight); try TheFileStream.Free; except end; end; function LoadDIBFromTBitmap(ABitmap : TBitmap; var lpBitmapInfo : pointer; var lpBits : Pointer; var BitmapWidth : integer; var BitmapHeight : integer) : BOOL; stdcall; var TheStream : TMemoryStream; begin lpBitmapInfo := nil; lpBits := nil; BitmapWidth := 0; BitmapHeight := 0; try TheStream := TMemoryStream.Create; except result := FALSE; exit; end; if (TheStream = nil) then begin result := FALSE; exit; end; try ABitmap.SaveToStream(TheStream); TheStream.Position := 0; except result := FALSE; exit; try TheStream.Free; except end; end; result := LoadDIBFromStream(TheStream, lpBitmapInfo, lpBits, BitmapWidth, BitmapHeight); try TheStream.Free; except end; end; function TAbortDialog.Aborted : BOOL; var Msg : TMsg; begin while (PeekMessage(Msg, Handle, 0, 0, PM_REMOVE)) do begin DispatchMessage(Msg); end; result := Canceled; end; procedure TAbortDialog.btnCancelClick(Sender: TObject); begin try Canceled := TRUE; except end; end; function CreateAbortDialog(ApplicationHandle : THandle; AOwner: TComponent) : TAbortDialog; stdcall; begin try Application.Handle := ApplicationHandle; result := TAbortDialog.Create(Aowner); result.Show; result.Aborted; except result := nil; end; end; procedure FreeAbortDialog(AbortDialog : TAbortDialog); stdcall; begin try AbortDialog.Free; except end; end; procedure AbortDialogSetCaption(AbortDialog : TAbortDialog; s : pChar); stdcall; begin try AbortDialog.Caption := s; AbortDialog.Aborted; except end; end; function AbortDialogUserHasCanceled(AbortDialog : TAbortDialog) : BOOL; stdcall; begin try result := AbortDialog.Aborted; except result := FALSE; end; end; {backwards compatible printer abort dialog functions} function CreatePrinterAbortDialog(ApplicationHandle : THandle; AOwner: TComponent) : TPrinterAbortDialog; stdcall; begin try result := CreateAbortDialog(ApplicationHandle, AOwner); except result := nil; end; end; procedure FreePrinterAbortDialog(AbortDialog : TPrinterAbortDialog); stdcall; begin try FreeAbortDialog(AbortDialog); except end; end; function PrinterAbortDialogAborted(AbortDialog : TPrinterAbortDialog) : BOOL; stdcall; begin try result := AbortDialogUserHasCanceled(AbortDialog); except result := FALSE; end; end; procedure PrinterAbortDialogSetCaption(AbortDialog : TPrinterAbortDialog; ACaption : pChar); stdcall; begin try AbortDialogSetCaption(AbortDialog, ACaption); except end; end; {$IFDEF PrnUtils_CKRANGE} {$UNDEF PrnUtils_CKRANGE} {$R+} {$ENDIF} {$IFDEF PrnUtils_CKOVERFLOW} {$UNDEF PrnUtils_CKOVERFLOW} {$Q+} {$ENDIF} end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit CrptGlobalTypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TCRPTDocumentFormat = (cdfManual, cdfUpd, cdfXml, cdfCsv); TCRPTDocumentFormats = set of TCRPTDocumentFormat; TDocumentDirection = (ddAll, ddInput, ddOutput); TDocumentType = ( AGGREGATION_DOCUMENT, AGGREGATION_DOCUMENT_CSV, AGGREGATION_DOCUMENT_XML, DISAGGREGATION_DOCUMENT, DISAGGREGATION_DOCUMENT_CSV, DISAGGREGATION_DOCUMENT_XML, REAGGREGATION_DOCUMENT, REAGGREGATION_DOCUMENT_XML, REAGGREGATION_DOCUMENT_CSV, LP_INTRODUCE_GOODS, LP_INTRODUCE_GOODS_CSV, LP_INTRODUCE_GOODS_XML, LP_SHIP_GOODS, LP_SHIP_GOODS_CSV, LP_SHIP_GOODS_XML, LP_SHIP_RECEIPT, LP_SHIP_RECEIPT_CSV, CSVLP_SHIP_RECEIPT_XML, LP_SHIP_GOODS_CROSSBORDER, LP_ACCEPT_GOODS, LP_ACCEPT_GOODS_XML, LK_REMARK, LK_REMARK_CSV, LK_REMARK_XML, LP_GOODS_IMPORT, LP_GOODS_IMPORT_CSV, LP_GOODS_IMPORT_XML, LP_CANCEL_SHIPMENT, LP_CANCEL_SHIPMENT_CROSSBORDER, LK_KM_CANCELLATION, LK_KM_CANCELLATION_XML, LK_KM_CANCELLATION_CSV, LK_APPLIED_KM_CANCELLATION, LK_APPLIED_KM_CANCELLATION_XML, LK_APPLIED_KM_CANCELLATION_CSV, LK_CONTRACT_COMMISSIONING, LK_CONTRACT_COMMISSIONING_CSV, LK_CONTRACT_COMMISSIONING_XML, LK_INDI_COMMISSIONING, LK_INDI_COMMISSIONING_CSV, LK_INDI_COMMISSIONING_XML, LP_RETURN, LP_RETURN_CSV, LP_RETURN_XML, OST_DESCRIPTION, OST_DESCRIPTION_CSV, OST_DESCRIPTION_XML, LP_INTRODUCE_OST, LP_INTRODUCE_OST_CSV, LP_INTRODUCE_OST_XML, CROSSBORDER, CROSSBORDER_CSV, CROSSBORDER_XML, LK_RECEIPT, LK_RECEIPT_CSV, LK_RECEIPT_XML, LP_INTRODUCE_GOODS_CROSSBORDER_CSD_JSON, LP_INTRODUCE_GOODS_CROSSBORDER_CSD_XML, LP_INTRODUCE_GOODS_CROSSBORDER_CSD_CSV, LP_FTS_INTRODUCE_JSON, LP_FTS_INTRODUCE_XML, LP_FTS_INTRODUCE_CSV, ATK_AGGREGATION, ATK_AGGREGATION_CSV, ATK_AGGREGATION_XML, ATK_TRANSFORMATION, ATK_TRANSFORMATION_CSV, ATK_TRANSFORMATION_XML, ATK_DISAGGREGATION, ATK_DISAGGREGATION_CSV, ATK_DISAGGREGATION_XML, RECEIPT, RECEIPT_RETURN, UNIVERSAL_TRANSFER_DOCUMENT, UNIVERSAL_TRANSFER_DOCUMENT_FIX, UNIVERSAL_CORRECTION_DOCUMENT, UNIVERSAL_CORRECTION_DOCUMENT_FIX, UNIVERSAL_CANCEL_DOCUMENT); TDocumentTypes = set of TDocumentType; TCISStatus = (CISStatusError = -1, EMITTED, APPLIED, INTRODUCED, WRITTEN_OFF, RETIRED, RESERVED_NOT_USED, INTRODUCED_RETURNED, DISAGGREGATED, WAIT_SHIPMENT, EXPORTED, LOAN_RETIRED, REMARK_RETIRED, APPLIED_NOT_PAID, FTS_RESPOND_NOT_OK, FTS_RESPOND_WAITING, FTS_CONTROL); TDocStatus = (UNDEFINED, IN_PROGRESS, CHECKED_OK, CHECKED_NOT_OK, PROCESSING_ERROR, CANCELLED, WAIT_ACCEPTANCE, WAIT_PARTICIPANT_REGISTRATION, WAIT_FOR_CONTINUATION, ACCEPTED); type TCrptDocListFilter = record DateFrom:TDateTime; DateTo:TDateTime; DocumentFormat:TCRPTDocumentFormats; Limit:Integer; DocumentTypes:TDocumentTypes; DocumentStatus:TDocStatus; ParticipantInn:string; DocumentDirection:TDocumentDirection; end; TCrptReceiptListLister = record //number DateFrom:TDateTime; DateTo:TDateTime; //participantInn //documentType //documentStatus //documentFormat //inputFormat //did Limit:Integer; //pageDir //order //orderColumn //orderedColumnValue //pg end; const DocStatusStr : array [TDocStatus] of string = ( 'UNDEFINED', 'IN_PROGRESS', 'CHECKED_OK', 'CHECKED_NOT_OK', 'PROCESSING_ERROR', 'CANCELLED', 'WAIT_ACCEPTANCE', 'WAIT_PARTICIPANT_REGISTRATION', 'WAIT_FOR_CONTINUATION', 'ACCEPTED'); DocumentTypeStr : array [TDocumentType] of string = ( 'AGGREGATION_DOCUMENT', 'AGGREGATION_DOCUMENT_CSV', 'AGGREGATION_DOCUMENT_XML', 'DISAGGREGATION_DOCUMENT', 'DISAGGREGATION_DOCUMENT_CSV', 'DISAGGREGATION_DOCUMENT_XML', 'REAGGREGATION_DOCUMENT', 'REAGGREGATION_DOCUMENT_XML', 'REAGGREGATION_DOCUMENT_CSV', 'LP_INTRODUCE_GOODS', 'LP_INTRODUCE_GOODS_CSV', 'LP_INTRODUCE_GOODS_XML', 'LP_SHIP_GOODS', 'LP_SHIP_GOODS_CSV', 'LP_SHIP_GOODS_XML', 'LP_SHIP_RECEIPT', 'LP_SHIP_RECEIPT_CSV', 'LP_SHIP_RECEIPT_XML', 'LP_SHIP_GOODS_CROSSBORDER', 'LP_ACCEPT_GOODS', 'LP_ACCEPT_GOODS_XML', 'LK_REMARK', 'LK_REMARK_CSV', 'LK_REMARK_XML', 'LP_GOODS_IMPORT', 'LP_GOODS_IMPORT_CSV', 'LP_GOODS_IMPORT_XML', 'LP_CANCEL_SHIPMENT', 'LP_CANCEL_SHIPMENT_CROSSBORDER', 'LK_KM_CANCELLATION', 'LK_KM_CANCELLATION_XML', 'LK_KM_CANCELLATION_CSV', 'LK_APPLIED_KM_CANCELLATION', 'LK_APPLIED_KM_CANCELLATION_XML', 'LK_APPLIED_KM_CANCELLATION_CSV', 'LK_CONTRACT_COMMISSIONING', 'LK_CONTRACT_COMMISSIONING_CSV', 'LK_CONTRACT_COMMISSIONING_XML', 'LK_INDI_COMMISSIONING', 'LK_INDI_COMMISSIONING_CSV', 'LK_INDI_COMMISSIONING_XML', 'LP_RETURN', 'LP_RETURN_CSV', 'LP_RETURN_XML', 'OST_DESCRIPTION', 'OST_DESCRIPTION_CSV', 'OST_DESCRIPTION_XML', 'LP_INTRODUCE_OST', 'LP_INTRODUCE_OST_CSV', 'LP_INTRODUCE_OST_XML', 'CROSSBORDER', 'CROSSBORDER_CSV', 'CROSSBORDER_XML', 'LK_RECEIPT', 'LK_RECEIPT_CSV', 'LK_RECEIPT_XML', 'LP_INTRODUCE_GOODS_CROSSBORDER_CSD_JSON', 'LP_INTRODUCE_GOODS_CROSSBORDER_CSD_XML', 'LP_INTRODUCE_GOODS_CROSSBORDER_CSD_CSV', 'LP_FTS_INTRODUCE_JSON', 'LP_FTS_INTRODUCE_XML', 'LP_FTS_INTRODUCE_CSV', 'ATK_AGGREGATION', 'ATK_AGGREGATION_CSV', 'ATK_AGGREGATION_XML', 'ATK_TRANSFORMATION', 'ATK_TRANSFORMATION_CSV', 'ATK_TRANSFORMATION_XML', 'ATK_DISAGGREGATION', 'ATK_DISAGGREGATION_CSV', 'ATK_DISAGGREGATION_XML', 'RECEIPT', 'RECEIPT_RETURN', 'UNIVERSAL_TRANSFER_DOCUMENT', 'UNIVERSAL_TRANSFER_DOCUMENT_FIX', 'UNIVERSAL_CORRECTION_DOCUMENT', 'UNIVERSAL_CORRECTION_DOCUMENT_FIX', 'UNIVERSAL_CANCEL_DOCUMENT' ); implementation end.
unit UCampeonato; interface type TCampeonatos = class private FId : Integer; FNome : String; FAno : Smallint; function getAno: Smallint; function getId: Integer; function getNome: String; procedure setAno(const Value: Smallint); procedure setId(const Value: Integer); procedure setNome(const Value: String); protected public property id : Integer read getId write setId; property nome : String read getNome write setNome; property ano : Smallint read getAno write setAno; procedure copyFromObject(campeonato : TCampeonatos); end; implementation { TCampeonatos } procedure TCampeonatos.copyFromObject(campeonato: TCampeonatos); begin Self.FId := campeonato.id; Self.FNome := campeonato.nome; Self.FAno :=campeonato.ano; end; function TCampeonatos.getAno: Smallint; begin Result:= FAno; end; function TCampeonatos.getId: Integer; begin Result:= FId; end; function TCampeonatos.getNome: String; begin Result:= FNome; end; procedure TCampeonatos.setAno(const Value: Smallint); begin Self.FAno:= Value; end; procedure TCampeonatos.setId(const Value: Integer); begin Self.FId:= Value; end; procedure TCampeonatos.setNome(const Value: String); begin Self.FNome:= Value; end; end.
{ File Name: AudioIO.PAS V 4.00 Created: 5-Oct-96 by John Mertus on the IBM PC Revision #1: 5-Oct-22 by John Mertus -John Mertus Version 1.00 Initial Release } { There are three Sound Components, the first is the base Component, TAudioIO. This defines the sampling rates, buffers and some of the common events. The second component is AudioOut, which started just loops playing out buffers. The third component is AudioIN, which, when started, just loops filling buffer with digital data. See AudioIO.Hlp for detailed explaination. } {-----------------Unit-AudioOut-------------------John Mertus---Oct 96---} Unit AudioIO; {*************************************************************************} Interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, MMSystem, UAFDefs; { Could make this dynamic, but the effort doesn't seem worth it. } Const MAXBUFFERS = 4; Type {TBuffer Event is what is called when a buffer is need or is full } TBufferEvent = Function(Buffer : pChar; Var Size : Integer) : Boolean of Object; PAudioIO = ^TAudioIO; PAudioOut = ^TAudioOut; PAudioIn = ^TAudioIn; TCallBackWinOut = Class(TWinControl) private { Private declarations } AudioComponent : PAudioOut; procedure BufferDone(var Msg: TMessage); message MM_WOM_DONE; procedure WaveOpen(var Msg: TMessage); message MM_WOM_OPEN; procedure WaveClose(var Msg: TMessage); message MM_WOM_CLOSE; protected { Protected declarations } public { Public declarations } published { Published declarations } End; TCallBackWinIn = Class(TWinControl) private { Private declarations } AudioComponent : PAudioIn; procedure BufferFinished(var Msg: TMessage); message MM_WIM_DATA; procedure WaveOpenIn(var Msg: TMessage); message MM_WIM_OPEN; procedure WaveCloseIn(var Msg: TMessage); message MM_WIM_CLOSE; End; {---------------------------TAudioIO Component-----------------------------} TAudioIO = class(TComponent) private { Private declarations } FBufferSize : Integer; { Actual buffer used } FRequestedBufferSize : Integer; { Buffer size requested } FNumBuffers : Integer; FPaused : Boolean; FWaveFmtEx : TWaveFormatEx; FonOpen : TNotifyEvent; FonClose : TNotifyEvent; FWaveDevice : Integer; hWaveHeader : Array [0..MAXBUFFERS-1] of THANDLE; WaveHdr : Array [0..MAXBUFFERS-1] of PWAVEHDR; WaveBuffer : Array [0..MAXBUFFERS-1] of lpstr; hWaveBuffer : Array [0..MAXBUFFERS-1] of THANDLE; BufIndex : Integer; ContinueProcessing : Boolean; { Set to TRUE to start FALSE to abort after filled buffers are done } { Property Functions } Procedure SetNumBuffers(Value : Integer); Procedure SetBufferSize(Value : Integer); Procedure SetFrameRate(Value : Integer); Procedure SetStereo(Value : Boolean); Procedure SetBits(Value : Word); Function GetFrameRate : Integer; Function GetStereo : Boolean; Procedure MakeWaveFmtConsistent; protected { Protected declarations } Function InitWaveHeaders : Boolean; Function AllocPCMBuffers : Boolean; Function FreePCMBuffers : Boolean; Function AllocWaveHeaders : Boolean; Procedure FreeWaveHeaders; public { Public declarations } ErrorMessage : String; Active : Boolean; FilledBuffers, QueuedBuffers, ProcessedBuffers : Integer; Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure StopAtOnce; Virtual; Procedure StopGracefully; Virtual; published { Published declarations } Property BufferSize : Integer read FBufferSize write SetBufferSize Default 8192; Property NumBuffers : Integer read FNumBuffers write SetNumBuffers Default 4; Property FrameRate : Integer read GetFrameRate Write SetFrameRate Default 22055; Property Stereo : Boolean read GetStereo Write SetStereo Default False; Property Quantization : Word Read FWaveFmtEx.wBitsPerSample Write SetBits Default 16; Property WaveDevice : Integer Read FWaveDevice Write FWaveDevice Default WAVE_MAPPER; Property OnStart : TNotifyEvent Read FOnOpen Write FOnOpen; Property OnStop : TNotifyEvent Read FOnClose Write FOnClose; end; {---------------------------TAudioOut Component-----------------------------} TAudioOut = Class(TAudioIO) private { Private declarations } WaveDeviceOpen : Boolean; CallBackWin : TCallBackWinOut; FOnFillBuffer : TBufferEvent; Function QueueBuffer : Boolean; Function ReadBuffer(Idx, N : Integer) : Boolean; Virtual; Procedure SetPaused(Value : Boolean); Procedure CloseWaveDevice; Virtual; Function Setup(Var TS: TAudioOut) : Boolean; Virtual; Function StartIt : Boolean; protected { Protected declarations } public { Public declarations } WaveHandle : HWaveOut; { Waveform output handle } Function Start(Var TS : TAudioOut) : Boolean; Procedure StopAtOnce; Override; Procedure StopGracefully; Override; Function ElapsedTime : Real; published { Published declarations } Property Paused : Boolean Read FPaused Write SetPaused Default FALSE; Property OnFillBuffer : TBufferEvent Read FOnFillBuffer Write FOnFillBuffer; End; {---------------------------TAudioIn Component-----------------------------} TAudioIn = Class(TAudioIO) private { Private declarations } WaveDeviceOpen : Boolean; CallBackWin : TCallBackWinIn; FOnBufferFilled : TBufferEvent; Function QueueBuffer : Boolean; Function ProcessBuffer(B : lpstr; N : Integer) : Boolean; Virtual; Procedure CloseWaveDevice; Virtual; Function Setup(Var TS: TAudioIn) : Boolean; Virtual; Function StartIt : Boolean; protected { Protected declarations } public { Public declarations } WaveHandle : HWaveOut; { Waveform output handle } Function Start(Var TS : TAudioIn) : Boolean; Procedure StopAtOnce; Override; Procedure StopGracefully; Override; Function ElapsedTime : Real; published { Published declarations } Property OnBufferFilled : TBufferEvent Read FOnBufferFilled Write FOnBufferFilled; End; procedure Register; {*************************************************************************} implementation {$R *.res} {---------------TWaveOutGetErrorText------------John Mertus Oct 96---} Function TWaveOutGetErrorText(iErr : Integer) : String; { This just gets the error text assocated with the output error ierr. } { } {**********************************************************************} Var ErrorMsgC : Array [0..255] of Char; BEGIN waveOutGetErrorText(iErr,ErrorMsgC,Sizeof(ErrorMsgC)); Result := StrPas(ErrorMsgC); END; {---------------TWaveInGetErrorText------------John Mertus Oct 96---} Function TWaveInGetErrorText(iErr : Integer) : String; { This just gets the error text assocated with the output error ierr. } { } {**********************************************************************} Var ErrorMsgC : Array [0..255] of Char; BEGIN waveInGetErrorText(iErr,ErrorMsgC,Sizeof(ErrorMsgC)); Result := StrPas(ErrorMsgC); END; procedure Register; begin RegisterComponents('Sound', [TAudioOut, TAudioIn]); end; {---------------SetBufferSize-------------------John Mertus Oct 96---} Procedure TAudioIO.SetBufferSize(Value : Integer); { This just set the buffersize, making sure it is too small. } { } {**********************************************************************} BEGIN If (Value < 512) Then Value := 512; { make the wave buffer size a multiple of the block align... } FRequestedBufferSize := Value; MakeWaveFmtConsistent; FreePCMBuffers; AllocPCMBuffers; END; {---------------SetNumBuffers-------------------John Mertus Oct 96---} Procedure TAudioIO.SetNumBuffers(Value : Integer); { This just set the numbers of buffers making sure it is between } { and MaxNumberBuffers } { } {**********************************************************************} BEGIN If (Value < 2) Then Value := 2; If (Value > MAXBUFFERS) Then Value := MAXBUFFERS; FNumBuffers := Value; END; {---------------SetStereo-----------------------John Mertus Oct 96---} Procedure TAudioIO.SetStereo(Value : Boolean); { This just set the numbers of channels, True 2, false 1. } { } {**********************************************************************} BEGIN If Value Then FWaveFmtEx.nChannels := 2 Else FWaveFmtEx.nChannels := 1; MakeWaveFmtConsistent; END; {---------------SetBits-------------------------John Mertus Oct 96---} Procedure TAudioIO.SetBits(Value : Word); { This just set the numbers of buffers making sure it is between } { and MaxNumberBuffers } { } {**********************************************************************} BEGIN If (Value < 8) Then Value := 8; If (Value > 8) Then Value := 16; FWaveFmtEx.wBitsPerSample := Value; MakeWaveFmtConsistent; END; {---------------SetFrameRate--------------------John Mertus Oct 96---} Procedure TAudioIO.SetFrameRate(Value : Integer); { This just set the frame rate for sampling. } { } {**********************************************************************} BEGIN FWaveFmtEx.nSamplesPerSec := Value; MakeWaveFmtConsistent; END; {---------------GetFrameRate--------------------John Mertus Oct 96---} Function TAudioIO.GetFrameRate : Integer; { This just returns the framerate for the current header. } { } {**********************************************************************} BEGIN Result := FWaveFmtEx.nSamplesPerSec; END; {---------------GetStereo-----------------------John Mertus Oct 96---} Function TAudioIO.GetStereo : Boolean; { This just returns the True if stereo, e.g. 2 channels } { } {**********************************************************************} BEGIN Result := (FWaveFmtEx.nChannels = 2); END; {-----------------Create------------------------John Mertus Oct 96---} Constructor TAudioIO.Create(AOwner: TComponent); { This just set the numbers of buffers making sure it is between } { and MaxNumberBuffers } { } {**********************************************************************} Var i : Integer; BEGIN Inherited Create(AOwner); FNumBuffers := 4; FRequestedBufferSize := 8192; Active := FALSE; FPaused := FALSE; FWaveDevice := WAVE_MAPPER; ErrorMessage := ''; { Set the indendent sampling rates } FWaveFmtEx.wFormatTag := WAVE_FORMAT_PCM; FWaveFmtEx.wBitsPerSample := 16; FWaveFmtEx.nchannels := 1; FWaveFmtEx.nSamplesPerSec := 22050; MakeWaveFmtConsistent; { Now make sure we know buffers are not allocated } For i := 0 to MAXBUFFERS-1 Do WaveBuffer[i] := Nil; AllocWaveHeaders; AllocPCMBuffers; END; {-----------------Destroy-----------------------John Mertus Oct 96---} Destructor TAudioIO.Destroy; { This cleans up the buffers. } { } {**********************************************************************} BEGIN FreePCMBuffers; FreeWaveHeaders; Inherited Destroy; END; {-----------------MakeWaveFmtConsistent---------John Mertus Oct 96---} Procedure TAudioIO.MakeWaveFmtConsistent; { This just trys to find the correct avgbytes and blockalign that } { one needs to use for the format. I DO NOT UNDERSTAND WHY MICROSOFT } { did this. } { } {**********************************************************************} BEGIN With FWaveFmtEx Do Begin nBlockAlign := (wBitsPerSample div 8)*nchannels; nAvgBytesPerSec := nSamplesPerSec*nBlockAlign; End; FBufferSize := FRequestedBufferSize - (FRequestedBufferSize mod FWaveFmtEx.nBlockAlign); END; {-------------InitWaveHeaders----------------John Mertus---14-June--97--} Function TAudioIO.InitWaveHeaders : Boolean; { This just initalizes the waveform headers, no memory allocated } { } {**********************************************************************} Var i : Integer; BEGIN { This should not be necessary, but to be safe... } MakeWaveFmtConsistent; { Set the wave headers } For i := 0 to FNumBuffers-1 Do With WaveHdr[i]^ Do Begin lpData := WaveBuffer[i]; // address of the waveform buffer dwBufferLength := FBufferSize; // length, in bytes, of the buffer dwBytesRecorded := 0; // see below dwUser := 0; // 32 bits of user data dwFlags := 0; // see below dwLoops := 0; // see below lpNext := Nil; // reserved; must be zero reserved := 0; // reserved; must be zero End; InitWaveHeaders := TRUE; END; {-------------AllocPCMBuffers----------------John Mertus---14-June--97--} Function TAudioIO.AllocPCMBuffers : Boolean; { Allocate and lock the waveform memory. } { } {***********************************************************************} Var i : Integer; BEGIN For i := 0 to fNumBuffers-1 Do begin hWaveBuffer[i] := GlobalAlloc( GMEM_MOVEABLE or GMEM_SHARE, fBufferSize ); If (hWaveBuffer[i] = 0) Then begin FreePCMBuffers; ErrorMessage := 'Error allocating wave buffer memory'; AllocPCMBuffers := False; Exit; end; WaveBuffer[i] := GlobalLock(hWaveBuffer[i]); If (WaveBuffer[i] = Nil) Then begin FreePCMBuffers; ErrorMessage := 'Error Locking wave buffer memory'; AllocPCMBuffers := False; Exit; end; WaveHdr[i].lpData := WaveBuffer[i]; End; AllocPCMBuffers := TRUE; END; {--------------FreePCMBuffers----------------John Mertus---14-June--97--} Function TAudioIO.FreePCMBuffers : Boolean; { Free up the meomry AllocPCMBuffers used. } { } {***********************************************************************} Var i : Integer; BEGIN Result := FALSE; For i := 0 to MaxBuffers-1 Do begin If (hWaveBuffer[i] <> 0) Then Begin GlobalUnlock(hWaveBuffer[i] ); GlobalFree(hWaveBuffer[i] ); hWaveBuffer[i] := 0; WaveBuffer[i] := Nil; Result := TRUE; End; end; END; {-------------AllocWaveHeaders---------------John Mertus---14-June--97--} Function TAudioIO.AllocWaveHeaders : Boolean; { Allocate and lock header memory } { } {***********************************************************************} Var i : Integer; BEGIN For i := 0 to MAXBUFFERS-1 Do begin hwaveheader[i] := GlobalAlloc( GMEM_MOVEABLE or GMEM_SHARE or GMEM_ZEROINIT, sizeof(TWAVEHDR)); if (hwaveheader[i] = 0) Then begin FreeWaveHeaders; ErrorMessage := 'Error allocating wave header memory'; AllocWaveHeaders := FALSE; Exit; end; WaveHdr[i] := GlobalLock (hwaveheader[i]); If (WaveHdr[i] = Nil ) Then begin FreeWaveHeaders; ErrorMessage := 'Could not lock header memory for recording'; AllocWaveHeaders := FALSE; Exit; end; End; AllocWaveHeaders := TRUE; END; {---------------FreeWaveHeaders---------------John Mertus---14-June--97--} Procedure TAudioIO.FreeWaveHeaders; { Just free up the memory AllocWaveHeaders allocated. } { } {***********************************************************************} Var i : Integer; BEGIN For i := 0 to MAXBUFFERS-1 Do begin If (hWaveHeader[i] <> 0) Then Begin GlobalUnlock(hwaveheader[i]); GlobalFree(hwaveheader[i]); hWaveHeader[i] := 0; WaveHdr[i] := Nil; End end; END; {--------------------StopAtOnce-------------John Mertus---14-June--97--} Procedure TAudioIO.StopAtOnce; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN Active := False; ContinueProcessing := FALSE; END; {--------------------StopGracefully---------John Mertus---14-June--97--} Procedure TAudioIO.StopGracefully; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN ContinueProcessing := FALSE; END; {-----------------ElapsedTime----------------John Mertus---14-June--97--} Function TAudioOut.ElapsedTime : Real; { This function returns the time since start of playout. } { } {**********************************************************************} Var pmmt : TMMTime; BEGIN If (Active) Then Begin pmmt.wType := TIME_SAMPLES; If (waveOutGetPosition(WaveHandle, @pmmt, Sizeof(TMMTime)) <> 0) Then Result := 0 Else Result := pmmt.Sample/FrameRate; End Else Result := 0; END; {---------------SetPaused-----------------------John Mertus Oct 96---} Procedure TAudioOut.SetPaused(Value : Boolean); { This pauses or restarts the output. } { } {**********************************************************************} BEGIN FPaused := Value; If (Not Active) Then Exit; If FPaused Then WaveOutPause(WaveHandle) Else WaveOutReStart(WaveHandle); END; {-------------CloseWaveDevice----------------John Mertus---14-June--97--} Procedure TAudioOut.CloseWaveDevice; { Closes the wave output device. } { } {**********************************************************************} Var i : Integer; BEGIN { unprepare the headers } Active := FALSE; Paused := FALSE; For i := 0 to FNumBuffers-1 Do waveOutUnprepareHeader( WaveHandle, WaveHdr[i], sizeof(TWAVEHDR)); { close the device } waveOutClose(WaveHandle); WaveDeviceOpen := FALSE; END; {-------------SetupOutput--------------------John Mertus---14-June--97--} Function TAudioOut.Setup(Var TS : TAudioOut) : Boolean; { This function just sets up the board for output. } { } {**********************************************************************} Var iErr : Integer; i : Integer; BEGIN { if the device is still open, return error } If (WaveDeviceOpen) Then Begin ErrorMessage := 'Wave output device is already open'; Result := FALSE; Exit; End; BufIndex := 0; { Now create the window component to handle the processing } CallBackWin := TCallBackWinOut.CreateParented(TWinControl(Owner).Handle); CallBackWin.Visible := FALSE; CallBackWin.AudioComponent := @TS; { Open the device for playout } { Either go via interrupt or window } iErr := WaveOutOpen(@WaveHandle, FWaveDevice, @FWaveFmtEx, Integer(CallBackWin.Handle), 0, CALLBACK_WINDOW or WAVE_ALLOWSYNC ); If (iErr <> 0) Then Begin ErrorMessage := TWaveOutGetErrorText(iErr); Result := FALSE; Exit; End; WaveDeviceOpen := TRUE; { Setup the buffers and headers } If (Not InitWaveHeaders) Then Begin Result := FALSE; Exit; End; { Now Prepare the buffers for output } For i := 0 to FNumBuffers-1 Do Begin iErr := WaveOutPrepareHeader(WaveHandle, WaveHdr[i], sizeof(TWAVEHDR)); If (iErr <> 0) Then Begin ErrorMessage := TWaveOutGetErrorText(iErr); CloseWaveDevice; Result := FALSE; Exit; End; End; { Read in the buffers } QueuedBuffers := 0; ProcessedBuffers := 0; FilledBuffers := 0; ContinueProcessing := TRUE; Active := TRUE; If (Not ReadBuffer(0, FBufferSize)) Then Begin CloseWaveDevice; ErrorMessage := 'There must be at least one filled buffer'; Result := FALSE; Exit; End; For i := 1 to FNumBuffers - 1 Do ReadBuffer(i, FBufferSize); Result := TRUE; END; {----------------QueueBuffer----------------John Mertus---14-June--97--} Function TAudioOut.QueueBuffer : Boolean; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} Var iErr : Integer; BEGIN { reset flags field (remove WHDR_DONE attribute) } WaveHdr[bufindex].dwFlags := WHDR_PREPARED; { now queue the buffer for output } iErr := waveOutWrite( WaveHandle, WaveHdr[bufindex], sizeof(TWAVEHDR)); If (iErr <> 0) Then Begin ErrorMessage := TwaveOutGetErrorText(iErr); StopGracefully; Result := FALSE; Exit; End; { Advance index } bufindex := (bufindex+1) mod FNumBuffers; Result := TRUE; END; {-------------StartIt------------------------John Mertus---14-June--97--} Function TAudioOut.StartIt : Boolean; { This function just starts the waveform playing } { } {**********************************************************************} Var i : Integer; BEGIN Active := TRUE; If (FPaused) Then WaveOutPause(WaveHandle); { Now we are ready to start the output } If (Not QueueBuffer) Then Begin CloseWaveDevice; Result := FALSE; Exit; End; For i := 0 to FNumBuffers - 2 Do QueueBuffer; Result := TRUE; END; {-----------------Start----------------------John Mertus---14-June--97--} Function TAudioOut.Start(Var TS : TAudioOut) : Boolean; { This function first sets up the output and then starts it. } { } {**********************************************************************} BEGIN Result := Setup(TS); If (Not Result) Then Exit; Result := StartIt; If (Not Result) Then Exit; END; {-------------ReadBuffer---------------------John Mertus---14-June--97--} Function TAudioOut.ReadBuffer(Idx, N : Integer) : Boolean; { This is called whenver move buffer data is needed. } { } {**********************************************************************} Var NSize : Integer; BEGIN { Do not call the read buffer routine if we want to stop } If (Not ContinueProcessing) Then Begin Result := FALSE; Exit; End; { If assigned, process the buffer, Notice that the Size returned may not be the size sent, so reset the output size } If Assigned(FOnFillBuffer) Then Begin NSize := N; Result := FOnFillBuffer(WaveBuffer[idx], NSize); WaveHdr[idx].dwBufferLength := NSize; End Else Result := FALSE; { On a filled buffer, increment it } If (Result) Then FilledBuffers := FilledBuffers + 1; QueuedBuffers := FilledBuffers - ProcessedBuffers; END; {--------------------StopAtOnce-------------John Mertus---14-June--97--} Procedure TAudioOut.StopAtOnce; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN { if the device isn't open, just return } If (Not WaveDeviceOpen) Then Exit; Active := False; ContinueProcessing := FALSE; { stop playing } waveOutReset(WaveHandle); { close the device and unprepare the headers } CloseWaveDevice; END; {--------------------StopGracefully---------John Mertus---14-June--97--} Procedure TAudioOut.StopGracefully; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN { if the device isn't open, just return } If (Not WaveDeviceOpen) Then Exit; ContinueProcessing := FALSE; END; {------------------BufferDone---------------John Mertus---14-June--97--} Procedure TCallBackWinOut.BufferDone(Var Msg : TMessage); { This is called when a buffer si done playing } { } {**********************************************************************} BEGIN With AudioComponent^ Do Begin ProcessedBuffers := ProcessedBuffers + 1; QueuedBuffers := FilledBuffers - ProcessedBuffers; Active := (QueuedBuffers > 0); If (ReadBuffer(BufIndex, FBufferSize)) Then QueueBuffer; If (Not Active) then Begin ContinueProcessing := FALSE; CloseWaveDevice; End; End; END; {------------------WaveOpen-----------------John Mertus---14-June--97--} Procedure TCallBackWinOut.WaveOpen(Var Msg : TMessage); { This is called at the termination of each buffer. } { } {**********************************************************************} BEGIN If Assigned(AudioComponent.FonOpen) Then AudioComponent.FonOpen(Self); END; {------------------WaveClose----------------John Mertus---14-June--97--} Procedure TCallBackWinOut.WaveClose(Var Msg : TMessage); { This is called at the termination of each buffer. } { } {**********************************************************************} BEGIN If Assigned(AudioComponent.FonClose) Then AudioComponent.FonClose(Self); END; {-----------------ElapsedTime----------------John Mertus---14-June--97--} Function TAudioIn.ElapsedTime : Real; { This function returns the time since start of playout. } { } {**********************************************************************} Var pmmt : TMMTime; BEGIN If (Active) Then Begin pmmt.wType := TIME_SAMPLES; If (waveInGetPosition(WaveHandle, @pmmt, Sizeof(TMMTime)) <> 0) Then Result := 0 Else Result := pmmt.sample/FrameRate; End Else Result := 0; END; {-------------CloseWaveDevice----------------John Mertus---14-June--97--} Procedure TAudioIn.CloseWaveDevice; { Closes the wave output device. } { } {**********************************************************************} Var i : Integer; BEGIN { unprepare the headers } Active := FALSE; For i := 0 to FNumBuffers-1 Do waveInUnprepareHeader( WaveHandle, WaveHdr[i], sizeof(TWAVEHDR)); { close the device } waveInReset(WaveHandle); waveInClose(WaveHandle); WaveDeviceOpen := FALSE; END; {-------------SetupOutput--------------------John Mertus---14-June--97--} Function TAudioIn.Setup(Var TS : TAudioIn) : Boolean; { This function just sets up the board for output. } { } {**********************************************************************} Var iErr : Integer; i : Integer; BEGIN { if the device is still open, return error } If (WaveDeviceOpen) Then Begin ErrorMessage := 'Wave Input device is already open'; Result := FALSE; Exit; End; BufIndex := 0; { Now create the window component to handle the processing } CallBackWin := TCallBackWinIn.CreateParented(TWinControl(Owner).Handle); CallBackWin.Visible := FALSE; CallBackWin.AudioComponent := @TS; { Open the device for playout } { Either go via interrupt or window } iErr := WaveInOpen(@WaveHandle, FWaveDevice, @FWaveFmtEx, Integer(CallBackWin.Handle), 0, CALLBACK_WINDOW or WAVE_ALLOWSYNC ); If (iErr <> 0) Then Begin ErrorMessage := TWaveInGetErrorText(iErr); Result := FALSE; Exit; End; WaveDeviceOpen := TRUE; { Setup the buffers and headers } If (Not InitWaveHeaders) Then Begin Result := FALSE; Exit; End; { Now Prepare the buffers for output } For i := 0 to FNumBuffers-1 Do Begin iErr := WaveInPrepareHeader(WaveHandle, WaveHdr[i], sizeof(TWAVEHDR)); If (iErr <> 0) Then Begin ErrorMessage := TWaveInGetErrorText(iErr); CloseWaveDevice; Result := FALSE; Exit; End; End; { Read in the buffers } QueuedBuffers := 0; ProcessedBuffers := 0; FilledBuffers := 0; ContinueProcessing := TRUE; Active := TRUE; Result := TRUE; END; {----------------QueueBuffer----------------John Mertus---14-June--97--} Function TAudioIn.QueueBuffer : Boolean; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} Var iErr : Integer; BEGIN { reset flags field (remove WHDR_DONE attribute) } WaveHdr[bufindex].dwFlags := WHDR_PREPARED; { now queue the buffer for output } iErr := waveInAddBuffer( WaveHandle, WaveHdr[bufindex], sizeof(TWAVEHDR)); If (iErr <> 0) Then Begin ErrorMessage := TWaveInGetErrorText(iErr); StopGracefully; Result := FALSE; Exit; End; { Advance index } bufindex := (bufindex+1) mod FNumBuffers; QueuedBuffers := QueuedBuffers + 1; Result := TRUE; END; {-------------StartIt------------------------John Mertus---14-June--97--} Function TAudioIn.StartIt : Boolean; { This function just starts the waveform playing } { } {**********************************************************************} Var i, iErr : Integer; BEGIN { start recording to first buffer } iErr := WaveInStart(WaveHandle); If (iErr <> 0) Then begin CloseWaveDevice; ErrorMessage := 'Error starting wave record: ' + TWaveInGetErrorText(iErr); Result := FALSE; Exit; end; Active := TRUE; { Now we are ready to start the output } For i := 0 to FNumBuffers - 1 Do If (Not QueueBuffer) Then Begin CloseWaveDevice; Result := FALSE; Exit; End; Result := TRUE; END; {-----------------Start----------------------John Mertus---14-June--97--} Function TAudioIn.Start(Var TS : TAudioIn) : Boolean; { This function first sets up the output and then starts it. } { } {**********************************************************************} BEGIN Result := Setup(TS); If (Not Result) Then Exit; Result := StartIt; If (Not Result) Then Exit; END; {-----------ProcessBuffer---------------------John Mertus---14-June--97--} Function TAudioIn.ProcessBuffer(B : lpstr; N : Integer) : Boolean; { This is called whenver move buffer data is needed. } { } {**********************************************************************} BEGIN { Do not call the read buffer routine if we want to stop } If (Not ContinueProcessing) Then Begin Result := FALSE; Exit; End; { N can change, but we dont' care } If Assigned(FOnBufferFilled) Then Begin Result := FOnBufferFilled(B, N); End Else Result := TRUE; { On a filled buffer, increment it } If (Result) Then FilledBuffers := FilledBuffers + 1; END; {--------------------StopAtOnce-------------John Mertus---14-June--97--} Procedure TAudioIn.StopAtOnce; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN { if the device isn't open, just return } If (Not WaveDeviceOpen) Then Exit; Active := False; ContinueProcessing := FALSE; { stop playing } waveInReset(WaveHandle); { close the device and unprepare the headers } CloseWaveDevice; END; {--------------------StopGracefully---------John Mertus---14-June--97--} Procedure TAudioIn.StopGracefully; { Write the buffer to the wave device and toggel buffer index. } { } {**********************************************************************} BEGIN { if the device isn't open, just return } If (Not WaveDeviceOpen) Then Exit; ContinueProcessing := FALSE; END; {------------------BufferFinished-----------John Mertus---14-June--97--} Procedure TCallBackWinIn.BufferFinished(Var Msg : TMessage); { This is called when each buffer is filled. } { } {**********************************************************************} BEGIN With AudioComponent^ Do Begin ProcessedBuffers := ProcessedBuffers + 1; QueuedBuffers := QueuedBuffers - 1; Active := (QueuedBuffers > 0); If (ProcessBuffer(WaveBuffer[BufIndex], FBufferSize)) Then QueueBuffer; If (Not Active) then Begin ContinueProcessing := FALSE; CloseWaveDevice; End; End; END; {------------------WaveOpenIn---------------John Mertus---14-June--97--} Procedure TCallBackWinIn.WaveOpenIn(Var Msg : TMessage); { This is called at the termination of each buffer. } { } {**********************************************************************} BEGIN If Assigned(AudioComponent.FonOpen) Then AudioComponent.FonOpen(Self); END; {------------------WaveCloseIn----------------John Mertus---14-June--97--} Procedure TCallBackWinIn.WaveCloseIn(Var Msg : TMessage); { This is called at the termination of each buffer. } { } {**********************************************************************} BEGIN If Assigned(AudioComponent.FonClose) Then AudioComponent.FonClose(Self); END; End.
unit main; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QActnList, QImgList, QExtCtrls, QComCtrls, QStdCtrls, QStdActns, QMenus, QTypes, About; type TForm1 = class(TForm) Memo1: TMemo; StatusBar1: TStatusBar; ActionList1: TActionList; ImageList1: TImageList; FileNew: TAction; FileOpen: TAction; FileSave: TAction; FileSaveAs: TAction; FileExit: TAction; HelpAbout: TAction; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; MainMenu1: TMainMenu; File1: TMenuItem; About1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; SaveAs1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; Edit1: TMenuItem; Cut1: TMenuItem; Copy1: TMenuItem; Paste1: TMenuItem; Help1: TMenuItem; About2: TMenuItem; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; procedure FileNewExecute(Sender: TObject); procedure FileOpenExecute(Sender: TObject); procedure FileSaveExecute(Sender: TObject); procedure FileSaveAsExecute(Sender: TObject); procedure FileExitExecute(Sender: TObject); procedure HelpAboutExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } FileName: string; end; var Form1: TForm1; implementation {$R *.xfm} procedure TForm1.FileNewExecute(Sender: TObject); begin Memo1.Clear; FileName := 'untitled.txt'; StatusBar1.Panels[0].Text := FileName; end; procedure TForm1.FileOpenExecute(Sender: TObject); begin if OpenDialog1.Execute then begin Memo1.Lines.LoadFromFile(OpenDialog1.FileName); FileName := OpenDialog1.FileName; StatusBar1.Panels[0].Text := FileName; end; end; procedure TForm1.FileSaveExecute(Sender: TObject); begin if (FileName = 'untitled.txt') then FileSaveAsExecute(nil) else Memo1.Lines.SaveToFile(FileName); end; procedure TForm1.FileSaveAsExecute(Sender: TObject); begin SaveDialog1.FileName := FileName; SaveDialog1.InitialDir := ExtractFilePath(FileName); if SaveDialog1.Execute then begin Memo1.Lines.SaveToFile(SaveDialog1.FileName); FileName := SaveDialog1.FileName; StatusBar1.Panels[0].Text := FileName; end; end; procedure TForm1.FileExitExecute(Sender: TObject); begin Close; end; procedure TForm1.HelpAboutExecute(Sender: TObject); begin AboutBox.ShowModal; end; procedure TForm1.FormCreate(Sender: TObject); begin FileName := 'untitled.txt'; StatusBar1.Panels[0].Text := FileName; Memo1.Clear; end; end.
{************************************************** llPDFLib Version 6.4.0.1389, 09.07.2016 Copyright (c) 2002-2016 Sybrex Systems Copyright (c) 2002-2016 Vadim M. Shakun All rights reserved mailto:em-info@sybrex.com **************************************************} unit llPDFMisc; {$i pdf.inc} interface uses {$ifndef USENAMESPACE} Windows, SysUtils, Classes, Graphics, {$else} WinAPI.Windows, System.SysUtils, System.Classes, Vcl.Graphics, {$endif} llPDFTypes; const MLS = MaxInt div 16; type TTextCTM = record a, b, c, d, x, y: Extended; end; PExt = ^Single; TSingleArray = array [ 0..$FFFF ] of Single; PSingleArray = ^TSingleArray; TDoublePoint = record x, y: Extended; end; function IntToStrWithZero ( ID, Count: Integer ): AnsiString; function DPoint ( x, y: Extended ): TDoublePoint; function FormatFloat ( Value: Extended; Quality:Boolean = false ): AnsiString; procedure RotateCoordinate ( X, Y, Angle: Extended; var XO, YO: Extended ); procedure NormalizeRect ( var Rect: TRect ); overload; procedure NormalizeRect ( var x1, y1, x2, y2: integer ); overload; procedure NormalizeRect ( var x1, y1, x2, y2: Extended ); overload; procedure QuickSortArray ( var Arr: array of Word ); procedure swp ( var A, B: Integer ); overload; procedure swp ( var A, B: Extended ); overload; function CharSetToCodePage ( Charset: Byte ): Integer; function EscapeSpecialChar ( TextStr: AnsiString ): AnsiString; function StringToHex(TextStr:AnsiString;WithPrefix:Boolean = True):AnsiString; procedure FlipBMP(BMP:TBitmap;FlipX, FlipY:Boolean); function IsTrueType(FontName: String; Charset: Byte): Boolean; function GetFontByCharset ( Charset: Byte ): AnsiString; function ByteToANSIUNICODE ( B: Byte ): Word; function IsANSICode ( UNICODE: Word ): Boolean; function ANSIUNICODEToByte ( Unicode: Word ): Byte; function StrToOctet ( st: string ): string; function ByteToOct ( B: Byte ): string; function ByteToHex ( B: Byte ): AnsiString; function WordToHex ( W: Word ): AnsiString; function ReplStr ( Source: AnsiString; Ch: ANSIChar; Sub: AnsiString ): AnsiString; function UCase(const S: AnsiString): AnsiString; function LCase(const S: AnsiString): AnsiString; {$ifndef UNICODE} function UnicodeChar ( Text: string; Charset: Integer ): string; {$else} function UnicodeChar( Text:string):AnsiString; {$endif} function PrepareFileSpec ( FileName: TFileName ): AnsiString; function GMTNow: TDateTime; function LocaleToGMT(const Value: TDateTime): TDateTime; function InvertPDFColor(Color:TPDFColor):TPDFColor; function PDFColorToStr(Color:TPDFColor):AnsiString; function PosText ( const FindString, SourceString: AnsiString; StartPos: Integer ): Integer; function GetRef(ID: Integer): AnsiString; function RectToStr( Left, Bottom, Right, Top: Integer): AnsiString;overload; function RectToStr( Rect: TRect): AnsiString;overload; function IStr( I: Integer): AnsiString; function WideStringToUTF8(const S: WideString): AnsiString; function UTF8ToWideString(const S: UTF8String): WideString; function MakeWideString(P:Pointer;Len:Integer):WideString; function ByteSwap ( Value: Cardinal ): Cardinal; overload; function ByteSwap ( Value: Integer ): Cardinal; overload; function ByteSwap (Value: Int64): Int64; overload; function ROL (x: LongWord; n: LongWord): LongWord; function DataToHex(Buffer:Pointer;Len:Cardinal):AnsiString; procedure StrAddTruncAt(Source:AnsiString; var Destination: AnsiString; APos: Integer; IncVal: Byte = 0); type {$ifdef UNICODE} PAnsiStringItem = ^TAnsiStringItem; TAnsiStringItem = record FString: AnsiString; end; PAnsiStringItemList = ^TAnsiStringItemList; TAnsiStringItemList = array[0..MLS] of TAnsiStringItem; TAnsiStringList = class private FList: PAnsiStringItemList; FCount: Integer; FCapacity: Integer; FLineBreak: AnsiString; procedure Grow; procedure Error(const Msg: string; Data: Integer); overload; procedure Error(Msg: PResStringRec; Data: Integer); overload; procedure InsertItem(Index: Integer; const S: AnsiString); function GetTextStr: AnsiString; procedure SetTextStr(const Value: AnsiString); protected function Get(Index: Integer): AnsiString; function GetCapacity: Integer; function GetCount: Integer; procedure Put(Index: Integer; const S: AnsiString); procedure SetCapacity(NewCapacity: Integer); public constructor Create; destructor Destroy; override; function Add(const S: AnsiString): Integer; procedure Clear; procedure Insert(Index: Integer; const S: AnsiString); procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); property Strings[Index: Integer]: AnsiString read Get write Put; default; property Count: Integer read GetCount; property Text: AnsiString read GetTextStr write SetTextStr; property LineBreak: AnsiString read FLineBreak write FLineBreak; end; {$else} TAnsiStringList = TStringList; {$endif} TBitStream = class private FStream: TStream; FBuffer: Cardinal; FCurrentBit: Integer; public constructor Create(AStream:TStream); destructor Destroy;override; procedure Put(Value: Cardinal; Count: Integer); overload; procedure Put(Value: Int64; Count: Integer); overload; procedure Write(Buffer: Pointer; Count: Integer); procedure FlushBits; end; TObjList = class(TList) private FOwnsObjects: Boolean; protected function GetItem(Index: Integer): TObject; public procedure Clear;override; property Items[Index: Integer]: TObject read GetItem; default; constructor Create(AOwnsObjects: Boolean=True); end; function log32(x: Cardinal): Integer; function flp2(x:Cardinal):Cardinal; implementation uses llPDFDocument, llPDFResources {$ifdef RTLINC} {$ifndef W3264} ,RTLConsts {$else} ,System.RTLConsts {$endif} {$endif } ; const HEX: array [ 0..15 ] of ANSIChar= ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); function RectToStr( Left, Bottom, Right, Top: Integer): AnsiString; begin {$ifdef UNICODE} Result := AnsiString( Format('%d %d %d %d',[Left, Bottom, Right, Top])); {$else} Result := Format('%d %d %d %d',[Left, Bottom, Right, Top]); {$endif} end; function RectToStr( Rect: TRect): AnsiString; begin result := RectToStr(Rect.left,Rect.Bottom,Rect.right,Rect.Top) end; function IStr( I: Integer): AnsiString; begin {$ifdef UNICODE} Result := AnsiString( Format('%d',[i])); {$else} Result := Format('%d',[i]); {$endif} end; function MakeWideString(P:Pointer;Len:Integer):WideString; begin if len = 0 then begin Result :=''; exit; end; SetLength(Result,Len); move(P^,Result[1],Len shl 1); end; function ones32(x: Cardinal): Integer; begin x := x - ((x shr 1) and $55555555); x := (((x shr 2) and $33333333) + (x and $33333333)); x := (((x shr 4) + x) and $0f0f0f0f); x := x + (x shr 8); x := x + (x shr 16); result := x and $0000003f; end; function log32(x: Cardinal): Integer; begin x := x or (x shr 1); x := x or (x shr 2); x := x or (x shr 4); x := x or (x shr 8); x := x or (x shr 16); result := Ones32(x) - 1; end; function flp2(x:Cardinal):Cardinal; var i,S: Cardinal; begin i := 0; s := 1; while s <= x do begin i := s; s := s shl 1; end; result := i; end; function PosText ( const FindString, SourceString: AnsiString; StartPos: Integer ): Integer; var S:AnsiString; p:Integer; begin if StartPos= 1 then Result := Pos(FindString,SourceString) else begin S := Copy(SourceString,StartPos, Length(SourceString)); p := Pos(FindString,s); if p = 0 then Result := 0 else Result := p+StartPos-1; end; end; procedure StrAddTruncAt(Source:AnsiString; var Destination: AnsiString; APos: Integer; IncVal: Byte = 0); var I: Integer; W: Word; D, S: PByteArray; DL, SL: Integer; begin if Source <> '' then begin DL := Length(Destination); SL := Length(Source); if IncVal = 0 then begin if DL > APos then begin if DL >= SL + APos then Move(Source[1],Destination[1+APos],SL) else Move(Source[1],Destination[1+APos],DL - APos) end; end else begin if (APos < 0) or (DL < SL + APos) then raise Exception.Create('Invalid parameters. Access Violation'); D := @Destination[APos+1]; S := @Source[1]; W := IncVal; for I := SL - 1 downto 0 do begin W := D^[I] + S^[I] + W; D^[I] := Lo(W); W := Hi(W); end; end; end; end; function ByteToHex ( B: Byte ): AnsiString; begin Result := HEX [ b shr 4 ] + HEX [ b and $F ]; end; function DataToHex(Buffer:Pointer;Len:Cardinal):AnsiString; var I: Integer; B:PByte; begin SetLength(Result,Len shl 1); B := Buffer; for i:= 0 to Len - 1 do begin Result[(i shl 1)+1] := Hex[B^ shr 4]; Result[(i shl 1)+2] := Hex[B^ and $f]; inc(B); end; end; function ROL (x: LongWord; n: LongWord): LongWord; begin Result:= (x Shl n) Or (x Shr (32-n)) end; function ByteSwap ( Value: Integer): Cardinal; overload; begin Result := ByteSwap(Cardinal(Value)); end; {$ifdef CPUX64} function ByteSwap ( Value: Cardinal ): Cardinal; overload; begin Result:= ((Value and $FF) shl 24) or ((Value and $FF00) shl 8) or ((Value and $FF0000) shr 8) or ((Value and $FF000000) shr 24); end; function ByteSwap (Value: Int64): Int64; overload; begin Result := (Int64(byteSwap(LongWord(Value and $FFFFFFFF))) shl 32) or byteSwap(LongWord(Value shr 32)); end; {$else} function ByteSwap(Value: LongWord): Longword;overload; asm bswap EAX end; function ByteSwap(Value: Int64): Int64;overload; asm mov EAX,dword ptr [Value + 4] mov EDX,dword ptr [Value] bswap EAX bswap EDX end; {$endif} function InvertPDFColor(Color:TPDFColor):TPDFColor; begin Result.ColorSpace := Color.ColorSpace; Result.Cyan := 1 - Color.Cyan; Result.Magenta := 1 - Color.Magenta; Result.Yellow := 1 - Color.Yellow; Result.Key := 1 - Result.Key; end; function PDFColorToStr(Color:TPDFColor):AnsiString; begin case Color.ColorSpace of csGray: Result := FormatFloat(Color.Gray); csRGB: Result := FormatFloat(Color.Red)+' '+FormatFloat(Color.Green)+' '+FormatFloat(Color.Blue); else Result := FormatFloat(Color.Cyan)+' '+FormatFloat(Color.Magenta)+' '+FormatFloat(Color.Yellow)+' '+FormatFloat(Color.Key); end; end; function PrepareFileSpec ( FileName: TFileName ): AnsiString; var S: AnsiString; WS: AnsiString; FF: AnsiString; function RepS ( Source, Rep, RP: AnsiString ): AnsiString; var I, L: Integer; RS, S: AnsiString; begin S := Source; RS := ''; L := Length ( Rep ); I := Pos ( Rep, S ); while I <> 0 do begin RS := RS + Copy ( S, 1, I - 1 ) + RP; Delete ( S, 1, L + I - 1 ); I := Pos ( Rep, S ); end; ; RS := RS + S; Result := RS; end; begin WS := AnsiString(ExtractFilePath ( FileName )); if WS = '' then begin Result := AnsiString(FileName); Exit; end; FF := AnsiString(ExtractFileDrive ( FileName )); if FF = '' then begin S := RepS ( AnsiString(FileName), '\', '/' ); if S [ 1 ] = '/' then S := '/' + S; Result := S; Exit; end; S := RepS ( AnsiString(FileName), '\\', '/' ); S := RepS ( S, ':\', '/' ); S := RepS ( S, '\', '/' ); S := RepS ( S, ':', '/' ); if S [ 1 ] <> '/' then S := '/' + S; Result := S; end; function GetGMTBias: Integer; var info: TTimeZoneInformation; Mode: DWord; begin Mode := GetTimeZoneInformation(info); Result := info.Bias; case Mode of TIME_ZONE_ID_STANDARD: Result := Result + info.StandardBias; TIME_ZONE_ID_DAYLIGHT: Result := Result + info.DaylightBias; end; end; function LocaleToGMT(const Value: TDateTime): TDateTime; const MinsPerDay = 24 * 60; begin Result := Value + (GetGMTBias / MinsPerDay); end; function GMTNow: TDateTime; begin Result := LocaleToGMT(Now); end; {$ifndef UNICODE} function UnicodeChar ( Text: string; Charset: Integer ): string; var A: array of Word; W: PWideChar; CodePage: Integer; OS, i : Integer; begin Result := ''; case Charset of EASTEUROPE_CHARSET: CodePage := 1250; RUSSIAN_CHARSET: CodePage := 1251; GREEK_CHARSET: CodePage := 1253; TURKISH_CHARSET: CodePage := 1254; BALTIC_CHARSET: CodePage := 1257; SHIFTJIS_CHARSET: CodePage := 932; 129: CodePage := 949; CHINESEBIG5_CHARSET: CodePage := 950; GB2312_CHARSET: CodePage := 936; else CodePage := 1252; end; OS := MultiByteToWideChar ( CodePage, 0, PChar ( Text ), Length ( Text ), nil, 0 ); if OS = 0 then Exit; SetLength ( A, OS ); W := @a [ 0 ]; if MultiByteToWideChar ( CodePage, 0, PChar ( Text ), Length ( Text ), W, OS ) <> 0 then begin SetLength(Result,(OS + 1) shl 1); Result[1] := chr($FE); Result[2] := chr($FF); for i:= 0 to OS -1 do begin Result[3+i shl 1] := char(a[i] shr 8); Result[4+i shl 1] := char(a[i] and $FF); end; end; end; {$endif} {$ifdef UNICODE} function UnicodeChar( Text:string):AnsiString; var i, L: integer; begin L := Length( Text ); SetLength(Result,(L + 1) shl 1); Result[1] := AnsiChar($FE); Result[2] := AnsiChar($FF); for i:= 1 to L do begin Result[1+i shl 1] := AnsiChar(Word(Text[i]) shr 8); Result[2+i shl 1] := AnsiChar(Word(Text[i]) and $FF); end; end; {$endif} function ReplStr ( Source: AnsiString; Ch: ANSIChar; Sub: AnsiString ): AnsiString; var I: Integer; begin Result := ''; for i := 1 to Length ( Source ) do if Source [ I ] <> Ch then Result := Result + Source [ i ] else Result := Result + Sub; end; function UCase(const S: AnsiString): AnsiString; var Ch: ANSIChar; L: Integer; Source, Dest: PANSIChar; begin L := Length(S); SetLength(Result, L); Source := Pointer(S); Dest := Pointer(Result); while L <> 0 do begin Ch := Source^; if (Ch >= 'a') and (Ch <= 'z') then Dec(Ch, 32); Dest^ := Ch; Inc(Source); Inc(Dest); Dec(L); end; end; function LCase (const S: AnsiString): AnsiString; var Ch: ANSIChar; L: Integer; Source, Dest: PANSIChar; begin L := Length(S); SetLength(Result, L); Source := Pointer(S); Dest := Pointer(Result); while L <> 0 do begin Ch := Source^; if (Ch >= 'A') and (Ch <= 'Z') then inc(Ch, 32); Dest^ := Ch; Inc(Source); Inc(Dest); Dec(L); end; end; procedure QuickSortArray ( var Arr: array of Word ); procedure QuickSort ( var A: array of Word; iLo, iHi: Integer ); var Lo, Hi, Mid, T: Integer; begin Lo := iLo; Hi := iHi; Mid := A [ ( Lo + Hi ) div 2 ]; repeat while A [ Lo ] < Mid do Inc ( Lo ); while A [ Hi ] > Mid do Dec ( Hi ); if Lo <= Hi then begin T := A [ Lo ]; A [ Lo ] := A [ Hi ]; A [ Hi ] := T; Inc ( Lo ); Dec ( Hi ); end; until Lo > Hi; if Hi > iLo then QuickSort ( A, iLo, Hi ); if Lo < iHi then QuickSort ( A, Lo, iHi ); end; begin QuickSort ( Arr, Low ( Arr ), High ( Arr ) ); end; function WordToHex ( W: Word ): AnsiString; begin Result := HEX [ (w shr 12) and $F ] + HEX [ (w shr 8) and $F ] + HEX [ (w shr 4) and $F ] + HEX [ w and $F ]; end; function StringToHex(TextStr:AnsiString;WithPrefix:Boolean):AnsiString; var i,sz: Integer; begin if WithPrefix then begin sz:=(Length(TextStr)+1) shl 1; SetLength(Result, sz); Result[1]:='<'; Result[sz]:='>'; for i := 1 to Length(TextStr) do begin Result[ i shl 1] := HEX [ Byte(TextStr[i]) shr 4 ]; Result[ i shl 1 + 1 ] := HEX [ Byte(TextStr[i]) and $F ]; end; end else begin sz:=(Length(TextStr)) shl 1; SetLength(Result, sz); for i := 1 to Length(TextStr) do begin Result[ i shl 1 - 1] := HEX [ Byte(TextStr[i]) shr 4 ]; Result[ i shl 1 ] := HEX [ Byte(TextStr[i]) and $F ]; end; end; end; function ByteToOct ( B: Byte ): string; begin Result := ''; while B > 7 do begin Result := IntToStr ( B mod 8 ) + Result; b := b div 8; end; Result := IntToStr ( b ) + Result; end; function StrToOctet ( st: string ): string; var i: Integer; begin Result := ''; for i := 1 to Length ( st ) do Result := Result + '\' + ByteToOct ( Ord ( st [ i ] ) ); end; function IsANSICode ( UNICODE: Word ): Boolean; begin if UNICODE < 128 then Result := True else if ( UNICODE < 255 ) and ( UNICODE > 159 ) then Result := True else if ( UNICODE = 8364 ) or ( UNICODE = 129 ) or ( UNICODE = 8218 ) or ( UNICODE = 402 ) or ( UNICODE = 8222 ) or ( UNICODE = 8230 ) or ( UNICODE = 8224 ) or ( UNICODE = 8225 ) or ( UNICODE = 710 ) or ( UNICODE = 8240 ) or ( UNICODE = 352 ) or ( UNICODE = 8249 ) or ( UNICODE = 338 ) or ( UNICODE = 141 ) or ( UNICODE = 381 ) or ( UNICODE = 143 ) or ( UNICODE = 144 ) or ( UNICODE = 8216 ) or ( UNICODE = 8217 ) or ( UNICODE = 8220 ) or ( UNICODE = 8221 ) or ( UNICODE = 8226 ) or ( UNICODE = 8211 ) or ( UNICODE = 8212 ) or ( UNICODE = 732 ) or ( UNICODE = 8482 ) or ( UNICODE = 353 ) or ( UNICODE = 8250 ) or ( UNICODE = 339 ) or ( UNICODE = 157 ) or ( UNICODE = 382 ) or ( UNICODE = 376 ) then Result := True else Result := False; end; function ANSIUNICODEToByte ( Unicode: Word ): Byte; begin if ( Unicode < 128 ) or ( ( UNICODE < 255 ) and ( UNICODE > 159 ) ) then Result := Byte ( Unicode ) else if UNICODE = 8364 then Result := 128 else if UNICODE = 129 then Result := 129 else if UNICODE = 8218 then Result := 130 else if UNICODE = 402 then Result := 131 else if UNICODE = 8222 then Result := 132 else if UNICODE = 8230 then Result := 133 else if UNICODE = 8224 then Result := 134 else if UNICODE = 8225 then Result := 135 else if UNICODE = 710 then Result := 136 else if UNICODE = 8240 then Result := 137 else if UNICODE = 352 then Result := 138 else if UNICODE = 8249 then Result := 139 else if UNICODE = 338 then Result := 140 else if UNICODE = 141 then Result := 141 else if UNICODE = 381 then Result := 142 else if UNICODE = 143 then Result := 143 else if UNICODE = 144 then Result := 144 else if UNICODE = 8216 then Result := 145 else if UNICODE = 8217 then Result := 146 else if UNICODE = 8220 then Result := 147 else if UNICODE = 8221 then Result := 148 else if UNICODE = 8226 then Result := 149 else if UNICODE = 8211 then Result := 150 else if UNICODE = 8212 then Result := 151 else if UNICODE = 732 then Result := 152 else if UNICODE = 8482 then Result := 153 else if UNICODE = 353 then Result := 154 else if UNICODE = 8250 then Result := 155 else if UNICODE = 339 then Result := 156 else if UNICODE = 157 then Result := 157 else if UNICODE = 382 then Result := 158 else if UNICODE = 376 then Result := 159 else Result := 0; end; function ByteToANSIUNICODE ( B: Byte ): Word; const UVAL: array [ 128..159 ] of word = ( 8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376 ); begin if ( B < 128 ) or ( B > 159 ) then Result := B else Result := UVAL [ B ]; end; type FND = record TT: Boolean; FontName: array [ 0..LF_FACESIZE - 1 ] of ANSIChar; end; Z = record Charset: Byte; Valid: boolean; end; function Check1 ( const Enum: ENUMLOGFONTEX; Noop: Pointer; FT: DWORD; var F: Z ): Integer; stdcall; begin if Enum.elfLogFont.lfCharSet = F.Charset then begin f.Valid := true; Result := 0; end else result := 1; end; function Check ( const Enum: ENUMLOGFONTEX; Noop: Pointer; FT: DWORD; var F: FND ): Integer; stdcall; var LF: TLogFont; DC: HDC; ZZ: Z; begin if FT = TRUETYPE_FONTTYPE then begin ZZ.Valid := False; ZZ.Charset := Enum.elfLogFont.lfCharSet; FillChar ( LF, SizeOf ( LF ), 0 ); LF.lfCharSet := 1; LF.lfFaceName := Enum.elfLogFont.lfFaceName; ZZ.CharSet := Enum.elfLogFont.lfCharSet; DC := GetDC ( 0 ); try EnumFontFamiliesEx ( DC, LF, @Check1, FInt( @ZZ ), 0 ); finally ReleaseDC ( 0, DC ); end; if ZZ.Valid then begin Move ( Enum.elfLogFont.lfFaceName, F.FontName, LF_FACESIZE - 1 ); F.TT := True; Result := 0; end else result := 1; end else result := 1; end; function GetFontByCharset ( Charset: Byte ): AnsiString; var LF: TLogFont; DC: HDC; F: FND; begin if Charset = 1 then Charset := GetDefFontCharSet; FillChar ( LF, SizeOf ( LF ), 0 ); FillChar ( F, SizeOf ( F ), 0 ); F.TT := False; LF.lfCharSet := Charset; DC := GetDC ( 0 ); try EnumFontFamiliesEx ( DC, LF, @Check, FInt ( @F ), 0 ); finally ReleaseDC ( 0, DC ); end; if F.TT then Result := F.FontName else Result := ''; end; function IsTTCheck ( const Enum: ENUMLOGFONTEX; Noop: Pointer; FT: DWORD; var TT: Boolean ): Integer; stdcall; begin TT := ( FT = TRUETYPE_FONTTYPE ); Result := 0; end; function IsTrueType ( FontName: String; Charset: Byte ): Boolean; var LF: TLogFont; TT: Boolean; DC: HDC; begin if FontName = '' then begin Result := False; Exit; end; FillChar ( LF, SizeOf ( LF ), 0 ); LF.lfCharSet := CHARSET; StrPCopy(LF.lfFaceName,FontName); DC := GetDC ( 0 ); try EnumFontFamiliesEx ( DC, LF, @IsTTCheck, FInt ( @TT ), 0 ); finally ReleaseDC ( 0, DC ); end; Result := tt; end; procedure FlipBMP(BMP:TBitmap;FlipX, FlipY:Boolean); begin if FlipX and FlipY then begin BMP.Canvas.StretchDraw(Rect(BMP.Width,BMP.Height,0, 0),BMP); end else if FlipX then begin BMP.Canvas.StretchDraw(Rect(BMP.Width,0,0, BMP.Height),BMP); end else if FlipY then begin BMP.Canvas.StretchDraw(Rect(0,BMP.Height,BMP.Width, 0),BMP); end end; function EscapeSpecialChar ( TextStr: AnsiString ): AnsiString; var I: Integer; begin Result := ''; for I := 1 to Length ( TextStr ) do case TextStr [ I ] of '(': Result := Result + '\('; ')': Result := Result + '\)'; '\': Result := Result + '\\'; #13: Result := result + '\r'; #10: Result := result + '\n'; else Result := Result + textstr [ i ] ; end; end; function CharSetToCodePage ( Charset: Byte ): Integer; begin if Charset = Default_Charset then Charset := GetDefFontCharSet; case Charset of ANSI_CHARSET: Result := 1252; RUSSIAN_CHARSET: Result := 1251; TURKISH_CHARSET: Result := 1254; SHIFTJIS_CHARSET: Result := 932; HANGEUL_CHARSET: Result := 949; CHINESEBIG5_CHARSET: Result := 950; GB2312_CHARSET: Result := 936; JOHAB_CHARSET: Result := 1361; HEBREW_CHARSET: Result := 1255; ARABIC_CHARSET: Result := 1256; GREEK_CHARSET: Result := 1253; THAI_CHARSET: Result := 874; EASTEUROPE_CHARSET: Result := 1250; MAC_CHARSET: Result := 10000; BALTIC_CHARSET: Result := 1257; VIETNAMESE_CHARSET: Result := 1258; else Result := 1252; end; end; procedure swp ( var A, B: Integer ); overload; var C: Integer; begin C := A; A := B; B := C; end; procedure swp ( var A, B: Extended ); overload; var C: Extended; begin C := A; A := B; B := C; end; procedure NormalizeRect ( var Rect: TRect ); overload; begin if Rect.Left > Rect.Right then swp ( Rect.Left, Rect.Right ); if Rect.Top > Rect.Bottom then swp ( Rect.Top, Rect.Bottom ); end; procedure NormalizeRect ( var x1, y1, x2, y2: integer ); overload; begin if x1 > x2 then swp ( x2, x1 ); if y1 > y2 then swp ( y2, y1 ); end; procedure NormalizeRect ( var x1, y1, x2, y2: Extended ); overload; begin if x1 > x2 then swp ( x2, x1 ); if y1 > y2 then swp ( y2, y1 ); end; function FormatFloat ( Value: Extended; Quality:Boolean = false): AnsiString; var c: Char; begin {$ifndef XE} c := DecimalSeparator; DecimalSeparator := '.'; {$ifndef UNICODE} if Quality then Result := SysUtils.FormatFloat ( '0.#####', Value ) else Result := SysUtils.FormatFloat ( '0.##', Value ); {$else} if Quality then Result := AnsiString(SysUtils.FormatFloat ( '0.#####', Value )) else Result := AnsiString(SysUtils.FormatFloat ( '0.##', Value )); {$endif} DecimalSeparator := c; {$else} c := FormatSettings.DecimalSeparator; FormatSettings.DecimalSeparator := '.'; {$ifndef UNICODE} if Quality then Result := System.SysUtils.FormatFloat ( '0.#####', Value ) else Result := System.SysUtils.FormatFloat ( '0.##', Value ); {$else} if Quality then {$ifdef W3264} Result := AnsiString(System.SysUtils.FormatFloat ( '0.#####', Value )) else Result := AnsiString(System.SysUtils.FormatFloat ( '0.##', Value )); {$else} Result := AnsiString(SysUtils.FormatFloat ( '0.#####', Value )) else Result := AnsiString(SysUtils.FormatFloat ( '0.##', Value )); {$endif} {$endif} FormatSettings.DecimalSeparator := c; {$endif} end; procedure RotateCoordinate ( X, Y, Angle: Extended; var XO, YO: Extended ); var rcos, rsin: Extended; begin Angle := Angle * ( PI / 180 ); rcos := cos ( angle ); rsin := sin ( angle ); XO := rcos * x - rsin * y; YO := rsin * x + rcos * y; end; function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PAnsiChar; SourceBytes: Cardinal): Cardinal; var i, count: Cardinal; c: Byte; wc: Cardinal; begin if Source = nil then begin Result := 0; Exit; end; Result := Cardinal(-1); count := 0; i := 0; if Dest <> nil then begin while (i < SourceBytes) and (count < MaxDestChars) do begin wc := Cardinal(Source[i]); Inc(i); if (wc and $80) <> 0 then begin if i >= SourceBytes then Exit; // incomplete multibyte char wc := wc and $3F; if (wc and $20) <> 0 then begin c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char if i >= SourceBytes then Exit; // incomplete multibyte char wc := (wc shl 6) or (c and $3F); end; c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then Exit; // malformed trail byte Dest[count] := WideChar((wc shl 6) or (c and $3F)); end else Dest[count] := WideChar(wc); Inc(count); end; if count >= MaxDestChars then count := MaxDestChars-1; Dest[count] := #0; end else begin while (i < SourceBytes) do begin c := Byte(Source[i]); Inc(i); if (c and $80) <> 0 then begin if i >= SourceBytes then Exit; // incomplete multibyte char c := c and $3F; if (c and $20) <> 0 then begin c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char if i >= SourceBytes then Exit; // incomplete multibyte char end; c := Byte(Source[i]); Inc(i); if (c and $C0) <> $80 then Exit; // malformed trail byte end; Inc(count); end; end; Result := count+1; end; function UTF8ToWideString(const S: UTF8String): WideString; var L: Integer; Temp: WideString; begin Result := ''; if S = '' then Exit; SetLength(Temp, Length(S)); L := Utf8ToUnicode(PWideChar(Temp), Length(Temp)+1, PAnsiChar(S), Length(S)); if L > 0 then SetLength(Temp, L-1) else Temp := ''; Result := Temp; end; function WideStringToUTF8(const S: WideString): AnsiString; var SrcLength, DestIndex: Integer; Code: Word; i: Integer; begin if S = '' then begin Result := ''; Exit; end; SrcLength := Length(S); SetLength(Result, SrcLength * 3); DestIndex := 1; for i := 1 to SrcLength do begin Code := Word(S[i]); if Code <= $7F then begin Result[DestIndex] := AnsiChar(Code); Inc(DestIndex); Continue; end; if Code <= $7FF then begin Result[DestIndex] := AnsiChar($C0 or (Code shr 6)); Result[DestIndex + 1] := AnsiChar((Code and $3F) or $80); Inc(DestIndex, 2); Continue; end; Result[DestIndex] := AnsiChar($E0 or (Code shr 12)); Result[DestIndex + 1] := AnsiChar(((Code shr 6) and $3F) or $80); Result[DestIndex + 2] := AnsiChar((Code and $3F) or $80); Inc(DestIndex, 3); end; SetLength(Result, DestIndex - 1); end; function DPoint ( x, y: Extended ): TDoublePoint; begin Result.x := x; Result.y := y; end; function IntToStrWithZero ( ID, Count: Integer ): AnsiString; var s, d: AnsiString; I: Integer; begin {$ifndef UNICODE} s := IntToStr ( ID ); {$else} s := AnsiString(IntToStr ( ID )); {$endif} I := Count - Length ( s ); d := ''; for I := 0 to I - 1 do d := d + '0'; Result := d + s; end; function GetRef(ID: Integer): AnsiString; begin {$ifndef UNICODE} Result := Format('%d 0 R', [ID]); {$else} Result := AnsiString(Format('%d 0 R', [ID])); {$endif} end; {$ifdef UNICODE} { TAnsiStringList } function TAnsiStringList.Add(const S: AnsiString): Integer; begin Result := FCount; InsertItem(Result, S); end; procedure TAnsiStringList.Clear; begin if FCount <> 0 then begin Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); end; end; constructor TAnsiStringList.Create; begin FCount := 0; FCapacity := 0; FList := nil; FLineBreak := #13#10; end; destructor TAnsiStringList.Destroy; begin if FCount <> 0 then Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); inherited; end; function TAnsiStringList.Get(Index: Integer): AnsiString; begin if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index); Result := FList^[Index].FString; end; function TAnsiStringList.GetCapacity: Integer; begin Result := FCapacity; end; function TAnsiStringList.GetCount: Integer; begin Result := FCount; end; function TAnsiStringList.GetTextStr: AnsiString; var I, L, Size, Count: Integer; P: PANSIChar; S, LB: AnsiString; begin Count := GetCount; Size := 0; LB := LineBreak; for I := 0 to Count - 1 do Inc(Size, Length(Get(I)) + Length(LB)); SetString(Result, nil, Size); P := Pointer(Result); for I := 0 to Count - 1 do begin S := Get(I); L := Length(S); if L <> 0 then begin System.Move(Pointer(S)^, P^, L * SizeOf(ANSIChar)); Inc(P, L); end; L := Length(LB); if L <> 0 then begin System.Move(Pointer(LB)^, P^, L * SizeOf(ANSIChar)); Inc(P, L); end; end; end; procedure TAnsiStringList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; procedure TAnsiStringList.Insert(Index: Integer; const S: AnsiString); begin if (Index < 0) or (Index > FCount) then Error(@SListIndexError, Index); InsertItem(Index, S); end; procedure TAnsiStringList.Put(Index: Integer; const S: AnsiString); begin if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index); FList^[Index].FString := S; end; procedure TAnsiStringList.SaveToStream(Stream: TStream); var S: AnsiString; begin S := GetTextStr; Stream.WriteBuffer(s[1], Length(s)); end; procedure TAnsiStringList.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MLS) then Error(@SListCapacityError, NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(TAnsiStringItem)); FCapacity := NewCapacity; end; end; procedure TAnsiStringList.SetTextStr(const Value: AnsiString); var P, Start: PANSIChar; S: AnsiString; begin Clear; P := Pointer(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not (P^ in [#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); Add(S); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; end; procedure TAnsiStringList.Error(const Msg: string; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end; begin raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; procedure TAnsiStringList.Error(Msg: PResStringRec; Data: Integer); begin Error(LoadResString(Msg), Data); end; procedure TAnsiStringList.InsertItem(Index: Integer; const S: AnsiString); begin if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TStringItem)); with FList^[Index] do begin Pointer(FString) := nil; FString := S; end; Inc(FCount); end; procedure TAnsiStringList.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; {$endif} { TBitStream } constructor TBitStream.Create(AStream: TStream); begin FStream := AStream; FBuffer := 0; FCurrentBit := 32; end; destructor TBitStream.Destroy; begin if FCurrentBit <> 32 then FlushBits; inherited; end; procedure TBitStream.FlushBits; begin FBuffer := ByteSwap(FBuffer); FCurrentBit := 32 - FCurrentBit; FStream.Write(FBuffer,(FCurrentBit +7) shr 3); FCurrentBit := 32; FBuffer := 0; end; procedure TBitStream.Put(Value: Cardinal; Count: Integer); begin Value := Value and ($FFFFFFFF shr (32-Count)); if FCurrentBit < Count then begin FBuffer := FBuffer or (Value shr (Count - FCurrentBit)); Dec(Count,FCurrentBit); FCurrentBit := 0; FlushBits; end; FBuffer := FBuffer or (Value shl (FCurrentBit- Count)); Dec(FCurrentBit, Count); if FCurrentBit = 0 then FlushBits; end; procedure TBitStream.Put(Value: Int64; Count: Integer); begin if Count <= 32 then begin Put(Int64Rec(Value).Lo,Count); end else begin Put(Int64Rec(Value).Lo,32); Put(Int64Rec(Value).Hi,Count-32); end; end; procedure TBitStream.Write( Buffer: Pointer; Count: Integer); var i: Integer; PB:PByte; begin if FCurrentBit = 32 then begin FStream.Write(Buffer^,Count); end else begin PB := Buffer; for i := 0 to Count -1 do begin Put(PB^,8); inc(PB); end; end; end; { TObjList } function TObjList.GetItem(Index: Integer): TObject; begin Result := inherited Items[Index]; end; procedure TObjList.Clear; var i: Integer; begin if FOwnsObjects then for i := 0 to Count - 1 do TObject(Items[i]).Free; inherited Clear; end; constructor TObjList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program PBCSEQ; Const maxN =100000; Type TSegment =Record x,y :LongInt end; Var n,res :LongInt; A :Array[1..maxN] of TSegment; F :Array[1..maxN] of LongInt; procedure Enter; var i :LongInt; begin Read(n); for i:=1 to n do with (A[i]) do Read(x,y); end; procedure QSort(l,r :LongInt); var i,j :LongInt; Key,Tmp :TSegment; begin if (l>=r) then Exit; i:=l; j:=r; Key:=A[(l+r) div 2]; repeat while (A[i].x>Key.x) or ((A[i].x=Key.x) and (A[i].y<Key.y)) do Inc(i); while (A[j].x<Key.x) or ((A[j].x=Key.x) and (A[j].y>Key.y)) do Dec(j); if (i<=j) then begin if (i<j) then begin Tmp:=A[i]; A[i]:=A[j]; A[j]:=Tmp; end; Inc(i); Dec(j); end; until (i>j); QSort(l,j); QSort(i,r); end; function BSearch(i :LongInt) :LongInt; var left,right,mid :LongInt; begin left:=1; right:=res; while (left<right) do begin mid:=(left+right) div 2; if (A[i].y>=A[F[mid]].y) then left:=mid+1 else right:=mid; end; Exit(left); end; procedure Optimize; var i :LongInt; begin F[1]:=1; res:=1; for i:=2 to n do if (A[i].y>=A[F[res]].y) then begin Inc(res); F[res]:=i; end else F[BSearch(i)]:=i; end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; QSort(1,n); Optimize; Write(res); Close(Input); Close(Output); End.
unit ncaFrmConfigComanda; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ncaFrmBaseOpcaoImgTxt, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, cxTextEdit, cxMaskEdit, cxSpinEdit, cxCheckBox, StdCtrls, cxButtons, cxLabel, LMDPNGImage, ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, uFrmPanFaixas; type TFrmConfigComanda = class(TFrmBaseOpcaoImgTxt) LMDSimplePanel2: TLMDSimplePanel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; panEdit: TLMDSimplePanel; lbComandaNumeracao: TcxLabel; cbUsarComandas: TcxCheckBox; procedure cbUsarComandasClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } panFaixas : TFrmFaixas; public { Public declarations } procedure Atualizar; procedure Ler; override; procedure Salvar; override; function Alterou: Boolean; override; procedure Renumera; override; function NumItens: Integer; override; end; var FrmConfigComanda: TFrmConfigComanda; implementation {$R *.dfm} uses ncClassesBase, ncaDM; { TFrmConfigComanda } resourcestring SNumeracaoComandaInvalida = 'O número final das comandas deve ser maior que o número inicial'; SNumeracaoComandaIgualMaq = 'Comandas e mesas devem ter numeração diferente'; function TFrmConfigComanda.Alterou: Boolean; begin Result := (cbUsarComandas.Checked<>(not gConfig.ComandaOff)) or (panFaixas.AsString<>gConfig.FaixaComanda); end; procedure TFrmConfigComanda.Atualizar; begin panFaixas.Habilitar(cbUsarComandas.Checked); lbComandaNumeracao.Enabled := cbUsarComandas.Checked; { if cbUsarComandas.Checked and (cbUsarComandas.Focused) then edComandaI.SetFocus;} end; procedure TFrmConfigComanda.cbUsarComandasClick(Sender: TObject); begin inherited; Atualizar; end; procedure TFrmConfigComanda.FormCreate(Sender: TObject); begin panFaixas := TFrmFaixas.Create(Self); panFaixas.panPri.Parent := panEdit; panFaixas.panPri.Top := 1000; panFaixas.panPri.Margins.Left := 26; panFaixas.panPri.AlignWithMargins := True; inherited; end; procedure TFrmConfigComanda.Ler; begin inherited; cbUsarComandas.Checked := not gConfig.ComandaOff; panFaixas.AsString := gConfig.FaixaComanda; Atualizar; end; function TFrmConfigComanda.NumItens: Integer; begin Result := 2; end; procedure TFrmConfigComanda.Renumera; begin inherited; cbUsarComandas.Caption := IntToStr(InicioNumItem)+'. '+cbUsarComandas.Caption; lbComandaNumeracao.Caption := IntToStr(InicioNumItem+1)+'. '+lbComandaNumeracao.Caption; end; procedure TFrmConfigComanda.Salvar; var I: Integer; begin inherited; if cbUsarComandas.Checked then begin panFaixas.Valida; with Dados.CM do for I := 0 to Maquinas.Count-1 do if panFaixas.DentroFaixa(Maquinas[I].Numero) then raise Exception.Create(SNumeracaoComandaIgualMaq); end; gConfig.AtualizaCache; gConfig.ComandaOff := not cbUsarComandas.Checked; gConfig.FaixaComanda := panFaixas.AsString; end; end.
unit Grammar; interface uses Classes, Generics.Collections; type TGrammar = Class(TObject) private gAxiom: String; // Map symbols to replacements gRules: TDictionary<String, String>; // Map symbols to turtle movements gMovements: TDictionary<String, String>; public constructor Create(axiom: String; rules: TDictionary<String, String>; movements: TDictionary<String, String>); published property axiom: String read gAxiom; property rules: TDictionary<String, String> read gRules; property movements: TDictionary<String, String> read gMovements; end; implementation // Constructor constructor TGrammar.Create(axiom: String; rules: TDictionary<String, String>; movements: TDictionary<String, String>); begin gAxiom := axiom; gRules := rules; gMovements := movements; end; end.
unit ncaFrmBaseCadastroMT; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseCadastro, dxBar, cxClasses, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, Data.DB, kbmMemTable, cxEdit; type TFrmBaseCadastroMT = class(TFrmBaseCadastro) MT: TkbmMemTable; DS: TDataSource; dxBarButton1: TdxBarButton; procedure FormCreate(Sender: TObject); procedure cmCancelarClick(Sender: TObject); private { Private declarations } FNovo : Boolean; FTab : TDataset; protected procedure LoadItens; virtual; procedure SaveItens; virtual; public function Editar(aNovo: Boolean; aTab: TDataset): Boolean; virtual; function ExceptFields: String; virtual; procedure Salvar; override; property Novo: Boolean read FNovo; property Tab: TDataset read FTab; { Public declarations } end; var FrmBaseCadastroMT: TFrmBaseCadastroMT; implementation {$R *.dfm} uses ncaDM; procedure TFrmBaseCadastroMT.cmCancelarClick(Sender: TObject); begin inherited; ModalResult := mrCancel; end; function TFrmBaseCadastroMT.Editar(aNovo: Boolean; aTab: TDataset): Boolean; begin FNovo := aNovo; FTab := aTab; MT.Insert; if not aNovo then TransfDados(aTab, MT); LoadItens; ShowModal; Result := (ModalResult=mrOk); end; function TFrmBaseCadastroMT.ExceptFields: String; begin Result := ''; end; procedure TFrmBaseCadastroMT.FormCreate(Sender: TObject); begin inherited; MT.Active := True; end; procedure TFrmBaseCadastroMT.LoadItens; begin end; procedure TFrmBaseCadastroMT.Salvar; begin if FNovo then FTab.Append else FTab.Edit; TransfDados(MT, FTab); FTab.Post; SaveItens; end; procedure TFrmBaseCadastroMT.SaveItens; begin end; end.
unit Ex9Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MTUtils, ComCtrls; const UM_PROGRESS_INIT = WM_USER + 1; UM_PROGRESS_CHANGE = WM_USER + 2; type TProgressData = class CurrValue: Integer; CalcResult: Int64; ThreadStateInfo: string; end; TMyThread = class(TThread) private ProgressData: TProgressData; FFormHandle: THandle; FMaxValue: Integer; public procedure Execute; override; constructor Create(AMaxValue: Integer; AFormHandle: THandle); destructor Destroy; override; end; TForm1 = class(TForm) btnRunInParallelThread: TButton; ProgressBar1: TProgressBar; Label1: TLabel; labResult: TLabel; edMaxValue: TEdit; Label2: TLabel; labThreadStateInfo: TLabel; procedure btnRunInParallelThreadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FMyThread: TMyThread; procedure UMProgressInit(var Msg: TMessage); message UM_PROGRESS_INIT; procedure UMProgressChange(var Msg: TMessage); message UM_PROGRESS_CHANGE; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnRunInParallelThreadClick(Sender: TObject); begin // Уничтожаем запущенный поток if Assigned(FMyThread) then FreeAndNil(FMyThread); // Создаём и запускаем новый поток FMyThread := TMyThread.Create(StrToInt(edMaxValue.Text), Handle); end; procedure TForm1.FormDestroy(Sender: TObject); begin FMyThread.Free; end; procedure TForm1.UMProgressChange(var Msg: TMessage); var ProgressData: TProgressData; begin ProgressData := TProgressData(Msg.WParam); ProgressBar1.Position := ProgressData.CurrValue; labResult.Caption := IntToStr(ProgressData.CalcResult); labThreadStateInfo.Caption := ProgressData.ThreadStateInfo; end; procedure TForm1.UMProgressInit(var Msg: TMessage); var MaxValue: Integer; begin MaxValue := Msg.WParam; ProgressBar1.Max := MaxValue; ProgressBar1.Position := 0; labResult.Caption := '0'; labThreadStateInfo.Caption := 'Start'; end; { TMyThread } constructor TMyThread.Create(AMaxValue: Integer; AFormHandle: THandle); begin inherited Create(False); FMaxValue := AMaxValue; FFormHandle := AFormHandle; ProgressData := TProgressData.Create; end; destructor TMyThread.Destroy; begin //ProgressData.Free; - НЕЛЬЗЯ ТУТ! inherited; ProgressData.Free; end; procedure TMyThread.Execute; var CurrVal: Integer; begin // Выставляем параметры компонента ProgressBar1 SendMessage(FFormHandle, UM_PROGRESS_INIT, FMaxValue, 0); ThreadWaitTimeout(Self, 1000); // Просто пауза 1 сек. CurrVal := 0; // Выполняем некоторые вычисления while CurrVal < FMaxValue do begin if Terminated then Break; Inc(CurrVal); ProgressData.CurrValue := CurrVal; ProgressData.CalcResult := ProgressData.CalcResult + CurrVal; ProgressData.ThreadStateInfo := Format('Progress: %f%%', [CurrVal / FMaxValue * 100]); // Обновление прогресса выполняется только 1 раз из 10000 if CurrVal mod 10000 = 0 then SendMessage(FFormHandle, UM_PROGRESS_CHANGE, WPARAM(ProgressData), 0); end; // Обновляем прогресс в конце вычислений SendMessage(FFormHandle, UM_PROGRESS_CHANGE, WPARAM(ProgressData), 0); end; end.
unit StrHelper; interface uses System.Generics.Collections; Type TMySplitRec = record BracketInBalance: Boolean; StringArray: TArray<String>; end; TBracket = class public LeftBracket: Char; RightBracket: Char; constructor Create(ALeftBracket, ARightBracket: Char); end; TBracketList = class(TObjectList<TBracket>) public function IsLeftBracket(AChar: Char): TBracket; function IsRightBracket(AChar: Char): TBracket; end; function NameForm(X: Integer; const s1: String; const s2: String; const s5: String): String; function DeleteDouble(const S: string; const AChar: Char): String; function Contain(const SubStr: String; const S: String; const ADelimiter: Char = ','): Boolean; function GetRelativeFileName(const AFullFileName, ARootDir: string): string; // Разбивает строку с учётом того, что разделитель может оказаться в скобках function MySplit(const S: string; ADelimiter: Char): TMySplitRec; function ReplaceInSQL(const ASQL: String; const AStipulation: String; ANumber: Integer): String; function GetWords(const S: String): String; function ReplaceNotKeyboadChars(const S: String): String; implementation uses System.SysUtils, System.RegularExpressions; Var ABracketList: TBracketList; function ReplaceInSQL(const ASQL: String; const AStipulation: String; ANumber: Integer): String; var ATemplate: string; lp: Integer; p: Integer; begin Assert(not ASQL.IsEmpty); Assert(not AStipulation.IsEmpty); ATemplate := Format('%d=%d', [ANumber, ANumber]); p := ASQL.IndexOf(ATemplate); Assert(p >= 0); lp := ASQL.LastIndexOf(ATemplate); // Только одно вхождение ! Assert(lp = p); Result := ASQL.Replace(ATemplate, AStipulation); end; function NameForm(X: Integer; const s1: String; const s2: String; const s5: String): String; var d: Integer; begin d := X mod 100; if (d >= 10) and (d <= 20) then begin Result := s5; Exit; end; d := X mod 10; if d = 1 then Result := s1 else if (d >= 2) and (d <= 4) then Result := s2 else Result := s5; end; function GetWords(const S: String): String; var m: TArray<String>; s2: string; s1: string; begin Result := ''; s1 := S.Trim(); m := s1.Split([' ', '/', '-']); for s1 in m do begin s2 := s1.Trim; if s2.IsEmpty then Continue; Result := Format('%s'#13'%s', [Result, s2]); end; Result := Result.Trim([#13]); end; function ReplaceNotKeyboadChars(const S: String): String; begin Result := S.Replace(chr($02C2), '<'); Result := Result.Replace(chr($02C3), '>'); end; function GetRelativeFileName(const AFullFileName, ARootDir: string): string; var i: Integer; S: String; begin Assert(not AFullFileName.IsEmpty); Assert(not ARootDir.IsEmpty); S := ARootDir.Trim(['\']) + '\'; // Ищем корневую папку в полном пути к файлу i := AFullFileName.IndexOf(S); Assert(i >= 0); Result := AFullFileName.Substring(i + S.Length); end; function Contain(const SubStr: String; const S: String; const ADelimiter: Char = ','): Boolean; var s1: string; s2: string; begin s1 := Format('%s%s%s', [ADelimiter, S.Trim([ADelimiter]), ADelimiter]); s2 := Format('%s%s%s', [ADelimiter, SubStr.Trim([ADelimiter]), ADelimiter]); Result := s1.IndexOf(s2) >= 0; end; function DeleteDouble(const S: string; const AChar: Char): String; var s1: String; s2: String; SS: string; begin Assert(AChar <> #0); s1 := String.Create(AChar, 1); s2 := String.Create(AChar, 2); Result := S; repeat SS := Result; Result := SS.Replace(s2, s1, [rfReplaceAll]); until Result = SS; end; // Разбивает строку с учётом того, что разделитель может оказаться в скобках function MySplit(const S: string; ADelimiter: Char): TMySplitRec; var ch: Char; i: Integer; Brackets: String; ABracket: TBracket; AList: TList<String>; Str: string; SubStr: string; begin Assert(ABracketList <> nil); Result.BracketInBalance := False; Str := S; AList := TList<String>.Create; try Brackets := ''; i := 0; while i < Str.Length do begin ch := Str.Chars[i]; // Может мы встретили левую скобку? ABracket := ABracketList.IsLeftBracket(ch); if ABracket <> nil then Brackets := Brackets + ch else begin // Может мы встретили правую скобку? ABracket := ABracketList.IsRightBracket(ch); if ABracket <> nil then begin // Если скобки не в балансе if (Brackets.Length = 0) or (Brackets.Chars[Brackets.Length - 1] <> ABracket.LeftBracket) then Exit; // Удаляем последнюю открытую скобку из строки Brackets := Brackets.Substring(0, Brackets.Length - 1); end; end; // Если очередной символ - это разделитель и все скобки закрылись if (ch = ADelimiter) and (Brackets.Length = 0) then begin SubStr := Str.Substring(0, i).Trim; if SubStr.Length > 0 then AList.Add(SubStr); Str := Str.Substring(i + 1); i := 0; end else Inc(i); end; // Если не все открытые скобки закрылись if Brackets.Length > 0 then Exit; SubStr := Str.Trim; // Добавляем хвостик в котором не нашлось разделителей if SubStr.Length > 0 then AList.Add(SubStr); Result.StringArray := AList.ToArray; Result.BracketInBalance := True; finally FreeAndNil(AList); end; end; constructor TBracket.Create(ALeftBracket, ARightBracket: Char); begin LeftBracket := ALeftBracket; RightBracket := ARightBracket; end; function TBracketList.IsLeftBracket(AChar: Char): TBracket; begin for Result in Self do begin if Result.LeftBracket = AChar then Exit; end; Result := nil; end; function TBracketList.IsRightBracket(AChar: Char): TBracket; begin for Result in Self do begin if Result.RightBracket = AChar then Exit; end; Result := nil; end; initialization ABracketList := TBracketList.Create; ABracketList.Add(TBracket.Create('(', ')')); ABracketList.Add(TBracket.Create('{', '}')); ABracketList.Add(TBracket.Create('[', ']')); finalization FreeAndNil(ABracketList); end.
unit Vigilante.Controller.Base.Impl; interface uses Vigilante.Controller.Base, Module.ValueObject.URL, Module.DataSet.VigilanteBase, Vigilante.Aplicacao.ModelBase; type TControllerBase<T: IVigilanteModelBase> = class abstract(TInterfacedObject, IBaseController) protected function GetDataSetInterno: TVigilanteDataSetBase<T>; virtual; abstract; public procedure AdicionarNovaURL(const AURL: IURL); virtual; procedure BuscarAtualizacoes; virtual; abstract; function PodeNotificarUsuario(const AID: TGUID): boolean; virtual; procedure VisualizadoPeloUsuario(const AID: TGUID); virtual; end; implementation uses Data.DB; { TControllerBase } procedure TControllerBase<T>.AdicionarNovaURL(const AURL: IURL); begin if GetDataSetInterno.State in dsEditModes then GetDataSetInterno.Cancel; GetDataSetInterno.Insert; GetDataSetInterno.URL := AURL.AsString; GetDataSetInterno.Post; end; function TControllerBase<T>.PodeNotificarUsuario(const AID: TGUID): boolean; begin Result := False; if GetDataSetInterno.LocalizarPorID(AID) then Result := GetDataSetInterno.Notificar; end; procedure TControllerBase<T>.VisualizadoPeloUsuario(const AID: TGUID); begin if not GetDataSetInterno.LocalizarPorID(AID) then Exit; GetDataSetInterno.Edit; GetDataSetInterno.Notificar := False; GetDataSetInterno.Post; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_MeshLoaderObj; interface uses Classes, Math, SysUtils, StrUtils, Types, RN_Helper; type TrcMeshLoaderObj = class private m_filename: string; m_scale: Single; m_verts: PSingle; m_tris: PInteger; m_normals: PSingle; m_vertCount: Integer; m_triCount: Integer; procedure addVertex(x,y,z: Single; cap: PInteger); procedure addTriangle(a,b,c: Integer; cap: PInteger); public constructor Create; destructor Destroy; override; function load(const fileName: string): Boolean; property getVerts: PSingle read m_verts; property getTris: PInteger read m_tris; property getNormals: PSingle read m_normals; property getVertCount: Integer read m_vertCount; property getTriCount: Integer read m_triCount; property getFileName: string read m_filename; end; implementation uses RN_RecastHelper; function StringLow(const aString: string): Integer; begin {$IFDEF FPC} Result := Low(aString); {$ELSE} {$IF CompilerVersion >= 24} Result := Low(aString); // Delphi XE3 and up can use Low(s) {$ELSE} Result := 1; // Delphi XE2 and below can't use Low(s), but don't have ZEROBASEDSTRINGS either {$IFEND} {$ENDIF} end; function StringHigh(const aString: string): Integer; begin {$IFDEF FPC} Result := Length(aString); {$ELSE} {$IF CompilerVersion >= 24} Result := High(aString); // Delphi XE3 and up can use High(s) {$ELSE} Result := Length(aString); // Delphi XE2 and below can't use High(s), but don't have ZEROBASEDSTRINGS either {$IFEND} {$ENDIF} end; constructor TrcMeshLoaderObj.Create; begin inherited; m_scale := 1.0; end; destructor TrcMeshLoaderObj.Destroy; begin FreeMem(m_verts); FreeMem(m_normals); FreeMem(m_tris); inherited; end; procedure TrcMeshLoaderObj.addVertex(x,y,z: Single; cap: PInteger); var nv,dst: PSingle; begin if (m_vertCount+1 > cap^) then begin if cap^ = 0 then cap^ := 8 else cap^ := cap^*2; GetMem(nv, SizeOf(Single)*cap^*3); if (m_vertCount <> 0) then Move(m_verts^, nv^, m_vertCount*3*sizeof(Single)); FreeMem(m_verts); m_verts := nv; end; dst := @m_verts[m_vertCount*3]; dst[0] := x*m_scale; dst[1] := y*m_scale; dst[2] := z*m_scale; Inc(m_vertCount); end; //void rcMeshLoaderObj::addTriangle(int a, int b, int c, int& cap) procedure TrcMeshLoaderObj.addTriangle(a,b,c: Integer; cap: PInteger); var nv,dst: PInteger; begin if (m_triCount+1 > cap^) then begin if cap^ = 0 then cap^ := 8 else cap^ := cap^*2; GetMem(nv, SizeOf(Integer)*cap^*3); if (m_triCount <> 0) then Move(m_tris^, nv^, m_triCount*3*sizeof(integer)); FreeMem(m_tris); m_tris := nv; end; dst := @m_tris[m_triCount*3]; dst[0] := a; dst[1] := b; dst[2] := c; Inc(m_triCount); end; function parseFace(row: string; var data: array of Integer; n, vcnt: Integer): Integer; var i,j,vi: Integer; items,elements: TStringDynArray; begin j := 0; items := SplitString(row, ' '); for i := 1 to High(items) do if items[i] <> '' then begin elements := SplitString(items[i], '/'); vi := StrToInt(elements[0]); if vi < 0 then data[j] := vi+vcnt else data[j] := vi-1; Inc(j); end; Result := j; if (j >= n) then Exit; end; function TrcMeshLoaderObj.load(const filename: string): Boolean; var sl: TStringList; i,j: Integer; s: string; nv,vcap,tcap: Integer; x,y,z: Single; a,b,c: Integer; face: array [0..31] of Integer; v0,v1,v2: PSingle; e0,e1: array [0..2] of Single; n: PSingle; d: Single; PrevDecimal: Char; begin sl := TStringList.Create; sl.LoadFromFile(fileName); PrevDecimal := FormatSettings.DecimalSeparator; FormatSettings.DecimalSeparator := '.'; vcap := 0; tcap := 0; for j := 0 to sl.Count - 1 do begin s := sl[j]; if Length(s) = 0 then Continue; if s[StringLow(s)] = '#' then Continue else if (s[StringLow(s)] = 'v') and (s[StringLow(s)+1] <> 'n') and (s[StringLow(s)+1] <> 't') then begin // Vertex pos Sscanf(RightStr(s, Length(s) - 2), '%f %f %f', [@x, @y, @z]); addVertex(x, y, z, @vcap); end else if s[StringLow(s)] = 'f' then begin // Faces nv := parseFace(s, face, 32, m_vertCount); for i := 2 to nv - 1 do begin a := face[0]; b := face[i-1]; c := face[i]; if (a < 0) or (a >= m_vertCount) or (b < 0) or (b >= m_vertCount) or (c < 0) or (c >= m_vertCount) then Continue; addTriangle(a, b, c, @tcap); end; end; end; sl.Free; // Calculate normals. GetMem(m_normals, sizeof(Single)*m_triCount*3); for i := 0 to m_triCount - 1 do begin v0 := @m_verts[m_tris[i*3]*3]; v1 := @m_verts[m_tris[i*3+1]*3]; v2 := @m_verts[m_tris[i*3+2]*3]; for j := 0 to 2 do begin e0[j] := v1[j] - v0[j]; e1[j] := v2[j] - v0[j]; end; n := @m_normals[i*3]; n[0] := e0[1]*e1[2] - e0[2]*e1[1]; n[1] := e0[2]*e1[0] - e0[0]*e1[2]; n[2] := e0[0]*e1[1] - e0[1]*e1[0]; d := sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]); if (d > 0) then begin d := 1.0/d; n[0] := n[0] * d; n[1] := n[1] * d; n[2] := n[2] * d; end; end; m_filename := filename; FormatSettings.DecimalSeparator := PrevDecimal; Result := true; end; end.
// GLScriptPython {: Python implementation for the GLScene scripting layer.<p> This unit is experimental.<p> <b>History : </b><font size=-1><ul> <li>11/11/2004 - SG - Creation </ul></font> } unit GLScriptPython; interface uses Classes, SysUtils, // GLScene XCollection, GLScriptBase, GLManager, // Python PythonEngine; type // TGLPythonEngine // {: This class only adds manager registration logic to the TPythonEngine class to enable the XCollection items (ie. TGLScriptPython) retain it's assigned compiler from design to run -time. } TGLPythonEngine = class(TPythonEngine) public constructor Create(AOnwer : TComponent); override; destructor Destroy; override; end; // GLScriptPython // {: Implements Python scripting functionality through the abstracted GLScriptBase. } TGLScriptPython = class(TGLScriptBase) private { Private Declarations } FEngine : TGLPythonEngine; FEngineName : String; FCompiled, FStarted : Boolean; protected { Protected Declarations } procedure SetEngine(const Value : TGLPythonEngine); procedure ReadFromFiler(reader : TReader); override; procedure WriteToFiler(writer : TWriter); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetState : TGLScriptState; override; public { Public Declarations } destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Compile; override; procedure Start; override; procedure Stop; override; procedure Execute; override; procedure Invalidate; override; function Call(aName : String; aParams : array of Variant) : Variant; override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; class function ItemCategory : String; override; published { Published Declarations } property Engine : TGLPythonEngine read FEngine write SetEngine; end; procedure Register; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- implementation // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- // --------------- // --------------- Miscellaneous --------------- // --------------- // Register // procedure Register; begin RegisterClasses([TGLPythonEngine, TGLScriptPython]); RegisterComponents('GLScene Python', [TGLPythonEngine]); end; // ---------- // ---------- TGLPythonEngine ---------- // ---------- // Create // constructor TGLPythonEngine.Create(AOnwer : TComponent); begin inherited; RegisterManager(Self); end; // Destroy // destructor TGLPythonEngine.Destroy; begin DeregisterManager(Self); inherited; end; // --------------- // --------------- TGLScriptPython --------------- // --------------- // Destroy // destructor TGLScriptPython.Destroy; begin Invalidate; inherited; end; // Assign // procedure TGLScriptPython.Assign(Source: TPersistent); begin inherited; if Source is TGLScriptPython then begin Engine:=TGLScriptPython(Source).Engine; end; end; // ReadFromFiler // procedure TGLScriptPython.ReadFromFiler(reader : TReader); var archiveVersion : Integer; begin inherited; archiveVersion:=reader.ReadInteger; Assert(archiveVersion = 0); with reader do begin FEngineName:=ReadString; end; end; // WriteToFiler // procedure TGLScriptPython.WriteToFiler(writer : TWriter); begin inherited; writer.WriteInteger(0); // archiveVersion with writer do begin if Assigned(FEngine) then WriteString(FEngine.GetNamePath) else WriteString(''); end; end; // Loaded // procedure TGLScriptPython.Loaded; var temp : TComponent; begin inherited; if FEngineName<>'' then begin temp:=FindManager(TGLPythonEngine, FEngineName); if Assigned(temp) then Engine:=TGLPythonEngine(temp); FEngineName:=''; end; end; // Notification // procedure TGLScriptPython.Notification(AComponent: TComponent; Operation: TOperation); begin if (AComponent = Engine) and (Operation = opRemove) then Engine:=nil; end; // FriendlyName // class function TGLScriptPython.FriendlyName : String; begin Result:='TGLScriptPython'; end; // FriendlyDescription // class function TGLScriptPython.FriendlyDescription : String; begin Result:='Python script'; end; // ItemCategory // class function TGLScriptPython.ItemCategory : String; begin Result:=''; end; // Compile // procedure TGLScriptPython.Compile; begin Invalidate; if Assigned(Engine) then begin Engine.ExecStrings(Text); FCompiled:=True; FStarted:=False; end else raise Exception.Create('No engine assigned!'); end; // Execute // procedure TGLScriptPython.Execute; begin Compile; end; // Invalidate // procedure TGLScriptPython.Invalidate; begin FStarted:=False; FCompiled:=False; end; // Start // procedure TGLScriptPython.Start; begin Compile; FStarted:=True; end; // Stop // procedure TGLScriptPython.Stop; begin FStarted:=False; end; // Call // function TGLScriptPython.Call(aName: String; aParams: array of Variant) : Variant; var func : PPyObject; args : array of TVarRec; i : Integer; begin if State = ssUncompiled then Start; if State = ssRunning then begin func:=Engine.FindFunction('__main__', aName); if Assigned(func) then if Length(aParams)>0 then begin SetLength(args, Length(aParams)); for i:=0 to Length(aParams)-1 do begin args[i].VType:=vtVariant; args[i].VVariant:=@aParams[i]; end; Result:=Engine.EvalFunction(func, args); end else Result:=Engine.EvalFunctionNoArgs(func); end; end; // SetCompiler // procedure TGLScriptPython.SetEngine(const Value : TGLPythonEngine); begin if Value<>FEngine then begin FEngine:=Value; Invalidate; end; end; // GetState // function TGLScriptPython.GetState : TGLScriptState; begin Result:=ssUncompiled; if Assigned(Engine) and FCompiled and FStarted then Result:=ssRunning; end; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- initialization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- RegisterXCollectionItemClass(TGLScriptPython); // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- finalization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- UnregisterXCollectionItemClass(TGLScriptPython); end.
program DNASequenceGenerator; uses crt, Sysutils, DNASequenceGeneratorUnit; var keyP: Char; begin sequences[0]:= 'A';//le asignamos a la posicion 0 el valor de A sequences[1]:= 'C';//le asignamos a la posicion 1 el valor de C sequences[2]:= 'G';//le asignamos a la posicion 2 el valor de G sequences[3]:= 'T';//le asignamos a la posicion 3 el valor de T repeat Write('Especificar la longitud de la secuencia de ADN: '); ReadLn(longitud); if( longitud < longitud_min) then begin WriteLn('la longitud debe ser mayor o igual a 7'); WriteLn('Presione ESC para salir'); ReadKey; Exit; end; if( longitud > longitud_max) then begin WriteLn('la longitud debe ser menor o igual a 1 000 000'); WriteLn('Presione ESC para salir'); readkey; Exit; end; Write('Escriba el nombre del archivo: '); ReadLn(nameFile); appendstr(nameFile, '.dna'); generateSequence(nameFile, longitud); WriteLn('Presione ESC para salir'); keyP:= ReadKey; until keyP=#27 {Esc} end.
//f10_tambah_jumlah_buku //Dev : Sandra //v1.0.0 unit f10_tambah_jumlah_buku; interface uses banana_csvparser; procedure tambah_jumlah_buku; //prosedur untuk menambahkan jumlah buku dengan id tertentu //input : id dan jumlah buku //output : jumlah buku bertambah dari sebelumnya type buku_baru = record b_id : string; b_jumlah : integer; end; var data : banana_csvdoc; k,baris,kol : integer; i : integer; buku : buku_baru; helper : string; helper2 : string; implementation procedure tambah_jumlah_buku; begin //load data data := load_csv('buku_tmp.csv'); baris := row_count(data); kol := coll_count(data); //input write('Masukkan ID buku : '); readln(buku.b_id); write('Masukkan jumlah buku yang ditambahkan : '); readln(buku.b_jumlah); //mencari data k:=1; while (buku.b_id <> data[k,1]) do begin k := k+1; end; //mengubah data helper := data[k,4]; val(helper,i); i := i + buku.b_jumlah; str(i,helper2); data[k,4] := helper2; //save save_csv(data,'buku_tmp.csv', baris,kol); //success message writeln(); writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ',data[k,2],' di perpustakaan menjadi ',data[k,4]); end; end.
unit oPKIEncryptionData; interface uses System.SysUtils, System.StrUtils, oPKIEncryption, oPKIEncryptionEx; type TPKIEncryptionData = class(TInterfacedObject, IPKIEncryptionData, IPKIEncryptionDataEx) protected fBuffer: string; fSignature: string; fSignatureID: string; fCrlURL: string; fHashValue: AnsiString; fHashText: AnsiString; fHashHex: AnsiString; fDateTimeSigned: TDateTime; function getBuffer: string; virtual; function getSignature: string; virtual; final; function getSignatureID: string; virtual; final; function getCrlURL: string; virtual; final; function getHashValue: AnsiString; virtual; final; function getHashHex: string; virtual; final; function getHashText: string; virtual; final; function getDateTimeSigned: TDateTime; virtual; final; function getFMDateTimeSigned: string; virtual; final; procedure setBuffer(const aValue: string); virtual; procedure setSignature(const aValue: string); virtual; final; procedure setSignatureID(const aValue: string); virtual; final; procedure setCrlURL(const aValue: string); virtual; final; procedure setHashHex(const aValue: AnsiString); virtual; final; procedure setHashText(const aValue: AnsiString); virtual; final; procedure setHashValue(const aValue: AnsiString); virtual; final; procedure setDateTimeSigned(const aValue: TDateTime); virtual; final; protected procedure AppendToBuffer(aStrings: array of string); virtual; final; procedure Clear; virtual; procedure Validate; virtual; public constructor Create; destructor Destroy; override; end; implementation { TPKIEncryptionData } constructor TPKIEncryptionData.Create; begin inherited; Clear; end; destructor TPKIEncryptionData.Destroy; begin inherited; end; function TPKIEncryptionData.getBuffer: string; begin Result := fBuffer; end; function TPKIEncryptionData.getCrlURL: string; begin Result := fCrlURL; end; function TPKIEncryptionData.getDateTimeSigned: TDateTime; begin Result := fDateTimeSigned; end; function TPKIEncryptionData.getFMDateTimeSigned: string; begin TDateTime2FMDateTime(fDateTimeSigned, Result, True, True); end; function TPKIEncryptionData.getHashHex: string; begin Result := String(fHashHex); end; function TPKIEncryptionData.getHashText: string; begin Result := String(fHashText); end; function TPKIEncryptionData.getHashValue: AnsiString; begin Result := fHashValue; end; function TPKIEncryptionData.getSignature: string; begin Result := fSignature; end; function TPKIEncryptionData.getSignatureID: string; begin Result := fSignatureID; end; procedure TPKIEncryptionData.setBuffer(const aValue: string); begin fBuffer := aValue; end; procedure TPKIEncryptionData.setCrlURL(const aValue: string); begin fCrlURL := aValue; end; procedure TPKIEncryptionData.setDateTimeSigned(const aValue: TDateTime); begin fDateTimeSigned := aValue; end; procedure TPKIEncryptionData.setHashHex(const aValue: AnsiString); begin fHashHex := aValue; end; procedure TPKIEncryptionData.setHashText(const aValue: AnsiString); begin fHashText := aValue; end; procedure TPKIEncryptionData.setHashValue(const aValue: AnsiString); begin fHashValue := aValue; end; procedure TPKIEncryptionData.setSignature(const aValue: string); begin fSignature := aValue; end; procedure TPKIEncryptionData.setSignatureID(const aValue: string); begin fSignatureID := aValue; end; procedure TPKIEncryptionData.AppendToBuffer(aStrings: array of string); var i: integer; begin for i := Low(aStrings) to High(aStrings) do fBuffer := fBuffer + aStrings[i]; end; procedure TPKIEncryptionData.Clear; var aGUID: TGUID; aGUIDStr: string; begin fBuffer := ''; fSignature := ''; fSignatureID := ''; fCrlURL := ''; fHashValue := ''; fHashText := ''; fHashHex := ''; fDateTimeSigned := 0; // assign a new ID on each call CreateGUID(aGUID); aGUIDStr := LowerCase(GUIDToString(aGUID)); aGUIDStr := AnsiReplaceStr(aGUIDStr, '{', ''); aGUIDStr := AnsiReplaceStr(aGUIDStr, '}', ''); aGUIDStr := AnsiReplaceStr(aGUIDStr, '-', ''); fSignatureID := aGUIDStr; end; procedure TPKIEncryptionData.Validate; begin // Handled via override methods when needed end; end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.OCZ; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TOCZSMARTSupport = class(TSMARTSupport) private function IsOCZAndNotVector(const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; function IsOCZTrion(const Model: String): Boolean; function ModelHasOCZString(const Model: String): Boolean; function SMARTHasOCZCharacteristics( const SMARTList: TSMARTValueList): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; const EntryID = $E9; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TOCZSMARTSupport } function TOCZSMARTSupport.GetTypeName: String; begin result := 'SmartOcz'; end; function TOCZSMARTSupport.IsSSD: Boolean; begin result := true; end; function TOCZSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := IsOCZTrion(IdentifyDevice.Model) or IsOCZAndNotVector(IdentifyDevice, SMARTList); end; function TOCZSMARTSupport.IsOCZTrion(const Model: String): Boolean; begin // OCZ-TRION100 2015/11/25 result := Find('OCZ-TRION', Model); end; function TOCZSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TOCZSMARTSupport.IsOCZAndNotVector( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := ModelHasOCZString(IdentifyDevice.Model) and SMARTHasOCZCharacteristics(SMARTList); end; function TOCZSMARTSupport.ModelHasOCZString(const Model: String): Boolean; begin result := Find('OCZ', Model); end; function TOCZSMARTSupport.SMARTHasOCZCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin // 2012/3/11 // OCZ-PETROL - http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=553;id=diskinfo#553 // OCZ-OCTANE S2 - http://crystalmark.info/bbs/c-board.cgi?cmd=one;no=577;id=diskinfo#577 // OCZ-VERTEX 4 - http://imageshack.us/a/img269/7506/ocz2.png result := (SMARTList.Count >= 8) and (SMARTList[0].Id = $01) and (SMARTList[1].Id = $03) and (SMARTList[2].Id = $04) and (SMARTList[3].Id = $05) and (SMARTList[4].Id = $09) and (SMARTList[5].Id = $0C) and (SMARTList[6].Id = $E8) and (SMARTList[7].Id = $E9); end; function TOCZSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID($E9)].Current; end; function TOCZSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TOCZSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(EntryID, SMARTList); end; function TOCZSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := false; result.Status := InnerCommonIsError(EntryID, SMARTList).Status; end; function TOCZSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TOCZSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID = $F1; begin try SMARTList.GetIndexByID(WriteID); result := true; except result := false; end; end; function TOCZSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $09; ThisErrorType = ReadError; ErrorID = $01; ReplacedSectorsID = $05; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.ReplacedSectors := SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID); result.TotalWrite := GetTotalWrite(SMARTList); end; function TOCZSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID = $F1; begin result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; result.InValue.ValueInMiB := LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID)); end; end.
unit NtUtils.Exec.Shell; interface uses NtUtils.Exec, NtUtils.Exceptions; type TExecShellExecute = class(TExecMethod) class function Supports(Parameter: TExecParam): Boolean; override; class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo): TNtxStatus; override; end; implementation uses Winapi.Shell, Winapi.WinUser, NtUtils.Exec.Win32, NtUtils.Objects; { TExecShellExecute } class function TExecShellExecute.Execute(ParamSet: IExecProvider; out Info: TProcessInfo): TNtxStatus; var ShellExecInfo: TShellExecuteInfoW; RunAsInvoker: IInterface; begin FillChar(ShellExecInfo, SizeOf(ShellExecInfo), 0); ShellExecInfo.cbSize := SizeOf(ShellExecInfo); ShellExecInfo.fMask := SEE_MASK_NOASYNC or SEE_MASK_UNICODE or SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_NO_UI; // SEE_MASK_NO_CONSOLE is opposite to CREATE_NEW_CONSOLE if ParamSet.Provides(ppNewConsole) and not ParamSet.NewConsole then ShellExecInfo.fMask := ShellExecInfo.fMask or SEE_MASK_NO_CONSOLE; ShellExecInfo.lpFile := PWideChar(ParamSet.Application); if ParamSet.Provides(ppParameters) then ShellExecInfo.lpParameters := PWideChar(ParamSet.Parameters); if ParamSet.Provides(ppCurrentDirectory) then ShellExecInfo.lpDirectory := PWideChar(ParamSet.CurrentDircetory); if ParamSet.Provides(ppRequireElevation) and ParamSet.RequireElevation then ShellExecInfo.lpVerb := 'runas'; if ParamSet.Provides(ppShowWindowMode) then ShellExecInfo.nShow := ParamSet.ShowWindowMode else ShellExecInfo.nShow := SW_SHOWNORMAL; // Set RunAsInvoker compatibility mode. It will be reverted // after exiting from the current function. if ParamSet.Provides(ppRunAsInvoker) then RunAsInvoker := TRunAsInvoker.SetCompatState(ParamSet.RunAsInvoker); Result.Location := 'ShellExecuteExW'; Result.Win32Result := ShellExecuteExW(ShellExecInfo); if Result.IsSuccess then with Info do begin FillChar(ClientId, SizeOf(ClientId), 0); // We use SEE_MASK_NOCLOSEPROCESS to get a handle to the process. hxProcess := TAutoHandle.Capture(ShellExecInfo.hProcess); hxThread := nil; end; end; class function TExecShellExecute.Supports(Parameter: TExecParam): Boolean; begin case Parameter of ppParameters, ppCurrentDirectory, ppNewConsole, ppRequireElevation, ppShowWindowMode, ppRunAsInvoker: Result := True; else Result := False; end; end; end.
unit TreeExcelDataModule; interface uses System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer, CustomExcelTable, Data.DB; type TTreeExcelTable = class(TCustomExcelTable) private function GetExternalID: TField; function GetParentExternalID: TField; function GetValue: TField; protected procedure SetFieldsInfo; override; public property ExternalID: TField read GetExternalID; property ParentExternalID: TField read GetParentExternalID; property Value: TField read GetValue; end; TTreeExcelDM = class(TExcelDM) private function GetExcelTable: TTreeExcelTable; { Private declarations } protected function CreateExcelTable: TCustomExcelTable; override; public property ExcelTable: TTreeExcelTable read GetExcelTable; { Public declarations } end; implementation uses FieldInfoUnit; function TTreeExcelTable.GetExternalID: TField; begin Result := FieldByName('ExternalID'); end; function TTreeExcelTable.GetParentExternalID: TField; begin Result := FieldByName('ParentExternalID'); end; function TTreeExcelTable.GetValue: TField; begin Result := FieldByName('Value'); end; procedure TTreeExcelTable.SetFieldsInfo; begin FieldsInfo.Add(TFieldInfo.Create('ExternalID', True, 'Идентификатор категории не может быть пустым')); FieldsInfo.Add(TFieldInfo.Create('Value', True, 'Название категории не может быть пустым')); FieldsInfo.Add(TFieldInfo.Create('ParentExternalID')); end; function TTreeExcelDM.CreateExcelTable: TCustomExcelTable; begin Result := TTreeExcelTable.Create(Self); end; function TTreeExcelDM.GetExcelTable: TTreeExcelTable; begin Result := CustomExcelTable as TTreeExcelTable; end; { %CLASSGROUP 'Vcl.Controls.TControl' } {$R *.dfm} end.
//En un evento culinario hay N personas que van a comer y un empleado que los atiende de acuerdo //al orden de llegada. La persona le indica al empleado que plato quiere y este se lo entrega. //Nota: maximizar la concurrencia. PROGRAM Parcial Maxi BEGIN Monitor Cola BEGIN cond colaPersona; cond colaEmpleado: queue personas; int cantidadPersonas =0; bool hayPersonas; procedure pedirPlato(int personaId) BEGIN if(hayPersonas) BEGIN personas.push(personaId); signal(colaEmpleado); wait(colaPersona); END ELSE THEN hayPersonas =true: personas.push(personaId) signal(colaEmpleado); wait(colaPersona); END END procedure entregarPlato() BEGIN if(empty(personas)) THEN hayPersonas = false; END signal(colaPersona); END procedure obtenerPersona(var int personaId) BEGIN if(empty(personas)) THEN wait(colaEmpleado); END personaId = personas.pop(); END END process Empleado [0] BEGIN while(true) DO int personaId Cola.obtenerPersona(personaId); //obtener plato Cola.entregarPlato(); END END process Persona [p=1 to N] BEGIN Cola.pedirPlato(p); END END
unit SMARTSupport; interface uses SysUtils, BufferInterpreter, Device.SMART.List, Support; const LifeNotSupported = Integer.MaxValue; CommonLifeThreshold = 10; type TSMARTStatus = (Unknown, Good, Caution, Bad); TSMARTErrorResult = record Status: Boolean; Override: Boolean; end; TSMARTSupport = class abstract private function IsOldSSD(const Model: string): Boolean; function IsNewSSD(const RotationRate: TRotationRate): Boolean; function IsErrorAvailableForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; function IsErrorAvailableForCommonSSD( const SMARTList: TSMARTValueList): Boolean; function IsCautionAvailableForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; function IsCautionAvailableForCommonSSD( const SMARTList: TSMARTValueList): Boolean; function IsErrorForCommonHarddisk(const SMARTList: TSMARTValueList): Boolean; function IsErrorForCommonSSD(const SMARTList: TSMARTValueList): Boolean; function IsCautionForCommonHarddisk(const SMARTList: TSMARTValueList): Boolean; function IsCautionForCommonSSD(const SMARTList: TSMARTValueList): Boolean; function HarddiskCautionCheck(const SMARTEntry: TSMARTValueEntry; const Threshold: Integer): Boolean; function IsCaution(const SMARTList: TSMARTValueList): Boolean; function IsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; function IsError(const SMARTList: TSMARTValueList): Boolean; function IsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; virtual; abstract; function GetTypeName: String; virtual; abstract; function IsSSD: Boolean; virtual; abstract; function GetLife(const SMARTList: TSMARTValueList): Integer; function GetDriveStatus(const SMARTList: TSMARTValueList): TSMARTStatus; function IsInsufficientSMART: Boolean; virtual; abstract; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; virtual; abstract; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; virtual; abstract; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; virtual; function Find(const ToFind, At: String): Boolean; function FindAtFirst(const ToFind, At: String): Boolean; function CheckIsSSDInCommonWay(const IdentifyDevice: TIdentifyDeviceResult): Boolean; function IsEntryAvailable(const ID: Byte; const SMARTList: TSMARTValueList): Boolean; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; virtual; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; virtual; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; virtual; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; virtual; function InnerCommonIsError( const EntryID: Byte; const SMARTList: TSMARTValueList): TSMARTErrorResult; function InnerCommonIsCaution( const EntryID: Byte; const SMARTList: TSMARTValueList; const Threshold: Integer): TSMARTErrorResult; end; const TSMARTStatusInString: Array[TSMARTStatus] of String = ( 'Unknown', 'Good', 'Caution', 'Bad'); implementation { TSMARTSupport } function TSMARTSupport.ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; begin result := LifeNotSupported; end; function TSMARTSupport.Find(const ToFind, At: String): Boolean; begin result := Pos(ToFind, At) > 0; end; function TSMARTSupport.FindAtFirst(const ToFind, At: String): Boolean; begin result := Pos(ToFind, At) = 1; end; function TSMARTSupport.GetLife(const SMARTList: TSMARTValueList): Integer; begin try result := ErrorCheckedGetLife(SMARTList); except exit(LifeNotSupported); end; if result > 100 then result := LifeNotSupported; end; function TSMARTSupport.CheckIsSSDInCommonWay( const IdentifyDevice: TIdentifyDeviceResult): Boolean; begin result := (IsOldSSD(IdentifyDevice.Model)) or (IsNewSSD(IdentifyDevice.RotationRate)); end; // Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) function TSMARTSupport.IsOldSSD(const Model: string): Boolean; begin result := FindAtFirst('OCZ', Model) or FindAtFirst('SPCC', Model) or FindAtFirst('PATRIOT', Model) or FindAtFirst('PHOTOFAST', Model) or FindAtFirst('STT_FTM', Model) or FindAtFirst('Super Talent', Model) or Find('Solid', Model) or Find('SSD', Model) or Find('SiliconHardDisk', Model); end; function TSMARTSupport.IsNewSSD(const RotationRate: TRotationRate): Boolean; const SSDRate = 1; begin result := (RotationRate.Supported) and (RotationRate.Value = SSDRate); end; function TSMARTSupport.GetDriveStatus(const SMARTList: TSMARTValueList): TSMARTStatus; var Error: Boolean; Unknown: Boolean; Caution: Boolean; begin Error := IsErrorAvailable(SMARTList) and IsError(SMARTList); Unknown := not IsCautionAvailable(SMARTList); Caution := IsCautionAvailable(SMARTList) and IsCaution(SMARTList); if Error then result := TSMARTStatus.Bad else if Unknown then result := TSMARTStatus.Unknown else if Caution then result := TSMARTStatus.Caution else result := TSMARTStatus.Good; end; function TSMARTSupport.IsError(const SMARTList: TSMARTValueList): Boolean; var InnerResult: TSMARTErrorResult; begin if IsSSD then result := IsErrorForCommonSSD(SMARTList) else result := IsErrorForCommonHarddisk(SMARTList); InnerResult := InnerIsError(SMARTList); result := result and InnerResult.Status; if InnerResult.Override then result := InnerResult.Status; end; function TSMARTSupport.IsCaution(const SMARTList: TSMARTValueList): Boolean; var InnerResult: TSMARTErrorResult; begin if IsSSD then result := IsCautionForCommonSSD(SMARTList) else result := IsCautionForCommonHarddisk(SMARTList); InnerResult := InnerIsCaution(SMARTList); result := result and InnerResult.Status; if InnerResult.Override then result := InnerResult.Status; end; function TSMARTSupport.IsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; begin if IsSSD then result := IsErrorAvailableForCommonSSD(SMARTList) else result := IsErrorAvailableForCommonHarddisk(SMARTList); result := result or InnerIsErrorAvailable(SMARTList); end; function TSMARTSupport.IsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; begin if IsSSD then result := IsCautionAvailableForCommonSSD(SMARTList) else result := IsCautionAvailableForCommonHarddisk(SMARTList); result := result or InnerIsCautionAvailable(SMARTList); end; function TSMARTSupport.IsErrorAvailableForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TSMARTSupport.IsErrorAvailableForCommonSSD( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TSMARTSupport.IsEntryAvailable(const ID: Byte; const SMARTList: TSMARTValueList): Boolean; begin try SMARTList.GetIndexByID(ID); result := true; except on E: EEntryNotFound do result := false; else raise; end; end; function TSMARTSupport.IsCautionAvailableForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(5, SMARTList) or IsEntryAvailable($C5, SMARTList) or IsEntryAvailable($C6, SMARTList); end; function TSMARTSupport.IsCautionAvailableForCommonSSD( const SMARTList: TSMARTValueList): Boolean; var CurrentEntry: TSMARTValueEntry; begin result := false; for CurrentEntry in SMARTList do result := result or (CurrentEntry.Threshold > 0); end; function TSMARTSupport.IsErrorForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; const Y = true; n = false; IsValueToBeChecked: Array[Byte] of Boolean = {0 1 2 3 4 5 6 7 8 9 A B C D E F} {0}(Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,n,n, {1} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {2} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {3} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {4} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {5} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {6} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {7} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {8} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {9} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {A} n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n, {B} n,n,n,n,n,n,n,n,n,n,n,Y,Y,Y,n,Y, {C} Y,Y,n,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y, {D} Y,Y,n,Y,Y,n,n,n,n,n,n,n,Y,Y,Y,Y, {E} Y,Y,Y,Y,Y,n,Y,Y,n,n,n,n,n,n,n,n, {F} Y,n,n,n,n,n,n,n,n,n,Y,n,n,n,Y,n); var CurrentEntry: TSMARTValueEntry; begin result := false; for CurrentEntry in SMARTList do if IsValueToBeChecked[CurrentEntry.ID] then if CurrentEntry.Threshold > CurrentEntry.Current then exit(true); end; function TSMARTSupport.IsErrorForCommonSSD( const SMARTList: TSMARTValueList): Boolean; var CurrentEntry: TSMARTValueEntry; begin result := false; for CurrentEntry in SMARTList do if CurrentEntry.ID <> $C2 then if CurrentEntry.Threshold > CurrentEntry.Current then exit(true); end; function TSMARTSupport.HarddiskCautionCheck( const SMARTEntry: TSMARTValueEntry; const Threshold: Integer): Boolean; const SkipValue = $FFFFFFFF; begin result := ((SMARTEntry.RAW and SkipValue) <> SkipValue) and (SMARTEntry.RAW >= Threshold); end; function TSMARTSupport.IsCautionForCommonHarddisk( const SMARTList: TSMARTValueList): Boolean; begin result := false; if IsEntryAvailable(5, SMARTList) then result := HarddiskCautionCheck(SMARTList[SMARTList.GetIndexByID(5)], 1); if IsEntryAvailable($C5, SMARTList) then result := result or HarddiskCautionCheck(SMARTList[SMARTList.GetIndexByID($C5)], 1); if IsEntryAvailable($C6, SMARTList) then result := result or HarddiskCautionCheck(SMARTList[SMARTList.GetIndexByID($C6)], 1); end; function TSMARTSupport.IsCautionForCommonSSD( const SMARTList: TSMARTValueList): Boolean; begin result := false; end; function TSMARTSupport.InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; begin result := false; end; function TSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := false; end; function TSMARTSupport.InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Status := false; result.Override := false; end; function TSMARTSupport.InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Status := false; result.Override := false; end; function TSMARTSupport.InnerCommonIsError( const EntryID: Byte; const SMARTList: TSMARTValueList): TSMARTErrorResult; var CurrentEntry: TSMARTValueEntry; begin result.Override := false; result.Status := false; if IsEntryAvailable(EntryID, SMARTList) then CurrentEntry := SMARTList[SMARTList.GetIndexByID(EntryID)]; result.Status := result.Status or (CurrentEntry.Current = 0) or (CurrentEntry.Current < CurrentEntry.Threshold); end; function TSMARTSupport.InnerCommonIsCaution( const EntryID: Byte; const SMARTList: TSMARTValueList; const Threshold: Integer): TSMARTErrorResult; var Entry: TSMARTValueEntry; begin result.Override := false; if IsEntryAvailable(EntryID, SMARTList) then Entry := SMARTList[SMARTList.GetIndexByID(EntryID)]; if Entry.Current < Threshold then result.Status := true; end; end.
unit Ths.Erp.StrinGrid.Helper; interface {$I ThsERP.inc} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.AppEvnts, Vcl.Menus, Data.DB, Ths.Erp.Database.Table, Ths.Erp.Functions; const COL_OBJ = 0; ROW_OBJ = 0; type TThsCellDataType = (ctString, ctInteger, ctDouble, ctDate, ctTime, ctDateTime); TThsCellBorder = class FLeftBorder: Boolean; FLeftBorderColor: TColor; FLeftBorderWidth: Integer; FLeftBorderStyle: TBorderStyle; FRightBorder: Boolean; FRightBorderColor: TColor; FRightBorderWidth: Integer; FRightBorderStyle: TBorderStyle; FTopBorder: Boolean; FTopBorderColor: TColor; FTopBorderWidth: Integer; FTopBorderStyle: TBorderStyle; FBottomBorder: Boolean; FBottomBorderColor: TColor; FBottomBorderWidth: Integer; FBottomBorderStyle: TBorderStyle; public property LeftBorder: Boolean read FLeftBorder write FLeftBorder; property LeftBorderColor: TColor read FLeftBorderColor write FLeftBorderColor; property LeftBorderWidth: Integer read FLeftBorderWidth write FLeftBorderWidth; property LeftBorderStyle: TBorderStyle read FLeftBorderStyle write FLeftBorderStyle; property RightBorder: Boolean read FRightBorder write FRightBorder; property RightBorderColor: TColor read FRightBorderColor write FRightBorderColor; property RightBorderWidth: Integer read FRightBorderWidth write FRightBorderWidth; property RightBorderStyle: TBorderStyle read FRightBorderStyle write FRightBorderStyle; property TopBorder: Boolean read FTopBorder write FTopBorder; property TopBorderColor: TColor read FTopBorderColor write FTopBorderColor; property TopBorderWidth: Integer read FTopBorderWidth write FTopBorderWidth; property TopBorderStyle: TBorderStyle read FTopBorderStyle write FTopBorderStyle; property BottomBorder: Boolean read FBottomBorder write FBottomBorder; property BottomBorderColor: TColor read FBottomBorderColor write FBottomBorderColor; property BottomBorderWidth: Integer read FBottomBorderWidth write FBottomBorderWidth; property BottomBorderStyle: TBorderStyle read FBottomBorderStyle write FBottomBorderStyle; constructor Create; end; TThsCellStyle = class private FCellDataType: TThsCellDataType; FFont: TFont; FBGColor: TColor; FTextAlign: TAlignment; FBorder: TThsCellBorder; FBorderWidth: Integer; FBorderColor: TColor; FBorderStyle: TBorderStyle; procedure SetBorderWidth(const Value: Integer); procedure SetBorderColor(const Value: TColor); procedure SetBorderStyle(const Value: TBorderStyle); public property CellDataType: TThsCellDataType read FCellDataType write FCellDataType; property Font: TFont read FFont write FFont; property BGColor: TColor read FBGColor write FBGColor; property TextAlign: TAlignment read FTextAlign write FTextAlign; property BorderWidth: Integer read FBorderWidth write SetBorderWidth; property Border: TThsCellBorder read FBorder write FBorder; property BorderColor: TColor read FBorderColor write SetBorderColor; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle; constructor Create(); destructor Destroy; override; end; TThsRowsStyle = class(TThsCellStyle) private FRowObject: TTable; public constructor Create(); destructor Destroy; override; property RowObject: TTable read FRowObject write FRowObject; end; THeaderRows = class private //FRows: ArrayInteger; FCellStyle: TThsCellStyle; public Rows: ArrayInteger; property CellStyle: TThsCellStyle read FCellStyle write FCellStyle; constructor Create; destructor Destroy; override; end; TSubTotalRows = class private FRows: ArrayInteger; FCellStyle: TThsCellStyle; public property Rows: ArrayInteger read FRows write FRows; property CellStyle: TThsCellStyle read FCellStyle write FCellStyle; constructor Create; destructor Destroy; override; end; TFooterRows = class private FRows: ArrayInteger; FCellStyle: TThsCellStyle; public property Rows: ArrayInteger read FRows write FRows; property CellStyle: TThsCellStyle read FCellStyle write FCellStyle; constructor Create; destructor Destroy; override; end; implementation constructor TThsRowsStyle.Create; begin inherited; FFont.Name := 'Arial'; FFont.Size := 9; FFont.Style := []; FFont.Color := clBlack; FBGColor := clWhite; FTextAlign := taLeftJustify; FBorderWidth := 1; FBorderColor := clBlack; FBorderStyle := bsSingle; end; destructor TThsRowsStyle.Destroy; begin if Assigned(FRowObject) then FRowObject.Free; inherited; end; { TGridCell } constructor TThsCellStyle.Create; begin FCellDataType := ctString; FFont := TFont.Create; FFont.Name := 'Verdana'; FFont.Size := 9; FFont.Style := []; FFont.Color := clBlack; FBGColor := clWhite; FTextAlign := taLeftJustify; FBorder := TThsCellBorder.Create; FBorderWidth := 1; FBorderColor := clBlack; FBorderStyle := bsSingle; end; destructor TThsCellStyle.Destroy; begin FFont.Free; FBorder.Free; inherited; end; procedure TThsCellStyle.SetBorderColor(const Value: TColor); begin FBorder.FLeftBorderColor := Value; FBorder.FRightBorderColor := Value; FBorder.FTopBorderColor := Value; FBorder.FBottomBorderColor := Value; end; procedure TThsCellStyle.SetBorderStyle(const Value: TBorderStyle); begin FBorder.FLeftBorderStyle := Value; FBorder.FRightBorderStyle := Value; FBorder.FTopBorderStyle := Value; FBorder.FBottomBorderStyle := Value; end; procedure TThsCellStyle.SetBorderWidth(const Value: Integer); begin FBorder.FLeftBorderWidth := Value; FBorder.FRightBorderWidth := Value; FBorder.FTopBorderWidth := Value; FBorder.FBottomBorderWidth := Value; end; { TGridCellBorder } constructor TThsCellBorder.Create(); begin LeftBorder := True; LeftBorderColor := clBlack; LeftBorderWidth := 1; LeftBorderStyle := bsSingle; RightBorder := True; RightBorderColor := clBlack; RightBorderWidth := 1; RightBorderStyle := bsSingle; TopBorder := True; TopBorderColor := clBlack; TopBorderWidth := 1; TopBorderStyle := bsSingle; BottomBorder := True; BottomBorderColor := clBlack; BottomBorderWidth := 1; BottomBorderStyle := bsSingle; end; { TFooterRows } constructor TFooterRows.Create; begin SetLength(FRows, 0); FCellStyle := TThsCellStyle.Create; FCellStyle.FFont.Name := 'Arial'; FCellStyle.FFont.Size := 9; FCellStyle.FFont.Style := [fsBold]; FCellStyle.FFont.Color := clBlack; FCellStyle.FBGColor := clSilver; FCellStyle.FTextAlign := taLeftJustify; FCellStyle.FBorderWidth := 1; FCellStyle.FBorderColor := clBlack; FCellStyle.FBorderStyle := bsSingle; end; destructor TFooterRows.Destroy; begin FCellStyle.Free; inherited; end; { TSubTotalRows } constructor TSubTotalRows.Create; begin SetLength(FRows, 0); FCellStyle := TThsCellStyle.Create; FCellStyle.FFont.Name := 'Arial'; FCellStyle.FFont.Size := 9; FCellStyle.FFont.Style := [fsBold, fsItalic]; FCellStyle.FFont.Color := clWhite; FCellStyle.FBGColor := clPurple; FCellStyle.FTextAlign := taLeftJustify; FCellStyle.FBorderWidth := 1; FCellStyle.FBorderColor := clBlack; FCellStyle.FBorderStyle := bsSingle; end; destructor TSubTotalRows.Destroy; begin FCellStyle.Free; inherited; end; { THeaderRows } constructor THeaderRows.Create; begin SetLength(Rows, 0); FCellStyle := TThsCellStyle.Create; FCellStyle.FFont.Name := 'Arial'; FCellStyle.FFont.Size := 9; FCellStyle.FFont.Style := [fsBold]; FCellStyle.FFont.Color := clBlack; FCellStyle.FBGColor := clWhite; FCellStyle.FTextAlign := taCenter; FCellStyle.FBorderWidth := 1; FCellStyle.FBorderColor := clBlack; FCellStyle.FBorderStyle := bsSingle; end; destructor THeaderRows.Destroy; begin FCellStyle.Free; inherited; end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Actions, Vcl.ActnList; type TMainForm = class(TForm) Label1: TLabel; Panel1: TPanel; Edit1: TEdit; ActionList: TActionList; acOpenChildForm: TAction; Button1: TButton; procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); procedure FormShow(Sender: TObject); procedure Label1Click(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure acOpenChildFormExecute(Sender: TObject); private FStart, FEnd: TDateTime; procedure UpdateDefaultAndSystemFonts; protected procedure Loaded; override; public procedure BuildLabels; constructor Create(AOwner: TComponent); override; end; var MainForm: TMainForm; procedure UpdateLabel(AForm: TForm; ALabel: TLabel; AEdit: TEdit; APanel: TPanel); implementation {$R *.dfm} uses ChildUnit; procedure UpdateLabel(AForm: TForm; ALabel: TLabel; AEdit: TEdit; APanel: TPanel); begin ALabel.Caption := Format( 'Parent: %d%s'+ 'Screen.IconFont.Height: %d%s'+ 'Screen.IconFont.PixelsPerInch: %d%s'+ 'App.DefaultFont.Height: %d%s'+ 'App.DefaultFont.PixelsPerInch: %d%s'+ 'Font.Height: %d%s'+ 'Font.PixelsPerInch: %d%s'+ 'Font.Size: %d%s'+ 'Font.Name: %s%s'+ 'Edit.Font.Height: %d%s'+ 'Edit.Height: %d%s'+ 'Panel.Height: %d%s'+ 'Scale Factor: %1.2f - MonitorPPI. %d', [Ord(AForm.ParentFont),sLineBreak, Screen.IconFont.Height,sLineBreak, Screen.IconFont.PixelsPerInch,sLineBreak, Application.DefaultFont.Height,sLineBreak, Application.DefaultFont.PixelsPerInch,sLineBreak, AForm.Font.Height,sLineBreak, AForm.Font.pixelsperinch,sLineBreak, AForm.Font.Size,sLineBreak, AForm.Font.Name,sLineBreak, AEdit.Font.Height,sLineBreak, AEdit.Height,sLineBreak, APanel.Height,sLineBreak, AForm.ScaleFactor, AForm.Monitor.PixelsPerInch]); AForm.Caption := Format('ClientWidth:%d - ClientHeight:%d',[ AForm.ClientWidth, AForm.ClientHeight]); end; procedure TMainForm.acOpenChildFormExecute(Sender: TObject); begin ChildForm := TChildForm.Create(nil); try ChildForm.ShowModal; finally ChildForm.Free; end; end; procedure TMainForm.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin UpdateLabel(Self, Label1, Edit1, Panel1); end; procedure TMainForm.UpdateDefaultAndSystemFonts; var LHeight: Integer; begin //Update Application.DefaultFont used by ChildForms with ParentFont = True Application.DefaultFont.Assign(Font); //Update system fonts as user preferences (without using Assign!) LHeight := Muldiv(Font.Height, Screen.PixelsPerInch, Monitor.PixelsPerInch); Screen.IconFont.Name := Font.Name; Screen.IconFont.Height := LHeight; Screen.MenuFont.Name := Font.Name; Screen.MenuFont.Height := LHeight; Screen.MessageFont.Name := Font.Name; Screen.MessageFont.Height := LHeight; Screen.HintFont.Name := Font.Name; Screen.HintFont.Height := LHeight; Screen.CaptionFont.Name := Font.Name; Screen.CaptionFont.Height := LHeight; end; procedure TMainForm.BuildLabels; var i: Integer; begin inherited; for I := 0 to 1000 do begin with TLabel.Create(Self) do begin Caption := 'Label: '+IntToStr(I); Parent := Self; SetBounds(I*10,I*10,100,100); end; end; end; constructor TMainForm.Create(AOwner: TComponent); var i: Integer; begin FStart := Now; inherited; //BuildLabels; end; procedure TMainForm.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); begin inherited; UpdateDefaultAndSystemFonts; end; procedure TMainForm.FormShow(Sender: TObject); var H,M,S,MS: Word; begin FEnd := Now; DecodeTime((FEnd - fStart),H,M,S,MS); Caption := Caption + Format('W:%d - H:%d - %d.%d sec.',[ ClientWidth, ClientHeight, S, MS]); end; procedure TMainForm.Label1Click(Sender: TObject); begin acOpenChildForm.Execute; end; procedure TMainForm.Loaded; begin //Very important for HighDPI: on Main Screen ParentFont must be always be False ParentFont := False; //Acquire system font and size (eg. for windows 10 Segoe UI and 14 at 96 DPI) //but without using Assign! Font.Name := Screen.IconFont.Name; //If you want to use system font Height: Font.Height := Muldiv(Screen.IconFont.Height, 96, Screen.IconFont.PixelsPerInch); (* //Sample assign Font by user preferences: Font.Name := 'Century Gothic'; Font.Color := clBlue; Font.Height := -14; *) inherited; //For Child Forms with ParentFont = True UpdateDefaultAndSystemFonts; //Test build run-time components //BuildLabels; end; end.
unit HttpUnit; interface uses IdHTTP; type TCBRHttp = class(TObject) public class function GetCourses(AValueNames: TArray<String>; ADate: TDateTime = 0) : TArray<Double>; static; class function ParseXML(const AXML: String; AValueNames: TArray<String>) : TArray<Double>; static; end; implementation uses System.Classes, System.SysUtils, Xml.XMLDoc, Xml.XMLIntf, System.Generics.Collections; class function TCBRHttp.GetCourses(AValueNames: TArray<String>; ADate: TDateTime = 0): TArray<Double>; var AidHttp: TIdHTTP; AURL: string; S: string; begin Assert(Length(AValueNames) > 0); AURL := 'http://www.cbr.ru/scripts/XML_daily.asp'; if ADate > 0 then AURL := AURL + Format('?date_req=%s', [FormatDateTime('dd/mm/yyyy', ADate)]); AidHttp := TIdHTTP.Create(nil); try AidHttp.HandleRedirects := True; // Чтобы сам обрабатывал перенаправление AidHttp.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'; S := AidHttp.Get(AURL); finally FreeAndNil(AidHttp); end; Result := ParseXML(S, AValueNames); end; class function TCBRHttp.ParseXML(const AXML: String; AValueNames: TArray<String>): TArray<Double>; var ACources: TList<Double>; ANode: IXMLNode; ANominal: Integer; ARootNode: IXMLNode; AValues: TList<String>; AXMLDocument: IXMLDocument; i: Integer; k: Integer; S: String; begin AValues := TList<String>.Create; ACources := TList<Double>.Create; try AValues.AddRange(AValueNames); for i := 0 to AValues.Count - 1 do ACources.Add(0); AXMLDocument := LoadXMLData(AXML); // TXMLDocument.Create(nil); ARootNode := AXMLDocument.DocumentElement; // Цикл по всем валютам for i := 0 to ARootNode.ChildNodes.Count - 1 do begin ANode := ARootNode.ChildNodes[i]; S := ANode.ChildValues['Name']; // Ищем, нужна ли нам такая валюта k := AValues.IndexOf(S); if k = -1 then Continue; ANominal := StrToIntDef(ANode.ChildValues['Nominal'], 0); if ANominal = 0 then Continue; S := ANode.ChildValues['Value']; ACources[k] := StrToFloatDef(S, 0) / ANominal; end; Result := ACources.ToArray; finally FreeAndNil(AValues); FreeAndNil(ACources); end; end; end.
{*******************************************************} { } { DelphiWebMVC } { } { 版权所有 (C) 2019 苏兴迎(PRSoft) } { } {*******************************************************} unit Command; interface uses System.SysUtils, System.Variants, RouleItem, System.Rtti, System.Classes, Web.HTTPApp, uConfig, System.DateUtils, SessionList, superobject, uInterceptor, uRouleMap, RedisList, LogUnit; var RouleMap: TRouleMap = nil; SessionListMap: TSessionList = nil; SessionName: string; rooturl: string; RTTIContext: TRttiContext; _Interceptor: TInterceptor; _RedisList: TRedisList; function OpenConfigFile(): ISuperObject; function OpenMIMEFile(): ISuperObject; procedure OpenRoule(web: TWebModule; RouleMap: TRouleMap; var Handled: boolean); function DateTimeToGMT(const ADate: TDateTime): string; function StartServer: string; procedure CloseServer; procedure setDataBase(jo: ISuperObject); implementation uses wnMain, DES, wnDM, ThSessionClear, FreeMemory, RedisM; var sessionclear: TThSessionClear; FreeMemory: TFreeMemory; procedure OpenRoule(web: TWebModule; RouleMap: TRouleMap; var Handled: boolean); var Action: TObject; ActoinClass: TRttiType; ActionMethod, CreateView, Interceptor: TRttiMethod; Response, Request, ActionPath: TRttiProperty; url, url1: string; item: TRouleItem; tmp: string; methodname: string; k: integer; ret: TValue; s: string; sessionid: string; begin web.Response.ContentEncoding := document_charset; web.Response.Server := 'IIS/6.0'; web.Response.Date := Now; url := LowerCase(web.Request.PathInfo); k := Pos('.', url); if k <= 0 then begin item := RouleMap.GetRoule(url, url1, methodname); if (item <> nil) then begin ActoinClass := RTTIContext.GetType(item.Action); ActionMethod := ActoinClass.GetMethod(methodname); CreateView := ActoinClass.GetMethod('CreateView'); if item.Interceptor then Interceptor := ActoinClass.GetMethod('Interceptor'); Request := ActoinClass.GetProperty('Request'); Response := ActoinClass.GetProperty('Response'); ActionPath := ActoinClass.GetProperty('ActionPath'); try if (ActionMethod <> nil) then begin try Action := item.Action.Create; Request.SetValue(Action, web.Request); Response.SetValue(Action, web.Response); ActionPath.SetValue(Action, item.path); CreateView.Invoke(Action, []); if item.Interceptor then begin ret := Interceptor.Invoke(Action, []); if (not ret.AsBoolean) then begin ActionMethod.Invoke(Action, []); end; end else begin ActionMethod.Invoke(Action, []); end; finally FreeAndNil(Action); end; end else begin web.Response.ContentType := 'text/html; charset=' + document_charset; s := '<html><body><div style="text-align: left;">'; s := s + '<div><h1>Error 404</h1></div>'; s := s + '<hr><div>[ ' + url + ' ] Not Find Page' + '</div></div></body></html>'; web.Response.Content := s; web.Response.SendResponse; end; finally Handled := true; end; end else begin web.Response.ContentType := 'text/html; charset=' + document_charset; s := '<html><body><div style="text-align: left;">'; s := s + '<div><h1>Error 404</h1></div>'; s := s + '<hr><div>[ ' + url + ' ] Not Find Page' + '</div></div></body></html>'; web.Response.Content := s; web.Response.SendResponse; end; end else begin if (not open_debug) and open_cache then begin web.Response.SetCustomHeader('Cache-Control', 'max-age='+cache_max_age); web.Response.SetCustomHeader('Pragma', 'Pragma'); tmp := DateTimeToGMT(TTimeZone.local.ToUniversalTime(now())); web.Response.SetCustomHeader('Last-Modified', tmp); tmp := DateTimeToGMT(TTimeZone.local.ToUniversalTime(now() + 24 * 60 * 60)); web.Response.SetCustomHeader('Expires', tmp); end else begin web.Response.SetCustomHeader('Cache-Control', 'no-cache,no-store'); end; end; end; function OpenConfigFile(): ISuperObject; var f: TStringList; jo: ISuperObject; txt: string; key: string; begin key := password_key; f := TStringList.Create; try try f.LoadFromFile(WebApplicationDirectory + config); txt := f.Text.Trim; if Trim(key) = '' then begin txt := f.Text; end else begin txt := DeCryptStr(txt, key); end; jo := SO(txt); jo.O['Server'].s['Port']; except log(config + '配置文件错误,服务启动失败'); jo := nil; end; finally f.Free; end; Result := jo; end; function OpenMIMEFile(): ISuperObject; var f: TStringList; jo: ISuperObject; txt: string; begin f := TStringList.Create; try try f.LoadFromFile(WebApplicationDirectory + mime); txt := f.Text.Trim; jo := SO(txt); except log(mime + '配置文件错误,服务启动失败'); jo := nil; end; finally f.Free; end; Result := jo; end; function DateTimeToGMT(const ADate: TDateTime): string; const WEEK: array[1..7] of PChar = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); MonthDig: array[1..12] of PChar = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); var wWeek, wYear, wMonth, wDay, wHour, wMin, wSec, wMilliSec: Word; sWeek, sMonth: string; begin DecodeDateTime(ADate, wYear, wMonth, wDay, wHour, wMin, wSec, wMilliSec); wWeek := DayOfWeek(ADate); sWeek := WEEK[wWeek]; sMonth := MonthDig[wMonth]; Result := Format('%s, %.2d %s %d %.2d:%.2d:%.2d GMT', [sWeek, wDay, sMonth, wYear, wHour, wMin, wSec]); end; function StartServer: string; var LURL: string; FPort: string; jo: ISuperObject; begin jo := OpenConfigFile(); if jo <> nil then begin //服务启动在SynWebApp查询 _LogList := TStringList.Create; _logThread := TLogTh.Create(false); SessionName := '__guid_session'; FPort := jo.O['Server'].s['Port']; _RedisList := nil; if jo.O['Redis'] <> nil then begin Redis_IP := jo.O['Redis'].s['Host']; Redis_Port := jo.O['Redis'].I['Port']; Redis_PassWord := jo.O['Redis'].s['PassWord']; Redis_InitSize := jo.O['Redis'].I['InitSize']; Redis_TimerOut := jo.O['Redis'].I['TimerOut']; if redis_ip <> '' then begin _RedisList := TRedisList.Create(Redis_InitSize); end; end; if auto_free_memory then FreeMemory := TFreeMemory.Create(False); RouleMap := TRouleMap.Create; SessionListMap := TSessionList.Create; sessionclear := TThSessionClear.Create(false); _Interceptor := TInterceptor.Create; setDataBase(jo); log('服务启动'); Result := FPort; end; end; procedure CloseServer; begin if SessionListMap <> nil then begin _LogList.Clear; _LogList.Free; _logThread.Terminate; Sleep(100); _logThread.Free; _Interceptor.Free; SessionListMap.Free; RouleMap.Free; DM.Free; sessionclear.Terminate; Sleep(100); sessionclear.Free; if auto_free_memory then begin FreeMemory.Terminate; Sleep(100); FreeMemory.Free; end; if _RedisList <> nil then _RedisList.Free; end; end; procedure setDataBase(jo: ISuperObject); var oParams: TStrings; dbjo, jo1: ISuperObject; dbitem, item: TSuperAvlEntry; value: string; begin DM := TDM.Create(nil); DM.DBManager.Active := false; try dbjo := jo.O['DBConfig']; if dbjo <> nil then begin for dbitem in dbjo.AsObject do begin oParams := TStringList.Create; jo1 := dbjo.O[dbitem.Name]; for item in jo1.AsObject do begin value := item.Name + '=' + item.Value.AsString; oParams.Add(value); end; DM.DBManager.AddConnectionDef(dbitem.Name, dbitem.Name, oParams); log('数据库配置:'+oParams.Text); oParams.Free; end; end; finally DM.DBManager.Active := true; end; end; end.
unit fWVPregLacStatusUpdate; { ================================================================================ * * Application: TDrugs Patch OR*3*377 and WV*1*24 * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * * Description: Update form to enter the appropriate information for * pregnancy and lactation data. Caller supplies the * appropriate patient via the TWVPatient object as * an IWVPaitent interface. * * Notes: * ================================================================================ } interface uses System.Actions, System.Classes, System.SysUtils, System.UITypes, System.Variants, Vcl.ActnList, Vcl.ComCtrls, Vcl.Controls, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.Menus, Vcl.StdCtrls, Winapi.Messages, Winapi.Windows, iWVInterface, DateUtils, rMisc, ORFn, ORCtrls, VAUtils, ORDtTm, rReminders, VA508AccessibilityManager; type TfrmWVPregLacStatusUpdate = class(TForm) btnCancel: TButton; btnSave: TButton; pnlOptions: TPanel; robnAbleToConceiveYes: TRadioButton; robnAbleToConceiveNo: TRadioButton; ckbxMenopause: TCheckBox; ckbxHysterectomy: TCheckBox; stxtAbleToConceive: TStaticText; stxtCurrentlyPregnant: TStaticText; pnlLactationStatus: TPanel; robnLactatingNo: TRadioButton; stxtLactationStatus: TStaticText; ckbxPermanent: TCheckBox; stxtReaderStop: TStaticText; grdConceive: TGridPanel; pnlConeiveLabel: TPanel; grdPregStatus: TGridPanel; pnlPregStatusLabel: TPanel; grdLayout: TGridPanel; pnlConveive: TPanel; pnlPregnant: TPanel; pnlLactationLabel: TPanel; grdLactation: TGridPanel; pnlOther: TPanel; ststxtOther: TStaticText; edtOther: TEdit; scrollBox: TScrollBox; pnlForm: TPanel; VA508AccessibilityManager1: TVA508AccessibilityManager; robnLactatingYes: TRadioButton; robnPregnantUnsure: TRadioButton; robnPregnantNo: TRadioButton; robnPregnantYes: TRadioButton; pnlLMP: TPanel; stxtLastMenstrualPeriod: TStaticText; dteLMPD: TORDateBox; pnlEDD: TPanel; stxtEDDMethod: TStaticText; dteEDD: TORDateBox; procedure AbleToConceiveYesNo(Sender: TObject); procedure PregnantYesNoUnsure(Sender: TObject); procedure CheckOkToSave(Sender: TObject); procedure robnLactatingYesNoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure dteLMPDExit(Sender: TObject); procedure dteLMPDChange(Sender: TObject); procedure dteEDDChange(Sender: TObject); procedure dteLMPDMouseLeave(Sender: TObject); procedure scrollBoxResize(Sender: TObject); procedure SetScrollBarHeight(FontSize: Integer); procedure dteLMPDDateDialogClosed(Sender: TObject); private { Private declarations } fDFN: string; MinFormHeight: Integer; //Determines when the scrollbars appear MinFormWidth: Integer; function calcDates(originalValue, newValue: TFMDateTime; update, patient: string): TFMDateTime; procedure updateEDD(date: TFMDateTime); public EDD: integer; function Execute: Boolean; function GetData(aList: TStringList): Boolean; end; function NewPLUpdateForm(aDFN: string): TfrmWVPregLacStatusUpdate; implementation {$R *.dfm} const { Names for Name=Value pairs } SUB_ABLE_TO_CONCEIVE = 'ABLE TO CONCEIVE'; SUB_LACTATION_STATUS = 'LACTATION STATUS'; SUB_LAST_MENSTRUAL_PERIOD = 'LAST MENSTRUAL PERIOD DATE'; SUB_EDD = 'EXPECTED DUE DATE'; SUB_MEDICAL_REASON = 'MEDICAL REASON'; SUB_PATIENT = 'PATIENT'; SUB_PREGNANCY_STATUS = 'PREGNANCY STATUS'; function NewPLUpdateForm(aDFN: string): TfrmWVPregLacStatusUpdate; begin Result := TfrmWVPregLacStatusUpdate.Create(Application.MainForm); with Result do begin Loaded; fDFN := aDFN; pnlLactationStatus.Visible := True; end; end; function TfrmWVPregLacStatusUpdate.calcDates(originalValue, newValue: TFMDateTime; update, patient: string): TFMDateTime; var itemID, temp: string; begin if update = 'EDD' then begin if EDD < 1 then begin Result := -1; Exit; end; itemID := IntToStr(EDD); end; temp := getLinkPromptValue(FloatToStr(newValue), itemID, FloatToStr(originalValue), patient); Result := StrToFloatDef(temp, -1); end; procedure TfrmWVPregLacStatusUpdate.CheckOkToSave(Sender: TObject); begin if robnAbleToConceiveYes.Checked then begin if robnPregnantYes.Checked then btnSave.Enabled := (dteEDD.FMDateTime > 0) else btnSave.Enabled := robnPregnantNo.Checked or robnPregnantUnsure.Checked; end else if robnAbleToConceiveNo.Checked then btnSave.Enabled := ckbxHysterectomy.Checked or ckbxMenopause.Checked or ckbxPermanent.Checked or (edtOther.Text <> '') else if robnLactatingYes.Checked or robnLactatingNo.Checked then btnSave.Enabled := True else btnSave.Enabled := False; end; procedure TfrmWVPregLacStatusUpdate.dteEDDChange(Sender: TObject); begin CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.dteLMPDChange(Sender: TObject); begin // CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.dteLMPDDateDialogClosed(Sender: TObject); begin updateEDD(dteLMPD.FMDateTime); CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.dteLMPDExit(Sender: TObject); begin updateEDD(dteLMPD.FMDateTime); end; procedure TfrmWVPregLacStatusUpdate.dteLMPDMouseLeave(Sender: TObject); begin updateEDD(dteLMPD.FMDateTime); CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.robnLactatingYesNoClick(Sender: TObject); begin CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.scrollBoxResize(Sender: TObject); begin inherited; ScrollBox.OnResize := nil; //At least minimum if (pnlForm.Width < MinFormWidth) or (pnlForm.Height < MinFormHeight) then pnlForm.Align := alNone; pnlForm.AutoSize := false; if (pnlForm.Width < MinFormWidth) then pnlForm.Width := MinFormWidth; if pnlForm.Height < MinFormHeight then pnlForm.Height := MinFormHeight; if (ScrollBox.Width >= MinFormWidth) then begin if (ScrollBox.Height >= (MinFormHeight)) then begin pnlForm.Align := alClient; end else begin pnlForm.Align := alTop; pnlForm.AutoSize := true; end; end else begin if (ScrollBox.Height >= (MinFormHeight)) then begin pnlForm.Align := alNone; pnlForm.Top := 0; pnlForm.Left := 0; pnlForm.AutoSize := false; pnlForm.Width := MinFormWidth; pnlForm.height := ScrollBox.Height; end else begin pnlForm.Align := alNone; pnlForm.Top := 0; pnlForm.Left := 0; pnlForm.AutoSize := true; end; end; ScrollBox.OnResize := ScrollBoxResize; end; procedure TfrmWVPregLacStatusUpdate.SetScrollBarHeight(FontSize: Integer); begin MinFormHeight := (self.grdPregStatus.Height + self.grdConceive.Height + self.grdConceive.Height); case FontSize of 8: MinFormWidth := self.ckbxPermanent.Left + self.ckbxPermanent.Width + 5; 10: MinFormWidth := self.ckbxPermanent.Left + self.ckbxPermanent.Width + 5; 12: MinFormWidth := self.ckbxPermanent.Left + self.ckbxPermanent.Width + 30; 14: MinFormWidth := 800; 18: MinFormWidth := 1000; end; end; procedure TfrmWVPregLacStatusUpdate.updateEDD(date: TFMDateTime); var aDate: TFMDateTime; begin aDate := calcDates(0, date, 'EDD', fDFN); if aDate > 0 then dteEDD.FMDateTime := aDate; end; procedure TfrmWVPregLacStatusUpdate.AbleToConceiveYesNo(Sender: TObject); begin if robnAbleToConceiveYes.Checked then begin ckbxMenopause.Checked := False; ckbxMenopause.Enabled := False; ckbxHysterectomy.Checked := False; ckbxHysterectomy.Enabled := False; ckbxPermanent.Checked := False; ckbxPermanent.Enabled := False; ststxtOther.Enabled := false; edtother.Enabled := false; robnPregnantYes.Enabled := True; robnPregnantYes.TabStop := True; robnPregnantNo.Enabled := True; robnPregnantUnsure.Enabled := True; stxtLastMenstrualPeriod.Enabled := False; dteLMPD.Enabled := false; dteEDD.Enabled := false; stxtEDDMethod.Enabled := False; end else if robnAbleToConceiveNo.Checked then begin ckbxMenopause.Enabled := True; ckbxHysterectomy.Enabled := True; ckbxPermanent.Enabled := True; ststxtOther.Enabled := true; edtOther.Enabled := true; robnPregnantYes.Enabled := False; robnPregnantYes.Checked := False; robnPregnantNo.Enabled := False; robnPregnantNo.Checked := False; robnPregnantUnsure.Enabled := False; robnPregnantUnsure.Checked := False; stxtLastMenstrualPeriod.Enabled := False; dteLMPD.Enabled := false; dteEDD.Enabled := false; stxtEDDMethod.Enabled := False; end else begin ckbxMenopause.Checked := False; ckbxMenopause.Enabled := False; ckbxHysterectomy.Checked := False; ckbxHysterectomy.Enabled := False; ckbxPermanent.Checked := False; ckbxPermanent.Enabled := False; ststxtOther.Enabled := false; edtOther.Enabled := false; robnPregnantYes.Enabled := False; robnPregnantYes.Checked := False; robnPregnantNo.Enabled := False; robnPregnantNo.Checked := False; robnPregnantUnsure.Enabled := False; robnPregnantUnsure.Checked := False; stxtLastMenstrualPeriod.Enabled := False; dteLMPD.Enabled := false; dteEDD.Enabled := false; stxtEDDMethod.Enabled := False; end; CheckOkToSave(Sender); end; procedure TfrmWVPregLacStatusUpdate.PregnantYesNoUnsure(Sender: TObject); begin if robnPregnantYes.Checked then begin stxtLastMenstrualPeriod.Enabled := True; dteLMPD.Enabled := true; dteEDD.Enabled := true; stxtEDDMethod.Enabled := True; // if ScreenReaderActive then // begin // stxtEDDMethod.TabStop := True; // stxtEDDMethod.TabOrder := 4; // end; end else begin stxtLastMenstrualPeriod.Enabled := False; dteLMPD.FMDateTime := 0; dteEDD.FMDateTime := 0; dteLMPD.Text := ''; dteEDD.Text := ''; dteLMPD.Enabled := false; dteEDD.Enabled := false; stxtEDDMethod.Enabled := False; end; CheckOkToSave(Sender); end; function TfrmWVPregLacStatusUpdate.Execute: Boolean; begin Result := (ShowModal = mrOk); end; procedure TfrmWVPregLacStatusUpdate.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; try SaveUserBounds(Self); Action := caFree; finally Action := caFree; end; end; procedure TfrmWVPregLacStatusUpdate.FormCreate(Sender: TObject); var height, dteheight: integer; begin inherited; SetFormPosition(Self); ResizeFormToFont(self); //setLabelTabStops(ScreenReaderActive); height := TextHeightByFont(stxtAbleToConceive.Font.Handle, stxtAbleToConceive.Caption); pnlConeiveLabel.Height := height + 5; pnlPregStatusLabel.Height := height + 5; pnlLactationLabel.Height := height + 5; SetScrollBarHeight(MainFontSize); dteheight := (height + 5); self.pnlLMP.Height := dteheight + 1; self.pnlEDD.Height := dteheight + 1; self.dteLMPD.Constraints.MaxHeight := dteheight; self.dteEDD.Constraints.MaxHeight := dteheight; self.dteLMPD.Constraints.MinHeight := dteheight; self.dteEDD.Constraints.MinHeight := dteheight; end; function TfrmWVPregLacStatusUpdate.GetData(aList: TStringList): Boolean; var aStr: string; procedure AddReason(var aStr: string; aValue: string); begin if aStr <> '' then begin // Remove any previous 'and's if Pos(' and ', aStr) > 0 then aStr := StringReplace(aStr, ' and ', ', ', [rfReplaceAll]); // Append on this value with a gramatically correct 'and' aStr := Format('%s and %s', [aStr, aValue]); // Set capitialization to gramatically correct first char only aStr := UpperCase(Copy(aStr, 1, 1)) + LowerCase(Copy(aStr, 2, Length(aStr))); end else aStr := aValue; end; begin aList.Clear; try aList.Values[SUB_PATIENT] := fDFN; if robnAbleToConceiveYes.Checked then begin aList.Values[SUB_ABLE_TO_CONCEIVE] := 'Yes'; if robnPregnantYes.Checked then begin aList.Values[SUB_PREGNANCY_STATUS] := 'Yes'; if dteLMPD.FMDateTime > 0 then aList.Values[SUB_LAST_MENSTRUAL_PERIOD] := FloatToStr(dteLMPD.FMDateTime); if dteEDD.FMDateTime > 0 then aList.Values[SUB_EDD] := FloatToStr(dteEDD.FMDateTime); end else if robnPregnantNo.Checked then aList.Values[SUB_PREGNANCY_STATUS] := 'No' else if robnPregnantUnsure.Checked then aList.Values[SUB_PREGNANCY_STATUS] := 'Unsure' else aList.Values[SUB_PREGNANCY_STATUS] := 'Unknown'; end else if robnAbleToConceiveNo.Checked then begin aList.Values[SUB_ABLE_TO_CONCEIVE] := 'No'; aStr := ''; if ckbxHysterectomy.Checked then AddReason(aStr, ckbxHysterectomy.Caption); if ckbxMenopause.Checked then AddReason(aStr, ckbxMenopause.Caption); if ckbxPermanent.Checked then AddReason(aStr, ckbxPermanent.Caption); if edtOther.Text <> '' then AddReason(aStr, edtOther.Text); aList.Values[SUB_MEDICAL_REASON] := aStr; end; if robnLactatingYes.Checked then aList.Values[SUB_LACTATION_STATUS] := 'Yes' else if robnLactatingNo.Checked then aList.Values[SUB_LACTATION_STATUS] := 'No'; Result := True; except on e: Exception do begin aList.Clear; aList.Add('-1^' + e.Message); Result := False; end; end; end; end.
unit TestDogMau; interface uses TestFramework, DogMau, DogClass, Viralata, System.SysUtils, LatidoNormal; type TestTDogMau = class(TTestCase) strict private FDogMau: TDogMau; protected procedure SetUp; override; procedure TearDown; override; published procedure ClassTest_TipoTDogMau_TDogMau; procedure LatidoTest_LatidoDogMau_AuAu; procedure RacaTest_RacaDogMau_Viralata; end; implementation procedure TestTDogMau.LatidoTest_LatidoDogMau_AuAu; begin CheckEquals('AU AU AU !', FDogMau.Latir); end; procedure TestTDogMau.RacaTest_RacaDogMau_Viralata; begin CheckEquals('E ai parça sou um Viralata da quebrada mermao !', FDogMau.RacaDog); end; procedure TestTDogMau.SetUp; begin inherited; FDogMau := TDogMau.Create; end; procedure TestTDogMau.TearDown; begin inherited; FDogMau.Free; end; procedure TestTDogMau.ClassTest_TipoTDogMau_TDogMau; begin CheckEquals(FDogMau.ClassType, TDogMau); end; initialization // Register any test cases with the test runner RegisterTest(TestTDogMau.Suite); end.
unit Monobank; interface uses Monobank.Types, Fix.REST.Client; type TMonobank = class private FClient: TRESTClient; FToken: string; protected procedure DoCheckToken; public /// <summary> /// Отримання курсів валют /// </summary> /// <remarks> /// Отримати базовий перелік курсів валют monobank. Інформація кешується та оновлюється не частіше 1 разу на 5 хвилин. /// </remarks> function Currency: TArray<TmonoCurrencyInfo>; /// <summary> /// Інформація про клієнта /// </summary> /// <remarks> /// Отримання інформації про клієнта та переліку його рахунків. Обмеження на використання функції не частіше ніж 1 раз у 60 секунд. /// </remarks> function ClientInfo: TmonoUserInfo; function Statement(AAccount: string; AFrom, ATo: Int64): TArray<TmonoStatementItem>; overload; function Statement(AAccount: string; AFrom, ATo: TDateTime): TArray<TmonoStatementItem>; overload; constructor Create; destructor Destroy; override; property Token: string read FToken write FToken; end; implementation uses System.SysUtils, System.DateUtils, REST.Types; { TMonobank } function TMonobank.ClientInfo: TmonoUserInfo; begin DoCheckToken; FClient.Params.AddHeader('X-Token', Token); Result := FClient.GetEntity<TmonoUserInfo>('/personal/client-info'); end; constructor TMonobank.Create; begin FClient := TRESTClient.Create('https://api.monobank.ua/'); end; function TMonobank.Currency: TArray<TmonoCurrencyInfo>; begin Result := FClient.GetEntityArray<TmonoCurrencyInfo>('/bank/currency'); end; destructor TMonobank.Destroy; begin FClient.Free; inherited; end; procedure TMonobank.DoCheckToken; begin if Token.IsEmpty then raise Exception.Create('Token is empty'); end; function TMonobank.Statement(AAccount: string; AFrom, ATo: TDateTime): TArray<TmonoStatementItem>; begin Result := Statement(AAccount, DateTimeToUnix(AFrom), DateTimeToUnix(ATo)); end; function TMonobank.Statement(AAccount: string; AFrom, ATo: Int64): TArray<TmonoStatementItem>; var LQuery: string; begin DoCheckToken; LQuery := '/personal/statement/{account}/{from}/{to}'; LQuery := LQuery.Replace('{account}', AAccount).Replace('{from}', AFrom.ToString).Replace('{to}', ATo.ToString); FClient.Params.AddHeader('X-Token', Token); Result := FClient.GetEntityArray<TmonoStatementItem>(LQuery); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, ExtCtrls, fphttpclient, Process, Registry; type { TLauncherForm } TLauncherForm = class(TForm) Button1: TButton; ButtonCancel: TButton; Message: TLabel; ProgressBar: TProgressBar; Timer: TTimer; procedure ButtonCancelClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormCreate(Sender: TObject); procedure TimerTimer(Sender: TObject); private {$IFDEF MSWINDOWS} function GetPathNodeWebkit: String; {$ENDIF} function DownloadNodeWebkit(AFrom, ATo: String): Boolean; procedure RunNodeWebkit(); procedure DataReceived(Sender : TObject; const ContentLength, CurrentPos : Int64); public end; var LauncherForm: TLauncherForm; HTTPClient: TFPHTTPClient; implementation {$R *.lfm} { TLauncherForm } {$IFDEF MSWINDOWS} function TLauncherForm.GetPathNodeWebkit: String; var Reg: TRegistry; begin Result := ''; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKeyReadOnly('SOFTWARE\StimiInc\nwjs-sdk-v0.54.1-win-x64') then begin if Reg.ValueExists('Path') then begin Result := Reg.ReadString('Path'); end end; finally Reg.Free; end; end; {$ENDIF} procedure TLauncherForm.DataReceived(Sender: TObject; const ContentLength, CurrentPos: Int64); begin Application.ProcessMessages; ProgressBar.Max := ContentLength; ProgressBar.Position := CurrentPos; end; procedure TLauncherForm.RunNodeWebkit(); var AProcess : TProcess; NodeWebkit: String; begin Application.ProcessMessages; {$IFDEF MSWINDOWS} NodeWebkit := GetPathNodeWebkit() + ' ' + ExtractFilePath(Application.ExeName) {$ENDIF} {$IFDEF DARWIN} NodeWebkit := ExtractFilePath(Application.ExeName) + '/node-webkit'; if not FileExists(NodeWebkit) then NodeWebkit := ''; {$ENDIF} if not (NodeWebkit = '') then begin AProcess := TProcess.Create(nil); try AProcess.ShowWindow := swoShowNormal; AProcess.CommandLine := NodeWebkit; AProcess.Execute; finally AProcess.Free; end; end; Application.Terminate; end; function TLauncherForm.DownloadNodeWebkit(AFrom, ATo: String): Boolean; begin try HTTPClient.OnDataReceived := @DataReceived; HTTPClient.AllowRedirect := True; HTTPClient.AddHeader('User-Agent', 'Launcher NW.js'); try HTTPClient.Get(AFrom, ATo); Result := True; except on E: Exception do ShowMessage(E.Message) end; finally HTTPClient.Free; end; end; procedure TLauncherForm.FormCreate(Sender: TObject); begin HTTPClient := TFPHTTPClient.Create(nil); {$IFDEF MSWINDOWS} if GetPathNodeWebkit() = '' then {$ENDIF} {$IFDEF DARWIN} if not FileExists('/Library/nwjs/0.54.1-sdk/nwjs.app/Contents/MacOS/nwjs') then {$ENDIF} begin Timer.Enabled := True; LauncherForm.Visible := True; end else begin RunNodeWebkit(); end end; procedure TLauncherForm.TimerTimer(Sender: TObject); var Result : AnsiString; TempDir : String; URL : String; NodeWebkit: String; begin Application.ProcessMessages; Timer.Enabled := False; TempDir := GetTempDir(); {$IFDEF MSWINDOWS} URL := 'http://downloads.oleksandrsovenko.com/nwjs/windows/nwjs-sdk-v0.54.1-win-x64.exe'; {$ENDIF} {$IFDEF DARWIN} URL := 'http://downloads.oleksandrsovenko.com/nwjs/macos/nwjs-sdk-v0.54.1-osx-x64.pkg'; {$ENDIF} NodeWebkit := TempDir + '/' + ExtractFileName(URL); if DownloadNodeWebkit(URL, NodeWebkit) then begin if FileExists(NodeWebkit) then begin {$IFDEF MSWINDOWS} RunCommand(NodeWebkit, [], Result); {$ENDIF} {$IFDEF DARWIN} RunCommand('open', [NodeWebkit], Result); {$ENDIF} end; RunNodeWebkit(); end; end; procedure TLauncherForm.ButtonCancelClick(Sender: TObject); begin if HTTPClient <> nil then HTTPClient.Terminate; Application.Terminate; end; procedure TLauncherForm.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin if HTTPClient <> nil then HTTPClient.Terminate; Application.Terminate; end; end.
unit BlockChain.Core; interface uses System.SysUtils, System.Classes, System.Hash, BlockChain.BaseBlock, BlockChain.MainChain, BlockChain.Account, BlockChain.Tokens, BlockChain.Transfer, BlockChain.Types, BlockChain.Inquiries, Crypto.RSA; type TBlockChainCore = class private MainChain: TMainChain; AccountsChain : TAccountChain; TokensChain: TTokensChain; TransfersChain: TTransferChain; public Inquiries: TBlockChainInquiries; constructor Create; destructor Destroy; override; end; implementation { TBlockChainCore } constructor TBlockChainCore.Create; begin SIZE_MAIN_CHAIN_INFO_V0 := Length(TMainBlockV0.GenerateInitBlock); SIZE_ACCOUNT_INFO_V0 := Length(TAccountBlockV0.GenerateInitBlock); SIZE_TOKENS_INFO_V0 := Length(TTokensBlockV0.GenerateInitBlock); SIZE_TRANSFER_INFO_V0 := Length(TTransferBlockV0.GenerateInitBlock); MainChain := TMainChain.Create('MainChain', TMainBlockV0.GenerateInitBlock, Main); AccountsChain := TAccountChain.Create('AccountChain', TAccountBlockV0.GenerateInitBlock, Accounts); TokensChain := TTokensChain.Create('TokensChain', TTokensBlockV0.GenerateInitBlock, Tokens); TransfersChain := TTransferChain.Create('TransfersChain', TTransferBlockV0.GenerateInitBlock, Transfers); Inquiries := TBlockChainInquiries.Create(MainChain,AccountsChain,TokensChain,TransfersChain); end; destructor TBlockChainCore.Destroy; begin AccountsChain.Free; inherited; end; end.
unit FIToolkit.Runner.Tasks; interface uses System.SysUtils, System.Threading, System.Generics.Collections, FIToolkit.Config.FixInsight; type TTaskRunner = class sealed strict private FExecutable : TFileName; FOptions : TFixInsightOptions; FOutputFileName : TFileName; private function GenerateOutputFileName : String; function GetInputFileName : TFileName; public constructor Create(const Executable : TFileName; Options : TFixInsightOptions); destructor Destroy; override; function Execute : ITask; property InputFileName : TFileName read GetInputFileName; property OutputFileName : TFileName read FOutputFileName; end; TTaskManager = class sealed private type TFilePair = TPair<TFileName, TFileName>; TTaskRunnerList = class (TObjectList<TTaskRunner>); strict private FRunners : TTaskRunnerList; public constructor Create(const Executable : TFileName; Options : TFixInsightOptions; const Files : array of TFileName; const TempDirectory : String); destructor Destroy; override; function RunAndGetOutput : TArray<TFilePair>; end; implementation uses System.IOUtils, System.Classes, Winapi.Windows, FIToolkit.Commons.Utils, FIToolkit.CommandLine.Types, FIToolkit.Runner.Exceptions, FIToolkit.Runner.Consts, FIToolkit.Logger.Default; { TTaskRunner } constructor TTaskRunner.Create(const Executable : TFileName; Options : TFixInsightOptions); begin inherited Create; FExecutable := Executable; FOptions := TFixInsightOptions.Create; FOptions.Assign(Options, False); end; destructor TTaskRunner.Destroy; begin FreeAndNil(FOptions); inherited Destroy; end; function TTaskRunner.Execute : ITask; var iExitCode : DWORD; begin Result := TTask.Run( procedure var sCmdLine : String; SI : TStartupInfo; PI : TProcessInformation; begin FOptions.OutputFileName := GenerateOutputFileName; FOutputFileName := FOptions.OutputFileName; sCmdLine := Format('%s %s', [TPath.GetQuotedPath(FExecutable, TCLIOptionString.CHR_QUOTE), FOptions.ToString]); FillChar(SI, SizeOf(TStartupInfo), 0); SI.cb := SizeOf(TStartupInfo); SI.wShowWindow := SW_HIDE; Log.Debug('sCmdLine = ' + sCmdLine); if CreateProcess(PChar(FExecutable), PChar(sCmdLine), nil, nil, False, CREATE_NO_WINDOW, nil, nil, SI, PI) then try while WaitForSingleObject(PI.hProcess, INFINITE) <> WAIT_OBJECT_0 do TThread.SpinWait(INT_SPIN_WAIT_ITERATIONS); if GetExitCodeProcess(PI.hProcess, iExitCode) and (iExitCode <> NOERROR) then if not WaitForFileAccess(FOutputFileName, TFileAccess.faRead, INT_FIOFILE_WAIT_CHECK_INTERVAL, INT_FIOFILE_WAIT_TIMEOUT) then raise ENonZeroExitCode.CreateFmt([iExitCode, sCmdLine]); finally CloseHandle(PI.hProcess); CloseHandle(PI.hThread); end else try RaiseLastOSError; except Exception.RaiseOuterException(ECreateProcessError.Create); end; end ); end; function TTaskRunner.GenerateOutputFileName : String; const CHR_DELIMITER = Char(CHR_TASK_OUTPUT_FILENAME_PARTS_DELIM); var sDir, sFileName, sFileExt, sProject, sUniquePart : String; begin sDir := TPath.GetDirectoryName(FOptions.OutputFileName, True); sFileName := TPath.GetFileNameWithoutExtension(FOptions.OutputFileName); sFileExt := TPath.GetExtension(FOptions.OutputFileName); sProject := TPath.GetFileNameWithoutExtension(FOptions.ProjectFileName); sUniquePart := TThread.CurrentThread.ThreadID.ToString + CHR_DELIMITER + TPath.GetGUIDFileName(False); Result := TPath.GetFullPath(sDir + sFileName + CHR_DELIMITER + sProject + CHR_DELIMITER + sUniquePart + sFileExt); end; function TTaskRunner.GetInputFileName : TFileName; begin Result := FOptions.ProjectFileName; end; { TTaskManager } constructor TTaskManager.Create(const Executable : TFileName; Options : TFixInsightOptions; const Files : array of TFileName; const TempDirectory : String); var FIO : TFixInsightOptions; S : String; begin inherited Create; FRunners := TTaskRunnerList.Create(True); FRunners.Capacity := Length(Files); FIO := TFixInsightOptions.Create; try FIO.Assign(Options, False); FIO.OutputFileName := TPath.Combine(TempDirectory, TPath.GetFileName(FIO.OutputFileName)); for S in Files do begin FIO.ProjectFileName := S; FRunners.Add(TTaskRunner.Create(Executable, FIO)); end; finally FIO.Free; end; end; destructor TTaskManager.Destroy; begin FreeAndNil(FRunners); inherited Destroy; end; function TTaskManager.RunAndGetOutput : TArray<TFilePair>; var arrTasks : TArray<ITask>; i : Integer; begin SetLength(arrTasks, FRunners.Count); for i := 0 to High(arrTasks) do arrTasks[i] := FRunners[i].Execute; try TTask.WaitForAll(arrTasks); except Exception.RaiseOuterException(ESomeTasksFailed.Create); end; SetLength(Result, FRunners.Count); for i := 0 to High(Result) do Result[i] := TFilePair.Create(FRunners[i].InputFileName, FRunners[i].OutputFileName); end; end.
program Sample; VAR C : Integer; procedure Output(A,B : Integer); VAR C : Integer; begin C := 2; WriteLn(A, ', ', B, ', ', C) end; begin C := 1; Output(7, 8); WriteLn('C = ', C) end.
unit uOpenComThread; interface uses Classes, Windows, SysUtils, uCommon, Dialogs; type TOpenComThread = class(TThread) private FPComVar: TPComVar; FComVisibility: Boolean; FExitEvent: THandle; // FThreadTerminated: Boolean; procedure SetPComVar(const Value: TPComVar); procedure SetComVisibility(const Value: Boolean); procedure SetExitEvent(const Value: THandle); // procedure SetThreadTerminated(const Value: Boolean); protected procedure Execute; override; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; procedure Init; procedure Term; property PComVar: TPComVar read FPComVar write SetPComVar; property ExitEvent: THandle read FExitEvent write SetExitEvent; property ComVisibility: Boolean read FComVisibility write SetComVisibility; // property ThreadTerminated: Boolean read FThreadTerminated write SetThreadTerminated; end; implementation { TOpenComThread } constructor TOpenComThread.Create; begin inherited Create(CreateSuspended); Init; end; destructor TOpenComThread.Destroy; begin Term; inherited; end; procedure TOpenComThread.Execute; var portName: AnsiString; begin FComVisibility := False; if PComVar <> nil then begin try PComVar^.hCom := INVALID_HANDLE_VALUE; PComVar^.ComVisibility := False; portName := ArrAnsiCharToAnsiStr(PComVar^.PortName); {FThreadTerminated := not} ResetEvent(FExitEvent); while (not Terminated) and (PComVar^.hCom = INVALID_HANDLE_VALUE) and (portName <> '') do begin //попытка открыть порт PComVar^.hCom := CreateFile(PChar('\\.\' + WideString(portName)),GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING, FILE_FLAG_OVERLAPPED,0); try Sleep(200); except CloseHandle(PComVar^.hCom); PComVar^.hCom := 0; end; end; if (PComVar^.hCom <> INVALID_HANDLE_VALUE) and (PComVar^.hCom <> 0) then begin FComVisibility := True; CloseHandle(PComVar^.hCom); PComVar^.hCom := 0; end; except CloseHandle(PComVar^.hCom); PComVar^.hCom := 0; end; end; ComVar.ComVisibility := ComVisibility; PComVar := nil; {FThreadTerminated :=} SetEvent(FExitEvent); end; procedure TOpenComThread.Init; begin // FThreadTerminated := False; end; procedure TOpenComThread.SetComVisibility(const Value: Boolean); begin FComVisibility := Value; end; procedure TOpenComThread.SetExitEvent(const Value: THandle); begin FExitEvent := Value; end; procedure TOpenComThread.SetPComVar(const Value: TPComVar); begin FPComVar := Value; end; //procedure TOpenComThread.SetThreadTerminated(const Value: Boolean); //begin // FThreadTerminated := Value; //end; procedure TOpenComThread.Term; begin CloseHandle(FExitEvent); end; end.
unit Book; interface type TBook = class private FTitle: AnsiString; FAuthor: AnsiString; public constructor Create; overload; constructor Create(Title, Author: AnsiString); overload; procedure SetTitle(Title: AnsiString); procedure SetAuthor(Author: AnsiString); function GetTitle: AnsiString; function GetAuthor: AnsiString; end; implementation constructor TBook.Create; begin FTitle := ''; FAuthor := ''; end; constructor TBook.Create(Title: AnsiString; Author: AnsiString); begin FTitle := Title; FAuthor := Author; end; procedure TBook.SetTitle(Title: AnsiString); begin FTitle := Title; end; procedure TBook.SetAuthor(Author: AnsiString); begin FAuthor := Author; end; function TBook.GetTitle; begin Result := FTitle; end; function TBook.GetAuthor; begin Result := FAuthor; end; end.
unit variant_0; interface implementation var V: Variant; procedure Test; begin V := SizeOF(Variant); Assert(V = 16); end; initialization Test(); finalization end.
(* CIStringSetUnit: MM, 2020-05-30 *) (* ------ *) (* A simple class for CaseInsensitiveStringSet Operations *) (* ========================================================================= *) UNIT CIStringSetUnit; INTERFACE USES StringSetUnit; TYPE CIStringSet = ^CIStringSetObj; CIStringSetObj = OBJECT(StringSetObj) PUBLIC CONSTRUCTOR Init(size: INTEGER); DESTRUCTOR Done; VIRTUAL; FUNCTION Contains(x: STRING): BOOLEAN; PROCEDURE Add(x: STRING); PROCEDURE Remove(x: STRING); END; (* StringSetObj *) IMPLEMENTATION CONSTRUCTOR CIStringSetObj.Init(size: INTEGER); BEGIN INHERITED Init(size); END; (* CIStringSetObj.Init *) DESTRUCTOR CIStringSetObj.Done; BEGIN INHERITED Done; END; (* CIStringSetObj.Done *) FUNCTION CIStringSetObj.Contains(x: STRING): BOOLEAN; BEGIN (* CIStringSetObj.Contains *) INHERITED Contains(UpCase(x)); END; (* CIStringSetObj.Contains *) PROCEDURE CIStringSetObj.Add(x: STRING); BEGIN (* StringSetObj.Add *) INHERITED Add(UpCase(x)); END; (* StringSetObj.Add *) PROCEDURE CIStringSetObj.Remove(x: STRING); BEGIN (* StringSetObj.Remove *) INHERITED Remove(UpCase(x)); END; (* StringSetObj.Remove *) END. (* CIStringSetUnit *)
unit TestCommandSet.Factory; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, CommandSet.Factory, Mock.CommandSets; type // Test methods for class TSCSIBufferInterpreter TestTCommandSetFactory = class(TTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure TestCreatingOrder; end; implementation procedure TestTCommandSetFactory.SetUp; begin end; procedure TestTCommandSetFactory.TearDown; begin end; procedure TestTCommandSetFactory.TestCreatingOrder; begin CheckEquals(True, GetCurrentCommandSet = CommandOrderOfNVMeIntel, 'CommandOrderOfNVMeIntel'); CommandSetFactory.GetSuitableCommandSet(''); CheckEquals(True, GetCurrentCommandSet = CommandOrderOfNVMeSamsung, 'CommandOrderOfNVMeSamsung'); CommandSetFactory.GetSuitableCommandSet(''); CheckEquals(True, GetCurrentCommandSet = CommandOrderOfATA, 'CommandOrderOfATA'); CommandSetFactory.GetSuitableCommandSet(''); CheckEquals(True, GetCurrentCommandSet = CommandOrderOfATALegacy, 'CommandOrderOfATALegacy'); CommandSetFactory.GetSuitableCommandSet(''); CheckEquals(True, GetCurrentCommandSet = CommandOrderOfSAT, 'CommandOrderOfSAT'); CommandSetFactory.GetSuitableCommandSet(''); CheckEquals(True, GetCurrentCommandSet = CommandOrderOfNVMeWithoutDriver, 'CommandOrderOfNVMeWithoutDriver'); StartExpectingException(ENoNVMeDriverException); CommandSetFactory.GetSuitableCommandSet(''); StopExpectingException('ENoNVMeDriverException'); end; initialization // Register any test cases with the test runner RegisterTest(TestTCommandSetFactory.Suite); end.
unit Model.Connection; interface uses System.JSON, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, Data.DB, FireDAC.Comp.Client, Firedac.DApt, FireDAC.Phys.FB, FireDAC.Phys.FBDef, System.Generics.Collections; var FDriver : TFDPhysFBDriverLink; FConnList : TObjectList<TFDConnection>; function Connected : Integer; procedure Disconnected(Index : Integer); implementation function Connected : Integer; begin if not Assigned(FConnList) then FConnList := TObjectList<TFDConnection>.Create; FConnList.Add(TFDConnection.Create(nil)); Result := Pred(FConnList.Count); FConnList.Items[Result].Params.DriverID := 'FB'; FConnList.Items[Result].Params.Database := 'D:\Projetos\Componentes\SimpleORM\SimpleORM.git\trunk\Sample\Database\PDVUPDATES.FDB'; FConnList.Items[Result].Params.UserName := 'SYSDBA'; FConnList.Items[Result].Params.Password := 'masterkey'; FConnList.Items[Result].Connected; end; procedure Disconnected(Index : Integer); begin FConnList.Items[Index].Connected := False; FConnList.Items[Index].Free; FConnList.TrimExcess; end; end.
{ "RTC Bitmap Utils (FMX)" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcFBmpUtils; interface {$INCLUDE rtcDefs.inc} uses SysUtils, System.Types, {$IFDEF IDE_XE5up} FMX.Graphics, {$ENDIF} {$IFNDEF IDE_XE6up} FMX.PixelFormats, {$ENDIF} FMX.Types, rtcTypes, rtcXJPEGConst, rtcXBmpUtils; type TRtcFMXMouseCursorData=class public FCursorMask: TBitmap; constructor Create; destructor Destroy; override; end; function NewBitmapInfo(FromScreen:boolean):TRtcBitmapInfo; // Make an in-memory Bitmap from a TBitmap (copies all info and image) procedure CopyBitmapToInfo(const SrcBmp:TBitmap; var DstBmp:TRtcBitmapInfo); // Copy in-memory bitmap to a TBitmap procedure CopyInfoToBitmap(const SrcBmp:TRtcBitmapInfo; var DstBmp:TBitmap); procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; const BmpOrig:TBitmap; NowMouseX, NowMouseY:integer; inControl:boolean); implementation function BitmapIsReverse(const Image: TBitmap;var Data:TBitmapData): boolean; begin With Image do if Height < 2 then Result := False else begin if not assigned(Data.Data) then if not Map(TMapAccess.maReadWrite,data) then raise Exception.Create('Can not access Bitmap data'); Result := RtcIntPtr(data.GetScanline(0))>RtcIntPtr(data.GetScanline(1)); end; end; function BitmapBytesPerLine(const Image: TBitmap;var Data:TBitmapData): integer; begin With Image do begin if not assigned(Data.Data) then if not Map(TMapAccess.maReadWrite,data) then raise Exception.Create('Can not access Bitmap data'); Result:=data.Pitch; end; end; function BitmapDataPtr(const Image: TBitmap; accMode:TMapAccess; var data:TBitmapData): pointer; begin With Image do begin if not assigned(Data.Data) then if not Map(accMode,data) then raise Exception.Create('Can not access Bitmap data'); if Height < 2 then Result := data.GetScanline(0) else if RtcIntPtr(data.GetScanLine(0)) < RtcIntPtr(data.GetScanLine(1)) then Result := data.GetScanLine(0) Else Result := data.GetScanline(data.Height - 1); End; end; function BitmapDataStride(const Image: TBitmap; var data:TBitmapData): integer; begin if not assigned(Data.Data) then if not Image.Map(TMapAccess.maReadWrite,data) then raise Exception.Create('Can not access Bitmap data'); Result:=RtcIntPtr(data.GetScanline(1))-RtcIntPtr(data.GetScanline(0)); end; function GetBitmapInfo(const Bmp:TBitmap; toRead,toWrite,FromScreen:boolean; var FMXData:TBitmapData):TRtcBitmapInfo; begin FillChar(Result,SizeOf(Result),0); FillChar(FMXData,SizeOf(FMXData),0); if toWrite then begin if toRead then Result.Data:=BitmapDataPtr(Bmp,TMapAccess.maReadWrite, FMXData) else Result.Data:=BitmapDataPtr(Bmp,TMapAccess.maWrite, FMXData); end else Result.Data:=BitmapDataPtr(Bmp,TMapAccess.maRead, FMXData); Result.Width:=Bmp.Width; Result.Height:=Bmp.Height; Result.Reverse:=BitmapIsReverse(Bmp,FMXData); Result.BytesPerLine:=BitmapBytesPerLine(Bmp,FMXData); case Bmp.PixelFormat of {$IFDEF IDE_XE6up} TPixelFormat.BGR, TPixelFormat.BGRA: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btRGBA32 else {$ENDIF} Result.BuffType:=btBGRA32; TPixelFormat.RGB, TPixelFormat.RGBA: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btBGRA32 else {$ENDIF} Result.BuffType:=btRGBA32; {$ELSE} pfA8R8G8B8: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btRGBA32 else {$ENDIF} Result.BuffType:=btBGRA32; pfA8B8G8R8: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btBGRA32 else {$ENDIF} Result.BuffType:=btRGBA32; {$ENDIF} else raise Exception.Create('Unsupported Bitmap Pixel Format'); end; Result.BytesPerPixel:=4; CompleteBitmapInfo(Result); end; procedure PutBitmapInfo(const Bmp:TBitmap; var BmpInfo:TRtcBitmapInfo;var FMXData:TBitmapData); begin if assigned(FMXData.Data) then begin Bmp.Unmap(FMXData); FMXData.Data:=nil; end; end; // Make an in-memory Bitmap from a TBitmap (copies all info and image) procedure CopyBitmapToInfo(const SrcBmp:TBitmap; var DstBmp:TRtcBitmapInfo); var FMXData:TBitmapData; SrcInfo:TRtcBitmapInfo; begin SrcInfo:=GetBitmapInfo(SrcBmp,True,False,False,FMXData); try CopyBitmapInfo(SrcInfo,DstBmp); finally PutBitmapInfo(SrcBmp,SrcInfo,FMXData); end; end; function MakeBitmapInfo(Bmp:TBitmap):TRtcBitmapInfo; var FMXData:TBitmapData; begin FillChar(Result,SizeOf(Result),0); FillChar(FMXData,SizeOf(FMXData),0); Result.Reverse:=BitmapIsReverse(Bmp,FMXData); case Bmp.PixelFormat of {$IFDEF IDE_XE6up} TPixelFormat.BGR, TPixelFormat.BGRA: Result.BuffType:=btBGRA32; TPixelFormat.RGB, TPixelFormat.RGBA: Result.BuffType:=btRGBA32; {$ELSE} pfA8R8G8B8: Result.BuffType:=btBGRA32; pfA8B8G8R8: Result.BuffType:=btRGBA32; {$ENDIF} else raise Exception.Create('Unsupported Bitmap Pixel Format'); end; Result.BytesPerPixel:=4; if assigned(FMXData.Data) then begin Bmp.Unmap(FMXData); FMXData.Data:=nil; end; CompleteBitmapInfo(Result); end; function NewBitmapInfo(FromScreen:boolean):TRtcBitmapInfo; var Bmp:TBitmap; FMXData:TBitmapData; begin FillChar(Result,SizeOf(Result),0); FillChar(FMXData,SizeOf(FMXData),0); {$IFDEF IDE_XE6up} Bmp:=TBitmap.Create; {$ELSE} Bmp:=TBitmap.Create(8,8); {$ENDIF} try Bmp.Width:=8; Bmp.Height:=8; Result.Reverse:=BitmapIsReverse(Bmp,FMXData); case Bmp.PixelFormat of {$IFDEF IDE_XE6up} TPixelFormat.BGR, TPixelFormat.BGRA: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btRGBA32 else {$ENDIF} Result.BuffType:=btBGRA32; TPixelFormat.RGB, TPixelFormat.RGBA: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btBGRA32 else {$ENDIF} Result.BuffType:=btRGBA32; {$ELSE} pfA8R8G8B8: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btRGBA32 else {$ENDIF} Result.BuffType:=btBGRA32; pfA8B8G8R8: {$IFDEF MACOSX} if FromScreen then Result.BuffType:=btBGRA32 else {$ENDIF} Result.BuffType:=btRGBA32; {$ENDIF} else raise Exception.Create('Unsupported Bitmap Pixel Format'); end; Result.BytesPerPixel:=4; if assigned(FMXData.Data) then begin Bmp.Unmap(FMXData); FMXData.Data:=nil; end; finally RtcFreeAndNil(Bmp); end; CompleteBitmapInfo(Result); end; procedure CopyInfoToBitmap(const SrcBmp:TRtcBitmapInfo; var DstBmp:TBitmap); var dstInfo:TRtcBitmapInfo; FMXData:TBitmapData; y,wid:integer; srcData,dstData:PByte; begin FillChar(FMXData,SizeOf(FMXData),0); if not assigned(DstBmp) then {$IFDEF IDE_XE6up} DstBmp:=TBitmap.Create; {$ELSE} DstBmp:=TBitmap.Create(SrcBmp.Width,SrcBmp.Height); {$ENDIF} if (DstBmp.Width<>SrcBmp.Width) or (DstBmp.Height<>SrcBmp.Height) then DstBmp.SetSize(SrcBmp.Width,SrcBmp.Height); if assigned(SrcBmp.Data) then begin DstInfo:=GetBitmapInfo(DstBmp,False,True,False,FMXData); try if assigned(dstInfo.Data) then begin if SrcBmp.BytesTotal>0 then begin if SrcBmp.BytesTotal = dstInfo.BytesTotal then Move(SrcBmp.Data^,DstInfo.Data^,SrcBmp.BytesTotal) else if (SrcBmp.Width=DstBmp.Width) and (SrcBmp.Height=DstBmp.Height) then begin wid:=srcBmp.Width*SrcBmp.BytesPerPixel; srcData:=PByte(srcBmp.TopData); dstData:=PByte(dstInfo.TopData); for Y := 0 to SrcBmp.Height-1 do begin Move(srcData^,dstData^,wid); Inc(srcData,SrcBmp.NextLine); Inc(dstData,dstInfo.NextLine); end; end else raise Exception.Create('DstBmp? '+IntToStr(dstInfo.BytesTotal)+'<>'+IntToStr(SrcBmp.BytesTotal)); end else raise Exception.Create('SrcBmp = 0?'); end else raise Exception.Create('DstBmp = NIL!'); finally PutBitmapInfo(DstBmp,DStInfo,FMXData); end; end else raise Exception.Create('SrcBmp = NIL!'); end; { TRtcVCLMouseCursorInfo } constructor TRtcFMXMouseCursorData.Create; begin inherited; FCursorMask:=nil; end; destructor TRtcFMXMouseCursorData.Destroy; begin FreeAndNil(FCursorMask); inherited; end; function RectF(x1,y1,x2,y2:integer):TRectF; begin Result.Left:=x1+0.5; Result.Top:=y1+0.5; Result.Right:=x2-0.5; Result.Bottom:=y2-0.5; end; procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; const BmpOrig:TBitmap; NowMouseX, NowMouseY:integer; inControl:boolean); var cX,cY,cW,cH:integer; ImgData:PColorBGR32; FMXData, FMXOrig:TBitmapData; Alpha:Double; cur:TRtcFMXMouseCursorData; procedure PaintMask_RGB; var SrcData,DstData:PColorRGB32; X,Y: integer; begin if (length(Cursor.MaskData)>0) then begin ImgData:=PColorBGR32(Addr(Cursor.MaskData[0])); // Apply "AND" mask for Y := 0 to cH - 1 do begin if ((Y+cY)>=0) and ((Y+cY)<FMXOrig.Height) then begin SrcData:=FMXOrig.GetScanline(Y+cY); Inc(SrcData,cX); DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if ((X+cX)>=0) and ((X+cX)<FMXOrig.Width) then begin DstData^.R:=SrcData^.R and ImgData^.R; DstData^.G:=SrcData^.G and ImgData^.G; DstData^.B:=SrcData^.B and ImgData^.B; DstData^.A:=255; end else begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; end; Inc(DstData); Inc(SrcData); Inc(ImgData); end; end else begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; Inc(DstData); Inc(ImgData); end; end; end; // Apply "INVERT" Mask if cH<Cursor.MaskH then for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if DstData^.A>0 then begin DstData^.R:=DstData^.R xor ImgData^.R; DstData^.G:=DstData^.G xor ImgData^.G; DstData^.B:=DstData^.B xor ImgData^.B; end; Inc(DstData); Inc(ImgData); end; end; end; // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if (DstData^.A>0) and (ImgData^.A>0) then begin Alpha:=ImgData^.A/255; DstData^.R:=trunc((DstData^.R*(1-Alpha)) + (ImgData^.R*Alpha)); DstData^.G:=trunc((DstData^.G*(1-Alpha)) + (ImgData^.G*Alpha)); DstData^.B:=trunc((DstData^.B*(1-Alpha)) + (ImgData^.B*Alpha)); end; Inc(DstData); Inc(ImgData); end; end; end; end; procedure PaintImg_RGB; var DstData:PColorRGB32; X,Y: integer; begin // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin DstData^.R:=ImgData^.R; DstData^.G:=ImgData^.G; DstData^.B:=ImgData^.B; DstData^.A:=ImgData^.A; Inc(DstData); Inc(ImgData); end; end; end; end; procedure PaintMask_BGR; var SrcData,DstData:PColorBGR32; X,Y: integer; begin if (length(Cursor.MaskData)>0) then begin ImgData:=PColorBGR32(Addr(Cursor.MaskData[0])); // Apply "AND" mask for Y := 0 to cH - 1 do begin if ((Y+cY)>=0) and ((Y+cY)<FMXOrig.Height) then begin SrcData:=FMXOrig.GetScanline(Y+cY); Inc(SrcData,cX); DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if ((X+cX)>=0) and ((X+cX)<FMXOrig.Width) then begin DstData^.R:=SrcData^.R and ImgData^.R; DstData^.G:=SrcData^.G and ImgData^.G; DstData^.B:=SrcData^.B and ImgData^.B; DstData^.A:=255; end else begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; end; Inc(DstData); Inc(SrcData); Inc(ImgData); end; end else begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; Inc(DstData); Inc(ImgData); end; end; end; // Apply "INVERT" Mask if cH<Cursor.MaskH then for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if DstData^.A>0 then begin DstData^.R:=DstData^.R xor ImgData^.R; DstData^.G:=DstData^.G xor ImgData^.G; DstData^.B:=DstData^.B xor ImgData^.B; end; Inc(DstData); Inc(ImgData); end; end; end; // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin if (DstData^.A>0) and (ImgData^.A>0) then begin Alpha:=ImgData^.A/255; DstData^.R:=trunc((DstData^.R*(1-Alpha)) + (ImgData^.R*Alpha)); DstData^.G:=trunc((DstData^.G*(1-Alpha)) + (ImgData^.G*Alpha)); DstData^.B:=trunc((DstData^.B*(1-Alpha)) + (ImgData^.B*Alpha)); end; Inc(DstData); Inc(ImgData); end; end; end; end; procedure PaintImg_BGR; var DstData:PColorBGR32; X,Y: integer; begin // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.GetScanline(Y); for X := 0 to cW-1 do begin DstData^.R:=ImgData^.R; DstData^.G:=ImgData^.G; DstData^.B:=ImgData^.B; DstData^.A:=ImgData^.A; Inc(DstData); Inc(ImgData); end; end; end; end; begin FillChar(FMXData,SizeOf(FMXData),0); FillChar(FMXOrig,SizeOf(FMXOrig),0); Cursor.Lock; try if Cursor.Data=nil then Cursor.Data:=TRtcFMXMouseCursorData.Create; cur:=TRtcFMXMouseCursorData(Cursor.Data); if Cursor.Visible and ( (length(Cursor.ImageData)>0) or (length(Cursor.MaskData)>0) ) then begin if inControl then begin cX:=NowMouseX-Cursor.HotX; cY:=NowMouseY-Cursor.HotY; end else begin cX:=Cursor.X-Cursor.HotX; cY:=Cursor.Y-Cursor.HotY; end; cW:=Cursor.ImageW; cH:=Cursor.ImageH; if (length(Cursor.MaskData)>0) and (length(Cursor.MaskData)=Cursor.MaskW*Cursor.MaskH*4) then begin if (length(Cursor.ImageData)>0) and (Cursor.MaskH = Cursor.ImageH) then begin cW:=Cursor.MaskW; cH:=Cursor.MaskH; end else if Cursor.MaskH > 1 then begin cW:=Cursor.MaskW; cH:=Cursor.MaskH div 2; end; if not assigned(cur.FCursorMask) then {$IFDEF IDE_XE6up} cur.FCursorMask := TBitmap.Create; {$ELSE} cur.FCursorMask := TBitmap.Create(cW,cH); {$ENDIF} cur.FCursorMask.Width:=cW; cur.FCursorMask.Height:=cH; {$IFDEF IDE_XE6up} if cur.FCursorMask.Map(TMapAccess.Write,FMXData) then try if BmpOrig.Map(TMapAccess.Read,FMXOrig) then try if BmpOrig.PixelFormat=TPixelFormat.RGBA then {$ELSE} if cur.FCursorMask.Map(TMapAccess.maWrite,FMXData) then try if BmpOrig.Map(TMapAccess.maRead,FMXOrig) then try if BmpOrig.PixelFormat=pfA8B8G8R8 then {$ENDIF} PaintMask_RGB else PaintMask_BGR; finally BmpOrig.Unmap(FMXOrig); end; finally cur.FCursorMask.Unmap(FMXData); end; end else if length(Cursor.ImageData)>0 then begin if not assigned(cur.FCursorMask) then {$IFDEF IDE_XE6up} cur.FCursorMask := TBitmap.Create; {$ELSE} cur.FCursorMask := TBitmap.Create(Cursor.ImageW,Cursor.ImageH); {$ENDIF} cur.FCursorMask.Width:=Cursor.ImageW; cur.FCursorMask.Height:=Cursor.ImageH; {$IFDEF IDE_XE6up} if cur.FCursorMask.Map(TMapAccess.Write,FMXData) then try if BmpOrig.PixelFormat=TPixelFormat.RGBA then {$ELSE} if cur.FCursorMask.Map(TMapAccess.maWrite,FMXData) then try if BmpOrig.PixelFormat=pfA8B8G8R8 then {$ENDIF} PaintImg_RGB else PaintImg_BGR; finally cur.FCursorMask.Unmap(FMXData); end; end else FreeAndNil(cur.FCursorMask); if assigned(cur.FCursorMask) then begin BmpCanvas.DrawBitmap(cur.FCursorMask, RectF(0, 0, cur.FCursorMask.Width, cur.FCursorMask.Height), RectF(cX, cY, cX+cur.FCursorMask.Width, cY+cur.FCursorMask.Height), 1,True); end; end; finally Cursor.UnLock; end; end; end.
unit Shared; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const Version = '0.1.0'; CommitNum = '5'; function DefaultFormat (Number: Double): UnicodeString; function AdvancedFormat (Number: Double): UnicodeString; implementation function DefaultFormat (Number: Double): UnicodeString; begin Result := FloatToStrF (Number, ffGeneral, 6, 6); end; function AdvancedFormat (Number: Double): UnicodeString; begin Result := FloatToStrF (Number, ffFixed, 12, 12); end; end.
program stack; type LongItemPtr = ^LongItem; LongItem = record data: longint; next: LongItemPtr; end; type StackLongInt = LongItemPtr; procedure StackInit(var stack: StackLongInt); begin stack := nil; end; procedure StackPush(var stack: StackLongInt; n: longint); var tmp: LongItemPtr; begin new(tmp); tmp^.data := n; tmp^.next := stack; stack := tmp; end; function StackPop(var stack: StackLongInt; var n: longint): boolean; var tmp: LongItemPtr; begin if stack = nil then begin StackPop := false; exit end; n := stack^.data; tmp := stack; stack := stack^.next; dispose(tmp); StackPop := true; end; function StackEmpty(var stack: StackLongInt): boolean; begin StackEmpty := stack = nil end; var s: StackLongInt; n: longint; begin StackInit(s); while not eof do begin readln(n); StackPush(s, n); end; while StackPop(s, n) do writeln(n) end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/chain.h // Bitcoin file: src/chain.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TBlockIndex; interface // Skybuck: example usage { uses arith_uint256, consensus.params, flatfile, primitives.block, tinyformat, uint256, vector; } // Skybuck: don't know for sure yet how to convert this probably just some constants. // perhaps these constats must be moved elsewhere or seperated into a unit if it's shared. (* // /** // * Maximum amount of time that a block timestamp is allowed to exceed the // * current network-adjusted time before the block will be accepted. // */ static constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60; // /** // * Timestamp window used as a grace period by code that compares external // * timestamps (such as timestamps passed to RPCs, or wallet key creation times) // * to block timestamps. This should be set at least as high as // * MAX_FUTURE_BLOCK_TIME. // */ static constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME; // /** // * Maximum gap between node time and block time used // * for the "Catching up..." mode in GUI. // * // * Ref: https://github.com/bitcoin/bitcoin/pull/1026 // */ static constexpr int64_t MAX_BLOCK_TIME_GAP = 90 * 60; *) type // /** The block chain is a tree shaped structure starting with the // * genesis block at the root, with each block potentially having multiple // * candidates to be the next block. A blockindex may have multiple pprev pointing // * to it, but at most one of them can be part of the currently active branch. // */ TBlockIndex = class public //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex const phashBlock: Puint256; //! pointer to the index of the predecessor of this block pprev: TBlockIndex; //! pointer to the index of some further predecessor of this block pskip: TBlockIndex; //! height of the entry in the chain. The genesis block has height 0 nHeight: Integer; //! Which # file this block is stored in (blk?????.dat) nFile: Integer; //! Byte offset within blk?????.dat where this block's data is stored nDataPos: Cardinal; //! Byte offset within rev?????.dat where this block's undo data is stored nUndoPos: Cardinal; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block nChainWork: arith_uint256; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon nTx: Cardinal; //! (memory only) Number of transactions in the chain up to and including this block. //! This value will be non-zero only if and only if transactions for this block and all its parents are available. //! Change to 64-bit type when necessary; won't happen before 2030 nChainTx: Cardinal; //! Verification status of this block. See enum BlockStatus nStatus: uint32_t; //! block header nVersion: int32_t; hashMerkleRoot: uint256; nTime: uint32_t; nBits: uint32_t; nNonce: uint32_t; //! (memory only) Sequential id assigned to distinguish order in which blocks are received. nSequenceId: int32_t; //! (memory only) Maximum nTime in the chain up to and including this block. nTimeMax: Cardinal; constructor Create(const CBlockHeader& block) function GetBlockPos() : FlatFilePos; function GetUndoPos() : FlatFilePos; function GetBlockHeader() : TBlockHeader; function GetBlockHash() : uint256; {** * Check whether this block's and all previous blocks' transactions have been * downloaded (and stored to disk) at some point. * * Does not imply the transactions are consensus-valid (ConnectTip might fail) * Does not imply the transactions are still stored on disk. (IsBlockPruned might return true) *} function HaveTxsDownloaded() : boolean; function GetBlockTime() : int64_t; function GetBlockTimeMax() : int64_t; static constexpr int nMedianTimeSpan = 11; function GetMedianTimePast() : int64_t; std::string ToString() const //! Check whether this block index entry is valid up to the passed validity level. function IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) : boolean; //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. function RaiseValidity(enum BlockStatus nUpTo) : boolean; //! Build the skiplist pointer for this entry. procedure BuildSkip(); //! Efficiently find an ancestor of this block. function GetAncestor(int height) : TBlockIndex; end; // Skybuck: might also have to be moved to a shared unit very maybe/perhaps. arith_uint256 GetBlockProof(const CBlockIndex& block); // /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&); // /** Find the forking point between two chain tips. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb); implementation constructor TBlockIndex.Create; begin end; constructor TBlockIndex.Create(const block: TBlockHeader) begin nVersion := block.nVersion; hashMerkleRoot := block.hashMerkleRoot; nTime := block.nTime; nBits := block.nBits; nNonce := block.nNonce; end; FlatFilePos GetBlockPos() const { FlatFilePos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } FlatFilePos GetUndoPos() const { FlatFilePos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } // /** // * Check whether this block's and all previous blocks' transactions have been // * downloaded (and stored to disk) at some point. // * // * Does not imply the transactions are consensus-valid (ConnectTip might fail) // * Does not imply the transactions are still stored on disk. (IsBlockPruned might return true) // */ bool HaveTxsDownloaded() const { return nChainTx != 0; } int64_t GetBlockTime() const { return (int64_t)nTime; } int64_t GetBlockTimeMax() const { return (int64_t)nTimeMax; } static constexpr int nMedianTimeSpan = 11; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } return false; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { if (height > nHeight || height < 0) { return nullptr; } const CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != nullptr && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } CBlockIndex* CBlockIndex::GetAncestor(int height) { return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height)); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for an arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (bnTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; } end.
unit SubsidiaryTypeList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton, Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, Vcl.DBCtrls, RzDBEdit; type TfrmSubsidiaryTypeList = class(TfrmBaseGridDetail) Label2: TLabel; edCode: TRzDBEdit; Label3: TLabel; edName: TRzDBEdit; Label4: TLabel; mmDescription: TRzDBMemo; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } protected function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; procedure SearchList; override; procedure BindToObject; override; public { Public declarations } end; implementation {$R *.dfm} uses AccountingAuxData, IFinanceDialogs; { TfrmBaseGridDetail1 } procedure TfrmSubsidiaryTypeList.BindToObject; begin inherited; end; function TfrmSubsidiaryTypeList.EditIsAllowed: boolean; begin end; function TfrmSubsidiaryTypeList.EntryIsValid: boolean; var error: string; begin if Trim(edCode.Text) = '' then error := 'Please enter code.' else if Trim(edName.Text) = '' then error := 'Please enter name.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; procedure TfrmSubsidiaryTypeList.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dmAccountingAux.Free; end; procedure TfrmSubsidiaryTypeList.FormCreate(Sender: TObject); begin dmAccountingAux := TdmAccountingAux.Create(self); inherited; end; function TfrmSubsidiaryTypeList.NewIsAllowed: boolean; begin end; procedure TfrmSubsidiaryTypeList.SearchList; begin grList.DataSource.DataSet.Locate('subsidiary_type_name',edSearchKey.Text, [loPartialKey,loCaseInsensitive]); end; end.
unit IdTCPServer; interface uses Classes, sysutils, IdComponent, IdException, IdSocketHandle, IdTCPConnection, IdThread, IdThreadMgr, IdThreadMgrDefault, IdIntercept; type TIdTCPServer = class; TIdListenerThread = class(TIdThread) protected FAcceptWait: Integer; FBindingList: TList; FServer: TIdTCPServer; public procedure AfterRun; override; constructor Create(axServer: TIdTCPServer); reintroduce; destructor Destroy; override; procedure Run; override; property AcceptWait: integer read FAcceptWait write FAcceptWait; property Server: TIdTCPServer read FServer; end; TIdTCPServerConnection = class(TIdTCPConnection) protected function GetServer: TIdTCPServer; public published property Server: TIdTCPServer read GetServer; end; TIdPeerThread = class(TIdThread) protected FConnection: TIdTCPServerConnection; procedure AfterRun; override; procedure BeforeRun; override; public procedure Run; override; property Connection: TIdTCPServerConnection read FConnection; end; TIdServerThreadEvent = procedure(AThread: TIdPeerThread) of object; TIdTCPServer = class(TIdComponent) protected FAcceptWait: integer; FActive, FImplicitThreadMgrCreated: Boolean; FThreadMgr: TIdThreadMgr; FBindings: TIdSocketHandles; FListenerThread: TIdListenerThread; FTerminateWaitTime: Integer; FThreadClass: TIdThreadClass; FThreads: TThreadList; FOnExecute, FOnConnect, FOnDisconnect: TIdServerThreadEvent; FIntercept: TIdServerIntercept; procedure DoConnect(axThread: TIdPeerThread); virtual; procedure DoDisconnect(axThread: TIdPeerThread); virtual; function DoExecute(AThread: TIdPeerThread): boolean; virtual; function GetDefaultPort: integer; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetAcceptWait(AValue: integer); procedure SetActive(AValue: Boolean); virtual; procedure SetBindings(const abValue: TIdSocketHandles); procedure SetDefaultPort(const AValue: integer); procedure SetIntercept(const Value: TIdServerIntercept); procedure SetThreadMgr(const Value: TIdThreadMgr); procedure TerminateAllThreads; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; property AcceptWait: integer read FAcceptWait write SetAcceptWait; property ImplicitThreadMgrCreated: Boolean read FImplicitThreadMgrCreated; property ThreadClass: TIdThreadClass read FThreadClass write FThreadClass; property Threads: TThreadList read FThreads; published property Active: boolean read FActive write SetActive default False; property Bindings: TIdSocketHandles read FBindings write SetBindings; property DefaultPort: integer read GetDefaultPort write SetDefaultPort; property Intercept: TIdServerIntercept read FIntercept write SetIntercept; property OnConnect: TIdServerThreadEvent read FOnConnect write FOnConnect; property OnExecute: TIdServerThreadEvent read FOnExecute write FOnExecute; property OnDisconnect: TIdServerThreadEvent read FOnDisconnect write FOnDisconnect; property TerminateWaitTime: Integer read FTerminateWaitTime write FTerminateWaitTime default 5000; property ThreadMgr: TIdThreadMgr read FThreadMgr write SetThreadMgr; end; EIdTCPServerError = class(EIdException); EIdAcceptWaitCannotBeModifiedWhileServerIsActive = class(EIdTCPServerError); EIdNoExecuteSpecified = class(EIdTCPServerError); implementation uses IdGlobal, IdResourceStrings, IdStack, IdStackConsts; constructor TIdTCPServer.Create(AOwner: TComponent); begin inherited; FAcceptWait := 1000; FTerminateWaitTime := 5000; FThreads := TThreadList.Create; FBindings := TIdSocketHandles.Create(Self); FThreadClass := TIdPeerThread; end; destructor TIdTCPServer.Destroy; begin Active := False; TerminateAllThreads; FreeAndNil(FBindings); FreeAndNil(FThreads); inherited; end; procedure TIdTCPServer.DoConnect(axThread: TIdPeerThread); begin if assigned(OnConnect) then begin OnConnect(axThread); end; end; procedure TIdTCPServer.DoDisconnect(axThread: TIdPeerThread); begin if assigned(OnDisconnect) then begin OnDisconnect(axThread); end; end; function TIdTCPServer.DoExecute(AThread: TIdPeerThread): boolean; begin result := assigned(OnExecute); if result then begin OnExecute(AThread); end; end; function TIdTCPServer.GetDefaultPort: integer; begin result := FBindings.DefaultPort; end; procedure TIdTCPServer.Loaded; begin inherited; if Active then begin FActive := False; Active := True; end; end; procedure TIdTCPServer.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) then begin if (AComponent = FThreadMgr) then begin FThreadMgr := nil; end else if (AComponent = FIntercept) then begin FIntercept := nil; end; end; end; procedure TIdTCPServer.SetAcceptWait(AValue: integer); begin if Active then begin raise EIdAcceptWaitCannotBeModifiedWhileServerIsActive.Create(RSAcceptWaitCannotBeModifiedWhileServerIsActive); end; FAcceptWait := AValue; end; procedure TIdTCPServer.SetActive(AValue: Boolean); var i: Integer; begin if (not (csDesigning in ComponentState)) and (FActive <> AValue) and (not (csLoading in ComponentState)) then begin if AValue then begin if Bindings.Count = 0 then begin Bindings.Add; end; for i := 0 to Bindings.Count - 1 do begin with Bindings[i] do begin AllocateSocket; SetSockOpt(Id_SOL_SOCKET, Id_SO_REUSEADDR, PChar(@Id_SO_True), SizeOf(Id_SO_True)); Bind; Listen; end; end; FImplicitThreadMgrCreated := not assigned(ThreadMgr); if ImplicitThreadMgrCreated then begin ThreadMgr := TIdThreadMgrDefault.Create(Self); end; ThreadMgr.ThreadClass := ThreadClass; FListenerThread := TIdListenerThread.Create(Self); FListenerThread.AcceptWait := AcceptWait; FListenerThread.Start; end else begin FListenerThread.Stop; for i := 0 to Bindings.Count - 1 do begin Bindings[i].CloseSocket(False); end; TerminateAllThreads; if ImplicitThreadMgrCreated then begin FreeAndNil(FThreadMgr); end; FImplicitThreadMgrCreated := false; FListenerThread.WaitFor; FListenerThread.Free; end; end; FActive := AValue; end; procedure TIdTCPServer.SetBindings(const abValue: TIdSocketHandles); begin FBindings.Assign(abValue); end; procedure TIdTCPServer.SetDefaultPort(const AValue: integer); begin FBindings.DefaultPort := AValue; end; procedure TIdTCPServer.SetIntercept(const Value: TIdServerIntercept); begin FIntercept := Value; if assigned(FIntercept) then begin FIntercept.FreeNotification(Self); end; end; procedure TIdTCPServer.SetThreadMgr(const Value: TIdThreadMgr); begin FThreadMgr := Value; if Value <> nil then begin Value.FreeNotification(self); end; end; procedure TIdTCPServer.TerminateAllThreads; var i: integer; list: TList; Thread: TIdPeerThread; const LSleepTime: integer = 250; begin list := Threads.LockList; try for i := 0 to list.Count - 1 do begin Thread := TIdPeerThread(list[i]); Thread.Connection.DisconnectSocket; end; finally Threads.UnlockList; end; for i := 1 to (TerminateWaitTime div LSleepTime) do begin Sleep(LSleepTime); list := Threads.LockList; try if list.Count = 0 then begin break; end; finally Threads.UnlockList; end; end; end; procedure TIdListenerThread.AfterRun; var i: Integer; begin inherited; for i := Server.Bindings.Count - 1 downto 0 do begin Server.Bindings[i].CloseSocket; end; end; constructor TIdListenerThread.Create(axServer: TIdTCPServer); begin inherited Create; FBindingList := TList.Create; FServer := axServer; end; destructor TIdListenerThread.Destroy; begin FBindinglist.Free; inherited; end; procedure TIdListenerThread.Run; var Peer: TIdTCPServerConnection; Thread: TIdPeerThread; i: Integer; begin FBindingList.Clear; for i := 0 to Server.Bindings.Count - 1 do begin FBindingList.Add(TObject(Server.Bindings[i].Handle)); end; if GStack.WSSelect(FBindingList, nil, nil, AcceptWait) > 0 then begin if not Terminated then begin for i := 0 to FBindingList.Count - 1 do begin Peer := TIdTCPServerConnection.Create(Server); with Peer do begin Binding.Accept(TIdStackSocketHandle(FBindingList[i])); if Assigned(Server.Intercept) then begin try Peer.Intercept := Server.Intercept.Accept(Binding); Peer.InterceptEnabled := True; except FreeAndNil(Peer); end; end; end; if Peer <> nil then begin Thread := TIdPeerThread(Server.ThreadMgr.GetThread); Thread.FConnection := Peer; Server.Threads.Add(Thread); Thread.Start; end; end; end; end; end; function TIdTCPServerConnection.GetServer: TIdTCPServer; begin result := Owner as TIdTCPServer; end; procedure TIdPeerThread.AfterRun; begin with Connection.Server do begin DoDisconnect(Self); ThreadMgr.ReleaseThread(Self); Threads.Remove(Self); end; FreeAndNil(FConnection); end; procedure TIdPeerThread.BeforeRun; begin Connection.Server.DoConnect(Self); end; procedure TIdPeerThread.Run; begin try if not Connection.Server.DoExecute(Self) then begin raise EIdNoExecuteSpecified.Create(RSNoExecuteSpecified); end; except on E: EIdSocketError do begin case E.LastError of Id_WSAECONNABORTED, Id_WSAECONNRESET: Connection.Disconnect; end; end; on EIdClosedSocket do ; else raise; end; if not Connection.Connected then begin Stop; end; end; end.
unit ChangePassword; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel, Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, RzButton, StrUtils, SaveIntf; type TfrmChangePassword = class(TfrmBaseDocked,ISave) Label1: TLabel; edPassword: TRzEdit; Label2: TLabel; edNewPassword: TRzEdit; Label3: TLabel; edConfirm: TRzEdit; pnlSave: TRzPanel; btnSave: TRzShapeButton; lblErrorMessage: TLabel; procedure btnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure ClearPasswords; function PasskeyIsValid: boolean; public { Public declarations } function Save: boolean; procedure Cancel; end; implementation {$R *.dfm} uses IFinanceGlobal, IFinanceDialogs, SecurityUtil; procedure TfrmChangePassword.btnSaveClick(Sender: TObject); begin Save; end; procedure TfrmChangePassword.Cancel; begin end; procedure TfrmChangePassword.ClearPasswords; begin edPassword.Clear; edNewPassword.Clear; edConfirm.Clear; end; procedure TfrmChangePassword.FormCreate(Sender: TObject); begin inherited; lblErrorMessage.Caption := ''; end; function TfrmChangePassword.PasskeyIsValid: boolean; var oldPassKey, newPassKey, confirm: string; error: string; begin error := ''; oldPassKey := Trim(edPassword.Text); newPassKey := Trim(edNewPassword.Text); confirm := Trim(edConfirm.Text); if not MatchStr(ifn.User.Passkey,oldPassKey) then error := 'Current password does not match the saved password.' else if newPasskey = '' then error := 'Password cannot be empty.' else if not MatchStr(newPassKey,confirm) then error := 'Passwords do not match.'; lblErrorMessage.Font.Color := clRed; lblErrorMessage.Caption := error; Result := error = ''; end; function TfrmChangePassword.Save: boolean; var newPassKey: AnsiString; begin Result := false; if PasskeyIsValid then begin // newPassKey := Encrypt(Trim(edNewPassword.Text)); newPassKey := Trim(edNewPassword.Text); if ifn.User.ChangePassword(newPassKey) then begin ShowConfirmationBox('Password changed successfully.'); ClearPasswords; Result := true; end; end; end; end.