text
stringlengths
14
6.51M
//Exercicio 45: Receber um número ímpar maior que 15 (com consistência de dados!). //Exibir quantas vezes esse número recebido é múltiplo de 3 ou se não ele não é múltiplo de 3. { Solução em Portugol Algoritmo Exercicio 45; Var numero, multiplo: inteiro; Inicio exiba("Programa que determina se um número ímpar e maior que 15 é múltiplo de 3."); exiba("Digite um número ímpar maior que 15: "); leia(numero); multiplo <- 0; enquanto(numero < 15 ou resto(numero,2) = 0)faça exiba("Digite um número ímpar maior que 15."); leia(numero); fimenquanto; enquanto(resto(numero,3) = 0)faça multiplo <- multiplo + 1; numero <- quociente(numero,3); fimenquanto; se(multiplo = 0) então exiba("O número não é divisível por 3.") senão exiba("O número é divisível por 3 ",multiplo," vezes."); fimse; Fim. } // Solução em Pascal Program Exercicio45; uses crt; var numero, multiplo: integer; begin clrscr; writeln('Programa que determina se um número ímpar e maior que 15 é múltiplo de 3.'); writeln('Digite um número ímpar maior que 15: '); readln(numero); multiplo := 0; while((numero < 15) or ((numero mod 2) = 0))do Begin writeln('Digite um número ímpar maior que 15.'); readln(numero); End; while((numero mod 3) = 0)do Begin multiplo := multiplo + 1; numero := (numero div 3); End; if(multiplo = 0) then writeln('O número não é divisível por 3.') else writeln('O número é divisível por 3: ',multiplo,' vez(es).'); repeat until keypressed; end.
unit NewTeamDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, MarqueeCtrl, FramedButton, VoyagerInterfaces, VoyagerServerInterfaces, InternationalizerComponent; type TNewTeamDlg = class(TForm) CloseBtn: TFramedButton; HintText: TMarquee; Shape1: TShape; Label4: TLabel; edTeamName: TEdit; btCreate: TFramedButton; pnError: TPanel; btCancel: TFramedButton; InternationalizerComponent1: TInternationalizerComponent; procedure edTeamNameChange(Sender: TObject); procedure btCreateClick(Sender: TObject); procedure btCancelClick(Sender: TObject); private fClientView : IClientView; fMasterURLHandler : IMasterURLHandler; fIllSystem : olevariant; fCriminalName : string; public property ClientView : IClientView write fClientView; property MasterURLHandler : IMasterURLHandler write fMasterURLHandler; property IllSystem : olevariant write fIllSystem; property CriminalName : string write fCriminalName; private procedure threadedNewTeam( const parms : array of const ); procedure syncNewTeam( const parms : array of const ); end; var NewTeamDlg: TNewTeamDlg; implementation {$R *.DFM} uses Threads, CrimeProtocol; procedure TNewTeamDlg.edTeamNameChange(Sender: TObject); begin btCreate.Enabled := edTeamName.Text <> ''; pnError.Visible := false; end; procedure TNewTeamDlg.btCreateClick(Sender: TObject); begin Fork( threadedNewTeam, priNormal, [edTeamName.Text] ); end; procedure TNewTeamDlg.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TNewTeamDlg.threadedNewTeam( const parms : array of const ); var name : string absolute parms[0].vPChar; ErrorCode : TErrorCode; begin try ErrorCode := fIllSystem.RDOCreateTeam( fCriminalName, name ); Join( syncNewTeam, [ErrorCode] ) except end; end; procedure TNewTeamDlg.syncNewTeam( const parms : array of const ); var ErrorCode : integer absolute parms[0].vInteger; begin case ErrorCode of CRIME_NOERROR : ModalResult := mrOk; CRIME_ERROR_WrongTeamName : begin pnError.Caption := 'Error: Invalid team name'; pnError.Visible := true; end; else begin pnError.Caption := 'Unknown error. Please try again.'; pnError.Visible := true; end; end; end; end.
unit RDOInterfaces; interface uses RDOProtocol, SocketComp; const MSG_GETTHREADDATA = $1001; MSG_SETTHREADDATA = $1002; {$IFNDEF AutoServer} type IRDOConnectionInit = interface [ '{410CAF20-64BA-11d1-AF26-008029E5CA8C}' ] function Get_Server : WideString; safecall; procedure Set_Server( const Value : WideString ); safecall; function Get_Port : Integer; safecall; procedure Set_Port( Value : Integer ); safecall; function Connect( TimeOut : Integer ) : WordBool; safecall; procedure Disconnect; safecall; property Server : WideString read Get_Server write Set_Server; property Port : Integer read Get_Port write Set_Port; end; {$ENDIF} type IRDOConnection = interface; ILogAgent = interface; ILogAgents = interface; TRDOClientConnectEvent = procedure ( const ClientConnection : IRDOConnection ) of object; TRDOClientDisconnectEvent = procedure ( const ClientConnection : IRDOConnection ) of object; IRDOConnection = interface [ '{5BDB3080-7467-11d1-AF26-008029E5CA8C}' ] function Alive : boolean; function SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; stdcall; procedure Send( const QueryText : string ); stdcall; function GetRemoteAddress : string; stdcall; function GetLocalAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; function GetOnConnect : TRDOClientConnectEvent; procedure SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); function GetOnDisconnect : TRDOClientDisconnectEvent; procedure SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); function GetTimeOut : integer; procedure SetTimeOut(TimeOut : integer); procedure SetData(data : pointer); function GetData : pointer; property LocalAddress : string read GetLocalAddress; property RemoteAddress : string read GetRemoteAddress; property LocalHost : string read GetLocalHost; property LocalPort : integer read GetLocalPort; property OnConnect : TRDOClientConnectEvent read GetOnConnect write SetOnConnect; property OnDisconnect : TRDOClientDisconnectEvent read GetOnDisconnect write SetOnDisconnect; property TimeOut : integer read GetTimeOut write SetTimeOut; end; pinteger = ^integer; IRDOQueryServer = interface function ExecQuery( const QueryText : string; ConnId : integer; var QueryStatus, RDOCallCnt : integer ) : string; function GetBusy : boolean; function GetStatus : integer; procedure SetBusy(value : boolean); property Busy : boolean read GetBusy write SetBusy; property Status : integer read GetStatus; end; IRDOServerConnection = interface [ '{1107CE00-7468-11d1-AF26-008029E5CA8C}' ] procedure SetQueryServer( const QueryServer : IRDOQueryServer ); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads( MaxQueryThreads : integer ); property MaxQueryThreads : integer read GetMaxQueryThreads write SetMaxQueryThreads; end; IRDOConnectionServerEvents = interface procedure OnClientConnect( const ClientConnection : IRDOConnection ); procedure OnClientDisconnect( const ClientConnection : IRDOConnection ); end; IRDOConnectionsServer = interface [ '{9AA0B820-7468-11d1-AF26-008029E5CA8C}' ] procedure StartListening; procedure StopListening; function GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection; function GetClientConnectionById( Id : integer ) : IRDOConnection; procedure InitEvents( const EventSink : IRDOConnectionServerEvents ); end; IRDOServerClientConnection = interface [ '{45AA7020-7492-11d1-AF26-008029E5CA8C}' ] procedure OnQueryResultArrival( const QueryResult : string ); end; ILockObject = interface ['{4B337CC0-57CE-11d1-AF26-008029E5CA8C}'] procedure Lock; procedure UnLock; end; TLogQueryEvent = procedure(Query : string) of object; ILogAgent = interface function GetId : string; function GetLogId(Obj : TObject) : string; function GetObject(ObjId : string) : TObject; procedure LogQuery(Query : string); end; ILogAgents = interface function LogableMethod(aName : string) : boolean; function GetLogAgentById(Id : string) : ILogAgent; function GetLogAgentByClass(aClass : TClass) : ILogAgent; procedure RegisterMethods(Names : array of string); procedure RegisterAgent(aClassName : string; anAgent : ILogAgent); end; IRDOLog = interface ['{4BA37CC0-57CE-11d1-AF26-008029E5CA8C}'] procedure RegisterAgents(Agents : ILogAgents); procedure ExecLogQuery(Query : string); end; IWinSocketWrap = interface function isValid : boolean; function getSocket : TCustomWinSocket; function getConnection : IRDOConnection; function getConnectionData : pointer; procedure setConnectionData(info : pointer); procedure Invalidate; procedure Lock; procedure Unlock; end; implementation end.
unit Cloud.Consts; interface const CLOUD_HOST_DEVNET = '185.27.192.156'; CLOUD_HOST_TESTNET = '190.2.130.231'; CLOUD_HOST_MAINNET = '190.2.137.77'; CLOUD_PORT_DEFAULT = 8765; PORT_BITCOIN = '18332'; PORT_LIGHTCOIN = '19332'; PORT_ETHEREUM = '5555'; DIRECTION_BUY = 1; DIRECTION_SELL = 2; implementation end.
{ TForge Library Copyright (c) Sergey Kasandrov 1997, 2018 ------------------------------------------------------- # generic stream cipher # inheritance: TForgeInstance <-- TCipherInstance <-- TStreamCipherInstance } unit tfStreamCiphers; {$I TFL.inc} interface uses tfTypes, tfUtils; type PStreamCipherInstance = ^TStreamCipherInstance; TStreamCipherInstance = record private {$HINTS OFF} FVTable: Pointer; FRefCount: Integer; FAlgID: TAlgID; FKeyFlags: UInt32; {$HINTS ON} FPos: Integer; // 0 .. BlockSize - 1 FCache: array[0..0] of Byte; public class function IncBlockNo(Inst: PStreamCipherInstance; Count: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdate(Inst: Pointer; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetKeyStream(Inst: PStreamCipherInstance; Data: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function Encrypt(Inst: PStreamCipherInstance; InData, OutData: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; implementation uses tfCipherHelpers; { TStreamCipherInstance } class function TStreamCipherInstance.Encrypt(Inst: PStreamCipherInstance; InData, OutData: PByte; DataSize: Cardinal): TF_RESULT; var LBlockSize: Integer; LGetKeyBlock: TCipherHelper.TBlockFunc; // LDataSize: Cardinal; Cnt: Cardinal; // NBlocks: Cardinal; // LBlock: TCipherHelper.TBlock; begin if Inst.FKeyFlags and TF_KEYFLAG_KEY = 0 then begin Result:= TF_E_UNEXPECTED; Exit; end; LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} @LGetKeyBlock:= TCipherHelper.GetKeyBlockFunc(Inst); // process current block's tail (if exists) if Inst.FPos > 0 then begin Cnt:= LBlockSize - Inst.FPos; if Cnt > DataSize then Cnt:= DataSize; Move(InData^, OutData^, Cnt); MoveXor(Inst.FCache[Inst.FPos], OutData^, Cnt); Inc(InData, Cnt); Inc(OutData, Cnt); Dec(DataSize, Cnt); Inc(Inst.FPos, Cnt); if (Inst.FPos = LBlockSize) then begin Inst.FPos:= 0; end; (* Result:= TCipherHelper.DecBlockNo(Inst, 1); if Result <> TF_S_OK then Exit; Result:= LGetKeyBlock(Inst, @LBlock); if Result <> TF_S_OK then Exit; LDataSize:= LBlockSize - Inst.FPos; if LDataSize > DataSize then LDataSize:= DataSize; Move(InData^, OutData^, LDataSize); MoveXor(LBlock[Inst.FPos], OutData^, LDataSize); Inst.FPos:= Inst.FPos + LDataSize; if Inst.FPos = LBlockSize then Inst.FPos:= 0; Inc(OutData, LDataSize); Inc(InData, LDataSize); Dec(DataSize, LDataSize); *) end; // process full blocks while DataSize >= Cardinal(LBlockSize) do begin // InData and OutData can be identical, so we use cache Result:= LGetKeyBlock(Inst, @Inst.FCache); if Result <> TF_S_OK then Exit; Move(InData^, OutData^, LBlockSize); MoveXor(Inst.FCache, OutData^, LBlockSize); Inc(OutData, LBlockSize); Inc(InData, LBlockSize); Dec(DataSize, LBlockSize); end; // process last incomplete block (if exists) if DataSize > 0 then begin Result:= LGetKeyBlock(Inst, @Inst.FCache); if Result <> TF_S_OK then Exit; Move(InData^, OutData^, DataSize); MoveXor(Inst.FCache, OutData^, DataSize); Inst.FPos:= DataSize; end; // if Last then Inst.FPos:= 0; Result:= TF_S_OK; end; class function TStreamCipherInstance.EncryptUpdate(Inst: Pointer; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; begin if DataSize > OutBufSize then begin Result:= TF_E_INVALIDARG; Exit; end; Result:= Encrypt(Inst, InBuffer, OutBuffer, DataSize); end; class function TStreamCipherInstance.GetKeyStream(Inst: PStreamCipherInstance; Data: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; var LBlockSize: Integer; LGetKeyBlock: TCipherHelper.TBlockFunc; // LDataSize: Cardinal; Cnt: Cardinal; // NBlocks: Cardinal; // LBlock: TCipherHelper.TBlock; begin {$IFDEF DEBUG} if Inst.FKeyFlags and TF_KEYFLAG_KEY = 0 then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} @LGetKeyBlock:= TCipherHelper.GetKeyBlockFunc(Inst); // process current block's tail (if exists) if Inst.FPos > 0 then begin Cnt:= LBlockSize - Inst.FPos; if Cnt > DataSize then Cnt:= DataSize; Move(Inst.FCache[Inst.FPos], Data^, Cnt); Inc(Data, Cnt); Dec(DataSize, Cnt); Inc(Inst.FPos, Cnt); if (Inst.FPos = LBlockSize) then begin Inst.FPos:= 0; end; (* Result:= TCipherHelper.DecBlockNo(Inst, 1); if Result <> TF_S_OK then Exit; Result:= LGetKeyBlock(Inst, @LBlock); if Result <> TF_S_OK then Exit; LDataSize:= LBlockSize - Inst.FPos; if LDataSize > DataSize then LDataSize:= DataSize; Move(LBlock[Inst.FPos], Data^, LDataSize); Inst.FPos:= Inst.FPos + LDataSize; if Inst.FPos = LBlockSize then Inst.FPos:= 0; Inc(Data, LDataSize); Dec(DataSize, LDataSize); *) end; // process full blocks while DataSize >= Cardinal(LBlockSize) do begin // LDataSize:= DataSize and not (LBlockSize - 1); Result:= LGetKeyBlock(Inst, Data); if Result <> TF_S_OK then Exit; // Move(LBlock, Data^, LDataSize); // Inc(Data, LDataSize); // Dec(DataSize, LDataSize); Inc(Data, LBlockSize); Dec(DataSize, LBlockSize); end; // process last incomplete block (if exists) if DataSize > 0 then begin Result:= LGetKeyBlock(Inst, @Inst.FCache); if Result <> TF_S_OK then Exit; Move(Inst.FCache, Data^, DataSize); Inst.FPos:= DataSize; end; if Last then Inst.FPos:= 0; Result:= TF_S_OK; end; class function TStreamCipherInstance.IncBlockNo(Inst: PStreamCipherInstance; Count: UInt64): TF_RESULT; var LBlockSize: Cardinal; LGetKeyBlock: TCipherHelper.TBlockFunc; LBlock: TCipherHelper.TBlock; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; @LGetKeyBlock:= TCipherHelper.GetKeyBlockFunc(Inst); while Count > 0 do begin LGetKeyBlock(Inst, @LBlock); Dec(Count); end; FillChar(LBlock, LBlockSize, 0); Result:= TF_S_OK; end; end.
unit uMD5; interface uses IdHashMessageDigest, IdHash, System.Classes, System.SysUtils; function getMD5Arquivo(const FileName: string): string; implementation function getMD5Arquivo(const FileName: string): string; var IdMD5: TIdHashMessageDigest5; FS: TFileStream; begin IdMD5 := nil; FS := nil; try IdMD5 := TIdHashMessageDigest5.Create; FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); Result := IdMD5.HashStreamAsHex(FS) finally FS.Free; IdMD5.Free; end; end; end.
unit ADLSConnector.Interfaces; interface type IADLSConnectorView = interface ['{9BB081F9-887B-44B5-A352-49BE0261FB0A}'] // Input function GetBaseURL: string; function GetClientID: string; function GetClientSecret: string; function GetAccessTokenEndpoint: string; function GetAuthorizationEndpoint: string; // Output procedure SetAccessToken(const AValue: string); procedure SetResponseData(const AValue: string); procedure AddResponseData(const AValue: string); end; IADLSConnectorPresenter = interface ['{DA1F18B3-78E3-45B5-B065-A993259B0FBC}'] procedure GetAccessToken; function GetBaseURL: string; function GetClientID: string; function GetToken: string; property AccessToken: string read GetToken; end; implementation end.
unit Service; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Bird.Socket; type TBirdSocketService = class(TService) procedure ServiceCreate(Sender: TObject); procedure ServiceDestroy(Sender: TObject); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceExecute(Sender: TService); private FBirdSocket: TBirdSocket; public function GetServiceController: TServiceController; override; end; var BirdSocketService: TBirdSocketService; implementation {$R *.dfm} procedure ServiceController(CtrlCode: DWord); stdcall; begin BirdSocketService.Controller(CtrlCode); end; function TBirdSocketService.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TBirdSocketService.ServiceCreate(Sender: TObject); begin FBirdSocket := TBirdSocket.Create(8080); FBirdSocket.AddEventListener(TEventType.EXECUTE, procedure(const ABird: TBirdSocketConnection) var LMessage: string; begin LMessage := ABird.WaitMessage; if LMessage.Trim.Equals('ping') then ABird.Send('pong') else if LMessage.Trim.IsEmpty then ABird.Send('empty message') else ABird.Send(Format('message received: "%s"', [LMessage])); end); end; procedure TBirdSocketService.ServiceDestroy(Sender: TObject); begin FBirdSocket.Stop; FBirdSocket.DisposeOf; end; procedure TBirdSocketService.ServiceExecute(Sender: TService); begin while not Self.Terminated do ServiceThread.ProcessRequests(True); end; procedure TBirdSocketService.ServicePause(Sender: TService; var Paused: Boolean); begin FBirdSocket.Stop; end; procedure TBirdSocketService.ServiceShutdown(Sender: TService); begin FBirdSocket.Stop; end; procedure TBirdSocketService.ServiceStart(Sender: TService; var Started: Boolean); begin FBirdSocket.Start; end; procedure TBirdSocketService.ServiceStop(Sender: TService; var Stopped: Boolean); begin FBirdSocket.Stop; end; end.
unit MFichas.Model.Caixa; interface uses System.SysUtils, System.Generics.Collections, System.TypInfo, MFichas.Model.Entidade.CAIXA, MFichas.Model.Caixa.Interfaces, MFichas.Model.Caixa.Metodos.Factory, MFichas.Model.Caixa.State.Factory, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Impressao, MFichas.Model.Impressao.Interfaces, MFichas.Controller.Types, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces; type TModelCaixa = class(TInterfacedObject, iModelCaixa, iModelCaixaMetodos) private FState : iModelCaixaMetodos; FEntidade : TCAIXA; FConn : iModelConexaoSQL; FDAO : iContainerObjectSet<TCAIXA>; FListaCaixa: TObjectList<TCaixa>; FImpressao : iModelImpressao; procedure Imprimir; class var FInstance: iModelCaixa; constructor Create; procedure RecuperarStatusCaixa; procedure InstanciarUmNovoCaixa; procedure FecharCaixaDeixadoAberto; procedure AtribuirStatusAoCaixa; procedure LimparEntidade; procedure ClonarObjeto; procedure DestruirListaEEntidade; procedure DestruirListaDeCaixas; public destructor Destroy; override; class function New: iModelCaixa; function SetState(AState: iModelCaixaMetodos): iModelCaixa; function Metodos : iModelCaixaMetodos; function Entidade: TCAIXA; overload; function Entidade(ACaixa: TCAIXA): iModelCaixa; overload; function DAO: iContainerObjectSet<TCAIXA>; //METODOS function Abrir : iModelCaixaMetodosAbrir; function Fechar : iModelCaixaMetodosFechar; function Suprimento: iModelCaixaMetodosSuprimento; function Sangria : iModelCaixaMetodosSangria; function &End : iModelCaixa; end; implementation { TModelCaixa } function TModelCaixa.Abrir: iModelCaixaMetodosAbrir; begin RecuperarStatusCaixa; FState.Abrir; Result := TModelCaixaMetodosFactory.New.CaixaMetodoAbrir(Self); end; function TModelCaixa.&End: iModelCaixa; begin Result := Self; end; procedure TModelCaixa.Imprimir; begin FImpressao .Caixa .Fechamento .TituloDaImpressao('FECHAMENTO DE CAIXA (DEIXADO ABERTO)') .CodigoDoCaixa(FEntidade.GUUID) .ExecutarImpressao .&End .&End; end; procedure TModelCaixa.FecharCaixaDeixadoAberto; begin ClonarObjeto; Imprimir; Sleep(5000); FDAO.Modify(FEntidade); FEntidade.STATUS := Integer(scFechado); FEntidade.DATAFECHAMENTO := Now; FDAO.Update(FEntidade); LimparEntidade; end; procedure TModelCaixa.InstanciarUmNovoCaixa; begin if not Assigned(FEntidade) then FEntidade := TCAIXA.Create; end; function TModelCaixa.Entidade: TCAIXA; begin Result := FEntidade; end; function TModelCaixa.Entidade(ACaixa: TCAIXA): iModelCaixa; begin Result := Self; FEntidade := ACaixa; end; procedure TModelCaixa.ClonarObjeto; begin if not Assigned(FEntidade) then FEntidade := TCAIXA.Create; FEntidade.GUUID := FListaCaixa.Items[0].GUUID; FEntidade.OPERADOR := FListaCaixa.Items[0].OPERADOR; FEntidade.STATUS := FListaCaixa.Items[0].STATUS; FEntidade.DATAABERTURA := FListaCaixa.Items[0].DATAABERTURA; FEntidade.DATAFECHAMENTO := FListaCaixa.Items[0].DATAFECHAMENTO; FEntidade.DATAALTERACAO := FListaCaixa.Items[0].DATAALTERACAO; FEntidade.VALORABERTURA := FListaCaixa.Items[0].VALORABERTURA; FEntidade.VALORFECHAMENTO := FListaCaixa.Items[0].VALORFECHAMENTO; end; constructor TModelCaixa.Create; begin //TODO: VERIFICAR STATUS DO ULTIMO REGISTRO DE CAIXA NO BANCO DE DADOS. FConn := TModelConexaoFactory.New.ConexaoSQL; FDAO := TContainerObjectSet<TCAIXA>.Create(FConn.Conn); FImpressao := TModelImpressao.New; end; function TModelCaixa.DAO: iContainerObjectSet<TCAIXA>; begin Result := FDAO; end; destructor TModelCaixa.Destroy; begin DestruirListaEEntidade; inherited; end; procedure TModelCaixa.DestruirListaDeCaixas; begin {$IFDEF MSWINDOWS} FreeAndNil(FListaCaixa); {$ELSE} FListaCaixa.Free; FListaCaixa.DisposeOf; {$ENDIF} end; procedure TModelCaixa.DestruirListaEEntidade; begin {$IFDEF MSWINDOWS} if Assigned(FListaCaixa) then FreeAndNil(FListaCaixa); if Assigned(FEntidade) then FreeAndNil(FEntidade); {$ELSE} if Assigned(FEntidade) then begin FEntidade.Free; FEntidade.DisposeOf; end; if Assigned(FListaCaixa) then begin FListaCaixa.Free; FListaCaixa.DisposeOf; end; {$ENDIF} end; function TModelCaixa.Fechar: iModelCaixaMetodosFechar; begin FState.Fechar; Result := TModelCaixaMetodosFactory.New.CaixaMetodoFechar(Self); end; procedure TModelCaixa.LimparEntidade; begin FreeAndNil(FEntidade); if not Assigned(FEntidade) then FEntidade := TCAIXA.Create; // FEntidade.CleanupInstance; // FEntidade.DATAABERTURA := StrToDate('30/12/1899'); // FEntidade.DATAFECHAMENTO := StrToDate('30/12/1899'); // FEntidade.DATAALTERACAO := StrToDate('30/12/1899'); // FEntidade.VALORABERTURA := 0; // FEntidade.OPERACOES.Clear; end; function TModelCaixa.Metodos: iModelCaixaMetodos; begin Result := Self; end; class function TModelCaixa.New: iModelCaixa; begin if not Assigned(FInstance) then FInstance := Self.Create; Result := FInstance; end; procedure TModelCaixa.RecuperarStatusCaixa; begin FListaCaixa := FDAO.FindWhere('STATUS = ' + Integer(scAberto).ToString); if FListaCaixa.Count <= 0 then InstanciarUmNovoCaixa else FecharCaixaDeixadoAberto; AtribuirStatusAoCaixa; DestruirListaDeCaixas; end; function TModelCaixa.Sangria: iModelCaixaMetodosSangria; begin FState.Sangria; Result := TModelCaixaMetodosFactory.New.CaixaMetodoSangria(Self); end; procedure TModelCaixa.AtribuirStatusAoCaixa; begin case TTypeStatusCaixa(FEntidade.STATUS) of scFechado: FState := TModelCaixaStateFactory.New.Fechado; scAberto: FState := TModelCaixaStateFactory.New.Aberto; end; end; function TModelCaixa.SetState(AState: iModelCaixaMetodos): iModelCaixa; begin Result := Self; FState := AState; end; function TModelCaixa.Suprimento: iModelCaixaMetodosSuprimento; begin FState.Suprimento; Result := TModelCaixaMetodosFactory.New.CaixaMetodoSuprimento(Self); end; end.
{ Steam Utilities Copyright (C) 2016, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/SteamUtils License: - You may use this library as you see fit, including use within commercial applications. - You may modify this library to suit your needs, without the requirement of distributing modified versions. - You may redistribute this library (in part or whole) individually, or as part of any other works. - You must NOT charge a fee for the distribution of this library (compiled or in its source form). It MUST be distributed freely. - This license and the surrounding comment block MUST remain in place on all copies and modified versions of this source code. - Modified versions of this source MUST be clearly marked, including the name of the person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog" detailing all additions/deletions/modifications made. Disclaimer: - Your use of this source constitutes your understanding and acceptance of this disclaimer. - Simon J Stuart, nor any other contributor, may be held liable for your use of this source code. This includes any losses and/or damages resulting from your use of this source code, be they physical, financial, or psychological. - There is no warranty or guarantee (implicit or otherwise) provided with this source code. It is provided on an "AS-IS" basis. Donations: - While not mandatory, contributions are always appreciated. They help keep the coffee flowing during the long hours invested in this and all other Open Source projects we produce. - Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com ^ Garbled to prevent spam! ^ } unit Steam.Workshop.Manifests.Intf; interface implementation end.
unit OptimizationParametersUnit; interface uses REST.Json.Types, System.Generics.Collections, SysUtils, JSONNullableAttributeUnit, HttpQueryMemberAttributeUnit, GenericParametersUnit, RouteParametersUnit, AddressUnit, NullableBasicTypesUnit, EnumsUnit; type TOptimizationParameters = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('optimization_problem_id')] [Nullable] FOptimizationProblemID: NullableString; [JSONMarshalled(False)] [HttpQueryMember('reoptimize')] [Nullable] FReOptimize: NullableBoolean; [JSONNameAttribute('parameters')] [NullableObject(TRouteParameters)] FParameters: NullableObject; [JSONNameAttribute('addresses')] [NullableArray(TAddress)] FAddresses: TAddressesArray; [JSONNameAttribute('directions')] [Nullable] FDirections: NullableInteger; [JSONNameAttribute('format')] [Nullable] FFormat: NullableString; [JSONNameAttribute('route_path_output')] [Nullable] FRoutePathOutput: NullableString; [JSONNameAttribute('optimized_callback_url')] [Nullable] FOptimizedCallbackUrl: NullableString; function GetAddress(AddressString: String; Addresses: TAddressesArray): TAddress; function GetFormatEnum: TOptimizationParametersFormat; procedure SetFormatEnum(const Value: TOptimizationParametersFormat); function GetRoutePathOutput: TRoutePathOutput; procedure SetRoutePathOutput(const Value: TRoutePathOutput); public constructor Create; override; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Optimization Problem ID /// </summary> property OptimizationProblemID: NullableString read FOptimizationProblemID write FOptimizationProblemID; /// <summary> /// If 1, reoptimize, if 0 - no /// </summary> property ReOptimize: NullableBoolean read FReOptimize write FReOptimize; /// <summary> /// Route Parameters. POST data /// </summary> property Parameters: NullableObject read FParameters write FParameters; /// <summary> /// Route Addresses. POST data /// </summary> property Addresses: TAddressesArray read FAddresses; procedure AddAddress(Address: TAddress); /// <summary> /// A flag to enable or disable driving and turn-by-turn directions being returned. Not returning them is more efficient for the database. Query string (GET fields). /// </summary> property Directions: NullableInteger read FDirections write FDirections; /// <summary> /// The format in which to return the route data. This parameter is ignored for now, as only JSON is supported. Query string (GET fields). /// </summary> property FormatEnum: TOptimizationParametersFormat read GetFormatEnum write SetFormatEnum; /// <summary> /// Return the path points when returning the newly created route... Query string (GET fields). /// </summary> property RoutePathOutput: TRoutePathOutput read GetRoutePathOutput write SetRoutePathOutput; /// <summary> /// A URL that gets called when the optimization is solved, or if there is an error. /// The callback is called with a POST request. /// The POST data sent is: /// - timestamp (Seconds): /// - Server timestamp of request sent optimization_problem_id (Hash String): /// - ID of the optimization state (Small Int). /// The state can be one of the values: /// 4 = OPTIMIZATION_STATE_OPTIMIZED, which means the optimization was successful; /// or 5 = OPTIMIZATION_STATE_ERROR, which means there was an error solving the optimization.. Query string (GET fields). /// </summary> property OptimizedCallbackUrl: NullableString read FOptimizedCallbackUrl write FOptimizedCallbackUrl; end; implementation { TOptimizationParameters } procedure TOptimizationParameters.AddAddress(Address: TAddress); begin SetLength(FAddresses, Length(FAddresses) + 1); FAddresses[High(FAddresses)] := Address; end; constructor TOptimizationParameters.Create; begin Inherited; FOptimizationProblemID := NullableString.Null; FReOptimize := NullableBoolean.Null; FDirections := NullableInteger.Null; FFormat := NullableString.Null; FRoutePathOutput := NullableString.Null; FOptimizedCallbackUrl := NullableString.Null; SetLength(FAddresses, 0); FParameters := NullableObject.Null; end; destructor TOptimizationParameters.Destroy; var i: integer; begin for i := Length(FAddresses) - 1 downto 0 do FreeAndNil(FAddresses[i]); FParameters.Free; inherited; end; function TOptimizationParameters.Equals(Obj: TObject): Boolean; var Other: TOptimizationParameters; Address, OtherAddress: TAddress; AddressEquals: boolean; begin Result := False; if not (Obj is TOptimizationParameters) then Exit; Other := TOptimizationParameters(Obj); Result := (OptimizationProblemID = Other.OptimizationProblemID) and (ReOptimize = Other.ReOptimize) and (Directions = Other.Directions) and (FormatEnum = Other.FormatEnum) and (RoutePathOutput = Other.RoutePathOutput) and (OptimizedCallbackUrl = Other.OptimizedCallbackUrl); if (not Result) then Exit; Result := False; if (Length(FAddresses) <> Length(Other.Addresses)) then Exit; AddressEquals := True; for Address in FAddresses do begin OtherAddress := GetAddress(Address.AddressString, Other.Addresses); if (OtherAddress = nil) then Exit; AddressEquals := AddressEquals and Address.Equals(OtherAddress); if not AddressEquals then Break; end; Result := (FParameters = Other.Parameters); end; function TOptimizationParameters.GetAddress(AddressString: String; Addresses: TAddressesArray): TAddress; var Address: TAddress; begin Result := nil; for Address in Addresses do if (Address.AddressString = AddressString) then Exit(Address); end; function TOptimizationParameters.GetFormatEnum: TOptimizationParametersFormat; var FormatEnum: TOptimizationParametersFormat; begin Result := TOptimizationParametersFormat.opUndefined; if FFormat.IsNotNull then for FormatEnum := Low(TOptimizationParametersFormat) to High(TOptimizationParametersFormat) do if (FFormat = TOptimizationParametersFormatDescription[FormatEnum]) then Exit(FormatEnum); end; function TOptimizationParameters.GetRoutePathOutput: TRoutePathOutput; var RoutePathOutput: TRoutePathOutput; begin Result := TRoutePathOutput.rpoUndefined; if FRoutePathOutput.IsNotNull then for RoutePathOutput := Low(TRoutePathOutput) to High(TRoutePathOutput) do if (FRoutePathOutput = TRoutePathOutputDescription[RoutePathOutput]) then Exit(RoutePathOutput); end; procedure TOptimizationParameters.SetFormatEnum( const Value: TOptimizationParametersFormat); begin FFormat := TOptimizationParametersFormatDescription[Value]; end; procedure TOptimizationParameters.SetRoutePathOutput( const Value: TRoutePathOutput); begin FRoutePathOutput := TRoutePathOutputDescription[Value]; end; end.
unit StepParamsIntf; interface uses Classes, StepParamIntf; type IStepParams = interface(IInterface) ['{74097CFC-21AA-402D-BECA-2AD9F1B7810B}'] function GetParam(AParam: variant): IStepParam; procedure SetParam(AParam: variant; const Value: IStepParam); procedure Clear; function ByName(const AParamName: string): IStepParam; function Add(const AParam: string): IStepParam; property Param[AParam: variant]: IStepParam read GetParam write SetParam; default; end; implementation end.
unit uTableName; interface type TableName = class(TCustomAttribute) private FName: String; public property Name: String read FName write FName; constructor Create(aName: String); end; implementation { TableName } constructor TableName.Create(aName: String); begin FName := aName; end; end.
unit TestVehicleSamplesUnit; interface uses TestFramework, Classes, SysUtils, BaseTestOnlineExamplesUnit; type TTestVehicleSamples = class(TTestOnlineExamples) private procedure GetVehicle; // working, but slowly and incorrectly procedure GetVehicles; // working, but slowly published end; implementation uses VehicleUnit; procedure TTestVehicleSamples.GetVehicle; var ErrorString: String; VehicleId: String; Vehicle: TVehicle; begin VehicleId := '0A18C14AB42F6B6D7E830CE4082493E3'; Vehicle := FRoute4MeManager.Vehicle.Get(VehicleId, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vehicle); finally FreeAndNil(Vehicle); end; VehicleId := 'random_id_dDFsd2@D3d'; Vehicle := FRoute4MeManager.Vehicle.Get(VehicleId, ErrorString); try CheckNotEquals(EmptyStr, ErrorString); CheckNull(Vehicle); finally FreeAndNil(Vehicle); end; end; procedure TTestVehicleSamples.GetVehicles; var ErrorString: String; Vehicles: TVehicleList; begin Vehicles := FRoute4MeManager.Vehicle.GetList(ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckNotNull(Vehicles); CheckTrue(Vehicles.Count > 0); finally FreeAndNil(Vehicles); end; end; initialization RegisterTest('Examples\Online\Vehicle\', TTestVehicleSamples.Suite); end.
unit Parsers.Excel.StroyInformResource; interface uses Parsers.Abstract, Parsers.Excel, GsDocument, SysUtils, Classes, StrUtils, Parsers.Excel.Tools; type TStroyInformResourceFileSuffix = (fsTER, fsFER); { Общий прототип для всех видов файлов СтройИнформРесурс } TStroyInformResourceParser = class(TExcelParser<TGsDocument, TExcelRowWrapper>) private FSuffix: TStroyInformResourceFileSuffix; FChapter: TGsAbstractContainer; protected procedure InitDocument(Document: TGsDocument); virtual; function DoGetDocument: TGsDocument; override; procedure DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); override; function GetName: string; override; public constructor Create(Suffix: TStroyInformResourceFileSuffix); reintroduce; end; { Парсер *_Индексы_Часть1_*.xls* } TIndexPart1Parser = class(TStroyInformResourceParser) protected procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Индексы_Часть2_*.xls* } TIndexPart2Parser = class(TStroyInformResourceParser) protected procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Индексы_Часть3_*.xls* } TIndexPart3Parser = class(TStroyInformResourceParser) protected procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Индексы_Часть4_Погрузка_*.xls* } TIndexPart4Parser = class(TStroyInformResourceParser) protected procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Индексы_Часть5_Перевозка_*.xls* } TIndexPart5Parser = class(TStroyInformResourceParser) protected function DoGetDocument: TGsDocument; override; procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Каталог_Материалы_dealer_*.xls* } TIndexCatalogMaterialParser = class(TStroyInformResourceParser) private function GetCargoClass(Value: string): Integer; protected procedure InitDocument(ADocument: TGsDocument); override; procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Парсер *_Каталог_Механизмы_dealer_*.xls* } TIndexCatalogMachineParser = class(TStroyInformResourceParser) protected procedure InitDocument(ADocument: TGsDocument); override; procedure DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); override; end; { Импортер файлов excel } TStroyInformResourceExcelImporter = class(TExcelImporter) protected procedure DoOnImportFile(FileName: string; SheetName: string; var DefaultImport: Boolean); override; end; { Импортер каталогов } TStroyInformResourceFolderImporter = class(TAbstractFolderImporter) protected function GetFolderImporter(const AFolder: string; var FileMask: string): IImporter; override; end; TStroyInformResourceParsersFactory = class public class function GetParser(FileName: string): IExcelParser; class function GetIndexPart1Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexPart2Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexPart3Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexPart4Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexPart5Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexCatalogMaterialParser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; class function GetIndexCatalogMachineParser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; end; var Shape1: String; Shape2: String; implementation uses GlobalData, Generics.Collections; { TStroyInformResourceFolderImporter } function TStroyInformResourceFolderImporter.GetFolderImporter(const AFolder: string; var FileMask: string): IImporter; begin FileMask := '*ЕР_*_*.xls*'; Result := TStroyInformResourceExcelImporter.Create(); end; { TStroyInformResourceParser } constructor TStroyInformResourceParser.Create(Suffix: TStroyInformResourceFileSuffix); begin inherited Create(); FSuffix := Suffix; end; function TStroyInformResourceParser.DoGetDocument: TGsDocument; begin Result := TGsDocument.Create(); Result.DocumentType := dtIndex; InitDocument(Result); FChapter := TGsAbstractContainer.Create(Result); case Result.DocumentType of dtIndex: Result.Chapters.Add(FChapter); dtPrice: begin if Self is TIndexCatalogMaterialParser then Result.Materials.Add(FChapter) else if Self is TIndexCatalogMachineParser then Result.Mashines.Add(FChapter); end; else Result.Chapters.Add(FChapter); end; FChapter.Caption := 'Импортированные данные'; end; procedure TStroyInformResourceParser.DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); begin inherited DoParseSheet(AExcelSheet, ADocument); ADocument.SaveToFile(ChangeFileExt(AExcelSheet.Owner.FileName, '.xml')); end; function TStroyInformResourceParser.GetName: string; begin Result := 'StroyInformResourceParser'; end; procedure TStroyInformResourceParser.InitDocument(Document: TGsDocument); begin Document.DocumentType := dtIndex; end; { TStroyInformResourceParsersFactory } class function TStroyInformResourceParsersFactory.GetIndexCatalogMachineParser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexCatalogMachineParser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexCatalogMaterialParser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexCatalogMaterialParser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexPart1Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexPart1Parser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexPart2Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexPart2Parser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexPart3Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexPart3Parser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexPart4Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexPart4Parser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetIndexPart5Parser(Suffix: TStroyInformResourceFileSuffix): IExcelParser; begin Result := TIndexPart5Parser.Create(Suffix); end; class function TStroyInformResourceParsersFactory.GetParser(FileName: string): IExcelParser; var Suffix: TStroyInformResourceFileSuffix; begin FileName := ExtractFileName(FileName); if FileName[1] = 'Ф' then Suffix := fsFER else if FileName[1] = 'Т' then Suffix := fsTER else Suffix := TStroyInformResourceFileSuffix(-1); if Pos('_Индексы_Часть1_', FileName) > 0 then Result := GetIndexPart1Parser(Suffix) else if Pos('_Индексы_Часть2_', FileName) > 0 then Result := GetIndexPart2Parser(Suffix) else if Pos('_Индексы_Часть3_', FileName) > 0 then Result := GetIndexPart3Parser(Suffix) else if Pos('_Индексы_Часть4_', FileName) > 0 then Result := GetIndexPart4Parser(Suffix) else if Pos('_Индексы_Часть5_', FileName) > 0 then Result := GetIndexPart5Parser(Suffix) else if Pos('_Каталог_Материалы_dealer_', FileName) > 0 then Result := GetIndexCatalogMaterialParser(Suffix) else if Pos('_Каталог_Машины_', FileName) > 0 then Result := GetIndexCatalogMachineParser(Suffix) else Result := nil; // при этом файл не будет обработан end; { TStroyInformResourceExcelImporter } procedure TStroyInformResourceExcelImporter.DoOnImportFile(FileName, SheetName: string; var DefaultImport: Boolean); var Parser: IExcelParser; begin DefaultImport := False; Parser := TStroyInformResourceParsersFactory.GetParser(FileName); if Parser <> nil then begin try Parser.ParseDoc(FileName, SheetName); finally Parser := nil; end; end; end; { TIndexPart1Parser } procedure TIndexPart1Parser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Index: TGsIndexElement; begin if AExcelRow.HasValuesOr(['Код', 'Наименование']) or AExcelRow.IsEmpty then Exit; Index := TGsIndexElement.Create(ADocument); FChapter.Add(Index); Index.Code := AExcelRow.FilledValues[1]; // Index.Caption := AExcelRow.FilledValues[2]; Index.OZ := ConvertToFloat(AExcelRow.Values[3]); Index.EM := ConvertToFloat(AExcelRow.Values[4]); Index.ZM := ConvertToFloat(AExcelRow.Values[5]); Index.MAT := ConvertToFloat(AExcelRow.Values[6]); Index.SMR := ConvertToFloat(AExcelRow.Values[7]); end; { TIndexPart2Parser } procedure TIndexPart2Parser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Index: TGsIndexElement; begin if AExcelRow.HasValuesOr(['Номер', 'Код', 'Индекс']) or AExcelRow.IsEmpty then Exit; Index := TGsIndexElement.Create(ADocument); FChapter.Add(Index); Index.Code := AExcelRow.FilledValues[1]; Index.MAT := ConvertToFloat(AExcelRow.Values[2]); Index.SMR := Index.MAT; end; { TIndexPart3Parser } procedure TIndexPart3Parser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Index: TGsIndexElement; begin if AExcelRow.HasValuesOr(['Номер', 'Код', 'Индекс']) or AExcelRow.IsEmpty then Exit; Index := TGsIndexElement.Create(ADocument); FChapter.Add(Index); Index.Code := AExcelRow.FilledValues[1]; Index.EM := ConvertToFloat(AExcelRow.Values[2]); Index.SMR := Index.EM; end; { TIndexPart4Parser } procedure TIndexPart4Parser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Index1, Index2: TGsIndexElement; begin if AExcelRow.HasValuesOr(['Погрузо-разгрузочные работы', 'Расширение кода', 'Наименование работ']) or AExcelRow.IsEmpty then Exit; Index1 := TGsIndexElement.Create(ADocument); Index2 := TGsIndexElement.Create(ADocument); FChapter.Add(Index1); FChapter.Add(Index2); Index1.Code := '01-01-01' + AExcelRow.FirstValue; Index2.Code := '01-01-02' + AExcelRow.FirstValue; Index1.Caption := 'Погрузка: ' + AExcelRow.FilledValues[1]; Index2.Caption := 'Разгрузка: ' + AExcelRow.FilledValues[1]; Index1.EM := ConvertToFloat(AExcelRow.Values[2]); Index1.SMR := Index1.EM; Index2.EM := ConvertToFloat(AExcelRow.Values[3]); Index2.SMR := Index2.EM; case FSuffix of fsTER: begin Index1.Code := 'ТССЦпг-' + Index1.Code; Index2.Code := 'ТССЦпг-' + Index2.Code; end; fsFER: begin Index1.Code := 'ФССЦпг-' + Index1.Code; Index2.Code := 'ФССЦпг-' + Index2.Code; end; end; end; { TIndexPart5Parser } function TIndexPart5Parser.DoGetDocument: TGsDocument; begin Result := TGsDocument.Create; case FSuffix of fsTER: Result.LoadFromFile(Shape1); fsFER: Result.LoadFromFile(Shape2); end; end; procedure TIndexPart5Parser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var L: TList<TGsIndexElement>; Index: TGsIndexElement; begin if AExcelRow.HasValuesOr(['Перевозка', 'Код таблицы']) or AExcelRow.IsEmpty then Exit; L := ADocument.GetAll<TGsIndexElement>; try for Index in L do begin Index.Code := StringReplace(index.Code, 'ТССЦпг-', '', [rfReplaceAll]); Index.Code := StringReplace(index.Code, 'ТССЦпг', '', [rfReplaceAll]); Index.Code := StringReplace(index.Code, 'ФССЦпг-', '', [rfReplaceAll]); Index.Code := StringReplace(index.Code, 'ФССЦпг', '', [rfReplaceAll]); Index.IntTag := 1; if AnsiStartsText(AExcelRow.FirstValue, Index.Code) then begin Index.IntTag := 0; if AExcelRow.FirstValue = '02' then Index.MAT := ConvertToFloat(AExcelRow.FilledValues[2]) else Index.EM := ConvertToFloat(AExcelRow.FilledValues[2]); Index.SMR := ConvertToFloat(AExcelRow.FilledValues[2]); end; case FSuffix of fsTER: Index.Code := 'ТССЦпг-' + index.Code; fsFER: Index.Code := 'ФССЦпг-' + index.Code; end; end; finally L.Free; end; end; { TIndexCatalogMaterialParser } procedure TIndexCatalogMaterialParser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Price: TGsPriceElement; begin if TParserTools.IsStandartChapter(AExcelRow.FirstValue) then begin FChapter := TGsDocument.CreateChapterByPriority(FChapter, TParserTools.GetChapterPriority(AExcelRow.FirstValue)); FChapter.Caption := AExcelRow.FirstValue; end else if TParserTools.IsDefaultMaterialCode(AExcelRow.Values[1]) then begin Price := TGsPriceElement.Create(ADocument); FChapter.Add(Price); Price.Code := AExcelRow.Values[1]; Price.Caption := AExcelRow.Values[2]; Price.Measure := AExcelRow.Values[3]; Price.Attributes[Ord(paMass)] := AExcelRow.Values[4]; Price.PriceBE := ConvertToFloat(AExcelRow.Values[5]); Price.Attributes[Ord(paCargo)] := GetCargoClass(AExcelRow.Values[6]); Price.PriceCE := ConvertToFloat(AExcelRow.Values[9]); Price.PriceCT := ConvertToFloat(AExcelRow.Values[8]); end; end; function TIndexCatalogMaterialParser.GetCargoClass(Value: string): Integer; begin Result := 1; if Value = 'I' then Result := 1 else if Value = 'II' then Result := 2 else if Value = 'III' then Result := 3 else if Value = 'IV' then Result := 4; end; procedure TIndexCatalogMaterialParser.InitDocument(ADocument: TGsDocument); begin ADocument.DocumentType := dtPrice; end; { TIndexCatalogMachineParser } procedure TIndexCatalogMachineParser.DoParseRow(AExcelRow: TExcelRowWrapper; ARowIndex: Integer; ADocument: TGsDocument); var Price: TGsPriceElement; begin // if AExcelRow.ContainsTextOr(['Наименование', 'единица измерения']) or AExcelRow.IsEmpty then // Exit; if TParserTools.IsStandartChapter(AExcelRow.FirstValue) or (AExcelRow.FilledValuesCount = 1) then begin FChapter := TGsDocument.CreateChapterByPriority(FChapter, TParserTools.GetChapterPriority(AExcelRow.FirstValue)); FChapter.Caption := AExcelRow.FirstValue; end else if TParserTools.IsDefaultMachineCode(AExcelRow.Values[1]) then begin Price := TGsPriceElement.Create(ADocument); FChapter.Add(Price); Price.Code := AExcelRow.Values[1]; Price.Caption := AExcelRow.Values[2]; Price.Measure := 'маш.-ч'; Price.PriceCE := ConvertToFloat(AExcelRow.Values[4]); Price.PriceCT := ConvertToFloat(AExcelRow.Values[5]); end; end; procedure TIndexCatalogMachineParser.InitDocument(ADocument: TGsDocument); begin ADocument.DocumentType := dtPrice; end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, DCPrc4, DCPsha1; type { TForm1 } TForm1 = class(TForm) ButtonEnCrypt: TButton; ButtonDeCrypt: TButton; EditSource: TEdit; EditTarget: TEdit; LabelSource: TLabel; LabelDestination: TLabel; procedure ButtonEnCryptClick(Sender: TObject); procedure ButtonDeCryptClick(Sender: TObject); private public DCP_rc4_1: TDCP_rc4; DCP_sha1_1: TDCP_sha1; end; var Form1: TForm1; KeyStr: string; implementation {$R *.lfm} { TForm1 } procedure TForm1.ButtonEnCryptClick(Sender: TObject); var Cipher: TDCP_rc4; Source, Target: TFileStream; begin if not FileExists(EditSource.Text) then begin ShowMessage('ERROR: Source file does not exist'); Exit; end; if FileExists(EditTarget.Text) then RenameFile(EditTarget.Text, EditTarget.Text+'.bak'); try Source:= TFileStream.Create(EditSource.Text,fmOpenRead); Target:= TFileStream.Create(EditTarget.Text,fmCreate); Cipher:= TDCP_rc4.Create(Self); Cipher.InitStr(KeyStr,TDCP_sha1); Cipher.EncryptStream(Source,Target,Source.Size); Cipher.Burn; Cipher.Free; Target.Free; Source.Free; ShowMessage('File encrypted'); except ShowMessage('ERROR: File IO error'); end; end; procedure TForm1.ButtonDeCryptClick(Sender: TObject); var Cipher: TDCP_rc4; Source, Target: TFileStream; begin if not FileExists(EditTarget.Text) then begin ShowMessage('ERROR: Destination file does not exist'); Exit; end; if FileExists(EditSource.Text) then RenameFile(EditSource.Text, EditSource.Text+'.bak'); try Source:= TFileStream.Create(EditTarget.Text,fmOpenRead); Target:= TFileStream.Create(EditSource.Text,fmCreate); Cipher:= TDCP_rc4.Create(Self); Cipher.InitStr(KeyStr,TDCP_sha1); Cipher.DecryptStream(Source,Target,Source.Size); Cipher.Burn; Cipher.Free; Target.Free; Source.Free; ShowMessage('File decrypted'); except ShowMessage('ERROR: File IO error'); end; end; end.
{This program is a demonstration of the SORT interface. It creates a file with random numbers in it, calls SORT to sort the file, and prints the first 20 lines in the sorted file. To run this program, load it with PASSRT.MAC. exec srttst.pas,passrt.mac This program does things in a more complex way than it needs to, just to show you how to do certain common things. It reads the file names from the user and constructs the command string to SORT dynamically. Since Pascal does not have strings, this can be a bit tricky. We construct the command string by openning the file OUTPUT on the command string and writing the command to OUTPUT. The ability to do this is a special feature of Tops-20 Pascal. It allows you to redirect a file, in this case OUTPUT, to a string (i.e. a packed array of char. Anything you write to OUTPUT shows up in that string. This turns out to be a simple and powerful way to build up strings, since the Pascal write procedure lets you format things fairly easily.} program test; const namelength=200; commandlength=2500; var numrecords,i:integer; unsortedfile,sortedfile:text; unsortedname,sortedname:packed array[1:namelength]of char; unsortedlength,sortedlength:integer; sortcommand:packed array[1:commandlength]of char; thing:real; {string is a built-in data type usable only in declarations of external procedures. It allows a packed array of char of any length. It passes both the address of the array and its length.} procedure sort(s:string);extern; begin for i := 1 to commandlength do sortcommand[i] := chr(0); {We clear the command buffer in case you decide to restart the program, and the new command is shorter than the old one. Blanks would be as good as nulls.} write(tty,'How many records would you like in the file? '); readln(tty); read(tty,numrecords); write(tty,'File name for unsorted random numbers: '); readln(tty); read(tty,unsortedname:unsortedlength); {Note that READ into a packed array of char reads until you fill the array or you get to the end of the line in the input, whichever happens first. UNSORTEDLENGTH gets set to the number of characters read.} write(tty,'File name for sorted random numbers: '); readln(tty); read(tty,sortedname:sortedlength); strwrite(output,sortcommand); {strwrite is like encode in Fortran - it directs a file to a packed array of char. That is, any writes done on OUTPUT will now go into that array} write('s/r:20/k:1,20 ',unsortedname:unsortedlength,' ', sortedname:sortedlength); rewrite(output,unsortedname); {this form of rewrite opens the file OUTPUT with whatever filename is in the variable UNSORTEDNAME} for i := 1 to numrecords do writeln(random(0):20:7); {this writes out a random number in format F20.7. Random(0) calls RAN(0) from the Fortran library. Fortran requires that the random number generator take an argument. However it completely ignores the argument.} close(output); {We must close the file, or SORT won't be able to see it. New files do not show up on disk until they are closed} sort(sortcommand); reset(input,sortedname); {Open the file INPUT for input, with filename stored in the variable SORTEDNAME} if numrecords > 20 {output only a reasonable number} then numrecords := 20; writeln(tty,'Please verify that these are in order'); for i := 1 to numrecords do begin read(thing); writeln(tty,thing:20:7) end; end.
unit FileUploadErrorsResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, NullableBasicTypesUnit, CommonTypesUnit, JSONNullableAttributeUnit; type TFileUploadErrorsResponse = class(TGenericParameters) private [JSONName('errors')] FErrors: TStringArray; [JSONName('timestamp')] [Nullable] FTimestamp: NullableInteger; public constructor Create; override; property Errors: TStringArray read FErrors write FErrors; property Timestamp: NullableInteger read FTimestamp write FTimestamp; end; implementation constructor TFileUploadErrorsResponse.Create; begin inherited; SetLength(FErrors, 0); FTimestamp := NullableInteger.Null; end; end.
unit LisAge; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, NxScrollControl, NxCustomGridControl, NxCustomGrid, NxGrid, NxColumns, NxColumnClasses, DB, DBTables, FMTBcd, SqlExpr, QuickRpt, QRCtrls, Menus, DBGrids, Vcl.OleServer, ComObj ; type TfrmLisAge = class(TForm) Panel1: TPanel; cmdModificar: TBitBtn; cmdEliminar: TBitBtn; cmdAgregar: TBitBtn; cmdCerrar: TBitBtn; Panel2: TPanel; Lista: TNextGrid; Nombre: TNxTextColumn; NxTextColumn1: TNxTextColumn; NxTextColumn2: TNxTextColumn; NxTextColumn3: TNxTextColumn; NxTextColumn4: TNxTextColumn; cmdReporte: TBitBtn; Reporte: TQuickRep; QRBand1: TQRBand; QRLabel1: TQRLabel; QRLabel4: TQRLabel; QRLabel5: TQRLabel; QRLabel6: TQRLabel; QRLabel7: TQRLabel; QRLabel8: TQRLabel; Qrband2: TQRBand; codoban: TQRLabel; xnombre_age: TQRLabel; xestado: TQRLabel; xgrupo: TQRLabel; codoage: TQRLabel; Label1: TLabel; Label2: TLabel; busco: TBitBtn; muestro: TBitBtn; xzona: TNxTextColumn; PopupMenu2: TPopupMenu; MenuItem1: TMenuItem; MovimientodelPrestamo1: TMenuItem; Label3: TLabel; xter: TNxTextColumn; xtri: TNxTextColumn; xgan: TNxTextColumn; xcobrador: TNxTextColumn; BitBtn1: TBitBtn; Panel3: TPanel; Edit4: TEdit; Label6: TLabel; Edit3: TEdit; Label5: TLabel; Label4: TLabel; Edit2: TEdit; procedure FormShow(Sender: TObject); procedure cmdCerrarClick(Sender: TObject); procedure cmdModificarClick(Sender: TObject); procedure cmdEliminarClick(Sender: TObject); procedure cmdAgregarClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure cmdReporteClick(Sender: TObject); procedure Qrband2BeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); procedure buscoClick(Sender: TObject); procedure muestroClick(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure MovimientodelPrestamo1Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure Rellenar; end; var frmLisAge: TfrmLisAge; implementation uses Data, agencia, RPTListas; {$R *.dfm} procedure TfrmLisAge.FormShow(Sender: TObject); begin //Rellenar; end; procedure TfrmLisAge.Rellenar; var cs:integer; begin cs:=0; Lista.ClearRows; frmdata.Query1.Close; frmdata.Query1.SQL.Clear; if frmData.Tipo='R' then frmdata.Query1.SQL.Add('SELECT cobrador_age,codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona,b_age_avg_ter(codigo_age) as xter,b_age_avg_por(codigo_age) as xtri,b_age_avg_gan(codigo_age) as xgan FROM agencias_banca WHERE esmiag(codigo_age,'+quotedStr(frmData.BDBANCA)+')='+quotedstr('SI')+' order by codigo_ban,codigo_age') else frmdata.Query1.SQL.Add('SELECT cobrador_age,codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona,b_age_avg_ter(codigo_age) as xter,b_age_avg_por(codigo_age) as xtri,b_age_avg_gan(codigo_age) as xgan FROM agencias_banca order by codigo_ban,codigo_age'); frmData.Ejecutar(frmdata.Query1); frmdata.Query1.First; while not frmdata.Query1.Eof do begin Lista.AddRow(1); Lista.Cell[0,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_ban']; Lista.Cell[1,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['grupo']; Lista.Cell[2,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_age']; Lista.Cell[3,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['nombre_age']; Lista.Cell[4,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['estado_age']; Lista.Cell[5,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['zona']; Lista.Cell[6,Lista.RowCount-1].AsString:=FormatFloat(frmdata.formato,frmdata.Query1.FieldValues['xter']); Lista.Cell[7,Lista.RowCount-1].AsString:=FormatFloat(frmdata.formato,frmdata.Query1.FieldValues['xtri']); Lista.Cell[8,Lista.RowCount-1].AsString:=FormatFloat(frmdata.formato,frmdata.Query1.FieldValues['xgan']); Lista.Cell[9,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['cobrador_age']; cs:=cs+1; frmdata.Query1.Next; end; frmdata.Query1.Close; label2.Caption:=inttostr(cs); end; procedure TfrmLisAge.cmdCerrarClick(Sender: TObject); begin frmlisage.Close; end; procedure TfrmLisAge.cmdModificarClick(Sender: TObject); var voyen: integer; codigoage:string; begin if Lista.SelectedRow>=0 then begin voyen:=Lista.SelectedRow; codigoage:=Lista.Cell[2,Lista.SelectedRow].AsString; frmAgencia.bancage:=Lista.Cell[0,Lista.SelectedRow].AsString; frmAgencia.mizona:=Lista.Cell[5,Lista.SelectedRow].AsString; frmAgencia.codiage:=Lista.Cell[2,Lista.SelectedRow].AsString; frmAgencia.xcobra:=Lista.Cell[9,Lista.SelectedRow].AsString; frmAgencia.MISION:=2; label3.Caption:='N'; frmAgencia.ShowModal; if label3.Caption='N' then begin frmdata.Query1.Close; frmdata.Query1.SQL.Clear; frmdata.Query1.SQL.Add('SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona FROM agencias_banca WHERE codigo_age='+quotedStr(codigoage)); frmData.Ejecutar(frmdata.Query1); Lista.Cell[0,voyen].AsString:=frmdata.Query1.FieldValues['codigo_ban']; Lista.Cell[1,voyen].AsString:=frmdata.Query1.FieldValues['grupo']; Lista.Cell[2,voyen].AsString:=frmdata.Query1.FieldValues['codigo_age']; Lista.Cell[3,voyen].AsString:=frmdata.Query1.FieldValues['nombre_age']; Lista.Cell[4,voyen].AsString:=frmdata.Query1.FieldValues['estado_age']; Lista.Cell[5,voyen].AsString:=frmdata.Query1.FieldValues['zona']; end; end; end; procedure TfrmLisAge.cmdEliminarClick(Sender: TObject); var A,cp1,SQL,ajo:string; begin if Lista.SelectedRow>=0 then begin A:='Esta seguro de eliminar: '+ #13 +'-La Agencia:'+ Lista.Cell[2,Lista.SelectedRow].AsString+ #13 +' Sera Borrada la Toda la informacion de esta taquilla'; if Application.MessageBox(PWideChar(A), 'Información', MB_YESNO+MB_ICONQUESTION)=ID_YES then begin // Aqui debe ir el procedure borrado frmdata.Query1.Close; frmdata.Query1.SQL.Clear; SQL:=''; SQL:='SELECT IFNULL(sum(monto),0) as v from ren_tickets where cod_agencia='+quotedstr(Lista.Cell[2,Lista.SelectedRow].AsString)+' and anulado='+quotedstr('N'); frmdata.Query1.SQL.Add(SQL); frmData.Ejecutar(frmdata.Query1); if frmdata.Query1.FieldValues['v']<>0 then begin showmessage('Tiene jugada para el dia de hoy y no podra ser eliminado...'); exit; end; ajo:=Lista.Cell[2,Lista.SelectedRow].AsString; frmdata.Query1.Close; frmdata.Query2.SQL.Clear; frmdata.Query2.SQL.Add('CALL b_age_eli('+quotedStr(Lista.Cell[2,Lista.SelectedRow].AsString)+')'); frmdata.Llamar(frmdata.Query2); frmdata.Query2.Close; // Lista.DeleteRow(Lista.SelectedRow); // Auditoria cp1:=('Elimino la Agencia -> '+ajo+' a pesar de que se le advirtio') ; frmRPTListas.elmiron(cp1); // end; Rellenar; end; end; procedure TfrmLisAge.cmdAgregarClick(Sender: TObject); begin frmAgencia.MISION:=1; frmAgencia.ShowModal; Rellenar; end; procedure TfrmLisAge.Button1Click(Sender: TObject); var cadena: string; begin cadena:=InputBox('Buscar','Ingrese el Código a Buscar: ',''); if (cadena='') then begin ShowMessage('Por favor Introduzca un Código!!!' ); exit; end else begin if not frmData.Datos_Banca.Locate('codigo_ban',cadena,[]) then begin ShowMessage('Agencia No encontrada!!!' ); exit; end end end; procedure TfrmLisAge.cmdReporteClick(Sender: TObject); var SQL,fec,final: string; begin fec:=DateToStr(frmData.SDate); final:=Copy(fec,7,4); final:=final+'-'; final:=final+Copy(fec,4,2); final:=final+'-'; final:=final+Copy(fec,1,2); frmdata.Query2.Close; frmdata.Query2.SQL.Clear; if frmData.Tipo='R' then SQL:='SELECT * FROM agencias_banca WHERE codigo_ban='+quotedStr(frmData.BDBANCA) else SQL:='SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age FROM agencias_banca'; frmdata.Query2.SQL.Add(SQL); frmData.Ejecutar(frmdata.Query2); if (frmdata.Query2.RecordCount<=0)then begin ShowMessage('No existen registros!!!' ); exit; end; Reporte.PreviewModal(); frmdata.Query2.Close; end; procedure TfrmLisAge.Qrband2BeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); begin codoban.Caption:=frmdata.Query2.FieldValues['codigo_ban']; xgrupo.Caption:=frmdata.Query2.FieldValues['grupo']; codoage.Caption:=frmdata.Query2.FieldValues['codigo_age']; xnombre_age.Caption:=frmdata.Query2.FieldValues['nombre_age']; xestado.Caption:=frmdata.Query2.FieldValues['estado_age']; end; procedure TfrmLisAge.BitBtn1Click(Sender: TObject); var PLANILHA,xlw: Variant; i,r,lineas: Integer; nombre,final2,borre:string; creado:boolean; begin lineas:=lista.rowcount; if lineas=0 then begin showmessage('No hay informacion para exportar...'); exit; end; try begin PLANILHA:=CreateOleObject('Excel.Application'); creado:=true; end; except on E : Exception do begin ShowMessage(E.ClassName+' No esta instalado Excel : '+E.Message); creado:=false; exit; end; end; lineas:=lineas+1; final2:=final2+Copy(datetostr(frmData.SDate),1,2); final2:=final2+'-'; final2:=final2+Copy(datetostr(frmData.SDate),4,2); final2:=final2+'-'; final2:=final2+Copy(datetostr(frmData.SDate),7,4); nombre:='Listado General de Agencias '+final2; xlw:=PLANILHA.workbooks.add; // PLANILHA.range['A2:F'+inttostr(lineas)].NumberFormat := AnsiChar('@'); // for r:=0 to lista.Columns.Count-5 do PLANILHA.cells[1,r+1]:=lista.Columns[r].Header.Caption; try for i:=0 to lista.rowcount-1 do for r:=0 to lista.Columns.Count-5 do begin if lista.Cells[r,i]='' then PLANILHA.cells[i+2,r+1]:='' else PLANILHA.cells[i+2,r+1]:=lista.Cells[r,i]; end; PLANILHA.columns.autofit; finally end; if (creado = true) then begin try PLANILHA.DisplayAlerts:=False; PLANILHA.ActiveWorkbook.SaveAs(GetCurrentDir+'\'+nombre); PLANILHA.DisplayAlerts:=True; showmessage('El archivo : '+GetCurrentDir+'\'+nombre+' fue grabado correctamente...'); except showmessage('ERROR !!!! El archivo : '+GetCurrentDir+'\'+nombre+' NO fue grabado..'); end; PLANILHA.Workbooks.Close; PLANILHA.Quit; PLANILHA:=Unassigned; end; end; procedure TfrmLisAge.buscoClick(Sender: TObject); var cs:integer; SQL,xedi2,xedi3,xedi4: string; begin cs:=0; Lista.ClearRows; frmdata.Query1.Close; frmdata.Query1.SQL.Clear; if edit2.Text='' then xedi2:='' else xedi2:=' and (codigo_ban like '+quotedstr(edit2.Text+'%'); if edit3.Text='' then xedi3:='' else if edit2.Text='' then xedi3:=' and (codigo_age like '+quotedstr(edit3.Text+'%') else xedi3:=' and codigo_age like '+quotedstr(edit3.Text+'%'); if edit4.Text='' then if (edit2.Text<>'') or (edit3.Text<>'') then xedi4:=')' else xedi4:='' else if (edit2.Text='') and (edit3.Text='') then xedi4:=' and (nombre_age like '+quotedstr(edit4.Text+'%')+')' else xedi4:=' and nombre_age like '+quotedstr(edit4.Text+'%')+')'; if frmData.Tipo='R' then SQL:='SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona FROM agencias_banca WHERE esmiag(codigo_age,'+ quotedStr(frmData.BDBANCA)+')='+quotedstr('SI')+ xedi2+xedi3+xedi4 else SQL:='SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona'+ ' FROM agencias_banca where codigo_age<>'+quotedstr('')+ xedi2+xedi3+xedi4; frmdata.Query1.SQL.Add(SQL); frmData.Ejecutar(frmdata.Query1); frmdata.Query1.First; while not frmdata.Query1.Eof do begin Lista.AddRow(1); Lista.Cell[0,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_ban']; Lista.Cell[1,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['grupo']; Lista.Cell[2,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_age']; Lista.Cell[3,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['nombre_age']; Lista.Cell[4,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['estado_age']; Lista.Cell[5,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['zona']; cs:=cs+1; frmdata.Query1.Next; end; frmdata.Query1.Close; label2.Caption:=inttostr(cs); {var cs:integer; begin cs:=0; Lista.ClearRows; frmdata.Query1.Close; frmdata.Query1.SQL.Clear; if frmData.Tipo='R' then frmdata.Query1.SQL.Add('SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona FROM agencias_banca WHERE esmiag(codigo_age,'+quotedStr(frmData.BDBANCA)+')='+quotedstr('SI')+' and (codigo_age like '+quotedstr(edit1.Text+'%')+' or codigo_ban like '+quotedstr(edit1.Text+'%')+' or nombre_age like '+quotedstr('%'+edit1.Text+'%')+')') else frmdata.Query1.SQL.Add('SELECT codigo_ban,grupo,codigo_age,nombre_age,estado_age,zona FROM agencias_banca where codigo_age like '+quotedstr(edit1.Text+'%')+' or codigo_ban like '+quotedstr(edit1.Text+'%')+' or nombre_age like '+quotedstr('%'+edit1.Text+'%') ) ; frmData.Ejecutar(frmdata.Query1); frmdata.Query1.First; while not frmdata.Query1.Eof do begin Lista.AddRow(1); Lista.Cell[0,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_ban']; Lista.Cell[1,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['grupo']; Lista.Cell[2,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['codigo_age']; Lista.Cell[3,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['nombre_age']; Lista.Cell[4,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['estado_age']; Lista.Cell[5,Lista.RowCount-1].AsString:=frmdata.Query1.FieldValues['zona']; cs:=cs+1; frmdata.Query1.Next; end; frmdata.Query1.Close; label2.Caption:=inttostr(cs); } end; procedure TfrmLisAge.muestroClick(Sender: TObject); begin edit2.Text:=''; edit3.Text:=''; edit4.Text:=''; rellenar; end; procedure TfrmLisAge.MenuItem1Click(Sender: TObject); var cp1,A:string; voyen: integer; begin if Lista.SelectedRow>=0 then begin A:='Esta seguro de Activar '+ #13 +'-La Zona :'+ Lista.Cell[5,Lista.SelectedRow].AsString+ #13 +' Seran Activadas Todas las taquillas de esa Zona'; if Application.MessageBox(PWideChar(A), 'Información', MB_YESNO+MB_ICONQUESTION)=ID_YES then begin voyen:=Lista.SelectedRow; frmdata.Query1.Close; frmdata.Query1.SQL.Clear; frmdata.Query1.SQL.Add('CALL b_age_zon('+quotedStr(Lista.Cell[5,Lista.SelectedRow].AsString)+','+quotedStr('A')+')'); frmdata.Llamar(frmdata.Query1); // Auditoria cp1:=('Activo la Zona -> '+ Lista.Cell[5,Lista.SelectedRow].AsString); frmRPTListas.elmiron(cp1); Rellenar; lista.ScrollToRow(voyen); // end; end; end; procedure TfrmLisAge.MovimientodelPrestamo1Click(Sender: TObject); var cp1,A:string; voyen: integer; begin A:='Esta seguro de Desactivar '+ #13 +'-La Zona :'+ Lista.Cell[5,Lista.SelectedRow].AsString+ #13 +' Seran Desactivadas Todas las taquillas de esa Zona'; if Application.MessageBox(PWideChar(A), 'Información', MB_YESNO+MB_ICONQUESTION)=ID_YES then begin voyen:=Lista.SelectedRow; frmdata.Query1.Close; frmdata.Query1.SQL.Clear; frmdata.Query1.SQL.Add('CALL b_age_zon('+quotedStr(Lista.Cell[5,Lista.SelectedRow].AsString)+','+quotedStr('D')+')'); frmdata.Llamar(frmdata.Query1); // Auditoria cp1:=('Desactivo la Zona -> '+ Lista.Cell[5,Lista.SelectedRow].AsString); frmRPTListas.elmiron(cp1); Rellenar; lista.ScrollToRow(voyen); // end; end; end.
unit Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs; type TdmPrincipal = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); procedure ServiceBeforeInstall(Sender: TService); procedure ServiceBeforeUninstall(Sender: TService); procedure ServiceContinue(Sender: TService; var Continued: Boolean); procedure ServiceExecute(Sender: TService); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); private { Private declarations } public function GetServiceController: TServiceController; override; { Public declarations } end; var dmPrincipal: TdmPrincipal; implementation uses LogUtils; {$R *.dfm} procedure TdmPrincipal.ServiceAfterInstall(Sender: TService); begin Log('TdmPrincipal.ServiceAfterInstall'); end; procedure TdmPrincipal.ServiceAfterUninstall(Sender: TService); begin Log('TdmPrincipal.ServiceAfterUninstall'); end; procedure TdmPrincipal.ServiceBeforeInstall(Sender: TService); begin Log('TdmPrincipal.ServiceBeforeInstall'); end; procedure TdmPrincipal.ServiceBeforeUninstall(Sender: TService); begin Log('TdmPrincipal.ServiceBeforeUninstall'); end; procedure TdmPrincipal.ServiceContinue(Sender: TService; var Continued: Boolean); begin Log('TdmPrincipal.ServiceContinue'); Continued := true; end; procedure TdmPrincipal.ServiceExecute(Sender: TService); begin Log('TdmPrincipal.ServiceExecute'); while not Self.Terminated do begin Sleep(200); ServiceThread.ProcessRequests(True); end; end; procedure TdmPrincipal.ServicePause(Sender: TService; var Paused: Boolean); begin Log('TdmPrincipal.ServicePause'); Paused := true; end; procedure TdmPrincipal.ServiceShutdown(Sender: TService); begin Log('TdmPrincipal.ServiceShutdown'); end; procedure TdmPrincipal.ServiceStart(Sender: TService; var Started: Boolean); begin Log('TdmPrincipal.ServiceStart'); Started := true; end; procedure TdmPrincipal.ServiceStop(Sender: TService; var Stopped: Boolean); begin Log('TdmPrincipal.ServiceStop'); Stopped := true; end; procedure ServiceController(CtrlCode: DWord); stdcall; begin dmPrincipal.Controller(CtrlCode); end; function TdmPrincipal.GetServiceController: TServiceController; begin Result := ServiceController; end; end.
unit l3ComponentNameHelper; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VCM$Visual" // Автор: Костицын // Модуль: "w:/common/components/gui/Garant/VCM/l3ComponentNameHelper.pas" // Начат: 28.03.2012 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VCM$Visual::TestSupport::Tl3ComponentNameHelper // // Следит за кликами на компоненты и показывает их имена. // Для тестов. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\VCM\vcmDefine.inc} interface {$If not defined(NoVCM)} uses l3Interfaces, vcmInterfaces, Controls, vcmEntityForm, l3ProtoObject, vcmMenuManager, l3Core ; {$IfEnd} //not NoVCM {$If not defined(NoVCM)} type Tl3ComponentNameHelper = class(Tl3ProtoObject, Il3GetMessageListener) {* Следит за кликами на компоненты и показывает их имена. Для тестов. } private // private fields f_Popup : TvcmPopupMenu; f_PopupForm : TvcmEntityForm; private // private methods function CheckPopup(const anEntityDef: IvcmEntityDef): IvcmEntity; protected // realized methods procedure GetMessageListenerNotify(Code: Integer; aWParam: WPARAM; Msg: PMsg; var theResult: Tl3HookProcResult); protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public // singleton factory method class function Instance: Tl3ComponentNameHelper; {- возвращает экземпляр синглетона. } end;//Tl3ComponentNameHelper {$IfEnd} //not NoVCM implementation {$If not defined(NoVCM)} uses l3Base {a}, l3ListenersManager, Windows, Messages, Forms, Classes, vcmEntityAction, vcmModuleAction {$If not defined(NoVGScene)} , vg_scene {$IfEnd} //not NoVGScene {$If not defined(NoVGScene)} , vg_controls {$IfEnd} //not NoVGScene , TypInfo, ActnList, vcmBase, vcmOperationAction, vcmMessagesSupport, Dialogs, l3MessageID, l3RTTI, StrUtils, Menus, vcmBaseMenuManager, SysUtils, vcmUserControls, vcmEntitiesDefIteratorForContextMenu, afwFacade, vcmMenus ; {$IfEnd} //not NoVCM {$If not defined(NoVCM)} // start class Tl3ComponentNameHelper var g_Tl3ComponentNameHelper : Tl3ComponentNameHelper = nil; procedure Tl3ComponentNameHelperFree; begin l3Free(g_Tl3ComponentNameHelper); end; class function Tl3ComponentNameHelper.Instance: Tl3ComponentNameHelper; begin if (g_Tl3ComponentNameHelper = nil) then begin l3System.AddExitProc(Tl3ComponentNameHelperFree); g_Tl3ComponentNameHelper := Create; end; Result := g_Tl3ComponentNameHelper; end; type THackControl = class(TControl) end;//THackControl // start class Tl3ComponentNameHelper function Tl3ComponentNameHelper.CheckPopup(const anEntityDef: IvcmEntityDef): IvcmEntity; //#UC START# *51ED0195036B_4F72CAA90045_var* //#UC END# *51ED0195036B_4F72CAA90045_var* begin //#UC START# *51ED0195036B_4F72CAA90045_impl* with f_Popup, f_PopupForm do if (PopupComponent Is TControl) then with TControl(PopupComponent).ScreenToClient(PopupPoint) do Result := GetInnerForControl(anEntityDef.ID, PopupComponent, X, Y) else Result := GetInnerForControl(anEntityDef.ID, PopupComponent); //#UC END# *51ED0195036B_4F72CAA90045_impl* end;//Tl3ComponentNameHelper.CheckPopup procedure Tl3ComponentNameHelper.GetMessageListenerNotify(Code: Integer; aWParam: WPARAM; Msg: PMsg; var theResult: Tl3HookProcResult); //#UC START# *4F62032D0058_4F72CAA90045_var* procedure AddInfo(var theInfo: string; const aCaption, aValue: string; aNewLine: Boolean = False); overload; begin if Length(aValue) > 0 then begin if Length(theInfo) > 0 then if aNewLine then theInfo := theInfo + #13#10 else theInfo := theInfo + ', '; theInfo := theInfo + aCaption + ':' + aValue; end; end; procedure AddInfo(var theInfo: string; const aCaption: string; aValue: Il3CString; aNewLine: Boolean = False); overload; begin AddInfo(theInfo, aCaption, vcmStr(aValue), aNewLine); end; function MenuInfo(aMenu: TMenu; const aCaption: string): string; function MenuItemInfo(anItem: TMenuItem; aLevel: Integer): string; function FormatName(const aName: string): string; begin Result := aName; if Length(aName) = 0 then Result := '-'; end; var I: Integer; l_Action: TCustomAction; l_ItemInfo: string; l_ActionInfo: string; l_OpName: string; l_S: string; begin Result := ''; if not (Assigned(anItem) and anItem.Visible) then Exit; {$IfDef l3HackedVCL} anItem.CallInitiateActions; {$EndIf l3HackedVCL} if aLevel > 0 then l_ItemInfo := '''' + anItem.Caption + ''' ' {+ FormatName(anItem.Name) + ': ' + anItem.ClassName} else l_ItemInfo := ''; if Assigned(anItem.Action) then begin Assert(anItem.Action is TCustomAction); l_Action := anItem.Action as TCustomAction; if Assigned(l_Action) then begin l_ActionInfo := FormatName(l_Action.Name) + ': ' + l_Action.ClassName; if l_Action is TvcmOperationAction then begin l_S := ''; AddInfo(l_S, 'OpDef', TvcmOperationAction(l_Action).OpDef.Name); if l_Action is TvcmEntityAction then AddInfo(l_S, 'EntityDef', TvcmEntityAction(l_Action).EntityDef.Name); if l_Action is TvcmActiveEntityActionEx then AddInfo(l_S, 'EntityDef', TvcmActiveEntityActionEx(l_Action).EntityDef.Name); if l_Action is TvcmModuleAction then AddInfo(l_S, 'ModuleDef', TvcmModuleAction(l_Action).ModuleDef.Name); l_ActionInfo := l_ActionInfo + ' (' + l_S + ');'; end; l_ItemInfo := l_ItemInfo + ', Action: ' + l_ActionInfo; end; end; if Length(l_ItemInfo) > 0 then l_ItemInfo := DupeString(' ', aLevel - 1) + l_ItemInfo; l_ItemInfo := l_ItemInfo + #13#10; for I := 0 to anItem.Count - 1 do l_ItemInfo := l_ItemInfo + MenuItemInfo(anItem.Items[I], aLevel + 1); Result := l_ItemInfo; end; // MenuItemInfo var l_Item: TMenuItem; begin Result := ''; if not Assigned(aMenu) then Exit; Result := Trim(MenuItemInfo(aMenu.Items, 0)); if Length(Result) > 0 then Result := '{cloak}'#13#10 + aCaption + #13#10 + Result + #13#10'{/cloak}'#13#10; end; // MenuInfo var l_Pos: TPoint; procedure InfoForControl(aControl: TControl; out theText: string; vgHierarchy: Boolean = False); var l_CPos: TPoint; l_VO: TvgVisualObject; l_O: TvgObject; l_ActionProp: TObject; begin if (aControl is TvgCustomScene) then begin l_CPos := TvgCustomScene(aControl).ScreenToClient(l_Pos); l_VO := TvgCustomScene(aControl).ObjectByPoint(l_CPos.X, l_CPos.Y); repeat if (l_VO <> nil) then begin AddInfo(theText, 'name', l_VO.Name, True); if l_VO is TvgTextControl then AddInfo(theText, 'text', TvgTextControl(l_VO).Text); AddInfo(theText, 'class', l_VO.ClassName); l_O := l_VO.Parent; if l_O is TvgVisualObject then l_VO := TvgVisualObject(l_O) else l_VO := nil; end;//l_VO <> nil until not (vgHierarchy and Assigned(l_VO)); end; if (theText = '') then if Assigned(aControl) then begin AddInfo(theText, 'name', aControl.Name, True); AddInfo(theText, 'class', aControl.ClassName); try l_ActionProp := GetObjectProp(aControl, 'Action', TCustomAction); except l_ActionProp := nil; end; if Assigned(l_ActionProp) then begin AddInfo(theText, 'act.name', TCustomAction(l_ActionProp).Name); if l_ActionProp is TvcmOperationAction then begin AddInfo(theText, 'act.OpDef', TvcmOperationAction(l_ActionProp).OpDef.Caption); AddInfo(theText, 'act.OpDef', TvcmOperationAction(l_ActionProp).OpDef.Name); if l_ActionProp is TvcmEntityAction then begin AddInfo(theText, 'act.EntityDef', TvcmEntityAction(l_ActionProp).EntityDef.Caption); AddInfo(theText, 'act.EntityDef', TvcmEntityAction(l_ActionProp).EntityDef.Name); end; if l_ActionProp is TvcmActiveEntityActionEx then begin AddInfo(theText, 'act.EntityDef', TvcmActiveEntityActionEx(l_ActionProp).EntityDef.Caption); AddInfo(theText, 'act.EntityDef', TvcmActiveEntityActionEx(l_ActionProp).EntityDef.Name); end; if l_ActionProp is TvcmModuleAction then begin AddInfo(theText, 'act.ModuleDef', TvcmModuleAction(l_ActionProp).ModuleDef.Caption); AddInfo(theText, 'act.ModuleDef', TvcmModuleAction(l_ActionProp).ModuleDef.Name); end; end;//l_ActionProp is TvcmOperationAction end;//Assigned(l_ActionProp) end;//Assigned(aControl) end;//procedure InfoForControl procedure GetvcmPopupMenu(aControl: TControl; aMenu: TMenuItem); var l_Form: TCustomForm; begin l_Form := afw.GetParentForm(aControl); if l_Form is TvcmEntityForm then begin f_PopupForm := TvcmEntityForm(l_Form); vcmMakeEntitiesMenus(aMenu, TvcmEntitiesDefIteratorForContextMenu.Make(f_PopupForm.GetEntitiesDefIterator), [vcm_ooShowInContextMenu], True, vcm_icExternal, nil, CheckPopup ); end; end; var l_Menu: TMenu; l_Control: TControl; l_LoopControl: TControl; l_Parent: TWinControl; l_S, l_Info, l_MenuInfo: string; l_C: string; //#UC END# *4F62032D0058_4F72CAA90045_var* begin //#UC START# *4F62032D0058_4F72CAA90045_impl* if ([ssShift, ssAlt, ssCtrl] * KeyboardStateToShiftState = [ssShift, ssAlt, ssCtrl]) then if (Msg.Message = WM_LBUTTONDOWN) or (Msg.Message = WM_RBUTTONDOWN) then begin l_S := ''; l_C := ''; GetCursorPos(l_Pos); l_Control := FindDragTarget(l_Pos, True); if not Assigned(l_Control) then Exit; if Msg.Message = WM_LBUTTONDOWN then begin // строим информацию по меню l_S := ''; l_LoopControl := l_Control; while (Length(l_S) = 0) and Assigned(l_LoopControl) do begin if l_LoopControl is TCustomForm then l_S := MenuInfo((l_LoopControl as TCustomForm).Menu, 'Главное меню'); l_LoopControl := l_LoopControl.Parent; end; l_MenuInfo := l_S; l_S := ''; l_LoopControl := l_Control; while (Length(l_S) = 0) and Assigned(l_LoopControl) do begin f_Popup := TvcmPopupMenu.Create(l_LoopControl); try f_Popup.PopupComponent := l_LoopControl; PPoint(@f_Popup.PopupPoint)^ := l_Pos; GetvcmPopupMenu(l_LoopControl, f_Popup.Items); if f_Popup.Items.Count > 0 then l_Menu := f_Popup; if not Assigned(l_Menu) then l_Menu := (g_MenuManager as TvcmCustomMenuManager).FillPopupMenu(l_Pos, l_LoopControl); if not Assigned(l_Menu) then l_Menu := THackControl(l_LoopControl).PopupMenu; if Assigned(l_Menu) then l_S := MenuInfo(l_Menu, 'Контекстное меню'); finally l3Free(f_Popup); end; l_LoopControl := l_LoopControl.Parent; end; l_MenuInfo := l_MenuInfo + l_S; end; InfoForControl(l_Control, l_Info, Msg.Message = WM_RBUTTONDOWN); l_S := l_Info; if Length(l_MenuInfo) > 0 then l_S := l_MenuInfo + #13#10 + l_Info; if (Msg.Message = WM_RBUTTONDOWN) then repeat l_Parent := l_Control.Parent; if Assigned(l_Parent) and (l_Parent is TControl) then begin l_Control := TControl(l_Parent); InfoForControl(l_Control, l_Info, True); l_S := l_S + #13#10 + l_Info; end else Break; until False; if (Msg.Message = WM_LBUTTONDOWN) then l_S := l_S + #13#10#13#10 + L3FormatRTTIInfo(l_Control); if (l_S <> '') then vcmMessageDlg(Tl3Message_C(vcmCStr(l_S), '', mtInformation)); Msg.Message := 0; end;//WM_LBUTTONDOWN or WM_RBUTTONDOWN //#UC END# *4F62032D0058_4F72CAA90045_impl* end;//Tl3ComponentNameHelper.GetMessageListenerNotify procedure Tl3ComponentNameHelper.Cleanup; //#UC START# *479731C50290_4F72CAA90045_var* //#UC END# *479731C50290_4F72CAA90045_var* begin //#UC START# *479731C50290_4F72CAA90045_impl* Tl3ListenersManager.RemoveGetMessageListener(Self); inherited; //#UC END# *479731C50290_4F72CAA90045_impl* end;//Tl3ComponentNameHelper.Cleanup procedure Tl3ComponentNameHelper.InitFields; //#UC START# *47A042E100E2_4F72CAA90045_var* //#UC END# *47A042E100E2_4F72CAA90045_var* begin //#UC START# *47A042E100E2_4F72CAA90045_impl* inherited; Tl3ListenersManager.AddGetMessageListener(Self); //#UC END# *47A042E100E2_4F72CAA90045_impl* end;//Tl3ComponentNameHelper.InitFields {$IfEnd} //not NoVCM initialization {$If not defined(NoVCM)} //#UC START# *4F72D9FF0074* Tl3ComponentNameHelper.Instance; //#UC END# *4F72D9FF0074* {$IfEnd} //not NoVCM end.
{ MIT License Copyright (c) 2017 Marcos Douglas B. Santos 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 James.Format.Base64.Clss; {$include james.inc} interface uses Classes, SysUtils, synacode, James.Data, James.Data.Clss; type TBase64Stream = class sealed(TInterfacedObject, IDataStream) private FOrigin: IDataStream; function OriginAsBase64: IDataStream; public constructor Create(Origin: IDataStream); reintroduce; class function New(Origin: IDataStream): IDataStream; function Save(Stream: TStream): IDataStream; overload; function Save(const FileName: string): IDataStream; overload; function Save(Strings: TStrings): IDataStream; overload; function AsString: string; function Size: Int64; end; implementation { TBase64Stream } function TBase64Stream.OriginAsBase64: IDataStream; var Buf1, Buf2: TStringStream; begin Buf2 := nil; Buf1 := TStringStream.Create(''); try FOrigin.Save(Buf1); Buf1.Position := soFromBeginning; Buf2 := TStringStream.Create(EncodeBase64(Buf1.DataString)); Result := TDataStream.New(Buf2); finally Buf1.Free; Buf2.Free; end; end; constructor TBase64Stream.Create(Origin: IDataStream); begin inherited Create; FOrigin := Origin; end; class function TBase64Stream.New(Origin: IDataStream): IDataStream; begin Result := Create(Origin); end; function TBase64Stream.Save(Stream: TStream): IDataStream; begin Result := OriginAsBase64.Save(Stream); end; function TBase64Stream.Save(const FileName: string): IDataStream; begin Result := OriginAsBase64.Save(FileName); end; function TBase64Stream.Save(Strings: TStrings): IDataStream; begin Result := OriginAsBase64.Save(Strings); end; function TBase64Stream.AsString: string; begin Result := Trim(OriginAsBase64.AsString); end; function TBase64Stream.Size: Int64; begin Result := OriginAsBase64.Size; end; 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$ } unit IdSysNet; interface uses System.Globalization, System.Text, //here so we can refer to StringBuilder class IdSysBase; type //I know EAbort violates our rule about basing exceptions on EIdException. //I'm doing this for one reason, to be compatible with SysUtils where a reference //is made to the EAbort exception. EAbort = class(Exception); EConvertError = class(Exception); TSysCharSet = set of AnsiChar; //I'm doing it this way because you can't inherit directly from StringBuilder //because of MS defined it. //This is necessary because the StringBuilder does NOT have an IndexOF method and //StringBuilder is being used for speed to prevent immutability problems with the String class //in DotNET TIdStringBuilder = System.Text.StringBuilder; TIdStringBuilderHelper = class helper for System.Text.StringBuilder public function IndexOf(const value : String; const startIndex, count : Integer) : Integer; overload; function IndexOf(const value : String; const startIndex : Integer) : Integer; overload; function IndexOf(const value : String) : Integer; overload; function LastIndexOf(const value : String; const startIndex, count : Integer) : Integer; overload; function LastIndexOf(const value : String; const startIndex : Integer) : Integer; overload; function LastIndexOf(const value : String) : Integer; overload; function ReplaceOnlyFirst(const oldValue, newValue : String): StringBuilder; overload; function ReplaceOnlyFirst(const oldValue, newValue : String; const startIndex, count : Integer ): StringBuilder; overload; function ReplaceOnlyLast(const oldValue, newValue : String): StringBuilder; overload; function ReplaceOnlyLast(const oldValue, newValue : String; const startIndex, count : Integer ): StringBuilder; overload; end; TIdDateTimeBase = &Double; TIdSysNet = class(TIdSysBase) private protected class function AddStringToFormat(SB: StringBuilder; I: Integer; S: String): Integer; static; class procedure FmtStr(var Result: string; const Format: string; const Args: array of const); static; public class function FormatBuf(var Buffer: System.Text.StringBuilder; const Format: string; FmtLen: Cardinal; const Args: array of const; Provider: IFormatProvider): Cardinal; overload; static; class function FormatBuf(var Buffer: System.Text.StringBuilder; const Format: string; FmtLen: Cardinal; const Args: array of const): Cardinal; overload; static; class function AnsiCompareText(const S1, S2: WideString): Integer; static; class function LastChars(const AStr : String; const ALen : Integer): String; static; class function AddMSecToTime(const ADateTime : TIdDateTimeBase; const AMSec : Integer): TIdDateTimeBase; static; class function StrToInt64(const S: string): Int64; overload; static; class function StrToInt64(const S: string; const Default : Int64): Int64; overload; static; class function TwoDigitYearCenturyWindow : Word; static; class function FloatToIntStr(const AFloat : Extended) : String; static; class function AlignLeftCol(const AStr : String; const AWidth : Integer=0) : String; static; class procedure DecodeTime(const ADateTime: TIdDateTimeBase; var Hour, Min, Sec, MSec: Word); static; class procedure DecodeDate(const ADateTime: TIdDateTimeBase; var Year, Month, Day: Word); static; class function EncodeTime(Hour, Min, Sec, MSec: Word): TIdDateTimeBase; static; class function EncodeDate(Year, Month, Day: Word): TIdDateTimeBase; static; class function DateTimeToStr(const ADateTime: TIdDateTimeBase): string; static; class function StrToDateTime(const S : String): TIdDateTimeBase; static; class function Now : TIdDateTimeBase; static; class function DayOfWeek(const ADateTime: TIdDateTimeBase): Word; static; class function FormatDateTime(const Format: string; ADateTime: TIdDateTimeBase): string; static; class function Format(const Format: string; const Args: array of const): string; static; class function SameText(const S1, S2 : String) : Boolean; static; class function CompareStr(const S1, S2: string): Integer; static; class function CompareDate(const D1, D2 : TIdDateTimeBase) : Integer; static; class procedure FreeAndNil(var Obj); static; class function IntToStr(Value: Integer): string; overload; static; class function IntToHex(Value: Integer; Digits: Integer): string; overload; static; class function IntToHex(Value: Int64; Digits: Integer): string; overload; static; class function DateTimeToInternetStr(const Value: TIdDateTimeBase; const AIsGMT : Boolean = False) : String; class function DateTimeGMTToHttpStr(const GMTValue: TIdDateTimeBase) : String; class function DateTimeToGmtOffSetStr(ADateTime: TIdDateTimeBase; SubGMT: Boolean): string; class function OffsetFromUTC: TIdDateTimeBase; class function IntToStr(Value: Int64): string; overload; static; class function UpperCase(const S: string): string; static; class function LowerCase(const S: string): string; static; class function IncludeTrailingPathDelimiter(const S: string): string; static; class function ExcludeTrailingPathDelimiter(const S: string): string; static; class function StrToInt(const S: string): Integer; overload; static; class function StrToInt(const S: string; Default: Integer): Integer; overload; static; class function Trim(const S: string): string; static; class function TrimLeft(const S: string): string; static; class function TrimRight(const S: string): string; static; class procedure Abort; static; class function FileAge(const FileName: string): TIdDateTimeBase; static; class function FileExists(const FileName: string): Boolean; static; class function DirectoryExists(const Directory: string): Boolean; static; class function DeleteFile(const FileName: string): Boolean; static; class function ExtractFileName(const FileName: string): string; static; class function ExtractFilePath(const AFileName: string) : string; static; class function ExtractFileExt(const FileName: string): string; static; class function ChangeFileExt(const FileName, Extension: string): string; static; class function LastDelimiter(const Delimiters, S: string): Integer; static; class function StrToInt64Def(const S: string; const Default: Int64): Int64; static; class function StringReplace(const S, OldPattern, NewPattern: string): string; overload; static; class function StringReplace(const S : String; const OldPattern, NewPattern: array of string): string; overload; static; class function ConvertFormat(const AFormat : String; const ADate : TIdDateTimeBase; DTInfo : System.Globalization.DateTimeFormatInfo): String; static; class function ReplaceOnlyFirst(const S, OldPattern, NewPattern: string): string; overload; static; class function AnsiCompareStr(const S1, S2: WideString): Integer; overload; deprecated; class function AnsiUpperCase(const S: WideString): WideString; overload; deprecated; class function IsLeapYear(Year: Word): Boolean; class function AnsiLowerCase(const S: WideString): WideString; overload; deprecated; class function AnsiPos(const Substr, S: WideString): Integer; overload; deprecated; end; const PATH_DELIN = '\'; implementation uses System.IO; { SysUtils } class procedure TIdSysNet.Abort; begin raise EAbort.Create; end; class function TIdSysNet.IsLeapYear(Year: Word): Boolean; begin Result := DateTime.IsLeapYear(Year) end; class function TIdSysNet.CompareStr(const S1, S2: string): Integer; begin Result := System.&String.Compare(S1,S2,False); end; class function TIdSysNet.DateTimeToStr(const ADateTime: TIdDateTimeBase): string; begin Result := ADateTime.ToString; end; class function TIdSysNet.FileExists(const FileName: string): Boolean; begin Result := System.IO.File.Exists(FileName); end; class function TIdSysNet.Format(const Format: string; const Args: array of const): string; begin FmtStr(Result, Format, Args); end; class procedure TIdSysNet.FreeAndNil(var Obj); begin TObject(Obj).Free; Obj := nil; end; class function TIdSysNet.IncludeTrailingPathDelimiter( const S: string): string; begin Result := S; if (S = '') or (S[Length(S)] <> PATH_DELIN) then begin Result := S + PATH_DELIN; end; end; class function TIdSysNet.ExcludeTrailingPathDelimiter(const S: string): string; begin Result := S; if (S <> '') and (S[Length(S)] = PATH_DELIN) then begin Result := Copy(S, 1, Length(S) - 1); end; end; class function TIdSysNet.IntToHex(Value: Int64; Digits: Integer): string; begin Result := System.&String.Format('{0:x' + Digits.ToString + '}', TObject(Value) ); //Borland's standard string is one based, not zero based Result := Copy(Result,Length(Result)-Digits+1,Digits); end; class function TIdSysNet.IntToHex(Value, Digits: Integer): string; begin Result := System.&String.Format('{0:x' + Digits.ToString + '}', TObject(Value)); //Borland's standard string is one based, not zero based Result := Copy(Result,Length(Result)-Digits+1,Digits); end; class function TIdSysNet.IntToStr(Value: Int64): string; begin Result := System.Convert.ToString(Value); end; class function TIdSysNet.IntToStr(Value: Integer): string; begin Result := System.Convert.ToString(Value); end; class function TIdSysNet.LastDelimiter(const Delimiters, S: string): Integer; begin Result := 0; if Assigned(S) and Assigned(Delimiters) then begin Result := s.LastIndexOfAny(Delimiters.ToCharArray) + 1; end; end; class function TIdSysNet.Now: TIdDateTimeBase; begin Result := System.DateTime.Now.ToOADate; end; class function TIdSysNet.StringReplace(const S, OldPattern, NewPattern: string): string; begin if Assigned(S) then begin Result := S.Replace(OldPattern, NewPattern) end else begin Result := S; end; end; class function TIdSysNet.ReplaceOnlyFirst(const S, OldPattern, NewPattern: string): string; var LS : StringBuilder; i : Integer; i2 : Integer; begin Result := S; if Assigned(S) then begin i := S.IndexOf(OldPattern); if i >= 0 then begin i2 := OldPattern.Length; LS := StringBuilder.Create; LS.Append(S,0,i); LS.Append(NewPattern); LS.Append(S,i+i2,S.Length-(i2+i)); Result := LS.ToString; end; end; end; class function TIdSysNet.StringReplace(const S: String; const OldPattern, NewPattern: array of string): string; var LS : StringBuilder; i : Integer; begin LS := StringBuilder.Create(S); for i := Low(OldPattern) to High(OldPattern) do begin LS.Replace(OldPattern[i],NewPattern[i]); end; Result := LS.ToString; end; class function TIdSysNet.StrToInt64Def(const S: string; const Default: Int64): Int64; var LErr : Integer; begin Val(Trim(S),Result,LErr); if LErr<>0 then begin Result := Default; end; end; class function TIdSysNet.StrToInt(const S: string): Integer; var LErr: Integer; begin Val(Trim(S),Result,LErr); if LErr <> 0 then begin raise EConvertError.Create(''); end; end; class function TIdSysNet.StrToInt(const S: string; Default: Integer): Integer; var LErr : Integer; begin Val(Trim(S),Result,LErr); if LErr<>0 then begin Result := Default; end; end; class function TIdSysNet.Trim(const S: string): string; begin Result := S; if Assigned(S) then begin Result := S.Trim; end; end; class function TIdSysNet.UpperCase(const S: string): string; begin Result := S; if Assigned(S) then begin Result := S.ToUpper end; end; class function TIdSysNet.LowerCase(const S: string): string; begin Result := S; if Assigned(S) then begin Result := S.ToLower; end; end; class procedure TIdSysNet.DecodeDate(const ADateTime: TIdDateTimeBase; var Year, Month, Day: Word); var TempDate: DateTime; begin TempDate := DateTime.FromOADate(ADateTime); Year := TempDate.Year; Month := TempDate.Month; Day := TempDate.Day; end; class procedure TIdSysNet.DecodeTime(const ADateTime: TIdDateTimeBase; var Hour, Min, Sec, MSec: Word); var TempDate: DateTime; begin TempDate := DateTime.FromOADate(ADateTime); Hour := TempDate.Hour; Min := TempDate.Minute; Sec := TempDate.Second; MSec := TempDate.Millisecond; end; class function TIdSysNet.TrimLeft(const S: string): string; var Len: Integer; LDelTo: Integer; begin Result := S; if Assigned(S) then begin Len := S.Length; LDelTo := 0; while (LDelTo < Len) and (S.Chars[LDelTo] <= ' ') do begin Inc(LDelTo); end; if LDelTo > 0 then begin Result := S.Substring(LDelTo); end; end; end; class function TIdSysNet.TrimRight(const S: string): string; var LastIndex: Integer; LDelPos: Integer; begin Result := S; if Assigned(S) then begin LastIndex := S.Length - 1; LDelPos := LastIndex; while (LDelPos >= 0) and (S.Chars[LDelPos] <= ' ') do begin Dec(LDelPos); end; if LDelPos < LastIndex then begin Result := S.Substring(0, LDelPos + 1); end; end; end; class function TIdSysNet.DirectoryExists(const Directory: string): Boolean; begin Result := System.IO.Directory.Exists(Directory); end; class function TIdSysNet.ExtractFileExt(const FileName: string): string; begin Result := System.IO.Path.GetExtension(FileName); end; class function TIdSysNet.EncodeTime(Hour, Min, Sec, MSec: Word): TIdDateTimeBase; begin Result := System.DateTime.Create(1, 1, 1, Hour, Min, Sec, MSec).ToOADate; end; class function TIdSysNet.EncodeDate(Year, Month, Day: Word): TIdDateTimeBase; begin Result := System.DateTime.Create(Year, Month, Day, 0, 0, 0, 0).ToOADate; end; class function TIdSysNet.AlignLeftCol(const AStr: String; const AWidth: Integer): String; begin Result := Copy(Result,Length(AStr)-AWidth+1,AWidth); end; class function TIdSysNet.FloatToIntStr(const AFloat: Extended): String; begin Result := Int(AFloat).ToString; end; class function TIdSysNet.TwoDigitYearCenturyWindow: Word; begin //in SysUtils, this value is adjustable but I haven't figured out how to do that //here. Borland's is 50 but for our purposes, 1970 should work since it is the Unix epech //and FTP was started around 1973 anyway. Besides, if I mess up, chances are //that I will not be around to fix it :-). Result := 70; end; class function TIdSysNet.ExtractFileName(const FileName: string): string; begin Result := System.IO.Path.GetFileName(FileName); end; class function TIdSysNet.DeleteFile(const FileName: string): Boolean; begin Result := False; if System.IO.&File.Exists(FileName) then begin System.IO.&File.Delete(FileName); Result := not System.IO.&File.Exists(FileName); end; end; class function TIdSysNet.FileAge(const FileName: string): TIdDateTimeBase; begin if System.IO.&File.Exists(FileName) then begin Result := System.IO.&File.GetLastWriteTime(FileName).ToOADate; end else begin Result := 0; end; end; class function TIdSysNet.CompareDate(const D1, D2: TIdDateTimeBase): Integer; begin Result := D1.CompareTo(&Object(D2)); end; class function TIdSysNet.StrToDateTime(const S: String): TIdDateTimeBase; begin Result := DateTime.Parse(S).ToOADate; end; class function TIdSysNet.StrToInt64(const S: string): Int64; var LErr : Integer; begin Val(Trim(S),Result,LErr); if LErr <> 0 then begin raise EConvertError.Create(''); end; end; class function TIdSysNet.StrToInt64(const S: string; const Default: Int64): Int64; var LErr : Integer; begin Val(Trim(S),Result,LErr); if LErr <> 0 then begin Result := Default; end; end; class function TIdSysNet.SameText(const S1, S2: String): Boolean; begin Result := System.&String.Compare(S1,S2,True)=0; end; class function TIdSysNet.AddStringToFormat(SB: StringBuilder; I: Integer; S: String): Integer; begin SB.Append(S); Result := I + 1; end; class function TIdSysNet.ConvertFormat(const AFormat : String; const ADate : TIdDateTimeBase; DTInfo : System.Globalization.DateTimeFormatInfo): String; var LSB : StringBuilder; I, LCount, LHPos, LH2Pos, LLen: Integer; c : Char; LAMPM : String; begin Result := ''; LSB := StringBuilder.Create; Llen := AFormat.Length; if LLen=0 then begin Exit; end; I := 1; LHPos := -1; LH2Pos := -1; repeat if I > LLen then begin Break; end; C := AFormat[I]; case C of 't', 'T' : //t - short time, tt - long time begin if (i < LLen) and ((AFormat[i+1]='t') or (AFormat.Chars[i]='T')) then begin LSB.Append(DTInfo.LongTimePattern ); i := i + 2; end else begin LSB.Append(DTInfo.ShortTimePattern ); i := i + 1; end; end; 'c', 'C' : // begin LSB.Append( DTInfo.ShortDatePattern ); i := AddStringToFormat(LSB,i,' '); LSB.Append( DTInfo.LongTimePattern ); end; 'd' : //must do some mapping begin LCount := 0; while (i + LCount<=LLen) and ((AFormat[i+LCount] ='D') or (AFormat[i+LCount] ='d')) do begin Inc(LCount); end; case LCount of 5 : LSB.Append(DTInfo.ShortDatePattern); 6 : LSB.Append(DTInfo.LongDatePattern); else LSB.Append(StringOfChar(c,LCount)); end; Inc(i,LCount); end; 'h' : //h - //assume 24 hour format //remember positions in case am/pm pattern appears later begin LHPos := LSB.Length; i := AddStringToFormat(LSB,i,'H'); if (i <= LLen) then begin if (AFormat[i] ='H') or (AFormat[i] = 'h') then begin LH2Pos := LSB.Length; i := AddStringToFormat(LSB,i,'H'); end; end; end; 'a' : //check for AM/PM formats begin if LAMPM ='' then begin //We want to honor both lower and uppercase just like Borland's //FormatDate should if DateTime.FromOADate(ADate).Hour <12 then begin LAMPM := DTInfo.AMDesignator; end else begin LAMPM := DTInfo.PMDesignator; end; end; if System.&String.Compare(AFormat,i-1,'am/pm',0,5,True)=0 then begin LSB.Append('"'); if AFormat.Chars[i-1]='a' then begin LSB.Append( System.Char.ToLower( LAMPM.Chars[0]) ); end else begin LSB.Append( LSB.Append( System.Char.ToUpper( LAMPM.Chars[0]) )); end; if AFormat.Chars[i]='m' then begin LSB.Append( System.Char.ToLower( LAMPM.Chars[1]) ); end else begin LSB.Append( LSB.Append( System.Char.ToUpper( LAMPM.Chars[1]) )); end; LSB.Append('"'); i := i + 5; end else begin if System.&String.Compare(AFormat,i-1,'a/p',0,3,True)=0 then begin LSB.Append('"'); if AFormat.Chars[i-1]='a' then begin LSB.Append( System.Char.ToLower( LAMPM.Chars[0]) ); end else begin LSB.Append( LSB.Append( System.Char.ToUpper( LAMPM.Chars[0]) )); end; LSB.Append('"'); i := i + 3; end else begin LSB.Append('"'); if AFormat.Chars[i-1]='a' then begin LSB.Append( System.Char.ToLower( LAMPM.Chars[0]) ); end else begin LSB.Append( LSB.Append( System.Char.ToUpper( LAMPM.Chars[0]) )); end; if AFormat.Chars[i]='m' then begin LSB.Append( System.Char.ToLower( LAMPM.Chars[1]) ); end else begin LSB.Append( LSB.Append( System.Char.ToUpper( LAMPM.Chars[1]) )); end; LSB.Append('"'); i := i + 5; end; end; if LHPos <> -1 then begin LSB.Chars[LHPos] := 'h'; if LH2Pos<>-1 then begin LSB.Chars[LH2Pos] := 'h'; end; LHPos := -1; LH2Pos := -1; end; end; 'z', 'Z' : begin if (i+2 < LLen) and (System.&String.Compare(AFormat,i-1,'zzz',0,3,True)=0) then begin LSB.Append(DateTime.FromOADate(ADate).Millisecond.ToString ); i := i + 3; end else begin LSB.Append('fff'); i := i + 1; end; end; '/' : //double his begin i := AddStringToFormat(LSB,i,'\\'); end; '''','"' : //litteral begin i := AddStringToFormat(LSB,i,C); LCount := 0; while (i + LCount < LLen) and (AFormat.Chars[I+LCount]<>C) do begin Inc(LCount); end; LSB.Append(AFormat,i-1,LCount); inc(i,LCount); if i<=LLen then begin AddStringToFormat(LSB,i,c); end; end; 'n','N' : //minutes - lowercase m begin i := AddStringToFormat(LSB,i,'m'); end; 'm','M' : //monthes - must be uppercase begin i := AddStringToFormat(LSB,i,'M'); end; 'y','Y' : //year - must be lowercase begin i := AddStringToFormat(LSB,i,'y'); end; 's','S' : //seconds -must be lowercase begin i := AddStringToFormat(LSB,i,'s'); end else begin i := AddStringToFormat(LSB,i,C); end; end; until False; Result := LSB.ToString; end; class function TIdSysNet.FormatDateTime(const Format: string; ADateTime: TIdDateTimeBase): string; var LF : System.Globalization.DateTimeFormatInfo; begin //unlike Borland's FormatDate, we only want the ENglish language LF := System.Globalization.DateTimeFormatInfo.InvariantInfo; Result := DateTime.FromOADate(ADateTime).ToString(ConvertFormat(Format,ADateTime,LF),LF); end; class function TIdSysNet.DayOfWeek(const ADateTime: TIdDateTimeBase): Word; begin Result := Integer(DateTime.FromOADate(ADateTime).DayOfWeek) + 1; end; class function TIdSysNet.AddMSecToTime(const ADateTime: TIdDateTimeBase; const AMSec: Integer): TIdDateTimeBase; var LD : DateTime; begin LD := DateTime.FromOADate(ADateTime); LD := LD.AddMilliseconds(AMSec); Result := LD.ToOADate; end; class function TIdSysNet.LastChars(const AStr: String; const ALen : Integer): String; begin if Assigned(AStr) and (AStr.Length > ALen) then begin Result := Copy(AStr,Length(AStr)-ALen+1,ALen); end else begin Result := AStr; end; end; { TIdStringBuilderHelper } function TIdStringBuilderHelper.IndexOf(const value: String): Integer; begin Result := IndexOf(value,0,Self.Length); end; function TIdStringBuilderHelper.IndexOf(const value: String; const startIndex: Integer): Integer; begin Result := IndexOf(value,startIndex,Self.Length); end; function TIdStringBuilderHelper.IndexOf(const value: String; const startIndex, count: Integer): Integer; var i,j,l : Integer; LFoundSubStr : Boolean; begin Result := -1; if not Assigned(value) or (value.Length + startIndex > (Self.Length + startIndex)) or (value.Length > startIndex + count) then begin Exit; end; l := (startIndex + count); if l > (Self.Length - 1) then begin l := Self.Length - 1; end; for i := startIndex to l-value.Length+1 do begin if i < 0 then begin break; end; if Self.Chars[i] = value.Chars[0] then begin //we don't want to loop through the substring if it has only //one char because there's no sense to evaluate the same thing //twice if value.Length > 1 then begin Result := i; Break; end else begin LFoundSubStr := True; for j := 1 to value.Length-1 do begin if Self.Chars[i + j] <> value.Chars[j] then begin LFoundSubStr := False; break; end; end; if LFoundSubStr then begin Result := i; Exit; end; end; end; end; end; function TIdStringBuilderHelper.LastIndexOf(const value: String): Integer; begin Result := LastIndexOf(value,Self.Length); end; function TIdStringBuilderHelper.LastIndexOf(const value: String; const startIndex: Integer): Integer; begin Result := LastIndexOf(value,startIndex,Self.Length); end; function TIdStringBuilderHelper.LastIndexOf(const value: String; const startIndex, count: Integer): Integer; var i,j : Integer; LFoundSubStr : Boolean; LEndIndex, LStartIndex : Integer; begin Result := -1; LEndIndex := startindex - count; if LEndIndex < 0 then begin LEndIndex := 0; end; if (LEndIndex > Self.Length) or not Assigned(value) then begin Exit; end; LStartIndex := startIndex; if LStartIndex >= Self.Length then begin LStartIndex := Self.Length-1; end; for i := LStartIndex downto LEndIndex+1+value.Length do begin if Self.Chars[i] = value.Chars[0] then begin //we don't want to loop through the substring if it has only //one char because there's no sense to evaluate the same thing //twice if value.Length < 2 then begin Result := i; Break; end else begin LFoundSubStr := True; for j := value.Length-1 downto 1 do begin if Self.Chars[i + j] <> value.Chars[j] then begin LFoundSubStr := False; break; end; end; if LFoundSubStr then begin Result := i; Exit; end; end; end; end; end; function TIdStringBuilderHelper.ReplaceOnlyFirst(const oldValue, newValue: String; const startIndex, count: Integer): StringBuilder; var i : Integer; begin Result := Self; i := Self.IndexOf(OldValue,startIndex,count); if i < 0 then begin Exit; end; if Assigned(oldValue) then begin Self.Remove(i,oldValue.Length); end; Self.Insert(i,newValue); end; function TIdStringBuilderHelper.ReplaceOnlyFirst(const oldValue, newValue: String): StringBuilder; begin Result := ReplaceOnlyFirst(oldValue,newValue,0,Self.Length); end; function TIdStringBuilderHelper.ReplaceOnlyLast(const oldValue, newValue: String; const startIndex, count: Integer): StringBuilder; var i : Integer; begin Result := Self; i := Self.LastIndexOf(OldValue,startIndex,count); if i < 0 then begin Exit; end; if Assigned(oldValue) then begin Self.Remove(i,oldValue.Length); end; Self.Insert(i,newValue); end; function TIdStringBuilderHelper.ReplaceOnlyLast(const oldValue, newValue: String): StringBuilder; begin Result := Self.ReplaceOnlyLast(oldValue,newValue,Self.Length,Self.Length); end; class function TIdSysNet.FormatBuf(var Buffer: System.Text.StringBuilder; const Format: string; FmtLen: Cardinal; const Args: array of const): Cardinal; var LFormat: NumberFormatInfo; begin //for most of our uses, we want the immutable settings instead of the user's //local settings. LFormat := NumberFormatInfo.InvariantInfo; Result := FormatBuf(Buffer, Format, FmtLen, Args, LFormat); end; class function TIdSysNet.FormatBuf(var Buffer: System.Text.StringBuilder; const Format: string; FmtLen: Cardinal; const Args: array of const; Provider: IFormatProvider): Cardinal; function ReadNumber(const AFmt : String; const AArgs: array of const; AProvider: IFormatProvider; var VIdx : Integer; var VArgIdx : Integer; AScratch : System.Text.StringBuilder): Integer; begin Result := 0; AScratch.Length := 0; if AFmt.Chars[VIdx] = '-' then begin AScratch.Append(AFmt.Chars[VIdx]); Inc(VIdx); if VIdx >= AFmt.Length then begin Exit; end; end; if AFmt.Chars[VIdx] = '*' then begin //The value is embedded in the Args paramer; AScratch.Append(AArgs[VArgIdx]); Inc(VArgIdx); Inc(VIdx); end else begin //parse the value repeat if VIdx >= AFmt.Length then begin Break; end; if System.Char.IsDigit(AFmt.Chars[VIdx]) then begin AScratch.Append( AFmt.Chars[VIdx]); end else begin break; end; inc(VIdx); until False; end; if AScratch.Length>0 then begin Result := System.Convert.ToInt32 ( AScratch.ToString, AProvider ); end; end; var LStrLen : Integer; LIdx, LArgIdx : Integer; LPerLen : Integer; LWidth : Integer; LFmStr : System.Text.StringBuilder; LScratch : System.Text.StringBuilder; //scratch pad for int. usage begin LWidth := 0; LIdx := 0; LArgIdx := 0; LStrLen := Format.Length; LFmStr := System.Text.StringBuilder.Create; LScratch := System.Text.StringBuilder.Create; repeat if LIdx >= LStrLen then begin Break; end; if Format.Chars[LIdx]='%' then begin inc(LIdx); if LIdx >= LStrLen then begin break; end; //interpret as one litteral % in a string if Format.Chars[LIdx] ='%' then begin Buffer.Append(Format.Chars[LIdx]); Continue; end; LFmStr.Length := 0; LFmStr.Append('{0'); //width specifier might be first LWidth := ReadNumber(Format,Args,Provider,LIdx,LArgIdx,LScratch); if Format.Chars[LIdx] = ':' then begin inc(LIdx); if LIdx >= LStrLen then begin break; end; //That was not the width but the Index if LWidth >-1 then begin LArgIdx := LWidth; LWidth := -1; end else begin LArgIdx := 0; Inc(LIdx); if LIdx >= LStrLen then begin break; end; end; LWidth := ReadNumber(Format,Args,Provider,LIdx,LArgIdx,LScratch); end; //Percission value if Format.Chars[LIdx] = '.' then begin inc(LIdx); if LIdx >= LStrLen then begin break; end; LPerLen := ReadNumber(Format,Args,Provider,LIdx,LArgIdx,LScratch); end else begin LPerLen := 0; end; if LWidth <> 0 then begin LFmStr.Append(','+LWidth.ToString); end; LFmStr.Append(Char(':')); case Format.Chars[LIdx] of 'd', 'D', 'u', 'U': LFmStr.Append(Char('d')); 'e', 'E', 'f', 'F', 'g', 'G', 'n', 'N', 'x', 'X': LFmStr.Append(Char(Format.Chars[LIdx])); 'm', 'M': LFmStr.Append(Char('c')); 'p', 'P': LFmStr.Append(Char('x')); 's', 'S': ; // no format spec needed for strings else Continue; end; if LPerLen>0 then begin LFmStr.Append(LPerLen.ToString); end; LFmStr.Append(Char('}')); //we'll AppendFormat to our scratchpad instead of directly into //buffer because the Width specifier needs to truncate with a string. LScratch.Length := 0; LScratch.AppendFormat(Provider, LFmStr.ToString, [Args[LArgIdx]]); if ((Format.Chars[LIdx] = 's') or (Format.Chars[LIdx] = 'S')) and (LPerLen>0) then begin LScratch.Length := LPerLen; end; Buffer.Append(LScratch); Inc(LArgIdx); end else begin Buffer.Append(Format.Chars[LIdx]); end; Inc(LIdx); until False; Result := Buffer.Length; end; class procedure TIdSysNet.FmtStr(var Result: string; const Format: string; const Args: array of const); var Buffer: System.Text.StringBuilder; begin Buffer := System.Text.StringBuilder.Create(Length(Format) * 2); FormatBuf(Buffer, Format, Length(Format), Args); Result := Buffer.ToString; end; class function TIdSysNet.AnsiCompareText(const S1, S2: WideString): Integer; begin Result := System.String.Compare(S1, S2, True); end; class function TIdSysNet.ChangeFileExt(const FileName, Extension: string): string; begin if Length(Extension) <> 0 then begin Result := System.IO.Path.ChangeExtension(FileName, Extension) end else begin Result := System.IO.Path.ChangeExtension(FileName, System.String(nil)); end; end; class function TIdSysNet.AnsiCompareStr(const S1, S2: string): Integer; begin if not Assigned(S1) and not Assigned(S2) then begin Result := 0; end else if not Assigned(S1) then begin Result := S1.CompareTo(S2); end else Result := -1; end; class function TIdSysNet.AnsiLowerCase(const S: WideString): WideString; begin Result := S; if Assigned(S) then begin Result := S.ToLower; end; end; class function TIdSysNet.AnsiUpperCase(const S: WideString): WideString; begin Result := S; if Assigned(S) then begin Result := S.ToUpper; end; end; class function TIdSysNet.AnsiPos(const Substr, S: WideString): Integer; begin Result := 0; if Assigned(S) then begin Result := S.IndexOf(Substr) + 1; end; end; class function TIdSysNet.OffsetFromUTC: TIdDateTimeBase; begin Result := System.Timezone.CurrentTimezone.GetUTCOffset(DateTime.FromOADate(Now)).TotalDays; end; const wdays: array[1..7] of string = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' {Do not Localize} , 'Sat'); {do not localize} monthnames: array[1..12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May' {Do not Localize} , 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); {do not localize} class function TIdSysNet.DateTimeGMTToHttpStr(const GMTValue: TIdDateTimeBase) : String; // should adhere to RFC 2616 var wDay, wMonth, wYear: Word; begin DecodeDate(GMTValue, wYear, wMonth, wDay); Result := Format('%s, %.2d %s %.4d %s %s', {do not localize} [wdays[DayOfWeek(GMTValue)], wDay, monthnames[wMonth], wYear, DateTime.FromOADate(GMTValue).ToString('HH:mm:ss'), 'GMT']); {do not localize} end; {This should never be localized} class function TIdSysNet.DateTimeToInternetStr(const Value: TIdDateTimeBase; const AIsGMT : Boolean = False) : String; var wDay, wMonth, wYear: Word; begin DecodeDate(Value, wYear, wMonth, wDay); Result := Format('%s, %d %s %d %s %s', {do not localize} [ wdays[DayOfWeek(Value)], wDay, monthnames[wMonth], wYear, DateTime.FromOADate(Value).ToString('HH:mm:ss'), {do not localize} DateTimeToGmtOffSetStr(OffsetFromUTC, AIsGMT)]); end; class function TIdSysNet.DateTimeToGmtOffSetStr(ADateTime: TIdDateTimeBase; SubGMT: Boolean): string; var AHour, AMin, ASec, AMSec: Word; begin if (ADateTime = 0.0) and SubGMT then begin Result := 'GMT'; {do not localize} Exit; end; DecodeTime(ADateTime, AHour, AMin, ASec, AMSec); Result := Format(' {0}{1}', [AHour.ToString('G2'), AMin.ToString('G2')]); {do not localize} if ADateTime < 0.0 then begin Result[1] := '-'; {do not localize} end else begin Result[1] := '+'; {do not localize} end; end; class function TIdSysNet.ExtractFilePath(const AFileName: string): string; begin Result := Path.GetDirectoryName(AFileName); end; end.
unit VoyagerTrains; interface uses ActorTypes, Automaton, StateEngine; procedure RegisterMetaData; function MetaPoolLocator( MetaPoolId : TMetaPoolId ) : TMetaStatePool; function ClientAutomatableFactory( Kind : TActorKind; const Context ) : IClientAutomatable; implementation uses SysUtils, ClassStorage, Train, TrainConst, ClientTrain, Protocol, TransportHandler; var CarBehavior : TMetaStatePool = nil; procedure RegisterMetaData; begin TMetaCar.Create( carA30, 'A-30 Engine', '', 50000, 30000, 100, vcarA30, TClientCar ).Register; TMetaCar.Create( carRefrigeratedA, 'Refrigerated Wagon', '', 10000, 30000, 100, vcarRefrigeratedA, TClientCar ).Register; // Define automatons CarBehavior := TMetaStatePool.Create( pstCarBehaviorId ); CarBehavior.AddMetaState( TMetaState.Create( carstRunning, TAutomatedState, [0], msoDistributable )); CarBehavior.AddMetaState( TMetaState.Create( carstLoading, TAutomatedState, [0], msoDistributable )); TMetaClientAutomaton.Create( carA30, poolIdTrains, TClientAutomaton, CarBehavior, ClientAutomatableFactory ).Register; TMetaClientAutomaton.Create( carRefrigeratedA, poolIdTrains, TClientAutomaton, CarBehavior, ClientAutomatableFactory ).Register; end; function MetaPoolLocator( MetaPoolId : TMetaPoolId ) : TMetaStatePool; begin result := CarBehavior; end; function ClientAutomatableFactory( Kind : TActorKind; const Context ) : IClientAutomatable; var MetaCar : TMetaCar; Car : TClientCar; TransportHandler : TTransportHandler absolute Context; begin MetaCar := TMetaCar(TheClassStorage.ClassById[tidClassFamily_TrainCars, IntToStr(Kind)]); if MetaCar <> nil then begin Car := TClientCar(MetaCar.Instantiate); Car.OnClientTrainModified := TransportHandler.ClientCarModified; result := Car; end else result := nil end; end.
unit TestManager; interface uses // VCL Windows, Classes; type TChangeType = (ctUpdate, ctGetPassword); TChangeEvent = procedure(Sender: TObject; ChangeType: TChangeType) of object; { TTestManager } TTestManager = class private FTickCount: DWORD; FPassword: Integer; FOnChange: TChangeEvent; function GetPassword: Integer; procedure DoChange(AChangeType: TChangeType); public procedure StopTest; procedure StartTest; property TickCount: DWORD read FTickCount; property Password: Integer read GetPassword write FPassword; property OnChange: TChangeEvent read FOnChange write FOnChange; end; var DriverManager: TTestManager; implementation { TTestManager } procedure TTestManager.DoChange(AChangeType: TChangeType); begin if Assigned(FOnChange) then FOnChange(Self, AChangeType); end; function TTestManager.GetPassword: Integer; begin DoChange(ctGetPassword); Result := FPassword; end; procedure TTestManager.StartTest; begin FTickCount := GetTickCount; end; procedure TTestManager.StopTest; begin DoChange(ctUpdate); end; initialization DriverManager := TTestManager.Create; finalization DriverManager.Free; end.
{@html(<hr>) @abstract(Types, constants, routines, etc. used troughout the Telemetry library.) @author(František Milt <fmilt@seznam.cz>) @created(2013-10-04) @lastmod(2014-05-05) @bold(@NoAutoLink(TelemetryCommon)) ©František Milt, all rights reserved. This file is intended to provide types, constants, routines, etc. used throughout the Telemetry library (that is, in more than one unit). Last change: 2014-05-05 Change List:@unorderedList( @item(2013-10-04 - First stable version.) @item(2014-04-06 - TGameSupportInfo.GameID and scs_value_localized_t.StringData fields type changed to @code(TelemetryString).) @item(2014-04-18 - cConfigFieldsSeparator constant moved to TelemetryIDs unit.) @item(2014-04-20 - Added following types:@unorderedList( @itemSpacing(Compact) @item(scs_named_value_localized_t) @item(p_scs_named_value_localized_t) @item(scs_telemetry_configuration_localized_t) @item(p_scs_telemetry_configuration_localized_t))) @item(2014-04-20 - Functions scs_value_localized and scs_value moved to TelemetryStreaming unit.) @item(2014-05-05 - TMulticastEvent placeholder added.)) @html(<hr>)} unit TelemetryCommon; interface {$INCLUDE '.\Telemetry_defs.inc'} uses {$IFDEF UseCondensedHeader} SCS_Telemetry_Condensed; {$ELSE} scssdk, scssdk_value; {$ENDIF} type {$IFDEF MulticastEvents} {$IFDEF Documentation} // @abstract(Placeholder intended to complete the classes hierarchy tree in // documentation.) // Actual class is defined in unit MulticastEvent and is not included in // documentation of telemetry library. Refer to mentioned unit located in // folder @italic(Source\Libs) for details. TMulticastEvent = class(TObject); {$ENDIF} {$ENDIF} { @abstract(Structure used internally in tables that keeps informations about supported games and their versions.) @member GameID Internal game identificator (not a game name). @member(GameVersion Internal game version (API-specific value - not equal to actual game version).) } TGameSupportInfo = record GameID: TelemetryString; GameVersion: scs_u32_t; end; // Pointer to TGameSupportInfo structure. PGameSupportInfo = ^TGameSupportInfo; { @abstract(Structure used to store content of @code(scs_value_t) variable.) @code(scs_value_t) is using pointers for some values, so it cannot be stored directly, as only reference and no actual data would be stored.@br Use this structure along with call to scs_value_localized function to store content of a variable of type @code(scs_value_t). @member ValueType Type of stored value. @member BinaryData Stored binary data (eg. integers, floats). @member(StringData Stored string data (used only when string data are stored, empty otherwise).) } scs_value_localized_t = record ValueType: scs_value_type_t; BinaryData: scs_value_t; StringData: TelemetryString; end; // Pointer to scs_value_localized_t structure. p_scs_value_localized_t = ^scs_value_localized_t; { @abstract(Structure used to store content of @code(scs_named_value_t) variable.) @code(scs_named_value_t) is using pointers for some values, so it cannot be stored directly, as only reference and no actual data would be stored.@br Use this structure along with call to scs_named_value_localized function to store content of a variable of type @code(scs_named_value_t). @member Name @NoAutoLink(Name) of the @NoAutoLink(value). @member Index @NoAutoLink(Index) of the @NoAutoLink(value). @member Value Named @NoAutoLink(value) itself. } scs_named_value_localized_t = record Name: TelemetryString; Index: scs_u32_t; Value: scs_value_localized_t; end; // Pointer to scs_named_value_localized_t structure. p_scs_named_value_localized_t = ^scs_named_value_localized_t; { @abstract(Structure used to store content of @code(scs_telemetry_configuration_t) variable.) @code(scs_telemetry_configuration_t) is using pointers for some values, so it cannot be stored directly, as only reference and no actual data would be stored.@br Use this structure along with call to scs_telemetry_configuration_localized function to store content of a variable of type @code(scs_telemetry_configuration_t). @member ID Configuration identifier. @member(Attributes Array of named values (@NoAutoLink(attributes)) this configuration contains.) } scs_telemetry_configuration_localized_t = record ID: TelemetryString; Attributes: Array of scs_named_value_localized_t end; // Pointer to scs_telemetry_configuration_localized_t structure. p_scs_telemetry_configuration_localized_t = ^scs_telemetry_configuration_localized_t; const // Constant containing an empty @code(scs_value_t) structure, or, more // precisely, structure with invalid value type. cEmptySCSValue: scs_value_t = (_type: SCS_VALUE_TYPE_INVALID); // Constant containing an empty scs_value_localized_t structure (invalid value // type). cEmptySCSValueLocalized: scs_value_localized_t = (ValueType: SCS_VALUE_TYPE_INVALID); implementation end.
Program Ejercicio8; Var Arch: text; A, Sum, Cont : integer; Begin Assign( Arch, 'Lote de prueba.TXT' ); {enlaza la variable Arch con el archivo 'Lote de prueba' necesario para la lectura} Reset ( Arch ); {Prepara el archivo para la lectura} Sum:=0; Cont := 0; While NOT eof ( Arch ) do {Hasta que llega al fin del archivo, lee los valores, los almacena en A y luego los suma y cuenta la cantidad de numeros del archivo} Begin Readln( Arch, A ); {se leen los valores del archivo y se almacenan en 'A'} If A > 0 then begin Sum := Sum + A ; Cont := Cont + 1; End; End; Close ( Arch ); {cierra el archivo} If Cont <> 0 then Writeln( (Sum / Cont):8:2 ) Else Writeln ('No hay numeros positivos'); readln(); End.
unit TxtRes; interface type TTxtResType = (txtPlain, txtHTML); // TTxtRes describes a textual resource. Location is the URL (relative) // to the resource. TxtType specifies the type of the text. TTxtRes = class public constructor Create( aLocation : string; aTxtType : TTxtResType ); private fLocation : string; fTxtType : TTxtResType; public property Location : string read fLocation; property TxtType : TTxtResType read fTxtType; end; implementation // TTxtRes constructor TTxtRes.Create( aLocation : string; aTxtType : TTxtResType ); begin inherited Create; fLocation := aLocation; fTextType := aTextType; end; end.
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Joel Ivey Description: Unit tests for RPCBroker functionality - requires dUnit to run unit tests. Current Release: Version 1.1 Patch 40 (January 7, 2005)) *************************************************************** } unit uUnitTestBroker; interface uses TestFramework, Sgnoncnf, Classes, Graphics, SysUtils, Forms; type TTestType = class(TTestCase) private // any private fields needed for processing protected // procedure SetUp; override; // procedure TearDown; override; published // procedure TestName1; // procedure TestName2; end; TTestSgnoncnf = class(TTestCase) private FSignonConfiguration: TSignonConfiguration; FRegValues: TStringList; protected procedure SetUp; override; procedure TearDown; override; published procedure TestReadRegistry; procedure TestShowModal1; procedure TestShowModal2; end; TTestMFunStr = class(TTestCase) private protected procedure Setup; override; public published procedure TestPiece1; procedure TestPiece2; procedure TestPiece3; procedure TestPiece4; procedure TestPiece5; procedure TestPiece6; procedure TestPiece7; procedure TestPiece8; procedure TestPiece9; end; implementation uses XWBut1, Dialogs, MFunStr, LoginFrm; var Str: String; Val: String; procedure TTestSgnoncnf.SetUp; begin { setup as would be done in loginfrm.pas } FSignonConfiguration := TSignonConfiguration.Create; { // if any data currently in registry then save it FRegValues := TStringList.Create; ReadRegValues(HKCU,'Software\Vista\Signon',FRegValues); // Now delete current data DeleteRegData(HKCU,'Software\Vista\Signon'); // Test for reading without registry data FOriginalValues := TSignonValues.Create; } with SignonDefaults do begin Position := '0'; Size := '0'; IntroFont := 'Courier New^11'; IntroFontStyles := 'B'; TextColor := clWindowText; BackColor := clWindow; end; // with FSignonConfiguration.SignonDefaults frmSignon := TfrmSignon.Create(Application); end; procedure TTestSgnoncnf.TearDown; begin FSignonConfiguration.Free; frmSignon.Free; end; procedure TTestSgnoncnf.TestReadRegistry; begin FSignonConfiguration.ReadRegistrySettings; with InitialValues do begin Check(Position = '0', 'ReadRegistry Error in Position value-'+Position); Check(Size = '0', 'ReadRegistry Error in Size value-'+Size); Check(IntroFont = 'Courier New^11', 'ReadRegistry Error in IntroFont-'+IntroFont); Check(IntroFontStyles = 'B', 'ReadRegistry Error in IntroFontStyles value-'+IntroFontStyles); Check(BackColor = clWindow, 'ReadRegistry Error in BackColor = '+IntToStr(BackColor)); Check(TextColor = clWindowText, 'ReadRegistry Error in TextColor = '+IntToStr(TextColor)); end; // with end; procedure TTestSgnoncnf.TestShowModal1; begin ShowMessage('Click on Default Button'); InitialValues.TextColor := clWindow; FSignonConfiguration.ShowModal; with InitialValues do begin Check(TextColor = clWindowText, 'TestShowModal bad TextColor on restore'); end; // with end; procedure TTestSgnoncnf.TestShowModal2; begin ShowMessage('Click on ''Select New'' Background Color then select OK (Standard) on next form Then click OK on Main Form'); InitialValues.TextColor := clWindowText; FSignonConfiguration.ShowModal; with InitialValues do begin Check(BackColor = clWindow, 'TestShowModal bad TextColor on restore'); end; // with end; procedure TTestMFunStr.TestPiece1; begin Val := Piece(Str,'^'); Check(Val = 'Piece1','Failed Piece not specified'); end; procedure TTestMFunStr.Setup; begin Str := 'Piece1^Piece2^Piece3'; end; procedure TTestMFunStr.TestPiece2; begin Val := Piece(Str,'^',2); Check(Val = 'Piece2', 'Failed Piece specified as 2'); end; procedure TTestMFunStr.TestPiece3; begin Val := Piece(Str,'^',3); Check(Val = 'Piece3', 'Failed Piece specifed as 3'); end; procedure TTestMFunStr.TestPiece4; begin Val := Piece(Str,'^',4); Check(Val = '','Failed piece specifed as 4'); end; procedure TTestMFunStr.TestPiece5; begin Val := Piece(Str,'^',1,2); Check(Val = 'Piece1^Piece2','Failed Piece 1,2'); end; procedure TTestMFunStr.TestPiece6; begin Val := Piece(Str,'^',2,3); Check(Val = 'Piece2^Piece3','Failed Piece 2,3'); end; procedure TTestMFunStr.TestPiece7; begin Val := Piece(Str,'^',2,4); Check(Val = 'Piece2^Piece3', 'Failed on Piece 2,4'); end; procedure TTestMFunStr.TestPiece8; begin Val := Piece(Str,'^',3,5); Check(Val = 'Piece3','Failed on Piece 3,5'); end; procedure TTestMFunStr.TestPiece9; begin Val := Piece(Str,'^',4,6); Check(Val = '','Failed on Piece 4,6'); end; { // used with second method of registering tests function UnitTests: ITestSuite; var ATestSuite: TTestSuite; begin ATestSuite := TTestSuite.create('Some trivial tests'); // add each test suite to be tested ATestSuite.addSuite(TTestType.Suite); // ATestSuite.addSuite(TTestStringlist.Suite); Result := ATestSuite; end; } { procedure TTestType.TestName1; begin // Check( Boolean true for success, String comment for failed test) Check(1+1=2,'Comment on Failure') end; } initialization // one entry per testclass TestFramework.RegisterTest('ReadRegistry',TTestSgnoncnf.Suite); TestFramework.RegisterTest('Test Piece',TTestMFunStr.Suite); // or // TestFramework.RegisterTest('SimpleTest',UnitTests); end.
unit settings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, IdMessageParts, IdExplicitTLSClientServerBase, Dialogs, StdCtrls, JvComponentBase, JvFormPlacement, IdAttachmentFile, IdText, Vcl.ComCtrls; type TFormSettings = class(TForm) GroupBox2: TGroupBox; Label6: TLabel; CmTime: TComboBox; EdTime: TEdit; ChAutoUpdate: TCheckBox; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label8: TLabel; EdSender: TEdit; EdSMTPHost: TEdit; EdMailPass: TEdit; ChSendMail: TCheckBox; EdMailLogin: TEdit; BtTestMail: TButton; edSMTPport: TEdit; ChSSL: TCheckBox; StaticText1: TStaticText; EdRecipients: TEdit; Button1: TButton; GroupBox3: TGroupBox; ChAutoHide: TCheckBox; JvFormStorage1: TJvFormStorage; GroupBox4: TGroupBox; BtDBcreate: TButton; BtnShowDB: TButton; ChDebuglog: TCheckBox; ChEventslog: TCheckBox; chkUpdateApp: TCheckBox; btUpdate: TButton; ProgressBar1: TProgressBar; LbSize: TLabel; ChAutoStartSearch: TCheckBox; ChAutoStartApp: TCheckBox; procedure Button1Click(Sender: TObject); procedure BtDBcreateClick(Sender: TObject); procedure BtnShowDBClick(Sender: TObject); procedure CmTimeChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtTestMailClick(Sender: TObject); procedure btUpdateClick(Sender: TObject); procedure ChAutoStartAppClick(Sender: TObject); private { Private declarations } public { Public declarations } AutoTime: integer; UpdateStart: Boolean; end; var FormSettings: TFormSettings; const sLogNameDebug: string = 'DebugLog'; sLogNameStack: string = 'StackLog'; implementation uses MainUnit, UnitDB, UnitVars, DBs, getstrparam, umpgSendMail, UnitUpdate; {$R *.dfm} procedure TFormSettings.BtDBcreateClick(Sender: TObject); var err: string; begin err := 'База данных не создана!'; if DM.CreateDB then begin // if DM.CreateTables then // begin err := 'База данных успешно создана!'; { end else err := 'Ошибка создания таблиц в базе данных!'; } end; FormMain.Log(err, 2); ShowMessage(err); { TODO : поменять на MessageDlg } end; procedure TFormSettings.BtnShowDBClick(Sender: TObject); begin FormDB := TFormDB.Create(self); FormDB.ShowModal; FormDB.Free; end; procedure TFormSettings.BtTestMailClick(Sender: TObject); var msgMail: TmpgSendMail; msgPart: TIdMessagePart; begin with FormMain.IdMessage1 do begin FormMain.Log('Assigning mail test message properties'); From.Text := 'Delphi Indy Client <' + FormSettings.EdSender.Text + '>'; Sender.Text := FormSettings.EdSender.Text; Recipients.EMailAddresses := FormSettings.EdRecipients.Text; Subject := 'Japancar.ru - Поиск автозапчастей по параметрам (TEST MESSAGE)'; ContentType := 'text/plain'; CharSet := 'Windows-1251'; ContentTransferEncoding := '8bit'; IsEncoded := true; Body.Text := 'Japancar.ru - Поиск автозапчастей по параметрам ' + #$D + #$A + 'TEST MESSAGE!' end; msgMail := TmpgSendMail.Create('Windows-1251'); FormMain.Log('SendMail test.'); { TODO : исправить кодировку! } // msgMail.MessagePart.AttachmentEncoding:= msgMail.Message.Body := ''; msgMail.Message.ContentType := 'text/plain'; TIdText.Create(msgMail.MessagePart, FormMain.IdMessage1.Body); msgMail.MessagePart.Items[0].ContentTransfer := FormMain.IdMessage1.ContentTransferEncoding; msgMail.MessagePart.Items[0].CharSet := FormMain.IdMessage1.CharSet; msgMail.MessagePart.Items[0].ContentType := FormMain.IdMessage1.ContentType; msgMail.Message.Subject := FormMain.IdMessage1.Subject; msgMail.MessagePart.CountParts; // ShowMessage(IntToStr(msgMail.MessagePart.Count)); msgMail.Server.UserName := FormSettings.EdMailLogin.Text; msgMail.Server.UserPws := FormSettings.EdMailPass.Text; msgMail.Server.Port := StrToInt(FormSettings.edSMTPport.Text); msgMail.Server.Host := FormSettings.EdSMTPHost.Text; msgMail.FromList.Address := FormSettings.EdSender.Text; msgMail.FromList.Name := FormSettings.EdSender.Text; msgMail.ToList.Address := FormSettings.EdRecipients.Text; msgMail.UseTLS := utUseImplicitTLS; // (ExplicitTLSVals); { IdMessage.Body.AddStrings(mMessage.Lines); for i := 0 to lbAttachments.Items.Count - 1 do begin if (FileExists(lbAttachments.Items[i])) then begin TIdAttachmentFile.Create(IdMessage.MessageParts, lbAttachments.Items[i]); end; end; } // msgPart:=msgMail.MessagePart.Add ; TIdAttachmentFile.Create(msgMail.MessagePart, ExtractFilePath(Application.ExeName) + '\autocar.jpeg'); // msgPart.FileName:=ExtractFilePath(Application.ExeName)+'\autocar.jpeg'; msgMail.SendMail; // FormMain.SendMail(FormMain.IdMessage1); FormMain.Log('Тестовое письмо отправлено.'); msgMail.Free; end; procedure TFormSettings.btUpdateClick(Sender: TObject); var fWorkThread: tWorkThread; begin if not(UpdateStart) then begin UpdateStart := true; fWorkThread := tWorkThread.Create(stHTTP, false); // fWorkThread.Start; // btUpdate.Enabled:=False; btUpdate.Caption := 'Остановить'; while (fWorkThread <> nil) and (UpdateStart) do Application.ProcessMessages; UpdateStart := false; btUpdate.Caption := 'Обновить';; end else begin if fWorkThread <> nil then begin // fWorkThread.Terminate; // btUpdate.Caption:='Обновить';; UpdateStart := false; end; end; end; { var upd: TUpdateApp; begin upd:=tupdateapp.create; upd.Enabled:=ChAutoUpdate.Checked; upd.URL:='http://avtoefi.ru/'+ExtractFileName(Application.ExeName); upd. end; } procedure TFormSettings.Button1Click(Sender: TObject); begin Close; end; procedure TFormSettings.ChAutoStartAppClick(Sender: TObject); begin case ChAutoStartApp.Checked of { TODO : Добавить программу в автозагрузку Windows } true: begin exit; end; false: begin Exit; end; end; end; procedure TFormSettings.CmTimeChange(Sender: TObject); begin try case CmTime.ItemIndex of 0: AutoTime := 1000 * StrToInt(EdTime.Text); 1: AutoTime := 60000 * StrToInt(EdTime.Text); 2: AutoTime := 60000 * 60 * StrToInt(EdTime.Text); end; finally end; end; procedure TFormSettings.FormCreate(Sender: TObject); begin AutoTime := 1000 * 60 * 20; UpdateStart := false; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clDkimUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clHeaderFieldList, clWUtils; type EclDkimError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; TclDkimQuotedPrintableEncoder = class public class function Encode(const ASource: string): string; class function Decode(const ASource: string): string; end; TclDkimHeaderFieldList = class(TclHeaderFieldList) private FLastFieldIndices: TStrings; function GetLastFieldIndex(const AName: string): Integer; procedure AddLastFieldIndex(const AName: string; AFieldIndex: Integer); protected function GetItemDelimiters: TCharSet; override; function InternalGetFieldValue(AIndex: Integer): string; override; public constructor Create; destructor Destroy; override; function NextFieldIndex(const AName: string): Integer; procedure ResetFieldIndex; end; resourcestring DkimInvalidFormat = 'The format of the DKIM-Signature header field is ivalid'; DkimInvalidSignatureParameters = 'There are errors in signature parameters'; DkimInvalidSignatureAlgorihm = 'The SignatureAlgorithm is invalid'; DkimVerifyBodyHashFailed = 'Body hash values differ'; DkimInvalidVersion = 'The version of the DKIM-Signature is unknown'; DkimKeyRequired = 'The key is required to complete the operation'; DkimSelectorRequired = 'The Selector is required to complete the operation'; DkimDomainRequired = 'The Domain is required to complete the operation'; DkimKeyRevoked = 'The key is revoked'; DkimInvalidKey = 'The publik key is invalid or has wrong parameters'; const DkimInvalidFormatCode = -10; DkimInvalidSignatureParametersCode = -11; DkimInvalidSignatureAlgorihmCode = -12; DkimVerifyBodyHashFailedCode = -13; DkimInvalidVersionCode = -14; DkimKeyRequiredCode = -15; DkimSelectorRequiredCode = -16; DkimDomainRequiredCode = -17; DkimKeyRevokedCode = -18; DkimInvalidKeyCode = -19; implementation uses clTranslator, clUtils; { EclDkimError } constructor EclDkimError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; { TclDkimQuotedPrintableEncoder } class function TclDkimQuotedPrintableEncoder.Decode(const ASource: string): string; var next: PChar; hexNumber: Integer; isDelimiter, isCodePresent: Boolean; begin Result := ''; if (Length(ASource) = 0) then Exit; isDelimiter := False; isCodePresent := False; hexNumber := 0; next := @ASource[1]; while (next^ <> #0) do begin if (isDelimiter) then begin case (next^) of 'A'..'F': begin hexNumber := hexNumber + (Ord(next^) - 55); end; '0'..'9': begin hexNumber := hexNumber + (Ord(next^) - 48); end; else begin isCodePresent := False; isDelimiter := False; hexNumber := 0; Result := Result + '=' + next^; end; end; if (not isCodePresent) then begin hexNumber := hexNumber * 16; isCodePresent := True; end else begin Result := Result + Chr(hexNumber); isCodePresent := False; isDelimiter := False; hexNumber := 0; end; end else if (next^ = '=') then begin isDelimiter := True; end else begin Result := Result + next^; end; Inc(next); end; end; class function TclDkimQuotedPrintableEncoder.Encode(const ASource: string): string; var i: Integer; buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} Result := ''; if (Length(ASource) = 0) then Exit; buf := TclTranslator.GetBytes(ASource, 'us-ascii'); for i := 0 to Length(buf) - 1 do begin case (buf[i]) of $21..$3A,$3C,$3E..$7E: Result := Result + Chr(buf[i]); else Result := Result + Format('=%2.2X', [buf[i]]); end; end; end; { TclDkimHeaderFieldList } constructor TclDkimHeaderFieldList.Create; begin inherited Create(); FLastFieldIndices := TStringList.Create(); end; destructor TclDkimHeaderFieldList.Destroy; begin FLastFieldIndices.Free(); inherited Destroy(); end; function TclDkimHeaderFieldList.InternalGetFieldValue(AIndex: Integer): string; var Ind, i: Integer; begin Assert(Source <> nil); if (AIndex > -1) and (AIndex < FieldList.Count) then begin Ind := GetFieldStart(AIndex); Result := Trim(System.Copy(Source[Ind], Length(FieldList[AIndex] + ':') + 1, MaxInt)); for i := Ind + 1 to Source.Count - 1 do begin if not ((Source[i] <> '') and CharInSet(Source[i][1], [#9, #32])) then begin Break; end; Result := Result + Trim(Source[i]); end; end else begin Result := ''; end; end; function TclDkimHeaderFieldList.GetItemDelimiters: TCharSet; begin Result := [';']; end; function TclDkimHeaderFieldList.GetLastFieldIndex(const AName: string): Integer; begin Result := FLastFieldIndices.IndexOf(AName); if (Result > -1) then begin Result := Integer(FLastFieldIndices.Objects[Result]); end; end; procedure TclDkimHeaderFieldList.AddLastFieldIndex(const AName: string; AFieldIndex: Integer); var ind: Integer; begin ind := FLastFieldIndices.IndexOf(AName); if (ind > -1) then begin FLastFieldIndices.Objects[ind] := TObject(AFieldIndex); end else begin FLastFieldIndices.AddObject(AName, TObject(AFieldIndex)); end; end; function TclDkimHeaderFieldList.NextFieldIndex(const AName: string): Integer; var i, startFrom: Integer; name: string; begin name := Trim(LowerCase(AName)); startFrom := GetLastFieldIndex(name); if (startFrom > -1) then begin Dec(startFrom); end else begin startFrom := FieldList.Count - 1; end; Result := -1; for i := startFrom downto 0 do begin if (FieldList[i] = name) then begin Result := i; AddLastFieldIndex(name, Result); Exit; end; end; end; procedure TclDkimHeaderFieldList.ResetFieldIndex; begin FLastFieldIndices.Clear(); end; end.
{*****************************************************************************\ * * Module Name: PMSHL.H * * OS/2 Presentation Manager Shell constants, types, messages and * function declarations * * Copyright (c) International Business Machines Corporation 1981, 1988-1990 * \*****************************************************************************} {| Version: 1.00 | Original translation: Peter Sawatzki ps | Contributing: | Peter Sawatzki ps | | change history: | Date: Ver: Author: | 11/11/93 1.00 ps original translation by ps } Unit PmShl; Interface Uses Os2Def, PmWin; Const { common types, constants and function declarations } { maximum title length } MAXNAMEL = 60; Type { window size structure } XYWINSIZE = Record x,y,cx,cy: SHORT; fsWindow: USHORT End; pXYWINSIZE = ^XYWINSIZE; Const { Definitions for fsWindow } XYF_NOAUTOCLOSE= $0008; XYF_MINIMIZED = $0004; { D23914 } XYF_MAXIMIZED = $0002; { D23914 } XYF_INVISIBLE = $0001; XYF_NORMAL = $0000; Type { program handle } HPROGRAM = LHANDLE; { hprog } pHPROGRAM = ^HPROGRAM; { ini file handle } HINI = LHANDLE; { hini } pHINI = ^HINI; Const HINI_PROFILE = NULL; HINI_USERPROFILE = -1; HINI_SYSTEMPROFILE = -2; HINI_USER = HINI_USERPROFILE; HINI_SYSTEM = HINI_SYSTEMPROFILE; Type PRFPROFILE = Record cchUserName: ULONG; pszUserName: pSZ; cchSysName: ULONG; pszSysName: pSZ End; pPRFPROFILE = ^PRFPROFILE; Const { maximum path length } MAXPATHL = 128; { root group handle } SGH_ROOT = HPROGRAM(-1); Type HPROGARRAY = Record ahprog: Array[0..0] Of HPROGRAM End; pHPROGARRAY = ^HPROGARRAY; PROGCATEGORY = Char; pPROGCATEGORY = pChar; Const { values acceptable for PROGCATEGORY for PM groups } PROG_DEFAULT = PROGCATEGORY(0 ); PROG_FULLSCREEN = PROGCATEGORY(1 ); PROG_WINDOWABLEVIO = PROGCATEGORY(2 ); PROG_PM = PROGCATEGORY(3 ); PROG_GROUP = PROGCATEGORY(5 ); PROG_REAL = PROGCATEGORY(4 );{ was 7 } PROG_DLL = PROGCATEGORY(6 ); PROG_RESERVED = PROGCATEGORY(255); { visibility flag for PROGTYPE structure } SHE_VISIBLE = $00; SHE_INVISIBLE = $01; SHE_RESERVED = $FF; { Protected group flag for PROGTYPE structure } SHE_UNPROTECTED = $00; SHE_PROTECTED = $02; Type PROGTYPE = Record progc: PROGCATEGORY; fbVisible: UCHAR End; pPROGTYPE = ^PROGTYPE; PROGRAMENTRY = Record hprog: HPROGRAM; progt: PROGTYPE; szTitle: Array[0..MAXNAMEL] Of Char End; pPROGRAMENTRY = ^PROGRAMENTRY; PIBSTRUCT = Record progt: PROGTYPE; szTitle: Array[0..MAXNAMEL] Of Char; szIconFileName, szExecutable, szStartupDir: Array[0..MAXPATHL] Of Char; xywinInitial: XYWINSIZE; res1: USHORT; res2: LHANDLE; cchEnvironmentVars: USHORT; pchEnvironmentVars: pCH; cchProgramParameter: USHORT; pchProgramParameter: pCH End; pPIBSTRUCT = ^PIBSTRUCT; {****************************************************************************} { } { Structures associated with 'Prf' calls } { } {****************************************************************************} PROGDETAILS = Record _Length: ULONG; { set this to sizeof(PROGDETAILS) } progt: PROGTYPE; pad1: Array[0..2] Of USHORT; { ready for 32-bit PROGTYPE } pszTitle, { any of the pointers can be NULL } pszExecutable, pszParameters, pszStartupDir, pszIcon, pszEnvironment:pSZ; { this is terminated by /0/0 } swpInitial: SWP; { this replaces XYWINSIZE } pad2: Array[0..4] Of USHORT;{ ready for 32-bit SWP } End; pPROGDETAILS = ^PROGDETAILS; PROGTITLE = Record hprog: HPROGRAM; progt: PROGTYPE; pad1: Array[0..2] Of USHORT; { padding ready for 32-bit PROGTYPE } pszTitle: pSZ End; pPROGTITLE = ^PROGTITLE; QFEOUTBLK = Record Total, Count: USHORT; ProgramArr: Array[0..0] Of HPROGRAM End; pQFEOUTBLK = ^QFEOUTBLK; { Program List API Function Definitions } {** Program Use } Function WinQueryProgramTitles(_hab: HAB; hprogGroup: HPROGRAM; aprogeBuffer: PPROGRAMENTRY; usBufferLen: USHORT; pusTotal: PUSHORT): BOOL; {** Single Program Manipulation } Function WinAddProgram(_hab: HAB; ppibProgramInfo: PPIBSTRUCT; hprogGroupHandle: HPROGRAM): HPROGRAM; Function WinQueryDefinition(_hab: HAB; hprogProgHandle: HPROGRAM; ppibProgramInfo: PPIBSTRUCT; usMaxLength: USHORT): USHORT; {** Group Manipulation } Function WinCreateGroup(_hab: HAB; pszTitle: PSZ; ucVisibility: UCHAR; flres1, flres2: ULONG): HPROGRAM; {****************************************************************************} { } { Program List API available 'Prf' calls } { } {****************************************************************************} Function PrfQueryProgramTitles(_hini: HINI; hprogGroup: HPROGRAM; pTitles: PPROGTITLE; cchBufferMax: ULONG; pulCount: PULONG): ULONG; {***************************************************************************} { } { NOTE: string information is concatanated after the array of PROGTITLE } { structures so you need to allocate storage greater than } { sizeof(PROGTITLE)*cPrograms to query programs in a group } { } { PrfQueryProgramTitles recommended usage to obtain titles of all progams } { in a group (Hgroup=SGH_ROOT is for all groups): } { } { BufLen = PrfQueryProgramTitles( Hini, Hgroup } { , (PPROGTITLE)NULL, 0, &Count); } { } { Alocate buffer of Buflen } { } { Len = PrfQueryProgramTitles( Hini, Hgroup, (PPROGTITLE)pBuffer, BufLen } { , pCount); } { } {***************************************************************************} Function PrfAddProgram (_hini: HINI; pDetails: PPROGDETAILS; hprogGroup: HPROGRAM): HPROGRAM; Function PrfChangeProgram (_hini: HINI; hprog: HPROGRAM; pDetails: PPROGDETAILS): BOOL; {*************************************************************************} { when adding/changing programs the PROGDETAILS Length field should be } { set to sizeof(PROGDETAILS) } {*************************************************************************} Function PrfQueryDefinition (_hini: HINI; hprog: HPROGRAM; pDetails: PPROGDETAILS; cchBufferMax: ULONG): ULONG; {***************************************************************************} { } { NOTE: string information is concatanated after the PROGDETAILS field } { structure so you need to allocate storage greater than } { sizeof(PROGDETAILS) to query programs } { } { PrfQueryDefinition recomended usage: } { } { bufferlen = PrfQueryDefinition( Hini, Hprog, (PPROGDETAILS)NULL, 0) } { } { Alocate buffer of bufferlen bytes } { set Length field (0 will be supported) } { } { (PPROGDETAILS)pBuffer->Length=sizeof(PPROGDETAILS) } { } { len = PrfQueryDefinition(Hini, Hprog, (PPROGDETAILS)pBuffer, bufferlen) } { } {***************************************************************************} Function PrfRemoveProgram(_hini: HINI; hprog: HPROGRAM): BOOL; Function PrfQueryProgramHandle (_hini: HINI; pszExe: PSZ; _phprogArray: PHPROGARRAY; cchBufferMax: ULONG; pulCount: PULONG): ULONG; Function PrfCreateGroup(_hini: HINI; pszTitle: PSZ; chVisibility: UCHAR): HPROGRAM; Function PrfDestroyGroup(_hini: HINI; hprogGroup: HPROGRAM): BOOL; Function PrfQueryProgramCategory(_hini: HINI; pszExe: PSZ): PROGCATEGORY; Type HSWITCH = LHANDLE; { hsw } pHSWITCH = ^HSWITCH; Const { visibility flag for SWCNTRL structure } SWL_VISIBLE = $04; SWL_INVISIBLE = $01; SWL_GRAYED = $02; { visibility flag for SWCNTRL structure } SWL_JUMPABLE = $02; SWL_NOTJUMPABLE = $01; Type SWCNTRL = Record hwnd, hwndIcon: HWND; hprog: HPROGRAM; idProcess, idSession: USHORT; uchVisibility, fbJump: UCHAR; szSwtitle: Array[0..MAXNAMEL] Of Char; fReserved: BYTE { To align on word boundary } End; pSWCNTRL = ^SWCNTRL; {** Switching Program functions } {E}Function WinAddSwitchEntry(_PSWCNTRL: PSWCNTRL): HSWITCH; {E}Function WinRemoveSwitchEntry(_HSWITCH: HSWITCH): USHORT; Type SWENTRY = Record _hswitch: HSWITCH; swctl: SWCNTRL End; pSWENTRY = ^SWENTRY; SWBLOCK = Record cswentry: USHORT; aswentry: Array[0..0] Of SWENTRY End; pSWBLOCK = ^SWBLOCK; Function WinChangeSwitchEntry(hswitchSwitch: HSWITCH; pswctlSwitchData: PSWCNTRL): USHORT; Function WinCreateSwitchEntry(_HAB: HAB; _PSWCNTRL: PSWCNTRL): HSWITCH; Function WinQuerySessionTitle(_hab: HAB; usSession: USHORT; pszTitle: PSZ; usTitlelen: USHORT): USHORT; Function WinQuerySwitchEntry(hswitchSwitch: HSWITCH; pswctlSwitchData: PSWCNTRL): USHORT; Function WinQuerySwitchHandle(_hwnd: HWND; usProcess: PID): HSWITCH; Function WinQuerySwitchList(_hab: HAB; pswblkSwitchEntries: PSWBLOCK; usDataLength: USHORT): USHORT; Function WinQueryTaskSizePos(_hab: HAB; usScreenGroup: USHORT; pswpPositionData: PSWP): USHORT; Function WinQueryTaskTitle(usSession: USHORT; pszTitle: PSZ; usTitlelen: USHORT): USHORT; Function WinSwitchToProgram(hswitchSwHandle: HSWITCH): USHORT; { if error definitions are required then allow Shell errors } {** OS2.INI Access functions } Function WinQueryProfileInt(hab: HAB; pszAppName: PSZ; pszKeyName: PSZ; sDefault: SHORT): SHORT; Function WinQueryProfileString(hab: HAB; pszAppName, pszKeyName: PSZ; pszDefault: PSZ; pProfileString: PVOID; usMaxPstring: USHORT): USHORT; Function WinWriteProfileString(hab: HAB; pszAppName, pszKeyName: PSZ; pszValue: PSZ): BOOL; Function WinQueryProfileSize(hab: HAB; pszAppName, pszKeyName: PSZ; pusValue: PUSHORT): USHORT; Function WinQueryProfileData(hab: HAB; pszAppName, pszKeyName: PSZ; pValue: PVOID; pusSize: PUSHORT): BOOL; Function WinWriteProfileData(hab: HAB; pszAppName, pszKeyName: PSZ; pValue: PVOID; usSize: USHORT): BOOL; {****************************************************************************} { } { INI file access API available calls 'Prf' } { } {****************************************************************************} Function PrfQueryProfileInt(hini: HINI; pszApp, pszKey: PSZ; sDefault: SHORT): SHORT; Function PrfQueryProfileString(hini: HINI; pszApp, pszKey: PSZ; pszDefault: PSZ; pBuffer: PVOID; cchBufferMax: ULONG): ULONG; Function PrfWriteProfileString(hini: HINI; pszApp, pszKey, pszData: PSZ): BOOL; Function PrfQueryProfileSize(hini: HINI; pszApp, pszKey: PSZ; pulReqLen: PULONG): BOOL; Function PrfQueryProfileData(hini: HINI; pszApp, pszKey: PSZ; pBuffer: PVOID; pulBuffLen: PULONG): BOOL; Function PrfWriteProfileData(hini: HINI; pszApp, pszKey: PSZ; pData: PVOID; cchDataLen: ULONG): BOOL; Function PrfOpenProfile(hab: HAB; pszFileName: PSZ): HINI; Function PrfCloseProfile(hini: HINI): BOOL; Function PrfReset(hab: HAB; pPrfProfile: PPRFPROFILE): BOOL; Function PrfQueryProfile(hab: HAB; pPrfProfile: PPRFPROFILE): BOOL; Const { new public message, broadcast on WinReset } PL_ALTERED = $008E; { WM_SHELLFIRST + 0E } Type HAPP = LHANDLE; ppSZ = ^pSZ; Function WinInstStartApp (hini: HINI;hwndNotifyWindow: HWND;cCount: USHORT;Var aszApplication: PSZ; pszCmdLine: PSZ;pData: PVOID;fsOptions: USHORT): HAPP; Function WinTerminateApp (happ: HAPP): BOOL; Const { bit values for Options parameter of WinInstStartAppl } SAF_VALIDFLAGS = $001F; SAF_INSTALLEDCMDLINE= $0001; { use installed parameters } SAF_STARTCHILDAPP= $0002; { related application } SAF_MAXIMIZED = $0004; { Start App maximized } SAF_MINIMIZED = $0008; { Start App minimized, if !SAF_MAXIMIZED } SAF_BACKGROUND= $0010; { Start app in the background } Implementation Function PrfAddProgram; External 'PMSHAPI' Index 50; Function PrfChangeProgram; External 'PMSHAPI' Index 52; Function PrfCloseProfile; External 'PMSHAPI' Index 39; Function PrfCreateGroup; External 'PMSHAPI' Index 55; Function PrfDestroyGroup; External 'PMSHAPI' Index 60; Function PrfOpenProfile; External 'PMSHAPI' Index 38; Function PrfQueryDefinition; External 'PMSHAPI' Index 53; Function PrfQueryProfile; External 'PMSHAPI' Index 43; Function PrfQueryProfileData; External 'PMSHAPI' Index 36; Function PrfQueryProfileInt; External 'PMSHAPI' Index 32; Function PrfQueryProfileSize; External 'PMSHAPI' Index 35; Function PrfQueryProfileString; External 'PMSHAPI' Index 33; Function PrfQueryProgramCategory; External 'PMSHAPI' Index 59; Function PrfQueryProgramHandle; External 'PMSHAPI' Index 58; Function PrfQueryProgramTitles; External 'PMSHAPI' Index 54; Function PrfRemoveProgram; External 'PMSHAPI' Index 51; Function PrfReset; External 'PMSHAPI' Index 42; Function PrfWriteProfileData; External 'PMSHAPI' Index 37; Function PrfWriteProfileString; External 'PMSHAPI' Index 34; Function WinAddProgram; External 'PMSHAPI' Index 12; Function WinAddSwitchEntry; External 'OS2SM' Index 9; Function WinChangeSwitchEntry; External 'OS2SM' Index 10; Function WinCreateGroup; External 'PMSHAPI' Index 17; Function WinCreateSwitchEntry; External 'OS2SM' Index 7; Function WinInstStartApp; External 'OS2SM' Index 5; Function WinQueryDefinition; External 'PMSHAPI' Index 15; Function WinQueryProfileData; External 'PMSHAPI' Index 6; Function WinQueryProfileInt; External 'PMSHAPI' Index 2; Function WinQueryProfileSize; External 'PMSHAPI' Index 5; Function WinQueryProfileString; External 'PMSHAPI' Index 3; Function WinQueryProgramTitles; External 'PMSHAPI' Index 16; Function WinQuerySessionTitle; External 'OS2SM' Index 8; Function WinQuerySwitchEntry; External 'OS2SM' Index 11; Function WinQuerySwitchHandle; External 'OS2SM' Index 12; Function WinQuerySwitchList; External 'OS2SM' Index 15; Function WinQueryTaskSizePos; External 'OS2SM' Index 14; Function WinQueryTaskTitle; External 'OS2SM' Index 13; Function WinRemoveSwitchEntry; External 'OS2SM' Index 16; Function WinSwitchToProgram; External 'OS2SM' Index 17; Function WinTerminateApp; External 'OS2SM' Index 6; Function WinWriteProfileData; External 'PMSHAPI' Index 7; Function WinWriteProfileString; External 'PMSHAPI' Index 4; End.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clThreadPool; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Windows, Classes, Contnrs, SyncObjs, ActiveX; {$ELSE} Winapi.Windows, System.Classes, System.Contnrs, System.SyncObjs, Winapi.ActiveX; {$ENDIF} type TclWorkItem = class protected procedure Execute(AThread: TThread); virtual; abstract; end; TclThreadPool = class; TclWorkerThread = class(TThread) private FOwner: TclThreadPool; FIsBusy: Boolean; FItem: TclWorkItem; FStartEvent: THandle; FStopEvent: THandle; protected procedure Execute; override; public constructor Create(AOwner: TclThreadPool); destructor Destroy; override; procedure Perform(AItem: TclWorkItem); procedure Stop; property IsBusy: Boolean read FIsBusy; end; TclWorkerThreadCom = class(TclWorkerThread) protected procedure Execute; override; end; TclCreateWorkerThreadEvent = procedure(Sender: TObject; var AThread: TclWorkerThread) of object; TclWorkItemEvent = procedure(Sender: TObject; AItem: TclWorkItem) of object; TclRunWorkItemEvent = procedure(Sender: TObject; AItem: TclWorkItem; AThread: TclWorkerThread) of object; TclFinishWorkItemEvent = procedure(Sender: TObject; AItem: TclWorkItem; AThread: TclWorkerThread; ATerminated: Boolean) of object; TclWorkItemExecuteProc = procedure(AContext: TObject; AThread: TThread) of object; TclThreadPool = class(TComponent) private FThreads: TObjectList; FItems: TQueue; FMinThreadCount: Integer; FMaxThreadCount: Integer; FAccessor: TCriticalSection; FInitializeCOM: Boolean; FOnCreateWorkerThread: TclCreateWorkerThreadEvent; FOnQueueWorkItem: TclWorkItemEvent; FOnRunWorkItem: TclRunWorkItemEvent; FOnFinishWorkItem: TclFinishWorkItemEvent; procedure SetMaxThreadCount(const Value: Integer); procedure SetMinThreadCount(const Value: Integer); function GetNonBusyThread: TclWorkerThread; procedure CreateMinWorkerThreads; procedure ProcessQueuedItem; procedure FreeUnneededThreads; protected function CreateWorkerThread: TclWorkerThread; virtual; procedure DoCreateWorkerThread(var AThread: TclWorkerThread); virtual; procedure DoQueueWorkItem(AItem: TclWorkItem); virtual; procedure DoRunWorkItem(AItem: TclWorkItem; AThread: TclWorkerThread); virtual; procedure DoFinishWorkItem(AItem: TclWorkItem; AThread: TclWorkerThread; ATerminated: Boolean); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Stop; procedure QueueWorkItem(AItem: TclWorkItem); overload; procedure QueueWorkItem(AContext: TObject; AExecProc: TclWorkItemExecuteProc); overload; published property MinThreadCount: Integer read FMinThreadCount write SetMinThreadCount default 1; property MaxThreadCount: Integer read FMaxThreadCount write SetMaxThreadCount default 5; property InitializeCOM: Boolean read FInitializeCOM write FInitializeCOM default False; property OnCreateWorkerThread: TclCreateWorkerThreadEvent read FOnCreateWorkerThread write FOnCreateWorkerThread; property OnQueueWorkItem: TclWorkItemEvent read FOnQueueWorkItem write FOnQueueWorkItem; property OnRunWorkItem: TclRunWorkItemEvent read FOnRunWorkItem write FOnRunWorkItem; property OnFinishWorkItem: TclFinishWorkItemEvent read FOnFinishWorkItem write FOnFinishWorkItem; end; implementation type TclExecProcWorkItem = class(TclWorkItem) private FContext: TObject; FExecProc: TclWorkItemExecuteProc; protected procedure Execute(AThread: TThread); override; public constructor Create(AContext: TObject; AExecProc: TclWorkItemExecuteProc); end; { TclThreadPool } constructor TclThreadPool.Create(AOwner: TComponent); begin inherited Create(AOwner); FAccessor := TCriticalSection.Create(); FThreads := TObjectList.Create(); FItems := TQueue.Create(); FMaxThreadCount := 5; FMinThreadCount := 1; FInitializeCOM := False; end; destructor TclThreadPool.Destroy; begin Stop(); FItems.Free(); FThreads.Free(); FAccessor.Free(); inherited Destroy(); end; procedure TclThreadPool.DoCreateWorkerThread(var AThread: TclWorkerThread); begin if Assigned(OnCreateWorkerThread) then begin OnCreateWorkerThread(Self, AThread); end; end; procedure TclThreadPool.DoFinishWorkItem(AItem: TclWorkItem; AThread: TclWorkerThread; ATerminated: Boolean); begin if Assigned(OnFinishWorkItem) then begin OnFinishWorkItem(Self, AItem, AThread, ATerminated); end; end; procedure TclThreadPool.DoQueueWorkItem(AItem: TclWorkItem); begin if Assigned(OnQueueWorkItem) then begin OnQueueWorkItem(Self, AItem); end; end; procedure TclThreadPool.DoRunWorkItem(AItem: TclWorkItem; AThread: TclWorkerThread); begin if Assigned(OnRunWorkItem) then begin OnRunWorkItem(Self, AItem, AThread); end; end; function TclThreadPool.GetNonBusyThread: TclWorkerThread; var i: Integer; begin for i := 0 to FThreads.Count - 1 do begin Result := TclWorkerThread(FThreads[i]); if (not Result.IsBusy) then Exit; end; Result := nil; end; function TclThreadPool.CreateWorkerThread: TclWorkerThread; begin Result := nil; DoCreateWorkerThread(Result); if (Result <> nil) then Exit; if InitializeCOM then begin Result := TclWorkerThreadCom.Create(Self); end else begin Result := TclWorkerThread.Create(Self); end; end; procedure TclThreadPool.CreateMinWorkerThreads; begin while (FThreads.Count < MinThreadCount) do begin CreateWorkerThread(); end; end; procedure TclThreadPool.QueueWorkItem(AItem: TclWorkItem); var thread: TclWorkerThread; 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; {$ENDIF} {$ENDIF} DoQueueWorkItem(AItem); FAccessor.Enter(); try thread := GetNonBusyThread(); if (thread = nil) and (FThreads.Count < MaxThreadCount) then begin thread := CreateWorkerThread(); end; if (thread <> nil) then begin thread.Perform(AItem); end else begin FItems.Push(AItem); end; CreateMinWorkerThreads(); FreeUnneededThreads(); finally FAccessor.Leave(); end; end; procedure TclThreadPool.SetMaxThreadCount(const Value: Integer); begin if (Value > 1) and (Value <= MAXIMUM_WAIT_OBJECTS) then begin FMaxThreadCount := Value; end; end; procedure TclThreadPool.SetMinThreadCount(const Value: Integer); begin if (Value > 1) and (Value <= MAXIMUM_WAIT_OBJECTS) then begin FMinThreadCount := Value; end; end; procedure TclThreadPool.Stop; var i: Integer; begin FAccessor.Enter(); try while FItems.AtLeast(1) do begin TObject(FItems.Pop()).Free(); end; for i := 0 to FThreads.Count - 1 do begin TclWorkerThread(FThreads[i]).Stop(); end; finally FAccessor.Leave(); end; while(FThreads.Count > 0) do begin FThreads.Delete(0); end; end; procedure TclThreadPool.FreeUnneededThreads; var i: Integer; begin for i := FThreads.Count downto MinThreadCount do begin if (not TclWorkerThread(FThreads[i - 1]).IsBusy) then begin FThreads.Delete(i - 1); end; end; end; procedure TclThreadPool.ProcessQueuedItem; var thread: TclWorkerThread; begin FAccessor.Enter(); try if FItems.AtLeast(1) then begin thread := GetNonBusyThread(); if (thread = nil) and (FThreads.Count < MaxThreadCount) then begin thread := CreateWorkerThread(); end; if (thread <> nil) then begin thread.Perform(FItems.Pop()); end; end; finally FAccessor.Leave(); end; end; procedure TclThreadPool.QueueWorkItem(AContext: TObject; AExecProc: TclWorkItemExecuteProc); begin QueueWorkItem(TclExecProcWorkItem.Create(AContext, AExecProc)); end; { TclWorkerThread } constructor TclWorkerThread.Create(AOwner: TclThreadPool); begin FStartEvent := CreateEvent(nil, False, False, nil); FStopEvent := CreateEvent(nil, False, False, nil); FOwner := AOwner; inherited Create(False); FOwner.FThreads.Add(Self); end; destructor TclWorkerThread.Destroy; begin Stop(); WaitForSingleObject(Handle, INFINITE); FItem.Free(); FItem := nil; inherited Destroy(); CloseHandle(FStopEvent); CloseHandle(FStartEvent); end; procedure TclWorkerThread.Execute; var dwResult: DWORD; arr: array[0..1] of THandle; begin try arr[0] := FStopEvent; arr[1] := FStartEvent; repeat dwResult := WaitForMultipleObjects(2, @arr, FALSE, INFINITE); if (dwResult = WAIT_OBJECT_0 + 1) then begin try FOwner.DoRunWorkItem(FItem, Self); FItem.Execute(Self); FOwner.DoFinishWorkItem(FItem, Self, Terminated); except Assert(False); end; FItem.Free(); FItem := nil; if not Terminated then begin FOwner.ProcessQueuedItem(); end; FIsBusy := False; end; until Terminated or (dwResult = WAIT_OBJECT_0); except Assert(False); end; end; procedure TclWorkerThread.Perform(AItem: TclWorkItem); begin Assert(not FIsBusy); FItem := AItem; FIsBusy := True; SetEvent(FStartEvent); end; procedure TclWorkerThread.Stop; begin Terminate(); SetEvent(FStopEvent); end; { TclWorkerThreadCom } procedure TclWorkerThreadCom.Execute; begin CoInitialize(nil); try inherited Execute(); finally CoUninitialize(); end; end; { TclExecProcWorkItem } constructor TclExecProcWorkItem.Create(AContext: TObject; AExecProc: TclWorkItemExecuteProc); begin inherited Create(); FContext := AContext; FExecProc := AExecProc; end; procedure TclExecProcWorkItem.Execute(AThread: TThread); begin Assert(@FExecProc <> nil); FExecProc(FContext, AThread); end; end.
unit ssExcelConst; interface uses SysUtils, Graphics; const OleClassName = 'Excel.Application'; //UnderLine Styles for Font property xlUnderlineStyleDouble = $FFFFEFE9; xlUnderlineStyleDoubleAccounting = $00000005; xlUnderlineStyleNone = $FFFFEFD2; xlUnderlineStyleSingle = $00000002; xlUnderlineStyleSingleAccounting = $00000004; // XlVAlign constants const xlVAlignBottom = $FFFFEFF5; xlVAlignCenter = $FFFFEFF4; xlVAlignDistributed = $FFFFEFEB; xlVAlignJustify = $FFFFEFDE; xlVAlignTop = $FFFFEFC0; //выравнивание xlCenter = -4108; xlRight = -4152; xlLeft = -4131; //толщина линии xlMedium = -4138; xlThin = 2; //стиль линии xlContinuous = 1; var ExcelVersion : integer = 8; //номер версии по умолчанию { Возвращает строковое обозначение в терминах Excel для прямоугольной области, заданной параметрами Left, Top, Right, Bottom.} { example: ExcelRectToStr(1,1,5,2) = 'A1:E2' } function ExcelRectToStr(Left, Top, Right, Bottom : LongInt) : string; { Задает параметры форматирования шрифта в области Rect } procedure SetCellsFont(Sheet : Variant; const Rect, FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); { Задает цвет области } procedure SetCellsBackground(Sheet : Variant; const Rect : string; Color : TColor); { Рисует рамку вокруг области с заданным стилем и толщиной } procedure SetCellsBorder(Sheet : Variant; const Rect : string; LineStyle, LineWeight : integer); { получить выделенный диапазон } function GetRange(Sheet : Variant; const Rect : string) : Variant; { объеденить ячейки } procedure MergeCells(Sheet : Variant; const Rect : string); { разъеденить ячейки } procedure UnMergeCells(Sheet : Variant; const Rect : string); implementation function ExcelVersionIs70 : boolean; begin Result:=(ExcelVersion=7); end; function ExcelRectToStr(Left, Top, Right, Bottom : LongInt) : string; begin if Top=0 then Result := chr(Left+ord('@'))+':'+chr(Right+ord('@')) else if Left = 0 then Result := IntToStr(Top)+':'+IntToStr(Bottom) else Result := chr(Left+ord('@'))+IntToStr(Top)+':'+ chr(Right+ord('@'))+IntToStr(Bottom); end; procedure SetCellsFont(Sheet : Variant; const Rect, FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin if ExcelVersionIs70 then begin Sheet.Range(Rect).Font.Name:=FontName; Sheet.Range(Rect).Font.Size:=FontSize; Sheet.Range(Rect).Font.Italic:=fsItalic in FontStyle; Sheet.Range(Rect).Font.Bold:=fsBold in FontStyle; Sheet.Range(Rect).Font.Strikethrough:=fsStrikeOut in FontStyle; Sheet.Range(Rect).Font.Color:=ColorToRGB(FontColor); end else begin Sheet.Range[Rect].Font.Name:=FontName; Sheet.Range[Rect].Font.Size:=FontSize; Sheet.Range[Rect].Font.Italic:=fsItalic in FontStyle; Sheet.Range[Rect].Font.Bold:=fsBold in FontStyle; Sheet.Range[Rect].Font.Strikethrough:=fsStrikeOut in FontStyle; if fsUnderLine in FontStyle then Sheet.Range[Rect].Font.Underline:=xlUnderlineStyleSingleAccounting; Sheet.Range[Rect].Font.Color:=ColorToRGB(FontColor); end; end; procedure SetCellsBackground(Sheet : Variant; const Rect : string; Color : TColor); begin if ExcelVersionIs70 then Sheet.Range(Rect).Interior.Color:=ColorToRGB(Color) else Sheet.Range[Rect].Interior.Color:=ColorToRGB(Color) end; procedure SetCellsBorder(Sheet : Variant; const Rect : string; LineStyle, LineWeight : integer); begin if ExcelVersionIs70 then begin Sheet.Range(Rect).Borders.LineStyle:=LineStyle; Sheet.Range(Rect).Borders.Weight:=LineWeight; end else begin Sheet.Range[Rect].Borders.LineStyle:=LineStyle; Sheet.Range[Rect].Borders.Weight:=LineWeight; end; end; function GetRange(Sheet : Variant; const Rect : string) : Variant; begin if ExcelVersionIs70 then Result:=Sheet.Range(Rect) else Result:=Sheet.Range[Rect] end; procedure MergeCells(Sheet : Variant; const Rect : string); var Range : Variant; begin Range:=GetRange(Sheet, Rect); Range.Merge; end; procedure UnMergeCells(Sheet : Variant; const Rect : string); var Range : Variant; begin Range:=GetRange(Sheet, Rect); Range.MergeCells:=False; end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.Arrays Description : Multifuntional Arrays Author : Kike Pérez Version : 1.2 Created : 24/03/2019 Modified : 16/10/2019 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.Arrays; {$i QuickLib.inc} interface uses SysUtils, Generics.Defaults, Generics.Collections, Quick.Value; type TXArray<T> = record type TEnumerator = class(Generics.Collections.TEnumerator<T>) private fArray : ^TArray<T>; fIndex : Integer; protected function DoGetCurrent: T; override; function DoMoveNext: Boolean; override; public constructor Create(var aArray: TArray<T>); end; private type arrayofT = array of T; ParrayofT = ^arrayofT; private fArray : TArray<T>; function GetItem(Index : Integer) : T; procedure SetItem(Index : Integer; const aValue : T); function GetCapacity: Integer; function GetCount: Integer; procedure SetCapacity(const Value: Integer); function GetPArray: ParrayofT; public function GetEnumerator: TEnumerator<T>; property AsArray : TArray<T> read fArray; property Items[Index : Integer] : T read GetItem write SetItem; default; property Count : Integer read GetCount; property Capacity : Integer read GetCapacity write SetCapacity; function Add(aValue : T) : Integer; procedure Insert(aItem : T; aIndex : Integer); procedure Delete(aIndex : Integer); procedure Remove(aItem : T); function Contains(aItem : T) : Boolean; function IndexOf(aItem : T) : Integer; property PArray : ParrayofT read GetPArray; class operator Implicit(const Value : TxArray<T>) : TArray<T>; class operator Implicit(const Value : TArray<T>) : TxArray<T>; end; TPair = record Name : string; Value : string; constructor Create(const aName, aValue : string); end; TPairArray = TArray<TPair>; PPairArray = ^TPairArray; TPairXArray = TXArray<TPair>; TFlexArray = TXArray<TFlexValue>; TFlexPairArray = TArray<TFlexPair>; TPairArrayHelper = record helper for TPairArray public function GetValue(const aName : string) : string; function GetPair(const aName : string) : TPair; function Add(aPair : TPair) : Integer; overload; function Add(const aName, aValue : string) : Integer; overload; procedure AddOrUpdate(const aName, aValue : string); function Exists(const aName : string) : Boolean; function Remove(const aName : string) : Boolean; function Count : Integer; property Items[const aName : string] : string read GetValue write AddOrUpdate; end; TFlexPairArrayHelper = record helper for TFlexPairArray public function GetValue(const aName : string) : TFlexValue; function GetPair(const aName : string) : TFlexPair; function Add(aFlexPair : TFlexPair) : Integer; overload; function Add(const aName: string; aValue : TFlexValue): Integer; overload; procedure AddOrUpdate(const aName : string; aValue : TFlexValue); function Exists(const aName : string) : Boolean; function Remove(const aName : string) : Boolean; function Count : Integer; property Items[const aName : string] : TFlexValue read GetValue write AddOrUpdate; end; implementation { TxArray } function TxArray<T>.GetItem(Index : Integer) : T; begin Result := fArray[Index]; end; function TXArray<T>.GetPArray: ParrayofT; begin Pointer(Result) := fArray; end; procedure TXArray<T>.SetCapacity(const Value: Integer); begin if Value = High(fArray) then Exit; if Value < 0 then SetLength(fArray,1) else SetLength(fArray, Value); end; procedure TxArray<T>.SetItem(Index : Integer; const aValue : T); begin fArray[Index] := aValue; end; function TXArray<T>.GetCapacity: Integer; begin Result := High(fArray) + 1; end; function TXArray<T>.GetCount: Integer; begin Result := High(fArray) + 1; end; function TxArray<T>.GetEnumerator: TEnumerator<T>; begin Result := TEnumerator.Create(fArray); end; function TxArray<T>.Add(aValue : T) : Integer; begin SetLength(fArray, Length(fArray) + 1); fArray[High(fArray)] := aValue; Result := High(fArray); end; procedure TxArray<T>.Delete(aIndex : Integer); begin System.Delete(fArray,aIndex,1); end; procedure TxArray<T>.Remove(aItem : T); var nindex : Integer; begin nindex := IndexOf(aItem); if nindex > -1 then System.Delete(fArray,nindex,1); end; procedure TxArray<T>.Insert(aItem : T; aIndex : Integer); begin System.Insert(aItem,fArray,aIndex); end; function TxArray<T>.Contains(aItem : T) : Boolean; var icomparer : IEqualityComparer<T>; i : Integer; begin Result := False; icomparer := TEqualityComparer<T>.Default; for i := Low(fArray) to High(fArray) do begin if icomparer.Equals(fArray[i],aItem) then Exit(True); end; end; function TxArray<T>.IndexOf(aItem : T) : Integer; var icomparer : IEqualityComparer<T>; i : Integer; begin icomparer := TEqualityComparer<T>.Default; for i := Low(fArray) to High(fArray) do begin if icomparer.Equals(fArray[i],aItem) then Exit(i); end; Result := -1; end; class operator TxArray<T>.Implicit(const Value : TxArray<T>) : TArray<T>; begin Result := Value.fArray; end; class operator TXArray<T>.Implicit(const Value: TArray<T>): TxArray<T>; begin Result.fArray := Value; end; { TXArray<T>.TEnumerator } constructor TXArray<T>.TEnumerator.Create(var aArray: TArray<T>); begin fIndex := -1; fArray := @aArray; end; function TXArray<T>.TEnumerator.DoGetCurrent: T; begin Result := TArray<T>(fArray^)[fIndex]; end; function TXArray<T>.TEnumerator.DoMoveNext: Boolean; begin Inc(fIndex); Result := fIndex < High(TArray<T>(fArray^))+1; end; { TFlexPairArrayHelper } function TFlexPairArrayHelper.Add(const aName: string; aValue : TFlexValue): Integer; begin SetLength(Self,Length(Self)+1); Self[High(Self)].Name := aName; Self[High(Self)].Value := aValue; Result := High(Self); end; function TFlexPairArrayHelper.Count: Integer; begin Result := High(Self) + 1; end; function TFlexPairArrayHelper.Add(aFlexPair: TFlexPair): Integer; begin SetLength(Self,Length(Self)+1); Self[High(Self)] := aFlexPair; Result := High(Self); end; function TFlexPairArrayHelper.Exists(const aName: string): Boolean; var i : Integer; begin Result := False; for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(True) end; end; function TFlexPairArrayHelper.GetPair(const aName: string): TFlexPair; var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(Self[i]); end; end; function TFlexPairArrayHelper.GetValue(const aName: string): TFlexValue; var i : Integer; begin Result.Clear; for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(Self[i].Value); end; end; function TFlexPairArrayHelper.Remove(const aName: string): Boolean; var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then begin System.Delete(Self,i,1); Exit(True); end; end; Result := False; end; procedure TFlexPairArrayHelper.AddOrUpdate(const aName : string; aValue : TFlexValue); var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then begin Self[i].Value := aValue; Exit; end; end; //if not exists add it Self.Add(aName,aValue); end; { TPair } constructor TPair.Create(const aName, aValue: string); begin Name := aName; Value := aValue; end; { TPairArrayHelper } function TPairArrayHelper.Add(aPair: TPair): Integer; begin SetLength(Self,Length(Self)+1); Self[High(Self)] := aPair; Result := High(Self); end; function TPairArrayHelper.Add(const aName, aValue: string): Integer; begin SetLength(Self,Length(Self)+1); Self[High(Self)].Name := aName; Self[High(Self)].Value := aValue; Result := High(Self); end; procedure TPairArrayHelper.AddOrUpdate(const aName, aValue: string); var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then begin Self[i].Value := aValue; Exit; end; end; //if not exists add it Self.Add(aName,aValue); end; function TPairArrayHelper.Count: Integer; begin Result := High(Self) + 1; end; function TPairArrayHelper.Exists(const aName: string): Boolean; var i : Integer; begin Result := False; for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(True) end; end; function TPairArrayHelper.GetPair(const aName: string): TPair; var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(Self[i]); end; end; function TPairArrayHelper.GetValue(const aName: string): string; var i : Integer; begin Result := ''; for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then Exit(Self[i].Value); end; end; function TPairArrayHelper.Remove(const aName: string): Boolean; var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i].Name,aName) = 0 then begin System.Delete(Self,i,1); Exit(True); end; end; Result := False; end; end.
unit evCellsOffsets; {* работа со смещениями ячеек } // Модуль: "w:\common\components\gui\Garant\Everest\evCellsOffsets.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevCellsOffsets" MUID: (49CB6E880188) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , evEpsilonLongIntList ; type TevCellsOffsets = class(Tl3ProtoObject) {* работа со смещениями ячеек } private f_Offsets: TevEpsilonLongIntList; {* Смещения ячеек } f_Widths: TevEpsilonLongIntList; {* Ширина ячеек по этому смещению } f_Width: Integer; {* Текущая ширина ячейки } f_Offset: Integer; {* Текущее смещение } f_CheckChildren: Boolean; {* Нужно ли проверять дочерние } protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure Clear; procedure AddCellWidth; procedure CheckOffset(aCheckWidth: Boolean); function CheckParam: Boolean; procedure RecalcOffset; procedure ClearOffset; procedure SetWidth(aWidth: Integer); end;//TevCellsOffsets implementation uses l3ImplUses , SysUtils , evConst //#UC START# *49CB6E880188impl_uses* //#UC END# *49CB6E880188impl_uses* ; procedure TevCellsOffsets.Clear; //#UC START# *4A562C3A013E_49CB6E880188_var* //#UC END# *4A562C3A013E_49CB6E880188_var* begin //#UC START# *4A562C3A013E_49CB6E880188_impl* if (f_Offsets <> nil) then begin f_Offsets.Clear; f_Widths.Clear; f_Offset := 0; f_Width := 0; end; // if (f_Offsets <> nil) then //#UC END# *4A562C3A013E_49CB6E880188_impl* end;//TevCellsOffsets.Clear procedure TevCellsOffsets.AddCellWidth; //#UC START# *4A562C5301A5_49CB6E880188_var* //#UC END# *4A562C5301A5_49CB6E880188_var* begin //#UC START# *4A562C5301A5_49CB6E880188_impl* if f_Offsets = nil then begin f_Offsets := TevEpsilonLongIntList.Make; f_Widths := TevEpsilonLongIntList.Make; end; // if f_Offsets = nil then f_Offsets.Add(f_Offset); f_Widths.Add(f_Width); //#UC END# *4A562C5301A5_49CB6E880188_impl* end;//TevCellsOffsets.AddCellWidth procedure TevCellsOffsets.CheckOffset(aCheckWidth: Boolean); var l_Index: Integer; //#UC START# *4A562C6C00A6_49CB6E880188_var* //#UC END# *4A562C6C00A6_49CB6E880188_var* begin //#UC START# *4A562C6C00A6_49CB6E880188_impl* if (f_Offsets <> nil) and f_Offsets.FindData(f_Offset, l_Index) then if not aCheckWidth or (Abs(f_Widths[l_Index] - f_Width) <= evFindCellDelta) then begin f_Offsets.Delete(l_Index); f_Widths.Delete(l_Index); end; // if Abs(f_Widths[l_Index]... //#UC END# *4A562C6C00A6_49CB6E880188_impl* end;//TevCellsOffsets.CheckOffset function TevCellsOffsets.CheckParam: Boolean; var l_Index: Integer; //#UC START# *4A562C85014A_49CB6E880188_var* //#UC END# *4A562C85014A_49CB6E880188_var* begin //#UC START# *4A562C85014A_49CB6E880188_impl* Result := f_Offsets = nil; // Result = True - не нашли! if not Result then Result := not (f_Offsets.FindData(f_Offset, l_Index) and (Abs(f_Widths[l_Index] - f_Width) <= evFindCellDelta)); //#UC END# *4A562C85014A_49CB6E880188_impl* end;//TevCellsOffsets.CheckParam procedure TevCellsOffsets.RecalcOffset; //#UC START# *4A562C9902F5_49CB6E880188_var* //#UC END# *4A562C9902F5_49CB6E880188_var* begin //#UC START# *4A562C9902F5_49CB6E880188_impl* Inc(f_Offset, f_Width); //#UC END# *4A562C9902F5_49CB6E880188_impl* end;//TevCellsOffsets.RecalcOffset procedure TevCellsOffsets.ClearOffset; //#UC START# *4A562CA901FA_49CB6E880188_var* //#UC END# *4A562CA901FA_49CB6E880188_var* begin //#UC START# *4A562CA901FA_49CB6E880188_impl* f_Offset := 0; f_Width := 0; //#UC END# *4A562CA901FA_49CB6E880188_impl* end;//TevCellsOffsets.ClearOffset procedure TevCellsOffsets.SetWidth(aWidth: Integer); //#UC START# *4A562CBD0279_49CB6E880188_var* //#UC END# *4A562CBD0279_49CB6E880188_var* begin //#UC START# *4A562CBD0279_49CB6E880188_impl* f_Width := aWidth; //#UC END# *4A562CBD0279_49CB6E880188_impl* end;//TevCellsOffsets.SetWidth procedure TevCellsOffsets.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_49CB6E880188_var* //#UC END# *479731C50290_49CB6E880188_var* begin //#UC START# *479731C50290_49CB6E880188_impl* FreeAndNil(f_Offsets); FreeAndNil(f_Widths); inherited; //#UC END# *479731C50290_49CB6E880188_impl* end;//TevCellsOffsets.Cleanup end.
unit PNGImageList; interface uses classes,controls; type TPngImageList=class(TImageList) protected procedure ReadData(Stream: TStream); override; procedure WriteData(Stream: TStream); override; end; procedure Register; implementation uses PNGImage,graphics; procedure Register; begin RegisterComponents('CautiousEdit',[TPngImageList]); end; procedure TPngImageList.ReadData(Stream: TStream); var img: TPngObject; btmp: TBitmap; begin // inherited WriteData(Stream); while Stream.Position<Stream.Size do begin img:=TPngObject.Create; btmp:=TBitmap.Create; img.LoadFromStream(Stream); img.AssignTo(btmp); Add(btmp,nil); btmp.Free; img.Free; end; end; procedure TPngImageList.WriteData(Stream: TStream); var i: Integer; img: TPngObject; btmp: TBitmap; begin // inherited WriteData(Stream); img:=TPngObject.Create; img.CompressionLevel:=9; img.Filters:=[pfNone, pfSub, pfUp, pfAverage, pfPaeth]; btmp:=TBitmap.Create; for i:=0 to Count-1 do begin btmp.Width:=0; btmp.Height:=0; GetBitmap(i,btmp); img.Assign(btmp); img.SaveToStream(Stream); end; btmp.Free; img.Free; end; initialization RegisterClass(TPngImageList); end.
unit GameForm; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX_Types, FMX_Controls, FMX_Forms, FMX_Dialogs, FMX_Grid, FMX_Layouts, FMX_Ani, GameXOImpl, XOPoint; type TfrmGame = class(TForm) pnlNotification: TPanel; pnlGamePane: TPanel; glButtons: TGridLayout; f11: TButton; f12: TButton; f13: TButton; f21: TButton; f22: TButton; f23: TButton; f31: TButton; f32: TButton; f33: TButton; RoundAnimationf11: TFloatAnimation; Panel1: TPanel; btnPlayX: TButton; btnplayO: TButton; lblNotification: TLabel; procedure btnPlayXClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnplayOClick(Sender: TObject); procedure FieldClick(Sender: TObject); private { Private declarations } FGame: TGameXOImpl; protected procedure ClearSurface(); procedure PerformComputerTurn(); procedure AnimeThePoint (Point:TXOPoint); public { Public declarations } end; var frmGame: TfrmGame; implementation {$R *.lfm} { TForm1 } procedure TfrmGame.AnimeThePoint(Point: TXOPoint); var Cmp: TComponent; Anim: TFloatAnimation; begin Cmp := frmGame.FindComponent('RoundAnimationf'+inttostr(Point.X+1)+inttostr(Point.Y+1)); if (Cmp<>nil) then begin Anim:=Cmp as TFloatAnimation; Anim.Start(); end; end; procedure TfrmGame.btnplayOClick(Sender: TObject); begin ClearSurface(); FGame.StartGame('O'); PerformComputerTurn(); end; procedure TfrmGame.btnPlayXClick(Sender: TObject); begin ClearSurface(); FGame.StartGame('X'); end; procedure TfrmGame.ClearSurface; var i:integer; currButt:TButton; begin lblNotification.Text := 'So, who will be a winner?'; for i := 0 to glButtons.ChildrenCount-1 do begin CurrButt := glButtons.Children[i] as TButton; CurrButt.Text:='?'; end; end; procedure TfrmGame.FieldClick(Sender: TObject); var button: TButton; Move: TXOPoint; Result: integer; begin button := Sender as TButton; if (button.Text <> '?') then begin lblNotification.Text := 'CELL IS OCCUPIED'; exit; end; Move := TXOPoint.Create(0,0); Move.X := StrToInt(button.Name[2])-1; Move.Y := StrToInt(button.Name[3])-1; button.Text := FGame.PlayerSign; AnimeThePoint(Move); FGame.PlayTurn(Move); lblNotification.Text := ''; Result:=FGame.CheckGameIsCompleted(FGame.PlayerSign); case Result of -1: begin lblNotification.Text := 'You: ('+IntToStr(Move.X)+','+IntToStr(Move.Y)+')'; PerformComputerTurn(); end; 0: begin lblNotification.Text := 'Good, noone. Once more?'; end; 1: begin lblNotification.Text := 'Greeting! You won'; end; end; end; procedure TfrmGame.FormCreate(Sender: TObject); begin self.FGame :=TGameXOImpl.Create(); end; procedure TfrmGame.PerformComputerTurn; var Turn: TXOPoint; Target: TComponent; Button: TButton; Result: integer; begin Turn := FGame.ComputerTurn; AnimeThePoint(Turn); Target := frmGame.FindComponent('f'+IntToStr(Turn.X+1)+IntToStr(Turn.Y+1)); Button := Target as TButton; Button.Text := FGame.ComputerSign; lblNotification.Text := lblNotification.Text + ' cmp:('+IntToStr(Turn.X)+','+IntToStr(Turn.Y)+')'; Result := FGame.CheckGameIsCompleted(FGame.ComputerSign); case Result of 0: begin lblNotification.Text := 'Good, noone. Once more?'; end; 1: begin lblNotification.Text := 'Heh! I WON!'; end; end; end; end.
unit DAO.Lancamentos; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Lancamentos; type TLancamentosDAO = class private FConexao : TConexao; public constructor Create; function GetID(): Integer; function Inserir(ALancamento: TLancamentos): Boolean; function Alterar(ALancamento: TLancamentos): Boolean; function Excluir(ALancamento: TLancamentos): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; function ExtratoLancamentos(aParam: Array of variant): TFDQuery; end; const TABLENAME = 'tblancamentos'; implementation { TLancamentosDAO } uses Control.Sistema; { TLancamentosDAO } function TLancamentosDAO.Alterar(ALancamento: TLancamentos): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DES_LANCAMENTO = :DES_LANCAMENTO, DAT_LANCAMENTO = :DAT_LANCAMENTO, ' + 'COD_ENTREGADOR = :COD_ENTREGADOR, COD_ENTREGADOR_ = :COD_ENTREGADOR_, DES_TIPO = :DES_TIPO, ' + 'VAL_LANCAMENTO = :VAL_LANCAMENTO, DOM_DESCONTO = :DOM_DESCONTO, DAT_DESCONTO = :DAT_DESCONTO, NUM_EXTRATO = :NUM_EXTRATO, ' + 'DOM_PERSISTIR = :DOM_PERSISTIR WHERE COD_LANCAMENTO = :COD_LANCAMENTO;',[ALancamento.Descricao, ALancamento.Data, ALancamento.Cadastro, ALancamento.Entregador ,ALancamento.Tipo, ALancamento.Valor, ALancamento.Desconto, ALancamento.DataDesconto, ALancamento.Extrato, ALancamento.Persistir, ALancamento.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TLancamentosDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TLancamentosDAO.Excluir(ALancamento: TLancamentos): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE COD_LANCAMENTO = :COD_LANCAMENTO;', [ALancamento.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentosDAO.ExtratoLancamentos(aParam: array of variant): TFDQuery; var fdQuery:TFDQuery; sSQL : String; begin fdQuery := FConexao.ReturnQuery; sSQL := 'select tblancamentos.cod_entregador as cod_entregador, tblancamentos.des_tipo as des_tipo, ' + 'sum(tblancamentos.val_lancamento) as val_total from ' + TABLENAME + ' where tblancamentos.dat_lancamento <= :data1 and tblancamentos.dom_desconto <> :dom ' + 'group by tblancamentos.cod_entregador, tblancamentos.des_tipo;'; fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(sSQL); fdQuery.ParamByName('data1').AsDate := aParam[0]; fdQuery.ParamByName('dom').AsString := 'S'; FDQuery.Open(); Result := FDQuery; end; function TLancamentosDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(COD_LANCAMENTO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentosDAO.Inserir(ALancamento: TLancamentos): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); ALancamento.Codigo := Self.GetID(); FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_LANCAMENTO, DES_LANCAMENTO, DAT_LANCAMENTO, COD_ENTREGADOR, ' + 'COD_ENTREGADOR_, DES_TIPO, VAL_LANCAMENTO, DOM_DESCONTO, DAT_DESCONTO, NUM_EXTRATO, DOM_PERSISTIR) ' + 'VALUES ' + '(:COD_LANCAMENTO, :DES_LANCAMENTO, :DAT_LANCAMENTO, :COD_ENTREGADOR, :COD_ENTREGADOR_, :DES_TIPO, ' + ':VAL_LANCAMENTO, :DOM_DESCONTO, :DAT_DESCONTO, :NUM_EXTRATO, :DOM_PERSISTIR);', [ALancamento.Codigo, ALancamento.Descricao, ALancamento.Data, ALancamento.Cadastro, ALancamento.Entregador ,ALancamento.Tipo, ALancamento.Valor, ALancamento.Desconto, ALancamento.DataDesconto, ALancamento.Extrato, ALancamento.Persistir]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentosDAO.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] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_LANCAMENTO = :COD_LANCAMENTO'); FDQuery.ParamByName('COD_LANCAMENTO').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('WHERE DES_LANCAMENTO LIKE :DES_LANCAMENTO'); FDQuery.ParamByName('DES_LANCAMENTO').AsString := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('WHERE DAT_LANCAMENTO = :DAT_LANCAMENTO'); FDQuery.ParamByName('WHERE DAT_LANCAMENTO').AsDate := aParam[1]; end; if aParam[0] = 'CADASTRO' then begin FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR'); FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1]; end; if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('WHERE NUM_EXTRATO LIKE :NUM_EXTRATO'); FDQuery.ParamByName('NUM_EXTRATO').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add(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.
unit cAtualizacaoCampoMySQL; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils, cFuncao, cAtualizacaoBancoDeDados; type TAtualizacaoCampoMySQL = class(TAtualizaBancoDados) private function CampoExisteNaTabela(aNomeTabela, aCampo:string):Boolean; procedure versao1; procedure versao2; procedure versao3; function ViewExiste(aNomeView: string): Boolean; function SPExiste(aNomeSP: string): Boolean; protected public constructor Create(aConexao: TFDConnection); destructor Destroy; override; end; implementation { TAtualizacaoCampoMySQL } var ver: Integer; function TAtualizacaoCampoMySQL.CampoExisteNaTabela(aNomeTabela, aCampo: string): Boolean; var Qry: TFDQuery; begin try Result := False; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT count(DISTINCT COLUMN_NAME) as ID '+ ' FROM INFORMATION_SCHEMA.COLUMNS '+ ' WHERE COLUMN_NAME = :Campo '+ ' AND TABLE_NAME = :NomeTabela'); Qry.ParamByName('NomeTabela').AsString := aNomeTabela; Qry.ParamByName('Campo').AsString := aCampo; Qry.Open; if Qry.FieldByName('ID').AsInteger>0 then Result := True; finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry) end; end; function TAtualizacaoCampoMySQL.ViewExiste(aNomeView :string): Boolean; var Qry: TFDQuery; begin try Result := False; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT COUNT(*)as ID FROM INFORMATION_SCHEMA.VIEWS '+ ' where TABLE_NAME = :view'); Qry.ParamByName('view').AsString := aNomeView; Qry.Open; if Qry.FieldByName('ID').AsInteger>0 then Result := True; finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry) end; end; function TAtualizacaoCampoMySQL.SPExiste(aNomeSP :string): Boolean; var Qry: TFDQuery; begin try Result := False; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT COUNT(*)as ID '+ ' FROM INFORMATION_SCHEMA.ROUTINES '+ ' where ROUTINE_NAME =:aNomeSP '); Qry.ParamByName('aNomeSP').AsString := aNomeSP; Qry.Open; if Qry.FieldByName('ID').AsInteger>0 then Result := True; finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry) end; end; constructor TAtualizacaoCampoMySQL.Create(aConexao: TFDConnection); var i:integer; begin ver:=2; ConexaoDB := aConexao; //Adicionar Nivel de cargo para utilizar como ordenação if not CampoExisteNaTabela('tb_parametro_sistema','versao_ajuste_bd') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_parametro_sistema ADD versao_ajuste_bd INT DEFAULT 1 NOT NULL;'); ExecutaDiretoBancoDeDados('update tb_parametro_sistema set versao_ajuste_bd = 1;'); end; i := StrToInt(TFuncao.SqlValor('select versao_ajuste_bd as VALOR from tb_parametro_sistema ',ConexaoDB)); case i of 1: versao1; 2: versao2; 3: versao3; end; end; destructor TAtualizacaoCampoMySQL.Destroy; begin inherited; end; procedure TAtualizacaoCampoMySQL.versao1; begin //Adicionar Nivel de cargo para utilizar como ordenação if not CampoExisteNaTabela('tb_cargo','nivel') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_cargo ADD nivel INT DEFAULT 0 NOT NULL;'); end; //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_recibo','cod_congregacao') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_recibo ADD cod_congregacao int(11) NULL;'); end; //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_congregacao','cod_dirigente') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_congregacao ADD cod_dirigente int(11) NULL;'); end; //Adicionar código da pessoa no dizimo if not CampoExisteNaTabela('tb_dizimista','cod_pessoa') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_dizimista ADD cod_pessoa INT(11) NULL;'); ExecutaDiretoBancoDeDados('ALTER TABLE tb_dizimista ADD CONSTRAINT '+ ' tb_dizimista_tb_pessoa_fk FOREIGN KEY (cod_pessoa) REFERENCES tb_pessoa(cod_pessoa);'); end; //Adicionar SIGLA DO DEPARTAMENTO if not CampoExisteNaTabela('tb_departamento','sigla') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_departamento ADD sigla varchar(10) NULL;'); end; if not CampoExisteNaTabela('tipo_saida','id') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tipo_saida CHANGE codigo id int(11) auto_increment NOT NULL ;'); end; if not ViewExiste('v_dizimista_total_mes_ano') then begin ExecutaDiretoBancoDeDados('create or replace view '+ ' `v_dizimista_total_mes_ano` as select '+ ' `x`.`nome` as `nome`, '+ ' sum(`x`.`valor`) as `valor`, '+ ' `x`.`nro_mes` as `nro_mes`, '+ ' `x`.`ano` as `ano` '+ ' from '+ ' ( '+ ' select `igreja`.`tb_dizimista`.`nome` as `nome`, '+ ' `igreja`.`tb_dizimista`.`data` as `data`, '+ ' `igreja`.`tb_dizimista`.`valor` as `valor`, '+ ' month(`igreja`.`tb_dizimista`.`data`) as `nro_mes`, '+ ' year(`igreja`.`tb_dizimista`.`data`) as `ano` '+ ' from '+ ' `igreja`.`tb_dizimista`) `x` '+ ' group by '+ ' `x`.`nome`, '+ ' `x`.`nro_mes`, '+ ' `x`.`ano` '+ ' order by '+ ' `x`.`nome`, '+ ' `x`.`nro_mes`'); end; if not ViewExiste('v_lancamentos_total') then begin ExecutaDiretoBancoDeDados('create or replace view v_lancamentos_total as '+ ' select * from '+ ' (SELECT sum(t.valor)as valor, t.tipo,t.dta_movimento as data, '+ ' year(t.dta_movimento) AS ano '+ ' ,month(t.dta_movimento) AS mes '+ ' ,week(t.dta_movimento) as semana '+ ' ,weekday(t.dta_movimento) as dia '+ ' FROM tb_tesouraria t join tb_parametro_sistema a '+ ' on a.cod_congregacao = t.cod_congregacao '+ ' group by year(t.dta_movimento),month(t.dta_movimento),t.tipo,t.dta_movimento)x'); end; if not ViewExiste('v_dizimistas') then begin ExecutaDiretoBancoDeDados('create or replace view v_dizimistas as '+ ' SELECT t.cod_dizimo, t.cod_talao, t.cod_cheque, t.nome, t.valor, t.`data`, t.cargo, t.cod_congregacao, '+ ' 0 as nivel,coalesce(y.nro_rol,0) as rol '+ ' FROM tb_dizimista t inner join tb_parametro_sistema a on a.cod_congregacao = t.cod_congregacao '+ ' left join tb_pessoa y on y.nome_pessoa = t.nome '+ ' and t.cargo = '+QuotedStr('MEMBRO' )+' '+ ' union all '+ ' select e.cod_dizimo,e.cod_talao,e.cod_cheque, c.nome_pessoa as nome,e.valor,e.`data` '+ ' ,"DIRIGENTE",c.cod_congregacao,100,c.nro_rol '+ ' from tb_congregacao a '+ ' inner join tb_parametro_sistema b on a.cod_congregacao = b.cod_congregacao '+ ' left join tb_pessoa c on c.cod_pessoa = a.cod_dirigente '+ ' inner join tb_obreiro_cargo d on d.COD_MEMBRO = c.cod_pessoa '+ ' left join tb_dizimista e on e.NOME = c.nome_pessoa and e.CARGO = d.CARGO '+ ' union all '+ ' select c.cod_dizimo,c.cod_talao,c.cod_cheque,a.NOME,c.valor,c.`data` '+ ' ,a.CARGO,a.COD_CONGREGACAO,x.nivel,y.nro_rol '+ ' from tb_obreiro_cargo a '+ ' inner join tb_cargo x on x.cod_cargo = a.COD_CARGO '+ ' inner join tb_pessoa y on y.cod_pessoa = a.cod_membro '+ ' inner join tb_parametro_sistema b on a.COD_CONGREGACAO = b.cod_congregacao '+ ' left join tb_dizimista c on c.cod_congregacao = a.COD_CONGREGACAO and c.cargo = a.CARGO and c.nome = a.NOME '+ ' where a.cod_membro <> (select c.cod_pessoa from tb_congregacao a '+ ' inner join tb_parametro_sistema b on a.cod_congregacao = b.cod_congregacao '+ ' left join tb_pessoa c on c.cod_pessoa = a.cod_dirigente) '+ ' order by nivel desc '); end; //Adicionar SIGLA DO DEPARTAMENTO if not CampoExisteNaTabela('tb_classe_professor','cod_congregacao') then begin ExecutaDiretoBancoDeDados('drop table tb_classe_professor'); ExecutaDiretoBancoDeDados('CREATE TABLE `tb_classe_professor` ( '+ ' `codigo` int(11) NOT NULL AUTO_INCREMENT, '+ ' `cod_professor` int(11) DEFAULT NULL, '+ ' `professor` varchar(50) DEFAULT NULL, '+ ' `cod_classe` int(11) DEFAULT NULL, '+ ' `classe` varchar(20) DEFAULT NULL, '+ ' `cod_congregacao` int(11) NOT NULL, '+ ' PRIMARY KEY (`codigo`), '+ ' KEY `tb_classe_professor_tb_classe_fk` (`cod_classe`), '+ ' KEY `tb_classe_professor_tb_professor_fk` (`cod_professor`) '+ ' ) ENGINE=InnoDB DEFAULT CHARSET=latin1;'); end; //Adicionar código de congregação na tb_classe_aluno if not CampoExisteNaTabela('tb_classe_aluno','cod_congregacao') then begin ExecutaDiretoBancoDeDados('drop table tb_classe_aluno'); ExecutaDiretoBancoDeDados('CREATE TABLE `tb_classe_aluno` ( '+ ' `codigo` int(11) NOT NULL AUTO_INCREMENT, '+ ' `cod_aluno` int(11) DEFAULT NULL, '+ ' `aluno` varchar(50) DEFAULT NULL, '+ ' `cod_classe` int(11) DEFAULT NULL, '+ ' `classe` varchar(50) DEFAULT NULL, '+ ' `cod_congregacao` int(11) DEFAULT NULL, '+ ' PRIMARY KEY (`codigo`), '+ ' KEY `tb_classe_aluno_tb_classe_fk` (`cod_classe`), '+ ' CONSTRAINT `tb_classe_aluno_tb_classe_fk` FOREIGN KEY (`cod_classe`) REFERENCES `tb_classe` (`cod_classe`) '+ ' )'); end; if not SPExiste('chamada_ebd') then begin ExecutaDiretoBancoDeDados('CREATE DEFINER=`root`@`localhost` '+ ' PROCEDURE `igreja`.`chamada_ebd`(cod_cong int, cod_class int, dta_chamada datetime) '+ ' BEGIN '+ ' INSERT INTO tb_ebd_chamada '+ ' (cod_aluno, cod_classe, dta_aula, cod_congregacao) '+ ' select cod_aluno,cod_classe, dta_chamada,cod_congregacao from tb_classe_aluno '+ ' where cod_congregacao =cod_cong and cod_classe =cod_class '+ ' and cod_aluno not in (select x.cod_aluno from tb_ebd_chamada x '+ ' where date(x.dta_aula) = date(dta_chamada) and x.cod_classe =cod_class ); '+ 'END'); end; if not SPExiste('aula_ebd') then begin ExecutaDiretoBancoDeDados('CREATE DEFINER=`root`@`localhost` '+ ' PROCEDURE `igreja`.`aula_ebd`(cod_cong int, cod_class int, '+ ' dta_aul datetime,nro_lic int,tlic varchar(100) ,trev varchar(100)) '+ ' begin '+ ' declare tri int(11); '+ ' set tri = (select trimestre '+ ' from tb_ebd_calendario '+ ' where date(dta_inicio) <= date(dta_aul) and date(dta_fim) >=date(dta_aul)) ; '+ ' IF NOT exists( SELECT a.codigo '+ ' FROM tb_ebd_aula a where a.cod_classe =cod_class '+ ' and date(a.dta_aula) = date(dta_aul) '+ ' and a.cod_congregacao =cod_cong ) '+ ' THEN '+ ' INSERT INTO tb_ebd_aula '+ ' ( dta_aula, cod_classe, qtd_biblias, qtd_revistas, trimestre, cod_congregacao, '+ ' nro_licao, titulo_licao, titulo_revista) '+ ' VALUES( dta_aul, cod_class, 0, 0, tri, cod_cong, nro_lic, tlic, trev); '+ ' END IF; '+ 'END;'); end; if not CampoExisteNaTabela('tipo_saida','id') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tipo_saida CHANGE codigo id int(11) auto_increment NOT NULL ;'); end; //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_tesouraria','cod_tipo_saida') then begin ExecutaDiretoBancoDeDados('ALTER TABLE `igreja`.`tb_tesouraria` '+ ' ADD COLUMN `cod_tipo_saida` INT(11) NULL AFTER `situacao`;'); end; //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_igreja','email_secretaria') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_igreja ADD email_secretaria varchar(50) NULL;'); ExecutaDiretoBancoDeDados('ALTER TABLE tb_igreja ADD cep varchar(20) NULL;'); end; if not CampoExisteNaTabela('tipo_culto','id') then begin ExecutaDiretoBancoDeDados('ALTER TABLE `igreja`.`tipo_culto` '+ ' CHANGE COLUMN `codigo` `id` INT(11) NOT NULL AUTO_INCREMENT ;'); end; if not CampoExisteNaTabela('tb_tesouraria','id_fornecedor') then begin ExecutaDiretoBancoDeDados('ALTER TABLE `tb_tesouraria` '+ ' ADD COLUMN `id_centro_custo` INT NULL AFTER `cod_tipo_saida`, '+ ' ADD COLUMN `id_tipo_lancamento` INT NULL AFTER `id_centro_custo`, '+ ' ADD COLUMN `id_forma_pagamento` INT NULL AFTER `id_tipo_lancamento`, '+ ' ADD COLUMN `id_fornecedor` INT NULL AFTER `id_forma_pagamento`, '+ ' ADD COLUMN `id_tipo_culto` INT NULL AFTER `id_fornecedor`, '+ ' ADD INDEX `tb_tesouraria_centro_custo_fk_idx` (`id_centro_custo` ASC), '+ ' ADD INDEX `tb_tesouraria_tb_tipo_lancamento_fk_idx` (`id_tipo_lancamento` ASC), '+ ' ADD INDEX `tb_tesouratia_forma_pgto_fk_idx` (`id_forma_pagamento` ASC), '+ ' ADD INDEX `tb_tesouraria_fornecedor_fk_idx` (`id_fornecedor` ASC), '+ ' ADD INDEX `tb_tesouraria_tipo_culto_fk_idx` (`id_tipo_culto` ASC); '+ ' ; '+ ' ALTER TABLE `tb_tesouraria` '+ ' ADD CONSTRAINT `tb_tesouraria_centro_custo_fk` '+ ' FOREIGN KEY (`id_centro_custo`) '+ ' REFERENCES `centro_custo` (`id`) '+ ' ON DELETE NO ACTION '+ ' ON UPDATE NO ACTION, '+ ' ADD CONSTRAINT `tb_tesouraria_tb_tipo_lancamento_fk` '+ ' FOREIGN KEY (`id_tipo_lancamento`) '+ ' REFERENCES `tipo_lancamento` (`id`) '+ ' ON DELETE NO ACTION '+ ' ON UPDATE NO ACTION, '+ ' ADD CONSTRAINT `tb_tesouraria_forma_pgto_fk` '+ ' FOREIGN KEY (`id_forma_pagamento`) '+ ' REFERENCES `forma_pagamento` (`id`) '+ ' ON DELETE NO ACTION '+ ' ON UPDATE NO ACTION, '+ ' ADD CONSTRAINT `tb_tesouraria_fornecedor_fk` '+ ' FOREIGN KEY (`id_fornecedor`) '+ ' REFERENCES `fornecedor` (`id`) '+ ' ON DELETE NO ACTION '+ ' ON UPDATE NO ACTION, '+ ' ADD CONSTRAINT `tb_tesouraria_tipo_culto_fk` '+ ' FOREIGN KEY (`id_tipo_culto`) '+ ' REFERENCES `tipo_culto` (`id`) '+ ' ON DELETE NO ACTION '+ ' ON UPDATE NO ACTION; '); end; //Adicionar valores de meta percental e fixa if not CampoExisteNaTabela('tb_congregacao','percentual_central') then begin ExecutaDiretoBancoDeDados('ALTER TABLE `tb_congregacao` '+ ' ADD COLUMN `percentual_central` VARCHAR(1) NULL AFTER `cod_dirigente`, '+ ' ADD COLUMN `percentual_valor` DOUBLE NULL AFTER `percentual_central`, '+ ' ADD COLUMN `meta_central` VARCHAR(1) NULL AFTER `percentual_valor`, '+ ' ADD COLUMN `meta_valor` DOUBLE NULL AFTER `meta_central`;'); ExecutaDiretoBancoDeDados('update tb_congregacao set percentual_central = 0,percentual_valor=0,meta_central=0,meta_valor=0;'); end; { //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_classe_aluno','tb_classe_aluno_tb_classe_fk') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_classe_aluno ADD CONSTRAINT tb_classe_aluno_tb_classe_fk FOREIGN KEY (cod_classe) REFERENCES tb_classe(cod_classe);'); end; //Adicionar código da congregação no recibo if not CampoExisteNaTabela('tb_classe_professor','tb_classe_professor_tb_classe_fk') then begin ExecutaDiretoBancoDeDados('ALTER TABLE tb_classe_professor ADD CONSTRAINT tb_classe_professor_tb_classe_fk FOREIGN KEY (cod_classe) REFERENCES tb_classe(cod_classe);'); end; } //ALTER TABLE igreja.tb_classe_professor MODIFY COLUMN professor varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL; //ALTER TABLE igreja.tb_classe_professor MODIFY COLUMN classe varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL; if ver > 1 then begin ExecutaDiretoBancoDeDados('update tb_parametro_sistema set versao_ajuste_bd = 2;'); versao2; end; end; procedure TAtualizacaoCampoMySQL.versao2; begin //ADICIONAR BLOCOS DE SQL SOMENTE NA 2 AGORA if ver > 2 then begin ExecutaDiretoBancoDeDados('update tb_parametro_sistema set versao_ajuste_bd = 3;'); versao3; end; end; procedure TAtualizacaoCampoMySQL.versao3; begin end; end.
unit FFSMaskEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, lmdCustomEdit, lmdcaret, lmdclass, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDBaseEdit, lmdGraph; const MapMax = 25; type TFFSCustomMaskEdit = class(TLMDCustomEdit) private FCurrentPos: integer; FMasked: boolean; procedure SetCurrentPos(const Value: integer); private FMap: array[1..MapMax] of byte; FMapLen : integer; FMask:string; FNoMaskText:string; FShortMask:string; property CurrentPos:integer read FCurrentPos write SetCurrentPos; procedure FormatMask; procedure SetMask(const Value: string); procedure SetNoMaskText(const Value: string); procedure ApplyMask; procedure WMLButtonUp (var Msg : TWMLButtonUp); message WM_LBUTTONUP; { Private declarations } protected { Protected declarations } procedure GetCommandKey(var KeyCode: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; property Masked:boolean read FMasked; property Mask:string read FMask write SetMask; property NoMaskText:string read FNoMaskText write SetNoMaskText; public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; end; TFFSMaskEdit = class(TFFSCustomMaskEdit) published { Published declarations } property Alignment; property Masked; property Mask; property NoMaskText; property Text; property CustomButtons; property CustomButtonStyle; property CustomButtonWidth; property ReadOnly; property PasswordChar; end; procedure Register; implementation uses ffsutils; procedure Register; begin RegisterComponents('FFS Data Entry', [TFFSMaskEdit]); end; { TFFSMaskEdit } constructor TFFSCustomMaskEdit.create(AOwner: TComponent); begin inherited; height := 18; width := 100; color := clWindow; Bevel.Mode := bmCustom; Transparent := true; parentcolor := true; bevel.Mode := bmEdge; bevel.EdgeStyle := etRaisedInner; bevel.BorderSides := [fsbottom]; Mask := ''; FCurrentPos := 1; end; destructor TFFSCustomMaskEdit.destroy; begin inherited; end; procedure TFFSCustomMaskEdit.GetCommandKey(var KeyCode: Word; Shift: TShiftState); var oldsel, i,j : Integer; l : integer; begin if not masked then begin inherited; exit; end; l := length(FNoMaskText); oldSel := SelLength; if not Enabled then exit; Case KeyCode of VK_HOME : CurrentPos := 1; VK_END : CurrentPos := FMapLen + 1; VK_LEFT : CurrentPos := CurrentPos - 1; VK_RIGHT : if CurrentPos <= l then CurrentPos := CurrentPos + 1; VK_DELETE: if currentPos <= l then begin FNoMaskText[CurrentPos] := ' '; ApplyMask; CurrentPos := CurrentPos; end; VK_BACK : if (l > 0) and (currentpos > 1) then begin FNoMaskText[CurrentPos-1] := ' '; ApplyMask; CurrentPos := CurrentPos - 1; end; VK_ESCAPE : SelLength := 0; { Ord('X') : if emCtrl in LMDApplication.EditMode then begin CopyToClipboard; for i := FSelStart to (FSelStart+SelLength-1) do begin for j := 1 to FMapLen do begin if i = FMap[j] then begin FNoMaskText[j] := ' '; break; end; end; end; // CurrentPos := ApplyMask; KeyCode := 0; end;} { Ord('V') : if emCtrl in LMDApplication.EditMode then begin PasteFromClipBoard; KeyCode := 0; end; } //sets Strg - C to CopyToClipBoard Ord('C') : if emCtrl in LMDApplication.EditMode then begin CopyToClipboard; KeyCode := 0; end; //sets Strg - A to SelectAll Ord('A') : if emCtrl in LMDApplication.EditMode then begin SelectAll; KeyCode := 0; end; end; if oldsel <> SelLength then DrawEditText(FCurrentChar); end; procedure TFFSCustomMaskEdit.FormatMask; var x : integer; begin // clear the mask FShortMask := ''; for x := 1 to MapMax do FMap[x] := 0; FMapLen := 0; // now map it out for x := 1 to Length(FMask) do begin if FMask[x] in ['_','9','A'] then begin inc(FMapLen); FMap[FMapLen] := x; FShortMask := FShortMask + FMask[x]; end; end; ApplyMask; end; procedure TFFSCustomMaskEdit.SetMask(const Value: string); begin FMask := Value; FMasked := FMask > ''; AutoSelect := not Masked; FormatMask; CurrentPos := 1; end; procedure TFFSCustomMaskEdit.KeyPress(var Key: Char); var ok : boolean; s : string; l : integer; effPos : integer; valid : boolean; begin if Masked then begin if (key < #32) then begin key := #0; exit; end; s := NoMaskText; l := Length(s); if l > 0 then begin if FCurrentPos <= l then effpos := FCurrentPos // overwrite the current char else EffPos := FMapLen; // we're at the end so write the last char again // now check the short map to see if the key is valid for the spot valid := false; case FShortMask[EffPos] of '_' : valid := true; 'A' : valid := key in ['A'..'Z','a'..'z']; '9' : valid := key in ['0'..'9']; end; if valid then begin s[EffPos] := key; NoMaskText := s; CurrentPos := CurrentPos + 1; // we can increment this always because it will be set back if it is too big end; end; key := #0; end; end; procedure TFFSCustomMaskEdit.ApplyMask; var x,l : integer; s : string; begin if csLoading in componentstate then exit; // make sure the mask is filled if masked then begin l := Length(FNoMaskText); if l < FMapLen then FNoMaskText := FNoMaskText + repeatchar(' ',FMapLen - l); l := Length(FNoMaskText); if l > FMapLen then FNoMaskText := system.copy(FNoMaskText,1,FMapLen); s := FMask; l := length(FNoMaskText); for x := 1 to l do s[FMap[x]] := FNoMaskText[x]; for x := l + 1 to FMapLen do s[FMap[x]] := ' '; if csdesigning in componentstate then exit; Text := s; end else Text := FNoMaskText; end; procedure TFFSCustomMaskEdit.SetNoMaskText(const Value: string); begin FNoMaskText := Value; ApplyMask; end; procedure TFFSCustomMaskEdit.SetCurrentPos(const Value: integer); begin if Value > FMapLen then FCurrentPos := FMapLen + 1 else if Value < 1 then FCurrentPos := 1 else FCurrentPos := Value; if FCurrentPos > FMapLen then CurrentChar := FMap[FMapLen] + 1 else CurrentChar := FMap[FCurrentPos]; end; procedure TFFSCustomMaskEdit.WMLButtonUp(var Msg: TWMLButtonUp); var x : integer; begin inherited; if masked then begin x := 1; for x := 1 to FMapLen do if FMap[x] > CurrentChar then break; if x <= FMapLen then CurrentPos := x-1 else CurrentPos := x; end; end; end.
unit TTreeNodeForTestsWordsPack; // Модуль: "w:\common\components\rtl\Garant\DUnit_Script_Support\TTreeNodeForTestsWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TTreeNodeForTestsWordsPack" MUID: (55C9F3800372) {$Include w:\common\components\rtl\Garant\DUnit_Script_Support\dsDefine.inc} interface {$If Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ComCtrls , tfwClassLike , tfwScriptingInterfaces , TypInfo , tfwAxiomaticsResNameGetter , FolderSupport , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *55C9F3800372impl_uses* //#UC END# *55C9F3800372impl_uses* ; type TkwPopTreeNodeIsNodeFolder = {final} class(TtfwClassLike) {* Слово скрипта pop:TreeNode:IsNodeFolder } private function IsNodeFolder(const aCtx: TtfwContext; aTreeNode: TTreeNode): Boolean; {* Реализация слова скрипта pop:TreeNode:IsNodeFolder } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopTreeNodeIsNodeFolder TTTreeNodeForTestsWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TTTreeNodeForTestsWordsPackResNameGetter function TkwPopTreeNodeIsNodeFolder.IsNodeFolder(const aCtx: TtfwContext; aTreeNode: TTreeNode): Boolean; {* Реализация слова скрипта pop:TreeNode:IsNodeFolder } //#UC START# *55C9F3B6011B_55C9F3B6011B_512F3FCB02F3_Word_var* //#UC END# *55C9F3B6011B_55C9F3B6011B_512F3FCB02F3_Word_var* begin //#UC START# *55C9F3B6011B_55C9F3B6011B_512F3FCB02F3_Word_impl* Result := FolderSupport.IsNodeFolder(aTreeNode); //#UC END# *55C9F3B6011B_55C9F3B6011B_512F3FCB02F3_Word_impl* end;//TkwPopTreeNodeIsNodeFolder.IsNodeFolder class function TkwPopTreeNodeIsNodeFolder.GetWordNameForRegister: AnsiString; begin Result := 'pop:TreeNode:IsNodeFolder'; end;//TkwPopTreeNodeIsNodeFolder.GetWordNameForRegister function TkwPopTreeNodeIsNodeFolder.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopTreeNodeIsNodeFolder.GetResultTypeInfo function TkwPopTreeNodeIsNodeFolder.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopTreeNodeIsNodeFolder.GetAllParamsCount function TkwPopTreeNodeIsNodeFolder.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TTreeNode)]); end;//TkwPopTreeNodeIsNodeFolder.ParamsTypes procedure TkwPopTreeNodeIsNodeFolder.DoDoIt(const aCtx: TtfwContext); var l_aTreeNode: TTreeNode; begin try l_aTreeNode := TTreeNode(aCtx.rEngine.PopObjAs(TTreeNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aTreeNode: TTreeNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsNodeFolder(aCtx, l_aTreeNode)); end;//TkwPopTreeNodeIsNodeFolder.DoDoIt class function TTTreeNodeForTestsWordsPackResNameGetter.ResName: AnsiString; begin Result := 'TTreeNodeForTestsWordsPack'; end;//TTTreeNodeForTestsWordsPackResNameGetter.ResName {$R TTreeNodeForTestsWordsPack.res} initialization TkwPopTreeNodeIsNodeFolder.RegisterInEngine; {* Регистрация pop_TreeNode_IsNodeFolder } TTTreeNodeForTestsWordsPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(TTreeNode)); {* Регистрация типа TTreeNode } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit cb_Main; {$I ProjectDefine.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, l3Types, Mask, ToolEdit; type TMainForm = class(TForm) btnStart: TButton; ProgressBar: TProgressBar; lblDisplay: TLabel; rbUpdate: TRadioButton; rbCreate: TRadioButton; lblRemoteCacheDir: TLabel; deRemoteCacheDir: TDirectoryEdit; cbDocs: TCheckBox; cbEditions: TCheckBox; cbStruct: TCheckBox; rbExternal: TRadioButton; cbOneDoc: TCheckBox; edOneDoc: TEdit; rbCleanupCache: TRadioButton; rbService: TRadioButton; cbUpdateTables: TCheckBox; procedure btnStartClick(Sender: TObject); procedure RadiobuttonClick(Sender: TObject); private { Private declarations } procedure DoProgress(aState: Byte; aValue: Long; const aMsg: String = ''); procedure DoSomeServiceStuff; public { Public declarations } end; var MainForm: TMainForm; implementation uses l3Interfaces, daSchemeConsts, daInterfaces, ddAutolinkCache, dtIntf, dt_Sab, dt_LinkServ, Dt_ReNum, dt_Const, dt_Doc, cb_Misc; {$R *.dfm} procedure TMainForm.DoProgress(aState: Byte; aValue: Long; const aMsg: String = ''); begin case aState of piStart: begin ProgressBar.Visible := True; lblDisplay.Visible := True; lblDisplay.Caption := aMsg; ProgressBar.Max := aValue; ProgressBar.Position := 0; end; piCurrent: begin ProgressBar.Position := aValue; end; piEnd: begin lblDisplay.Caption := ''; ProgressBar.Position := ProgressBar.Max; end; end; Application.ProcessMessages; end; procedure TMainForm.btnStartClick(Sender: TObject); var I: Integer; l_DocID: Integer; l_Sab: ISab; begin if rbExternal.Checked and ((deRemoteCacheDir.Text = '') or not DirectoryExists(deRemoteCacheDir.Text)) then begin MessageDlg('Укажите существующую директорию на диске', mtError, [mbOK], 0); FocusControl(deRemoteCacheDir); Exit; end; btnStart.Enabled := False; try Application.ProcessMessages; if rbUpdate.Checked then begin if not cbOneDoc.Checked then UpdateAutolinkCache(DoProgress, cbUpdateTables.Checked) else begin l_DocID := StrToIntDef(edOneDoc.Text, -1); if l_DocID > 0 then begin l_DocID := LinkServer(CurrentFamily).Renum.ConvertToRealNumber(l_DocID); if l_DocID <> cUndefDocID then begin l_Sab := MakeValueSet(DocumentServer(CurrentFamily).FileTbl, fId_Fld, @l_DocID, 1); BuildActualDocsCache(DoProgress, l_Sab, cbUpdateTables.Checked); BuildEditionsCache(DoProgress, l_Sab, cbUpdateTables.Checked); BuildStructCache(DoProgress, l_Sab); end else MessageDlg('Такого документа нет в базе', mtError, [mbOK], 0); end else MessageDlg('Неверный ID документа', mtError, [mbOK], 0); end; end else if rbCreate.Checked then begin if cbDocs.Checked then BuildActualDocsCache(DoProgress, nil, True); if cbEditions.Checked then BuildEditionsCache(DoProgress, nil, True); if cbStruct.Checked then BuildStructCache(DoProgress); TouchAutolinkCache; end else if rbExternal.Checked then MakeRemoteAutolinkCache(deRemoteCacheDir.Text) else if rbCleanupCache.Checked then CleanupAutolinkCache(DoProgress) else if rbService.Checked then DoSomeServiceStuff else MessageDlg('Нереализованный функционал', mtError, [mbOk], 0); finally btnStart.Enabled := True; end; end; procedure TMainForm.DoSomeServiceStuff; begin UpcaseNumbersInCache; end; procedure TMainForm.RadiobuttonClick(Sender: TObject); begin cbDocs.Enabled := rbCreate.Checked; cbEditions.Enabled := rbCreate.Checked; cbStruct.Enabled := rbCreate.Checked; lblRemoteCacheDir.Enabled := rbExternal.Checked; deRemoteCacheDir.Enabled := rbExternal.Checked; cbOneDoc.Enabled := rbUpdate.Checked; edOneDoc.Enabled := cbOneDoc.Enabled and cbOneDoc.Checked; cbUpdateTables.Enabled := rbUpdate.Checked; end; end.
{=============================================================================== SimpleLog ©František Milt 2014-05-07 Version 1.2.3 ===============================================================================} unit SimpleLog; interface uses SysUtils, Classes, Contnrs, SyncObjs; type TLogEvent = procedure(Sender: TObject; LogText: String) of Object; {==============================================================================} { TSimpleLog // Class declaration } {==============================================================================} TSimpleLog = class(TObject) private fFormatSettings: TFormatSettings; fTimeOfCreation: TDateTime; fTimeFormat: String; fTimeSeparator: String; fBreaker: String; fHeaderText: String; fIndentNewLines: Boolean; fThreadLockedAdd: Boolean; fWriteToConsole: Boolean; fInMemoryLog: Boolean; fStreamToFile: Boolean; fStreamAppend: Boolean; fStreamFileName: String; fThreadLock: TCriticalSection; fInMemoryLogObj: TStringList; fExternalLogs: TObjectList; fStreamFile: TFileStream; fLogCounter: Integer; fForceTime: Boolean; fForcedTime: TDateTIme; fOnLog: TLogEvent; Function GetExternalLog(Index: Integer): TStrings; procedure SetStreamToFile(Value: Boolean); procedure SetStreamFileName(Value: String); Function GetInMemoryLogCount: Integer; Function GetExternalLogsCount: Integer; protected Function GetCurrentTime: TDateTime; Function GetTimeAsStr(Time: TDateTime; Format: String = '$'): String; virtual; procedure ProtectedAddLog(LogText: String; IndentCount: Integer = 0); virtual; public constructor Create; destructor Destroy; override; procedure DoIndentNewLines(var Str: String; IndentCount: Integer); virtual; procedure ThreadLock; virtual; procedure ThreadUnlock; virtual; procedure AddLog(Text: String); virtual; procedure AddLogForceTime(Text: String; Time: TDateTime); virtual; procedure AddLogNoTime(Text: String); virtual; procedure AddEmpty; virtual; procedure AddBreaker; virtual; procedure AddTimeStamp; virtual; procedure AddStartStamp; virtual; procedure AddEndStamp; virtual; procedure AddAppendStamp; virtual; procedure AddHeader; virtual; procedure ForceTimeSet(Time: TDateTime); procedure UnforceTimeSet; Function InMemoryLogGetLog(LogIndex: Integer): String; virtual; Function InMemoryLogGetAsText: String; virtual; procedure InMemoryLogClear; virtual; Function InMemoryLogSaveToFile(FileName: String; Append: Boolean = False): Boolean; virtual; Function InMemoryLogLoadFromFile(FileName: String; Append: Boolean = False): Boolean; virtual; Function ExternalLogAdd(ExternalLog: TStrings): Integer; virtual; Function ExternalLogIndexOf(ExternalLog: TStrings): Integer; virtual; Function ExternalLogRemove(ExternalLog: TStrings): Integer; virtual; procedure ExternalLogDelete(Index: Integer); virtual; property ExternalLogs[Index: Integer]: TStrings read GetExternalLog; default; published property TimeOfCreation: TDateTime read fTimeOfCreation; property TimeFormat: String read fTimeFormat write fTimeFormat; property TimeSeparator: String read fTimeSeparator write fTimeSeparator; property Breaker: String read fBreaker write fBreaker; property HeaderText: String read fHeaderText write fHeaderText; property IndentNewLines: Boolean read fIndentNewLines write fIndentNewLines; property ThreadLockedAdd: Boolean read fThreadLockedAdd write fThreadLockedAdd; property WriteToConsole: Boolean read fWriteToConsole write fWriteToConsole; property InMemoryLog: Boolean read fInMemoryLog write fInMemoryLog; property StreamToFile: Boolean read fStreamToFile write SetStreamToFile; property StreamAppend: Boolean read fStreamAppend write fStreamAppend; property StreamFileName: String read fStreamFileName write SetStreamFileName; property LogCounter: Integer read fLogCounter; property ForceTime: Boolean read fForceTime write fForceTime; property ForcedTime: TDateTIme read fForcedTime write fForcedTime; property InMemoryLogCount: Integer read GetInMemoryLogCount; property ExternalLogsCount: Integer read GetExternalLogsCount; property OnLog: TLogEvent read fOnLog write fOnLog; end; implementation uses Windows, StrUtils; {==============================================================================} { TSimpleLog // Class implementation } {==============================================================================} {------------------------------------------------------------------------------} { TSimpleLog // Constants } {------------------------------------------------------------------------------} const cHeaderLines = '================================================================================'; cLineLength = 80; //--- default settings --- def_TimeFormat = 'yyyy-mm-dd hh:nn:ss.zzz'; def_TimeSeparator = ' //: '; def_Breaker = '--------------------------------------------------------------------------------'; def_HeaderText = 'Created by SimpleLog 1.2.2, ©František Milt 2014-05-04'; def_ThreadLockedAdd = False; def_WriteToConsole = False; def_InMemoryLog = True; def_StreamToFile = False; def_StreamAppend = False; def_StreamFileName = ''; {------------------------------------------------------------------------------} { TSimpleLog // Private routines } {------------------------------------------------------------------------------} Function TSimpleLog.GetExternalLog(Index: Integer): TStrings; begin If (Index >= 0) and (Index < fExternalLogs.Count) then Result := TStrings(fExternalLogs[Index]) else raise exception.Create('TSimpleLog.GetExternalLog(Index):' + sLineBreak + 'Index(' + IntToStr(Index) + ') out of bounds.'); end; //------------------------------------------------------------------------------ procedure TSimpleLog.SetStreamToFile(Value: Boolean); begin If fStreamToFile <> Value then If fStreamToFile then begin FreeAndNil(fStreamFile); fStreamToFile := Value; end else begin If FileExists(fStreamFileName) then fStreamFile := TFileStream.Create(fStreamFileName,fmOpenReadWrite or fmShareDenyWrite) else fStreamFile := TFileStream.Create(fStreamFileName,fmCreate or fmShareDenyWrite); If fStreamAppend then fStreamFile.Seek(0,soEnd) else fStreamFile.Size := 0; fStreamToFile := Value; end; end; //------------------------------------------------------------------------------ procedure TSimpleLog.SetStreamFileName(Value: String); begin If Value = '' then Value := ExtractFileName(ParamStr(0)) + '_' + GetTimeAsStr(fTimeOfCreation,'YYYY-MM-DD-HH-NN-SS') + '.log'; If not AnsiSameText(fStreamFileName,Value) then begin If fStreamToFile then begin fStreamFileName := Value; FreeAndNil(fStreamFile); If FileExists(fStreamFileName) then fStreamFile := TFileStream.Create(fStreamFileName,fmOpenReadWrite or fmShareDenyWrite) else fStreamFile := TFileStream.Create(fStreamFileName,fmCreate or fmShareDenyWrite); If fStreamAppend then fStreamFile.Seek(0,soEnd) else fStreamFile.Size := 0; end else fStreamFileName := Value; end; end; //------------------------------------------------------------------------------ Function TSimpleLog.GetInMemoryLogCount: Integer; begin Result := fInMemoryLogObj.Count; end; //------------------------------------------------------------------------------ Function TSimpleLog.GetExternalLogsCount: Integer; begin Result := fExternalLogs.Count; end; {------------------------------------------------------------------------------} { TSimpleLog // Protected routines } {------------------------------------------------------------------------------} Function TSimpleLog.GetCurrentTime: TDateTime; begin If ForceTime then Result := ForcedTime else Result := Now; end; //------------------------------------------------------------------------------ Function TSimpleLog.GetTimeAsStr(Time: TDateTime; Format: String = '$'): String; begin If Format <> '$' then DateTimeToString(Result,Format,Time,fFormatSettings) else DateTimeToString(Result,fTimeFormat,Time,fFormatSettings); end; //------------------------------------------------------------------------------ procedure TSimpleLog.ProtectedAddLog(LogText: String; IndentCount: Integer = 0); var i: Integer; Temp: String; begin If IndentNewLines then DoIndentNewLines(LogText,IndentCount); If fWriteToConsole and System.IsConsole then WriteLn(LogText); If fInMemoryLog then fInMemoryLogObj.Add(LogText); For i := 0 to (fExternalLogs.Count - 1) do TStrings(fExternalLogs[i]).Add(LogText); If fStreamToFile then begin Temp := LogText + sLineBreak; fStreamFile.WriteBuffer(PChar(Temp)^, Length(Temp) * SizeOf(Char)); end; Inc(fLogCounter); If Assigned(fOnLog) then fOnLog(Self,LogText); end; {------------------------------------------------------------------------------} { TSimpleLog // Public routines } {------------------------------------------------------------------------------} constructor TSimpleLog.Create; begin inherited Create; fTimeOfCreation := Now; fThreadLock := TCriticalSection.Create; fInMemoryLogObj := TStringList.Create; fExternalLogs := TObjectList.Create(False); TimeFormat := def_TimeFormat; TimeSeparator := def_TimeSeparator; Breaker := def_Breaker; HeaderText := def_HeaderText; ThreadLockedAdd := def_ThreadLockedAdd; WriteToConsole := def_WriteToConsole; InMemoryLog := def_InMemoryLog; StreamToFile := def_StreamToFile; StreamAppend := def_StreamAppend; StreamFileName := def_StreamFileName; GetLocaleFormatSettings(LOCALE_USER_DEFAULT,fFormatSettings); end; //------------------------------------------------------------------------------ destructor TSimpleLog.Destroy; begin If Assigned(fStreamFile) then FreeAndNil(fStreamFile); fExternalLogs.Free; fInMemoryLogObj.Free; fThreadLock.Free; inherited; end; //------------------------------------------------------------------------------ procedure TSimpleLog.DoIndentNewLines(var Str: String; IndentCount: Integer); begin If (IndentCount > 0) and AnsiContainsStr(Str,sLineBreak) then Str := AnsiReplaceStr(Str,sLineBreak,sLineBreak + StringOfChar(' ',IndentCount)); end; //------------------------------------------------------------------------------ procedure TSimpleLog.ThreadLock; begin fThreadLock.Enter; end; //------------------------------------------------------------------------------ procedure TSimpleLog.ThreadUnlock; begin fThreadLock.Leave; end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddLog(Text: String); begin AddLogForceTime(Text,GetCurrentTime); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddLogForceTime(Text: String; Time: TDateTime); var TimeStr: String; begin TimeStr := GetTimeAsStr(Time) + fTimeSeparator; If fThreadLockedAdd then begin fThreadLock.Enter; try ProtectedAddLog(TimeStr + Text,Length(TimeStr)); finally fThreadLock.Leave; end; end else ProtectedAddLog(TimeStr + Text,Length(TimeStr)); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddLogNoTime(Text: String); begin If fThreadLockedAdd then begin fThreadLock.Enter; try ProtectedAddLog(Text); finally fThreadLock.Leave; end; end else ProtectedAddLog(Text); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddEmpty; begin AddLogNoTime(''); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddBreaker; begin AddLogNoTime(fBreaker); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddTimeStamp; begin AddLogNoTime(fBreaker + sLineBreak + 'TimeStamp: ' + GetTimeAsStr(GetCurrentTime) + sLineBreak + fBreaker); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddStartStamp; begin AddLogNoTime(fBreaker + sLineBreak + GetTimeAsStr(GetCurrentTime) + ' - Starting log...' + sLineBreak + fBreaker); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddEndStamp; begin AddLogNoTime(fBreaker + sLineBreak + GetTimeAsStr(GetCurrentTime) + ' - Ending log.' + sLineBreak + fBreaker); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddAppendStamp; begin AddLogNoTime(fBreaker + sLineBreak + GetTimeAsStr(GetCurrentTime) + ' - Appending log...' + sLineBreak + fBreaker); end; //------------------------------------------------------------------------------ procedure TSimpleLog.AddHeader; var TempStrings: TStringList; i: Integer; begin TempStrings := TStringList.Create; try TempStrings.Text := HeaderText; For i := 0 to (TempStrings.Count - 1) do If Length(TempStrings[i]) < cLineLength then TempStrings[i] := StringOfChar(' ', (cLineLength - Length(TempStrings[i])) div 2) + TempStrings[i]; AddLogNoTime(cHeaderLines + sLineBreak + TempStrings.Text + cHeaderLines); finally TempStrings.Free; end; end; //------------------------------------------------------------------------------ procedure TSimpleLog.ForceTimeSet(Time: TDateTime); begin fForcedTime := Time; fForceTime := True; end; //------------------------------------------------------------------------------ procedure TSimpleLog.UnforceTimeSet; begin fForceTime := False; end; //------------------------------------------------------------------------------ Function TSimpleLog.InMemoryLogGetLog(LogIndex: Integer): String; begin If (LogIndex < 0) or (LogIndex >= fInMemoryLogObj.Count) then Result := '' else Result := fInMemoryLogObj[LogIndex]; end; Function TSimpleLog.InMemoryLogGetAsText: String; begin Result := fInMemoryLogObj.Text; end; //------------------------------------------------------------------------------ procedure TSimpleLog.InMemoryLogClear; begin fInMemoryLogObj.Clear; end; //------------------------------------------------------------------------------ Function TSimpleLog.InMemoryLogSaveToFile(FileName: String; Append: Boolean = False): Boolean; var FileStream: TFileStream; StringBuffer: String; begin Result := True; try If FileExists(FileName) then FileStream := TFileStream.Create(FileName,fmOpenReadWrite or fmShareDenyWrite) else FileStream := TFileStream.Create(FileName,fmCreate or fmShareDenyWrite); try If not Append then FileStream.Size := 0; StringBuffer := fInMemoryLogObj.Text; FileStream.Seek(0,soEnd); FileStream.WriteBuffer(PChar(StringBuffer)^,Length(StringBuffer) * SizeOf(Char)); finally FileStream.Free; end; except Result := False; end; end; //------------------------------------------------------------------------------ Function TSimpleLog.InMemoryLogLoadFromFile(FileName: String; Append: Boolean = False): Boolean; var FileStream: TFileStream; StringBuffer: String; begin Result := True; try FileStream := TFileStream.Create(FileName,fmOpenRead or fmShareDenyWrite); try If not Append then fInMemoryLogObj.Clear; FileStream.Position := 0; SetLength(StringBuffer,FileStream.Size div SizeOf(Char)); FileStream.ReadBuffer(PChar(StringBuffer)^,Length(StringBuffer) * SizeOf(Char)); fInMemoryLogObj.Text := fInMemoryLogObj.Text + StringBuffer; finally FileStream.Free; end; except Result := False; end; end; //------------------------------------------------------------------------------ Function TSimpleLog.ExternalLogAdd(ExternalLog: TStrings): Integer; begin Result := fExternalLogs.Add(ExternalLog); end; //------------------------------------------------------------------------------ Function TSimpleLog.ExternalLogIndexOf(ExternalLog: TStrings): Integer; begin Result := fExternalLogs.IndexOf(ExternalLog); end; //------------------------------------------------------------------------------ Function TSimpleLog.ExternalLogRemove(ExternalLog: TStrings): Integer; var Index: Integer; begin Result := -1; Index := fExternalLogs.IndexOf(ExternalLog); If Index >= 0 then Result := fExternalLogs.Remove(ExternalLog); end; //------------------------------------------------------------------------------ procedure TSimpleLog.ExternalLogDelete(Index: Integer); begin If (Index >= 0) and (Index < fExternalLogs.Count) then fExternalLogs.Delete(Index) else raise exception.Create('TSimpleLog.ExternalLogDelete(Index):' + sLineBreak + 'Index(' + IntToStr(Index) + ') out of bounds.'); end; end.
unit uRelPedidoVendaSimp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uModeloRel, StdCtrls, Buttons, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Mask, JvExControls, JvSpeedButton, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, JvExMask, JvToolEdit, ExtCtrls, JvNavigationPane, DB, ZAbstractRODataset, ZDataset, frxClass, frxDBSet, ZConnection, ACBrBase, ACBrEnterTab, frxExportPDF; type TfrmPedidoVendaSimp = class(TfrmModeloRel) frxDBVendaSimp: TfrxDBDataset; frxVendaSimp: TfrxReport; qrVendaSimp: TZReadOnlyQuery; qrVendaSimpnome_empresa: TStringField; qrVendaSimpsite_empresa: TStringField; qrVendaSimptelefone_empresa: TStringField; qrVendaSimpendereco_empresa: TStringField; qrVendaSimpcomplemento_empresa: TStringField; qrVendaSimpcidade_empresa: TStringField; qrVendaSimpuf_empresa: TStringField; qrVendaSimpcep_empresa: TStringField; qrVendaSimpcliente_codigo: TLargeintField; qrVendaSimpcliente_filial: TLargeintField; qrVendaSimpfantasia: TStringField; qrVendaSimpid: TIntegerField; qrVendaSimpnumero: TIntegerField; qrVendaSimpdata: TDateField; qrVendaSimpvencimento: TDateField; qrVendaSimpvalor_pedido: TFloatField; qrVendaSimpstatus: TStringField; qrVendaSimpoperacao: TStringField; JvNavPanelHeader1: TJvNavPanelHeader; Bevel1: TBevel; Bevel2: TBevel; Label10: TLabel; Label1: TLabel; Label2: TLabel; Bevel3: TBevel; Label11: TLabel; Label7: TLabel; Label8: TLabel; d02: TJvDateEdit; d01: TJvDateEdit; d03: TJvDateEdit; d04: TJvDateEdit; Bevel7: TBevel; Label15: TLabel; Label16: TLabel; Bevel8: TBevel; Label19: TLabel; Label20: TLabel; cbStatus: TComboBox; cbVendedor: TcxImageComboBox; Bevel4: TBevel; Label12: TLabel; Label3: TLabel; Label4: TLabel; Label9: TLabel; Label17: TLabel; Label18: TLabel; edCNPJ: TMaskEdit; cbPagamento: TcxImageComboBox; cbForma: TcxImageComboBox; edCliente: TJvComboEdit; edFantasia: TJvComboEdit; ACBrEnterTab1: TACBrEnterTab; Label5: TLabel; cbOperacao: TcxImageComboBox; Label6: TLabel; frxPDFExport1: TfrxPDFExport; procedure btnImprimirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edClienteButtonClick(Sender: TObject); procedure edFantasiaButtonClick(Sender: TObject); procedure frxVendaSimpGetValue(const VarName: string; var Value: Variant); procedure Label6MouseEnter(Sender: TObject); procedure Label6MouseLeave(Sender: TObject); procedure Label6Click(Sender: TObject); private { Private declarations } cliente, filial: string; procedure RelVendaSimp; procedure ApagaCampos; public { Public declarations } end; var frmPedidoVendaSimp: TfrmPedidoVendaSimp; implementation uses udmPrincipal, funcoes, uConsulta_Padrao; {$R *.dfm} procedure TfrmPedidoVendaSimp.btnImprimirClick(Sender: TObject); begin inherited; RelVendaSimp; end; procedure TfrmPedidoVendaSimp.RelVendaSimp; begin try if (d01.Date = 0) and (d02.Date = 0) and (cliente = EmptyStr) and (filial = EmptyStr) and (d03.Date = 0) and (d04.Date = 0) and (edCNPJ.Text = EmptyStr) and (cbVendedor.ItemIndex < 0) then begin Application.MessageBox('Você deve selecionar algum tipo filtro!', 'Atenção', MB_ICONERROR); Exit; end; if (edCNPJ.Text = EmptyStr) and (edCliente.Text = EmptyStr) and (edFantasia.Text = EmptyStr) then begin Application.MessageBox('Você deve selecionar um cliente!', 'Atenção', MB_ICONERROR); Exit; end; qrVendaSimp.Close; qrVendaSimp.SQL.Clear; qrVendaSimp.SQL.Add('select'); qrVendaSimp.SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, e.telefone as telefone_empresa,'); qrVendaSimp.SQL.Add('concat(e.logradouro,", ",e.numero) as endereco_empresa,'); qrVendaSimp.SQL.Add('e.complemento as complemento_empresa,'); qrVendaSimp.SQL.Add('e.cidade as cidade_empresa, e.uf as uf_empresa, e.cep as cep_empresa,'); qrVendaSimp.SQL.Add('v.cliente_codigo, v.cliente_filial, cf.fantasia,'); qrVendaSimp.SQL.Add('v.id, v.numero, v.data, v.vencimento,'); qrVendaSimp.SQL.Add('(v.valor_pedido-v.desconto_nota-v.desconto_financeiro) as valor_pedido,'); qrVendaSimp.SQL.Add('if(v.status in (0,1),"EM ABERTO", "QUITADO") as status,'); qrVendaSimp.SQL.Add('o.nome as operacao'); qrVendaSimp.SQL.Add('from vendas v'); qrVendaSimp.SQL.Add('left join empresas as e on v.empresa_codigo=e.codigo'); qrVendaSimp.SQL.Add('left join clientes_fornecedores as cf on v.cliente_codigo=cf.codigo and v.cliente_filial=cf.filial'); qrVendaSimp.SQL.Add('left join vendedores as vd on vd.codigo=v.vendedor'); qrVendaSimp.SQL.Add('left join operacoes o on o.codigo=v.operacao'); qrVendaSimp.SQL.Add('where v.empresa_codigo=:EmpresaLogada and isnull(v.data_exc)'); qrVendaSimp.ParamByName('EmpresaLogada').AsInteger := dmPrincipal.empresa_login; if (d01.Date <> 0) and (d02.Date = 0) then begin qrVendaSimp.SQL.add('and v.data=:data1'); qrVendaSimp.ParamByName('data1').AsDate := d01.Date; end else if (d01.Date > 0) and (d02.Date > 0) then begin qrVendaSimp.SQL.add('and v.data between :data1 and :data2'); qrVendaSimp.ParamByName('data1').AsDate := d01.Date; qrVendaSimp.ParamByName('data2').AsDate := d02.Date; end; if (d03.Date <> 0) and (d04.Date = 0) then begin qrVendaSimp.SQL.add('and v.vencimento=:data3'); qrVendaSimp.ParamByName('data3').AsDate := d03.Date; end else if (d03.Date > 0) and (d04.Date > 0) then begin qrVendaSimp.SQL.add('and v.vencimento between :data3 and :data4'); qrVendaSimp.ParamByName('data3').AsDate := d03.Date; qrVendaSimp.ParamByName('data4').AsDate := d04.Date; end; if edCNPJ.Text <> EmptyStr then begin qrVendaSimp.SQL.add('and left(replace(cf.cliente_cnpj,".",""),8)=:cnpj'); qrVendaSimp.ParamByName('cnpj').AsString := Copy(edCNPJ.Text, 1, 8); end; if cliente <> '' then qrVendaSimp.SQL.Add('and v.cliente_codigo=' + cliente); if filial <> '' then qrVendaSimp.SQL.Add('and v.cliente_filial=' + filial); if cbPagamento.ItemIndex <> -1 then begin qrVendaSimp.SQL.add('and v.meio_pagamento=:MeioPagamento'); qrVendaSimp.ParamByName('MeioPagamento').AsInteger := cbPagamento.Properties.Items.Items[cbPagamento.ItemIndex].Value; end; if cbForma.ItemIndex <> -1 then begin qrVendaSimp.SQL.add('and v.forma_pagamento=:FormaPagamento'); qrVendaSimp.ParamByName('FormaPagamento').AsInteger := cbForma.Properties.Items.Items[cbForma.ItemIndex].Value; end; if cbVendedor.ItemIndex <> -1 then begin qrVendaSimp.SQL.add('and v.vendedor=:Vendedor'); qrVendaSimp.ParamByName('Vendedor').AsInteger := cbVendedor.Properties.Items.Items[cbVendedor.ItemIndex].Value; end; if cbOperacao.ItemIndex <> -1 then begin qrVendaSimp.SQL.add('and v.operacao=:Operacao'); qrVendaSimp.ParamByName('Operacao').AsInteger := cbOperacao.Properties.Items.Items[cbOperacao.ItemIndex].Value; end; case cbStatus.ItemIndex of 0: qrVendaSimp.SQL.Add(''); 1: qrVendaSimp.SQL.Add('and v.status in (0,1)'); 2: qrVendaSimp.SQL.Add('and v.status=2'); end; qrVendaSimp.SQL.Add('order by v.data, id'); qrVendaSimp.Open; if qrVendaSimp.IsEmpty then begin Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR); Exit; end else begin frxVendaSimp.ShowReport; end; finally qrVendaSimp.Close; ApagaCampos; end end; procedure TfrmPedidoVendaSimp.FormCreate(Sender: TObject); begin inherited; CarregaCombo(cbPagamento, 'select id,a.descricao from meio_pagamento a join meio_cobranca b on meio_cobranca=b.codigo where ativo="S" order by descricao'); CarregaCombo(cbForma, 'select id,descricao from forma_pagamento where ativo="S" order by descricao'); CarregaCombo(cbVendedor, 'select codigo, nome from vendedores where ativo="S" order by nome'); CarregaCombo(cbOperacao, 'select codigo, nome from operacoes where tipo="S" and ativo="S" order by nome'); cliente := ''; filial := ''; d01.Date := dmPrincipal.SoData; end; procedure TfrmPedidoVendaSimp.edClienteButtonClick(Sender: TObject); begin inherited; with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select nome Nome, codigo Código from clientes_fornecedores'); Add('where nome like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")'); Add('group by codigo order by 1'); end; CampoLocate := 'nome'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edCliente.Text := Query.Fields[0].Value; cliente := Query.Fields[1].Value; end; Free; end; end; procedure TfrmPedidoVendaSimp.edFantasiaButtonClick(Sender: TObject); begin inherited; with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select fantasia Fantasia, filial Filial, codigo Código from clientes_fornecedores'); Add('where fantasia like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")'); if cliente <> '' then begin Add('and codigo=:pCodigo'); Query.ParamByName('pCodigo').Value := cliente; end; Add('order by 1'); end; CampoLocate := 'fantasia'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edFantasia.Text := Query.Fields[0].Value; cliente := Query.Fields[2].Value; filial := Query.Fields[1].Value; end; Free; end; end; procedure TfrmPedidoVendaSimp.frxVendaSimpGetValue(const VarName: string; var Value: Variant); var s: string; begin inherited; if (d01.Date <> 0) and (d02.Date = 0) then s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date)) else if (d01.Date > 0) and (d02.Date > 0) then s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date), ' Até ', formatdatetime('dd/mm/yyyy', d02.Date)); if CompareText(VarName, 'periodo') = 0 then Value := s; end; procedure TfrmPedidoVendaSimp.ApagaCampos; begin d01.Clear; d02.Clear; d03.Clear; d04.Clear; cbVendedor.ItemIndex := -1; cbPagamento.ItemIndex := -1; cbForma.ItemIndex := -1; cbOperacao.ItemIndex := -1; edCliente.Clear; edFantasia.Clear; cliente := ''; filial := ''; edCNPJ.Clear; end; procedure TfrmPedidoVendaSimp.Label6MouseEnter(Sender: TObject); begin inherited; (Sender as TLabel).Font.Style := [fsBold]; end; procedure TfrmPedidoVendaSimp.Label6MouseLeave(Sender: TObject); begin inherited; (Sender as TLabel).Font.Style := []; end; procedure TfrmPedidoVendaSimp.Label6Click(Sender: TObject); begin inherited; ApagaCampos; end; end.
PROGRAM Fibonacci; VAR calls, depth, maxDepth: INTEGER; FUNCTION FibonacciRec(n: INTEGER): INTEGER; BEGIN calls := calls + 1; depth := depth + 1; IF depth > maxDepth THEN maxDepth := depth; IF n <= 2 THEN FibonacciRec := 1 ELSE FibonacciRec := FibonacciRec(n-2) + FibonacciRec(n-1); depth := depth - 1; END; FUNCTION FibonacciInter(n: INTEGER): INTEGER; VAR fib, fib1, fib2, i: INTEGER; BEGIN IF n = 2 THEN FibonacciInter := 1 ELSE BEGIN fib1 := 1; fib2 := 1; FOR i := 3 TO n DO BEGIN fib := fib1 + fib2; fib2 := fib1; fib1 := fib; END; END; FibonacciInter := fib; END; VAR n: INTEGER; BEGIN calls := 0; depth := 0; maxDepth := 0; n := 5; WriteLn('Fib: ', FibonacciRec(n)); WriteLn(#9,'calls: ', calls); WriteLn(#9,'depth: ', depth); WriteLn(#9,'maxdepth: ', maxDepth); WriteLn('Fib: ', FibonacciInter(n)); WriteLn(#9,'calls: ', calls); WriteLn(#9,'depth: ', depth); WriteLn(#9,'maxdepth: ', maxDepth); END.
unit StringGroup; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TStringGroup = class(TComponent) private FList : TList; ActiveList : TStringList; FGroupList:TStringList; FActiveGroupIndex: integer; function GetGroupName(i: integer): string; function GetItem(i: integer): string; procedure SetActiveGroupIndex(const Value: integer); function GetGroupCount: integer; function GetActiveGroup: string; function GetItemCount: integer; function GetItemAsCommaText: string; procedure SetItemAsCommaText(const Value: string); { Private declarations } protected { Protected declarations } public { Public declarations } // Groups constructor create(AOwner:TComponent);override; destructor destroy;override; property GroupName[i:integer]:string read GetGroupName; function GroupIndexOf(s:string):integer; property GroupCount:integer read GetGroupCount; property ActiveGroupIndex:integer read FActiveGroupIndex write SetActiveGroupIndex; property ActiveGroup:string read GetActiveGroup; procedure AddGroup(AGroupName:string); procedure RemoveGroup(AGroupIndex:integer); procedure ClearGroups; // Items property ItemCount:integer read GetItemCount; property Item[i:integer]:string read GetItem; property ItemAsCommaText:string read GetItemAsCommaText write SetItemAsCommaText; function ItemIndexOf(s:string):integer; procedure AddItem(s:string); procedure RemoveItem(n:integer); procedure ClearItems; published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Controls', [TStringGroup]); end; { TStringGroup } procedure TStringGroup.AddGroup(AGroupName: string); var sl : TStringList; begin if FGroupList.IndexOf(AGroupName) < 0 then begin FGroupList.Add(AGroupName); sl := TStringList.create; FList.Add(sl); end; ActiveGroupIndex := FGroupList.IndexOf(AGroupName); end; procedure TStringGroup.AddItem(s: string); begin if ActiveGroupIndex < 0 then exit; ActiveList.Add(s); end; procedure TStringGroup.ClearGroups; begin while GroupCount > 0 do RemoveGroup(0); end; procedure TStringGroup.ClearItems; begin if ActiveGroupIndex < 0 then exit; ActiveList.Clear; end; constructor TStringGroup.create(AOwner: TComponent); begin inherited; FGroupList := TStringList.create; FList := TList.Create; end; destructor TStringGroup.destroy; var x : integer; begin for x := 0 to FList.Count - 1 do TStringList(FList[x]).free; FList.Free; FGroupList.free; inherited; end; function TStringGroup.GetActiveGroup: string; begin if FActiveGroupIndex >= 0 then result := FGroupList[FActiveGroupIndex] else result := ''; end; function TStringGroup.GetGroupCount: integer; begin result := FGroupList.Count; end; function TStringGroup.GetGroupName(i: integer): string; begin if (i >= 0) and (i < FGroupList.count) then result := FGroupList[i] else result := ''; end; function TStringGroup.GetItem(i: integer): string; begin result := ''; if ActiveList = nil then exit; result := ActiveList.Strings[i]; end; function TStringGroup.GetItemAsCommaText: string; begin result := ''; if ActiveList = nil then exit; result := ActiveList.CommaText; end; function TStringGroup.GetItemCount: integer; begin result := 0; if ActiveList = nil then exit; result := ActiveList.Count; end; function TStringGroup.GroupIndexOf(s: string): integer; begin result := FGroupList.IndexOf(s); end; function TStringGroup.ItemIndexOf(s: string): integer; begin result := -1; if ActiveList = nil then exit; result := ActiveList.IndexOf(s); end; procedure TStringGroup.RemoveGroup(AGroupIndex: integer); begin if (AGroupIndex >= 0) then begin try FGroupList.Delete(AGroupIndex); TStringList(FList[AGroupIndex]).Free; FList.Delete(AGroupIndex); if ActiveGroupIndex >= GroupCount then ActiveGroupIndex := GroupCount -1; except end; end; end; procedure TStringGroup.RemoveItem(n: integer); begin if ActiveGroupIndex < 0 then exit; ActiveList.Delete(n); end; procedure TStringGroup.SetActiveGroupIndex(const Value: integer); begin if (value >= 0) and (value < FGroupList.count) then begin FActiveGroupIndex := Value; ActiveList := FList[FActiveGroupIndex]; end else begin FActiveGroupIndex := -1; ActiveList := nil; end; end; procedure TStringGroup.SetItemAsCommaText(const Value: string); begin if ActiveGroupIndex < 0 then exit; ActiveList.CommaText := Value; end; end.
unit NtUtils.WinUser; interface uses Winapi.WinNt, Winapi.WinUser, NtUtils.Exceptions, NtUtils.Security.Sid; type TNtxStatus = NtUtils.Exceptions.TNtxStatus; { Open } // Open desktop function UsrxOpenDesktop(out hDesktop: THandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean = False): TNtxStatus; // Open window station function UsrxOpenWindowStation(out hWinSta: THandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean = False): TNtxStatus; { Query information } // Query any information function UsrxQueryBufferObject(hObj: THandle; InfoClass: TUserObjectInfoClass; out Status: TNtxStatus): Pointer; // Quer user object name function UsrxQueryObjectName(hObj: THandle; out Name: String): TNtxStatus; // Query user object SID function UsrxQueryObjectSid(hObj: THandle; out Sid: ISid): TNtxStatus; // Query a name of a current desktop function UsrxCurrentDesktopName: String; { Enumerations } // Enumerate window stations of current session function UsrxEnumWindowStations(out WinStations: TArray<String>): TNtxStatus; // Enumerate desktops of a window station function UsrxEnumDesktops(WinSta: HWINSTA; out Desktops: TArray<String>): TNtxStatus; // Enumerate all accessable desktops from different window stations function UsrxEnumAllDesktops: TArray<String>; { Actions } // Switch to a desktop function UsrxSwithToDesktop(hDesktop: THandle; FadeTime: Cardinal = 0) : TNtxStatus; function UsrxSwithToDesktopByName(DesktopName: String; FadeTime: Cardinal = 0) : TNtxStatus; implementation uses Winapi.ProcessThreadsApi, Ntapi.ntpsapi, NtUtils.Objects; function UsrxOpenDesktop(out hDesktop: THandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean): TNtxStatus; begin Result.Location := 'OpenDesktopW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @DesktopAccessType; hDesktop := OpenDesktopW(PWideChar(Name), 0, InheritHandle, DesiredAccess); Result.Win32Result := (hDesktop <> 0); end; function UsrxOpenWindowStation(out hWinSta: THandle; Name: String; DesiredAccess: TAccessMask; InheritHandle: Boolean): TNtxStatus; begin Result.Location := 'OpenWindowStationW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @WinStaAccessType; hWinSta := OpenWindowStationW(PWideChar(Name), InheritHandle, DesiredAccess); Result.Win32Result := (hWinSta <> 0); end; function UsrxQueryBufferObject(hObj: THandle; InfoClass: TUserObjectInfoClass; out Status: TNtxStatus): Pointer; var BufferSize, Required: Cardinal; begin Status.Location := 'GetUserObjectInformationW'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TUserObjectInfoClass); BufferSize := 0; repeat Result := AllocMem(BufferSize); Required := 0; Status.Win32Result := GetUserObjectInformationW(hObj, InfoClass, Result, BufferSize, @Required); if not Status.IsSuccess then begin FreeMem(Result); Result := nil; end; until not NtxExpandBuffer(Status, BufferSize, Required); end; function UsrxQueryObjectName(hObj: THandle; out Name: String): TNtxStatus; var Buffer: PWideChar; begin Buffer := UsrxQueryBufferObject(hObj, UserObjectName, Result); if not Result.IsSuccess then Exit; Name := String(Buffer); FreeMem(Buffer); end; function UsrxQueryObjectSid(hObj: THandle; out Sid: ISid): TNtxStatus; var Buffer: PSid; begin Buffer := UsrxQueryBufferObject(hObj, UserObjectUserSid, Result); if not Result.IsSuccess then Exit; if Assigned(Buffer) then Sid := TSid.CreateCopy(Buffer) else Sid := nil; FreeMem(Buffer); end; function UsrxCurrentDesktopName: String; var WinStaName: String; StartupInfo: TStartupInfoW; begin // Read our thread's desktop and query its name if UsrxQueryObjectName(GetThreadDesktop(NtCurrentThreadId), Result).IsSuccess then begin if UsrxQueryObjectName(GetProcessWindowStation, WinStaName).IsSuccess then Result := WinStaName + '\' + Result; end else begin // This is very unlikely to happen. Fall back to using the value // from the startupinfo structure. GetStartupInfoW(StartupInfo); Result := String(StartupInfo.lpDesktop); end; end; function EnumCallback(Name: PWideChar; var Context: TArray<String>): LongBool; stdcall; begin // Save the value and succeed SetLength(Context, Length(Context) + 1); Context[High(Context)] := String(Name); Result := True; end; function UsrxEnumWindowStations(out WinStations: TArray<String>): TNtxStatus; begin SetLength(WinStations, 0); Result.Location := 'EnumWindowStationsW'; Result.Win32Result := EnumWindowStationsW(EnumCallback, WinStations); end; function UsrxEnumDesktops(WinSta: HWINSTA; out Desktops: TArray<String>): TNtxStatus; begin SetLength(Desktops, 0); Result.Location := 'EnumDesktopsW'; Result.Win32Result := EnumDesktopsW(WinSta, EnumCallback, Desktops); end; function UsrxEnumAllDesktops: TArray<String>; var i, j: Integer; hWinStation: HWINSTA; WinStations, Desktops: TArray<String>; begin SetLength(Result, 0); // Enumerate accessable window stations if not UsrxEnumWindowStations(WinStations).IsSuccess then Exit; for i := 0 to High(WinStations) do begin // Open each window station hWinStation := OpenWindowStationW(PWideChar(WinStations[i]), False, WINSTA_ENUMDESKTOPS); if hWinStation = 0 then Continue; // Enumerate desktops of this window station if UsrxEnumDesktops(hWinStation, Desktops).IsSuccess then begin // Expand each name for j := 0 to High(Desktops) do Desktops[j] := WinStations[i] + '\' + Desktops[j]; Insert(Desktops, Result, Length(Result)); end; CloseWindowStation(hWinStation); end; end; function UsrxSwithToDesktop(hDesktop: THandle; FadeTime: Cardinal): TNtxStatus; begin if FadeTime = 0 then begin Result.Location := 'SwitchDesktop'; Result.LastCall.Expects(DESKTOP_SWITCHDESKTOP, @DesktopAccessType); Result.Win32Result := SwitchDesktop(hDesktop); end else begin Result.Location := 'SwitchDesktopWithFade'; Result.LastCall.Expects(DESKTOP_SWITCHDESKTOP, @DesktopAccessType); Result.Win32Result := SwitchDesktopWithFade(hDesktop, FadeTime); end; end; function UsrxSwithToDesktopByName(DesktopName: String; FadeTime: Cardinal) : TNtxStatus; var hDesktop: THandle; begin Result := UsrxOpenDesktop(hDesktop, DesktopName, DESKTOP_SWITCHDESKTOP); if Result.IsSuccess then begin Result := UsrxSwithToDesktop(hDesktop, FadeTime); NtxSafeClose(hDesktop); end; end; 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.2 10/26/2004 9:55:58 PM JPMugaas Updated refs. Rev 1.1 6/11/2004 9:38:48 AM DSiders Added "Do not Localize" comments. Rev 1.0 6/7/2004 7:46:26 PM JPMugaas } unit IdFTPListParseTSXPlus; { FTP List parser for TSX+. This is based on: http://www.gweep.net/~shifty/music/miragehack/gcc/xasm/cug292.lst } interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdTSXPlusFTPListItem = class(TIdMinimalFTPListItem) protected FNumberBlocks : Integer; public property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; end; TIdFTPLPTSXPlus = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function IsFooter(const AData : String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function GetIdent : String; 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 "IdFTPListParseTSXPlus"'*) implementation uses IdFTPCommon, IdGlobal, SysUtils; { TIdFTPLPTSXPlus } class function TIdFTPLPTSXPlus.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var i : Integer; begin Result := False; if AListing.Count > 0 then begin for i := AListing.Count-1 downto 0 do begin if AListing[i] <> '' then begin if IsFooter(AListing[i]) then begin Result := True; Break; end; end; end; end; end; class function TIdFTPLPTSXPlus.GetIdent: String; begin Result := 'TSX+'; {do not localize} end; class function TIdFTPLPTSXPlus.IsFooter(const AData: String): Boolean; var LBuf, LPart : String; begin //The footer is like this: //Directory [du3:/cug292/pcdsk4/*.*] / 9 Files / 563 Blocks Result := False; LBuf := AData; LPart := Fetch(LBuf, '['); {do not localize} if LBuf = '' then begin Exit; end; LPart := TrimRight(LPart); if LPart = 'Directory' then {do not localize} begin Fetch(LBuf, ']'); {do not localize} if LBuf = '' then begin Exit; end; LBuf := TrimLeft(LBuf); if TextStartsWith(LBuf, '/') then {do not localize} begin IdDelete(LBuf, 1, 1); if IndyPos('Files', LBuf) > 0 then {do not localize} begin LPart := Fetch(LPart, '/'); {do not localize} if LBuf = '' then begin Exit; end; Result := (IndyPos('Block', LBuf) > 0); {do not localize} end; end; end; end; class function TIdFTPLPTSXPlus.IsHeader(const AData: String): Boolean; begin Result := False; end; class function TIdFTPLPTSXPlus.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdTSXPlusFTPListItem.Create(AOwner); end; class function TIdFTPLPTSXPlus.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf, LExt : String; LNewItem : TIdFTPListItem; begin { Note that this parser is odd because it will create a new TIdFTPListItem. I know that is not according to the current conventional design. However, KA9Q is unusual because a single line can have two items (maybe more) } Result := True; LBuf := TrimLeft(AItem.Data); AItem.FileName := Fetch(LBuf, '.'); {do not localize} LExt := Fetch(LBuf); if LExt = 'dsk' then begin {do not localize} AItem.ItemType := ditDirectory; end else begin AItem.ItemType := ditFile; AItem.FileName := AItem.FileName + '.' + LExt; {do not localize} end; LBuf := TrimLeft(LBuf); //block count (AItem as TIdTSXPlusFTPListItem).NumberBlocks := IndyStrToInt(Fetch(LBuf), 0); LBuf := TrimRight(LBuf); if LBuf <> '' then begin LNewItem := MakeNewItem(AItem.Collection as TIdFTPListItems); LNewItem.Data := LBuf; Result := ParseLine(LNewItem, APath); if not Result then begin FreeAndNil(LNewItem); Exit; end; LNewItem.Data := AItem.Data; end; end; initialization RegisterFTPListParser(TIdFTPLPTSXPlus); finalization UnRegisterFTPListParser(TIdFTPLPTSXPlus); end.
unit npControls; {* указывает от какого навигатора на форме был отстыкован компонент } // Модуль: "w:\common\components\gui\Garant\VT\npControls.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnpControls" MUID: (4F61DED90246) {$Include w:\common\components\gui\Garant\VT\vtDefine.inc} interface {$If NOT Defined(NoVCM)} uses l3IntfUses , l3ProtoDataContainer {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) , vtNavigator , l3Memory , l3Types , l3Interfaces , l3Core , l3Except , Classes ; type _ItemType_ = TControl; _l3ObjectPtrList_Parent_ = Tl3ProtoDataContainer; {$Define l3Items_IsProto} {$Include w:\common\components\rtl\Garant\L3\l3ObjectPtrList.imp.pas} TnpControls = class(_l3ObjectPtrList_) {* указывает от какого навигатора на форме был отстыкован компонент } private f_Navigator: TvtNavigatorPrim; public function DeleteControl(aControl: TControl): Boolean; constructor Create(aNavigator: TvtNavigatorPrim); reintroduce; public property Navigator: TvtNavigatorPrim read f_Navigator; end;//TnpControls {$IfEnd} // NOT Defined(NoVCM) implementation {$If NOT Defined(NoVCM)} uses l3ImplUses , l3Base , l3MinMax , RTLConsts , SysUtils //#UC START# *4F61DED90246impl_uses* //#UC END# *4F61DED90246impl_uses* ; type _Instance_R_ = TnpControls; {$Include w:\common\components\rtl\Garant\L3\l3ObjectPtrList.imp.pas} function TnpControls.DeleteControl(aControl: TControl): Boolean; //#UC START# *4F61EDD001B7_4F61DED90246_var* var l_Index : Integer; //#UC END# *4F61EDD001B7_4F61DED90246_var* begin //#UC START# *4F61EDD001B7_4F61DED90246_impl* Result := false; l_Index := IndexOf(aControl); if (l_Index <> -1) then begin Delete(l_Index); Result := true; end;//l_Index <> -1 //#UC END# *4F61EDD001B7_4F61DED90246_impl* end;//TnpControls.DeleteControl constructor TnpControls.Create(aNavigator: TvtNavigatorPrim); //#UC START# *4F61F57501B6_4F61DED90246_var* //#UC END# *4F61F57501B6_4F61DED90246_var* begin //#UC START# *4F61F57501B6_4F61DED90246_impl* inherited Create; f_Navigator := aNavigator; //#UC END# *4F61F57501B6_4F61DED90246_impl* end;//TnpControls.Create {$IfEnd} // NOT Defined(NoVCM) end.
unit PI.Resources; interface uses // RTL System.SysUtils, System.Classes, System.ImageList, // FMX FMX.Types, FMX.Controls, FMX.ImgList; type TResources = class(TDataModule) StyleBook: TStyleBook; ImageList: TImageList; private procedure LoadStyle; public constructor Create(AOwner: TComponent); override; end; var Resources: TResources; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses // RTL System.Types; const cApplicationStyleResourceName = 'Application'; { TResources } constructor TResources.Create(AOwner: TComponent); begin inherited; LoadStyle; end; procedure TResources.LoadStyle; var LStream: TStream; begin if FindResource(HInstance, PChar(cApplicationStyleResourceName), RT_RCDATA) > 0 then begin LStream := TResourceStream.Create(HInstance, cApplicationStyleResourceName, RT_RCDATA); try StyleBook.LoadFromStream(LStream); finally LStream.Free; end; end; 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 ClpAsn1OutputStream; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpDerOutputStream; type TAsn1OutputStream = class sealed(TDerOutputStream) public constructor Create(os: TStream); end; implementation { TAsn1OutputStream } constructor TAsn1OutputStream.Create(os: TStream); begin Inherited Create(os); end; end.
unit osActionList; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList; type TosActionList = class(TActionList) private { Private declarations } protected { Protected declarations } public function GetActionByName(const PName: string): TAction; procedure EnableActions(const PCategory: string; const PState: boolean); published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('OS Controls', [TosActionList]); end; { TosActionList } procedure TosActionList.EnableActions(const PCategory: string; const PState: boolean); var i: integer; begin for i:=0 to ActionCount - 1 do if Actions[i].Category = PCategory then TAction(Actions[i]).Enabled := PState; end; function TosActionList.GetActionByName(const PName: string): TAction; var i: integer; begin Result := nil; for i:=0 to ActionCount - 1 do if Actions[i].Name = PName then begin Result := TAction(Actions[i]); break; end; end; end.
{ Subroutine SST_R_PAS_VAR_INIT (DTYPE, EXP_P) * * Process the VAR_INITIALIZER syntax. The tag for this syntax has just been * read. DTYPE is the data type descriptor for the variable being initialized. * EXP_P will be returned pointing to the initial value expression. } module sst_r_pas_VAR_INIT; define sst_r_pas_var_init; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_var_init ( {process VAR_INITIALIZER syntax} in dtype: sst_dtype_t; {data type that init value must match} out exp_p: sst_exp_p_t); {returned pointing to initial value expression} const max_msg_parms = 2; {max parameters we can pass to a message} var tag: sys_int_machine_t; {syntax tag from .syn file} str_h: syo_string_t; {handle to string for a tag} dt_p: sst_dtype_p_t; {points to base data type descriptor for var} dt_junk_p: sst_dtype_p_t; {unused dtype descriptor pointer} dt: sst_dtype_k_t; {base data type ID of var} term_p: sst_exp_term_p_t; {points to current term in expression} name: string_var80_t; {name of current field in record} ind_n: sys_int_machine_t; {number of next array element} sym_p: sst_symbol_p_t; {scratch symbol pointer} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label loop_tag, field_found, done_varinit, error_syntax; begin name.max := sizeof(name.str); {init var string} sst_dtype_resolve (dtype, dt_p, dt); {resolve variable's base data types} syo_level_down; {down into VAR_INITIALIZER syntax} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'var_init_bad', nil, 0); case tag of { *************************** * * Tag is for a list of VAR_INIT_FIELD syntaxes separated by commas. } 1: begin sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {alloc mem for expression descriptor} exp_p^.str_h := str_h; {save handle to source characters} exp_p^.dtype_p := dt_p; {point to root data type for expression} exp_p^.dtype_hard := true; exp_p^.val_eval := true; {expression will have known value (or else)} exp_p^.val_fnd := true; exp_p^.val.dtype := dt; {set base data type ID for whole expression} exp_p^.rwflag := [sst_rwflag_read_k]; {expression is read-only} term_p := nil; {init to no current term yet} ind_n := 0; {init to next array index number, if used} loop_tag: {back here each new tag in VAR_INITIALIZER} syo_get_tag_msg ( {get tag for next VAR_INIT_FIELD syntax} tag, str_h, 'sst_pas_read', 'var_init_bad', nil, 0); case tag of 1: ; {regular VAR_INIT_FIELD syntax} syo_tag_end_k: begin {end of VAR_INITIALIZER syntax} goto done_varinit; {done with VAR_INITIALIZER syntax} end; otherwise {unexpected TAG value} syo_error_tag_unexp (tag, str_h); end; if term_p = nil then begin {no current term, init to first term} term_p := addr(exp_p^.term1); end else begin {make new term and chain to old term} sst_mem_alloc_scope (sizeof(term_p^), term_p^.next_p); {grab mem for new term} term_p := term_p^.next_p; {make new term the current term} end ; term_p^.next_p := nil; {init descriptor for this term} term_p^.op2 := sst_op2_none_k; term_p^.op1 := sst_op1_none_k; term_p^.str_h := str_h; term_p^.dtype_hard := true; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.rwflag := [sst_rwflag_read_k]; syo_level_down; {down into VAR_INIT_FIELD syntax} case dt_p^.dtype of {what is var base data type ?} { * The variable being initialized is a RECORD. } sst_dtype_rec_k: begin syo_get_tag_msg ( {get field name tag} tag, str_h, 'sst_pas_read', 'var_init_bad', nil, 0); case tag of {check for proper tag value} 1: ; 2: goto error_syntax; otherwise syo_error_tag_unexp (tag, str_h); end; syo_get_tag_string (str_h, name); {get name of this field} string_downcase (name); {make lower case for matching} sym_p := dt_p^.rec_first_p; {init to first field in record} while sym_p <> nil do begin {loop thru the fields in this record} if string_equal(sym_p^.name_in_p^, name) {found symbol descriptor for this field ?} then goto field_found; sym_p := sym_p^.field_next_p; {advance to next field in this record} end; {back and check this new field in record} sys_msg_parm_vstr (msg_parm[1], name); sys_msg_parm_vstr (msg_parm[2], dtype.symbol_p^.name_in_p^); syo_error (str_h, 'sst_pas_read', 'field_name_not_found', msg_parm, 2); field_found: {SYM_P is pointing to selected field in rec} term_p^.ttype := sst_term_field_k; {this term describes value of field in record} term_p^.dtype_p := sym_p^.field_dtype_p; {point to data type for this field} term_p^.field_sym_p := sym_p; {point to symbol for this field} syo_get_tag_msg ( {get VAR_INITIALIZER value tag} tag, str_h, 'sst_pas_read', 'var_init_bad', nil, 0); if tag <> 2 then syo_error_tag_unexp (tag, str_h); sst_r_pas_var_init ( {get initializer expression for this field} term_p^.dtype_p^, term_p^.field_exp_p); end; {done with initialized var is a RECORD} { * The variable being initialized is an ARRAY. } sst_dtype_array_k: begin syo_get_tag_msg ( {get VAR_INITIALIZER value tag} tag, str_h, 'sst_pas_read', 'var_init_bad', nil, 0); case tag of {check for proper tag value} 1: goto error_syntax; 2: ; otherwise syo_error_tag_unexp (tag, str_h); end; term_p^.ttype := sst_term_arele_k; {this term describes array element value} if dt_p^.ar_dtype_rem_p = nil then begin {array has only one subscript} term_p^.dtype_p := dt_p^.ar_dtype_ele_p; {"next" dtype is for the elements} end else begin {array has more than one subscript} term_p^.dtype_p := dt_p^.ar_dtype_rem_p; {"next" dtype is for rest of array} end ; if ind_n >= dt_p^.ar_ind_n then begin {more values than array indicies ?} sys_msg_parm_int (msg_parm[1], dt_p^.ar_ind_n); syo_error (str_h, 'sst_pas_read', 'var_init_index_too_many', msg_parm, 1); end; term_p^.arele_start := ind_n; {first index value} ind_n := ind_n + 1; {make index ordinal for next value} term_p^.arele_n := 1; {number of indicies covered by this value} sst_r_pas_var_init ( {get initializer expression for this field} term_p^.dtype_p^, term_p^.arele_exp_p); term_p^.val := term_p^.arele_exp_p^.val; {copy ele value back up to this term} end; { * The variable being initialized is a SET. } sst_dtype_set_k: begin syo_error (str_h, 'sst_pas_read', 'var_init_set_unimp', nil, 0); end; { * The data type of the variable does not match the syntax of the initializer * declaration. } otherwise goto error_syntax; end; syo_level_up; {back up from VAR_INIT_FIELD syntax} sst_dtype_resolve (term_p^.dtype_p^, dt_junk_p, term_p^.val.dtype); goto loop_tag; {back for next tag in VAR_INITIALIZER} { * Done with the whole VAR_INITIALIZER syntax. } done_varinit: if dt_p^.dtype = sst_dtype_array_k then begin {initialization was for array ?} if ind_n <> dt_p^.ar_ind_n then begin {not right number of values found ?} sys_msg_parm_int (msg_parm[1], dt_p^.ar_ind_n); sys_msg_parm_int (msg_parm[2], ind_n); syo_error ( term_p^.str_h, 'sst_pas_read', 'var_init_index_too_few', msg_parm, 2); end; if dt_p^.ar_string then begin {array is a character string ?} sst_mem_alloc_scope ( {allocate memory for string constant value} string_size(dt_p^.ar_ind_n), {amount of memory to allocate} exp_p^.val.ar_str_p); {returned pointer to the new memory} exp_p^.val.ar_str_p^.max := dt_p^.ar_ind_n; {set var string max length} exp_p^.val.ar_str_p^.len := 0; {init string to empty} term_p := addr(exp_p^.term1); {init pointer to first} while term_p <> nil do begin {once for each character in string} string_append1 (exp_p^.val.ar_str_p^, term_p^.val.char_val); {append char} term_p := term_p^.next_p; {advance to next array value} end; {back and process this new array value} end; {end of array is a character string} end; {end of variable was an array special case} end; {end of list of VAR_INIT_FIELD case} { *************************** * * Tag is for an EXPRESSION syntax. This must be for a "simple" variable. } 2: begin case dt_p^.dtype of {what is var base data type ?} sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_array_k, sst_dtype_range_k, sst_dtype_pnt_k: begin {all the legal data types for EXRESSION} sst_r_pas_exp (str_h, true, exp_p); {get descriptor for this expression} sst_exp_useage_check ( {check expression attributes for this useage} exp_p^, {expression to check} [sst_rwflag_read_k], {read/write access needed to expression value} dt_p^); {data type value must be compatible with} end; otherwise goto error_syntax; end; end; { *************************** * * Unexpected TAG value. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of TAG value cases} syo_level_up; {back up from VAR_INITIALIZER syntax} return; {normal return} error_syntax: {jump here on syntax error} syo_error (str_h, 'sst_pas_read', 'var_init_bad', nil, 0); end;
unit udmAcessoDados; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.Client, Data.DB, FireDAC.Comp.DataSet, FireDAC.Stan.StorageJSON, FireDAC.Phys.SQLite, FireDAC.FMXUI.Wait, FireDAC.Comp.UI, ClientModuleUnit1, Data.FireDACJSONReflect, FMX.Dialogs; type TdmAcessoDados = class(TDataModule) cnnConexao: TFDConnection; driver: TFDPhysSQLiteDriverLink; json: TFDStanStorageJSONLink; qryProdutos: TFDQuery; qryInsercao: TFDQuery; memInsercao: TFDMemTable; qryProdutosidproduto: TFDAutoIncField; qryProdutoscodigo: TStringField; qryProdutosnome: TStringField; WaitCursor: TFDGUIxWaitCursor; procedure DataModuleCreate(Sender: TObject); private { Private declarations } function ExisteProduto(ACodigo, ANome: String): Boolean; public { Public declarations } procedure AtualizaProdutosDoServidor; procedure EnviaProdutosParaServidor; end; var dmAcessoDados: TdmAcessoDados; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} procedure TdmAcessoDados.AtualizaProdutosDoServidor; var dsProdutos: TFDJSONDataSets; ACodigo, ANome: String; vlCliente1 : TClientModule1; begin vlCliente1 := TClientModule1.Create(Self); dsProdutos := vlCliente1.ServerMethods1Client.GetProdutos(); if TFDJSONDataSetsReader.GetListCount(dsProdutos) = 1 then begin memInsercao.Active := false; memInsercao.AppendData(TFDJSONDataSetsReader.GetListValue(dsProdutos, 0)); qryInsercao.SQL.Clear; qryInsercao.SQL.Add('insert into produtos (codigo, nome) values (:codigo, :nome)'); while not memInsercao.Eof do begin ACodigo := memInsercao.FieldByName('cod').AsString; ANome := memInsercao.FieldByName('descricao').AsString; if not ExisteProduto(ACodigo, ANome) then begin qryInsercao.ParamByName('codigo').AsString := ACodigo; qryInsercao.ParamByName('nome').AsString := ANome; qryInsercao.ExecSQL; end; memInsercao.Next; end; end; end; procedure TdmAcessoDados.DataModuleCreate(Sender: TObject); begin qryProdutos.Open(); end; procedure TdmAcessoDados.EnviaProdutosParaServidor; var dsProdutos: TFDJSONDataSets; vlCliente1 : TClientModule1; begin vlCliente1 := TClientModule1.Create(Self); dsProdutos := TFDJSONDataSets.Create; TFDJSONDataSetsWriter.ListAdd(dsProdutos, qryProdutos); if not vlCliente1.ServerMethods1Client.InsereProdutosCliente(dsProdutos) then ShowMessage('Erro ao enviar para o servidor'); end; function TdmAcessoDados.ExisteProduto(ACodigo, ANome: String): Boolean; begin with TFDQuery.Create(Self) do try Connection := cnnConexao; SQL.Text := 'select idproduto from produtos where codigo = :codigo and nome = :nome'; Params[0].AsString := ACodigo; Params[1].AsString := ANome; Open(); if IsEmpty then Result := False else Result := True; finally Free; end; end; end.
unit TTSNOTICETAGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSNOTICETAGRecord = record PCifFlag: String[1]; PLoanNum: String[20]; PCollNum: Integer; PTrackCode: String[8]; PCategorySub: Integer; PSendToType: String[1]; PSeparateBy: String[10]; PSortBy: String[120]; PNoticeCycle: Integer; PStdNotice: Boolean; PName1: String[40]; PPriorNoticeDate: String[10]; PLapse: Integer; End; TTTSNOTICETAGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSNOTICETAGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSNOTICETAG = (TTSNOTICETAGPrimaryKey, TTSNOTICETAGBySort); TTTSNOTICETAGTable = class( TDBISAMTableAU ) private FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFCollNum: TIntegerField; FDFTrackCode: TStringField; FDFCategorySub: TIntegerField; FDFSendToType: TStringField; FDFSeparateBy: TStringField; FDFSortBy: TStringField; FDFNoticeCycle: TIntegerField; FDFStdNotice: TBooleanField; FDFNoticeText: TBlobField; FDFName1: TStringField; FDFPriorNoticeDate: TStringField; FDFLapse: TIntegerField; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPCategorySub(const Value: Integer); function GetPCategorySub:Integer; procedure SetPSendToType(const Value: String); function GetPSendToType:String; procedure SetPSeparateBy(const Value: String); function GetPSeparateBy:String; procedure SetPSortBy(const Value: String); function GetPSortBy:String; procedure SetPNoticeCycle(const Value: Integer); function GetPNoticeCycle:Integer; procedure SetPStdNotice(const Value: Boolean); function GetPStdNotice:Boolean; procedure SetPName1(const Value: String); function GetPName1:String; procedure SetPPriorNoticeDate(const Value: String); function GetPPriorNoticeDate:String; procedure SetPLapse(const Value: Integer); function GetPLapse:Integer; procedure SetEnumIndex(Value: TEITTSNOTICETAG); function GetEnumIndex: TEITTSNOTICETAG; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSNOTICETAGRecord; procedure StoreDataBuffer(ABuffer:TTTSNOTICETAGRecord); property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TIntegerField read FDFCollNum; property DFTrackCode: TStringField read FDFTrackCode; property DFCategorySub: TIntegerField read FDFCategorySub; property DFSendToType: TStringField read FDFSendToType; property DFSeparateBy: TStringField read FDFSeparateBy; property DFSortBy: TStringField read FDFSortBy; property DFNoticeCycle: TIntegerField read FDFNoticeCycle; property DFStdNotice: TBooleanField read FDFStdNotice; property DFNoticeText: TBlobField read FDFNoticeText; property DFName1: TStringField read FDFName1; property DFPriorNoticeDate: TStringField read FDFPriorNoticeDate; property DFLapse: TIntegerField read FDFLapse; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: Integer read GetPCollNum write SetPCollNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PCategorySub: Integer read GetPCategorySub write SetPCategorySub; property PSendToType: String read GetPSendToType write SetPSendToType; property PSeparateBy: String read GetPSeparateBy write SetPSeparateBy; property PSortBy: String read GetPSortBy write SetPSortBy; property PNoticeCycle: Integer read GetPNoticeCycle write SetPNoticeCycle; property PStdNotice: Boolean read GetPStdNotice write SetPStdNotice; property PName1: String read GetPName1 write SetPName1; property PPriorNoticeDate: String read GetPPriorNoticeDate write SetPPriorNoticeDate; property PLapse: Integer read GetPLapse write SetPLapse; published property Active write SetActive; property EnumIndex: TEITTSNOTICETAG read GetEnumIndex write SetEnumIndex; end; { TTTSNOTICETAGTable } procedure Register; implementation procedure TTTSNOTICETAGTable.CreateFields; begin FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFCategorySub := CreateField( 'CategorySub' ) as TIntegerField; FDFSendToType := CreateField( 'SendToType' ) as TStringField; FDFSeparateBy := CreateField( 'SeparateBy' ) as TStringField; FDFSortBy := CreateField( 'SortBy' ) as TStringField; FDFNoticeCycle := CreateField( 'NoticeCycle' ) as TIntegerField; FDFStdNotice := CreateField( 'StdNotice' ) as TBooleanField; FDFNoticeText := CreateField( 'NoticeText' ) as TBlobField; FDFName1 := CreateField( 'Name1' ) as TStringField; FDFPriorNoticeDate := CreateField( 'PriorNoticeDate' ) as TStringField; FDFLapse := CreateField( 'Lapse' ) as TIntegerField; end; { TTTSNOTICETAGTable.CreateFields } procedure TTTSNOTICETAGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSNOTICETAGTable.SetActive } procedure TTTSNOTICETAGTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSNOTICETAGTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSNOTICETAGTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSNOTICETAGTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSNOTICETAGTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSNOTICETAGTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSNOTICETAGTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSNOTICETAGTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSNOTICETAGTable.SetPCategorySub(const Value: Integer); begin DFCategorySub.Value := Value; end; function TTTSNOTICETAGTable.GetPCategorySub:Integer; begin result := DFCategorySub.Value; end; procedure TTTSNOTICETAGTable.SetPSendToType(const Value: String); begin DFSendToType.Value := Value; end; function TTTSNOTICETAGTable.GetPSendToType:String; begin result := DFSendToType.Value; end; procedure TTTSNOTICETAGTable.SetPSeparateBy(const Value: String); begin DFSeparateBy.Value := Value; end; function TTTSNOTICETAGTable.GetPSeparateBy:String; begin result := DFSeparateBy.Value; end; procedure TTTSNOTICETAGTable.SetPSortBy(const Value: String); begin DFSortBy.Value := Value; end; function TTTSNOTICETAGTable.GetPSortBy:String; begin result := DFSortBy.Value; end; procedure TTTSNOTICETAGTable.SetPNoticeCycle(const Value: Integer); begin DFNoticeCycle.Value := Value; end; function TTTSNOTICETAGTable.GetPNoticeCycle:Integer; begin result := DFNoticeCycle.Value; end; procedure TTTSNOTICETAGTable.SetPStdNotice(const Value: Boolean); begin DFStdNotice.Value := Value; end; function TTTSNOTICETAGTable.GetPStdNotice:Boolean; begin result := DFStdNotice.Value; end; procedure TTTSNOTICETAGTable.SetPName1(const Value: String); begin DFName1.Value := Value; end; function TTTSNOTICETAGTable.GetPName1:String; begin result := DFName1.Value; end; procedure TTTSNOTICETAGTable.SetPPriorNoticeDate(const Value: String); begin DFPriorNoticeDate.Value := Value; end; function TTTSNOTICETAGTable.GetPPriorNoticeDate:String; begin result := DFPriorNoticeDate.Value; end; procedure TTTSNOTICETAGTable.SetPLapse(const Value: Integer); begin DFLapse.Value := Value; end; function TTTSNOTICETAGTable.GetPLapse:Integer; begin result := DFLapse.Value; end; procedure TTTSNOTICETAGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('CollNum, Integer, 0, N'); Add('TrackCode, String, 8, N'); Add('CategorySub, Integer, 0, N'); Add('SendToType, String, 1, N'); Add('SeparateBy, String, 10, N'); Add('SortBy, String, 120, N'); Add('NoticeCycle, Integer, 0, N'); Add('StdNotice, Boolean, 0, N'); Add('NoticeText, Memo, 0, N'); Add('Name1, String, 40, N'); Add('PriorNoticeDate, String, 10, N'); Add('Lapse, Integer, 0, N'); end; end; procedure TTTSNOTICETAGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, CifFlag;LoanNum;CollNum;TrackCode;CategorySub;SendToType, Y, Y, N, N'); Add('BySort, SeparateBy;SortBy, N, N, Y, N'); end; end; procedure TTTSNOTICETAGTable.SetEnumIndex(Value: TEITTSNOTICETAG); begin case Value of TTSNOTICETAGPrimaryKey : IndexName := ''; TTSNOTICETAGBySort : IndexName := 'BySort'; end; end; function TTTSNOTICETAGTable.GetDataBuffer:TTTSNOTICETAGRecord; var buf: TTTSNOTICETAGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCollNum := DFCollNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PCategorySub := DFCategorySub.Value; buf.PSendToType := DFSendToType.Value; buf.PSeparateBy := DFSeparateBy.Value; buf.PSortBy := DFSortBy.Value; buf.PNoticeCycle := DFNoticeCycle.Value; buf.PStdNotice := DFStdNotice.Value; buf.PName1 := DFName1.Value; buf.PPriorNoticeDate := DFPriorNoticeDate.Value; buf.PLapse := DFLapse.Value; result := buf; end; procedure TTTSNOTICETAGTable.StoreDataBuffer(ABuffer:TTTSNOTICETAGRecord); begin DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFCollNum.Value := ABuffer.PCollNum; DFTrackCode.Value := ABuffer.PTrackCode; DFCategorySub.Value := ABuffer.PCategorySub; DFSendToType.Value := ABuffer.PSendToType; DFSeparateBy.Value := ABuffer.PSeparateBy; DFSortBy.Value := ABuffer.PSortBy; DFNoticeCycle.Value := ABuffer.PNoticeCycle; DFStdNotice.Value := ABuffer.PStdNotice; DFName1.Value := ABuffer.PName1; DFPriorNoticeDate.Value := ABuffer.PPriorNoticeDate; DFLapse.Value := ABuffer.PLapse; end; function TTTSNOTICETAGTable.GetEnumIndex: TEITTSNOTICETAG; var iname : string; begin result := TTSNOTICETAGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSNOTICETAGPrimaryKey; if iname = 'BYSORT' then result := TTSNOTICETAGBySort; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSNOTICETAGTable, TTTSNOTICETAGBuffer ] ); end; { Register } function TTTSNOTICETAGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..13] of string = ('CIFFLAG','LOANNUM','COLLNUM','TRACKCODE','CATEGORYSUB','SENDTOTYPE' ,'SEPARATEBY','SORTBY','NOTICECYCLE','STDNOTICE','NAME1','PRIORNOTICEDATE','LAPSE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 13) and (flist[x] <> s) do inc(x); if x <= 13 then result := x else result := 0; end; function TTTSNOTICETAGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftInteger; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftInteger; 10 : result := ftBoolean; 11 : result := ftString; 12 : result := ftString; 13 : result := ftInteger; end; end; function TTTSNOTICETAGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCifFlag; 2 : result := @Data.PLoanNum; 3 : result := @Data.PCollNum; 4 : result := @Data.PTrackCode; 5 : result := @Data.PCategorySub; 6 : result := @Data.PSendToType; 7 : result := @Data.PSeparateBy; 8 : result := @Data.PSortBy; 9 : result := @Data.PNoticeCycle; 10 : result := @Data.PStdNotice; 11 : result := @Data.PName1; 12 : result := @Data.PPriorNoticeDate; 13 : result := @Data.PLapse; end; end; end.
unit xNumInWords_ENG; interface function NumInWords_ENG(number: Int64): String; implementation uses {xLngDefs, xLngManager,} SysUtils; const smalls: array [0..19] of String = ( 'zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen ' ); maxstop = 4; stopsn: array [1..maxstop] of int64 = (1000000000, 1000000, 1000, 100); stopss: array [1..maxstop] of String = ('trillion', 'million', 'thousand', 'hundred'); //============================================================================================== function niwRS(n: int64; s,r: string; sp:integer): String; begin { if n > 1 then Result := rs(s, r + 'm' + niwGenderChars[gender], sp) else Result := rs(s, r + 's' + niwGenderChars[gender], sp); } end; //============================================================================================== function niwHundreds(number: Int64): String; begin // Result := NumInWords_ENG(number, gender) + rs(rs_lang, 'hundred' + IntToStr(number), 2); end; //============================================================================================== function niwTens(number: Int64): String; begin case number of 2: Result := 'twenty '; 3: Result := 'thirty '; 4: Result := 'fourty '; 5: Result := 'fifty '; 6: Result := 'sixty '; 7: Result := 'seventy '; 8: Result := 'eighty '; 9: Result := 'ninety '; end; end; //============================================================================================== function suff(n: int64): String; begin if n = 1 then Result := ' ' else Result := 's '; end; //============================================================================================== function NumInWords_ENG(number: Int64): String; var i: Integer; n: Int64; begin if number = 0 then begin Result := 'zero '; Exit; end; Result := ''; i := 0; while (number > 0) and (i <= maxstop) do begin inc(i); if number >= stopsn[i] then begin n := number div stopsn[i]; Result := Result + NumInwords_ENG(n) + stopss[i] + suff(n); number := number - n * stopsn[i]; end; end; if number >= 20 then begin n := number div 10; Result := Result + niwTens(n); number := number - n * 10; end; if number > 0 then Result := Result + smalls[number]; end; end.
unit GX_ReselectDesktop; interface uses SysUtils, Classes, Forms, GX_Experts; type TReselectDesktopExpert = class(TGX_Expert) public function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; function HasConfigOptions: Boolean; override; function GetHelpString: string; override; end; implementation uses StdCtrls, Messages, Windows; { TReslectDesktopExpert } type TComboBoxHack = class(TComboBox) end; procedure TReselectDesktopExpert.Execute(Sender: TObject); var AppBuilder: TForm; cbDesktop: TComboBoxHack; begin AppBuilder := TForm(Application.FindComponent('AppBuilder')); if not Assigned(AppBuilder) then Exit; cbDesktop := TComboBoxHack(AppBuilder.FindComponent('cbDesktop')); if not Assigned(cbDesktop) then Exit; cbDesktop.Click; end; function TReselectDesktopExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Reselect Desktop'; begin Result := SMenuCaption; end; function TReselectDesktopExpert.GetHelpString: string; resourcestring SReselectDesktopHelpString = ' This expert does the same as selecting the currently active desktop again'#13#10 + ' so it saves one mouse click or several key strokes.'#13#10 + ' It is meant to be put as an icon onto the Desktop toolbar.'; begin Result := SReselectDesktopHelpString; end; class function TReselectDesktopExpert.GetName: string; begin Result := 'ReselectDesktop'; end; function TReselectDesktopExpert.HasConfigOptions: Boolean; begin Result := False; end; initialization RegisterGX_Expert(TReselectDesktopExpert); end.
{ Mark Sattolo 428500 CSI-1100A DGD-1 TA: Chris Lankester Assignment 9, Question 1 } program MagicSquare (input,output); const MaxSize = 20; type ArrayType = array[1..MaxSize, 1..MaxSize] of integer; { *************************************************************************** } procedure SumRow (Matrix: ArrayType; Dim, RowIndex: integer; var RowSum: integer); { Find the sum of the elements in row RowIndex of Matrix } { Data Dictionary Givens: Matrix, Dim - Matrix is a Dim x Dim matrix. RowIndex - the row index for Matrix. Results: RowSum - the sum of the numbers in row RowIndex of Matrix. Intermediates: ColIndex - a column index for Matrix. } var ColIndex : integer; begin RowSum := 0; for ColIndex := 1 to Dim do RowSum := RowSum + Matrix[RowIndex, ColIndex]; end; { *************************************************************************** } procedure SumBackDiag (Matrix:ArrayType; Dim:integer; var BackDiagSum:integer); { Find the sum of the back diagonal of Matrix } { Data Dictionary Givens: Matrix, Dim - Matrix is a Dim x Dim matrix. Results: BackDiagSum - the sum of the numbers in the back diagonal of Matrix. Intermediates: Index - a row/column index for Matrix. } var Index : integer; begin BackDiagSum := 0; for Index := Dim downto 1 do BackDiagSum := BackDiagSum + Matrix[Index, (Dim+1-Index)]; end; { *************************************************************************** } procedure InMatrix (Matrix:ArrayType; Dim, Target:integer; var Total: integer); { Find the number of times Target appears in Matrix } { Data Dictionary Givens: Matrix, Dim - Matrix is a Dim x Dim matrix. Target - the number to search for in Matrix. Results: Total - the number of times that Target appears in Matrix. Intermediates: i,j - a row & column index, respectively, for Matrix. } var i, j : integer; begin Total := 0; for i := 1 to Dim do for j := 1 to Dim do if Target = Matrix[i,j] then Total := Total + 1; end; { *************************************************************************** } procedure TrueMagic (Matrix:ArrayType; Dim:integer; var MagicYes:boolean); { See if Matrix meets the requirements of a TRUE magic square, i.e. the numbers in the square are 1 through Dim^2, and each number appears only once. } { Data Dictionary Givens: Matrix, Dim - Matrix is a Dim x Dim matrix. Results: MagicYes - a boolean which is true if Matrix is a true magic square, and false otherwise. Intermediates: i,j - a row & column index, respectively, for Matrix. Total - an integer holding the answer from a call to InMatrix. Range - a boolean which is true if an element of Matrix is in the range of 1 to Dim^2, and false otherwise. Uses: InMatrix, SQR } var i, j, Total : integer; Range : boolean; begin MagicYes := true; i := 1; while MagicYes and (i <= Dim) do begin j := 1; while MagicYes and (j <= Dim) do begin InMatrix(Matrix, Dim, Matrix[i,j], Total); Range := (Matrix[i,j] >= 1) and (Matrix[i,j] <= SQR(Dim)); if (Total > 1) or (not Range) then MagicYes := false; inc(j); end; { j while loop } inc(i); end; { i while loop } end; { procedure TrueMagic } { *************************************************************************** } procedure SumColumn (A: arraytype; N, J: integer; var Sum: integer); { This procedure finds the sum of the Jth column in matrix A } { Data Dictionary Givens: A, N, J - A is an N x N matrix of numbers J is a column index for A Results: Sum - the sum of the numbers in the Jth column of A Intermediates: I - a row index for A } var I: integer; begin sum:= 0; For I:= 1 to N do Sum:= Sum + A[I,J]; end; { *************************************************************************** } procedure SumDiagonal (A: arraytype; N: integer; var Sum: integer); { This procedure finds the sum of the forward diagonal in matrix A } { Data Dictionary Givens: A, N - A is an N x N matrix of numbers Results: Sum - the sum of the numbers in the forward diagonal of A Intermediates: I - a row/column index for A } var I: integer; begin sum:= 0; For I:= 1 to N do Sum:= Sum + A[I,I]; end; { *************************************************************************** } { Program MagicSquare: See if a given matrix is a magic square, and a true magic square. } { Data Dictionary Givens: Square, N - Square is an N x N matrix. Intermediates: i,j - a row & column index, respectively, for Square. k - a row/column index for Square. RowSum - the sum of the elements in a row of Square. ColSum - the sum of the elements in a column of Square. SumDiag1 - the sum of the elements in the forward diagonal of Square. SumDiag2 - the sum of the elements in the back diagonal of Square. Nsum - the common sum of the elements in a row, column, or diagonal of Square. Results: Magic - a boolean which is true if Square is a (basic) magic square, and false otherwise. RealMagic - a boolean which is true if Square is a true magic square, and false otherwise. Uses: SumRow, SumBackDiag, TrueMagic, SumColumn, SumDiagonal, inc } var Square : ArrayType; N, i, j, k, RowSum, ColSum, Nsum, SumDiag1, SumDiag2 : integer; Magic, RealMagic : boolean; begin repeat { start outer input loop } { Read in the program's givens. } repeat write('Please enter a value from 1 to ', MaxSize, ' [ <1 to exit ] for N: '); readln(N); until N <= MaxSize; for i := 1 to N do begin writeln('Please enter values (with a space between) for row #', i); for j := 1 to N do read(Square[i,j]); end; { row, sum, and diagonal calculations } SumRow(Square, N, 1, RowSum); SumColumn(Square, N, 1, ColSum); Magic := (RowSum = ColSum); if Magic then Nsum := RowSum; { check that row 1 and column 1 have the same sum } k := 2; while Magic and (k <= N) do begin SumRow(Square, N, k, RowSum); SumColumn(Square, N, k, ColSum); Magic := (RowSum = ColSum); if Magic then Magic := (RowSum = Nsum); inc(k); end; { while loop Row and Sum comparisons } if Magic then begin SumBackDiag(Square, N, SumDiag2); SumDiagonal(Square, N, SumDiag1); Magic := (SumDiag1 = SumDiag2); if Magic then Magic := (SumDiag1 = Nsum); end; { while loop Diagonal comparisons } { check if a True magic square } RealMagic := false; if Magic then TrueMagic(Square, N, RealMagic); { write out the results } writeln; writeln('**********************************************'); writeln(' Mark Sattolo 428500'); writeln(' CSI-1100A DGD-1 TA: Chris Lankester'); writeln(' Assignment 9, Question 1'); writeln('**********************************************'); writeln; for i := 1 to N do begin for j := 1 to N do write(Square[i,j]:3, ' '); writeln; end; { for loop to write Square } { inform user of the "amount of magic" in the given matrix } if N in [1..MaxSize] then begin writeln; write('is '); if not Magic then write('NOT '); write('a '); if RealMagic then write('TRUE '); write('magic square'); if Magic then write(' with a row/column/diagonal sum of ', Nsum); writeln('.'); writeln('**************************************************************'); writeln; end; { if N in the proper range } until N < 1; { end outer input loop } end.
unit mungo.components.bgrabitmap.Canvas2D; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, BGRACanvas2D, BGRABitmapTypes, BGRAGraphics, bgrabitmap, mungo.components.types, mungo.components.renderer, mungo.components.geometry, mungo.components.styles, p3d.math; type IDrawToCanvas = interface ['{4F5E6559-EE2E-4E3A-A7C4-A025A25CBB02}'] procedure DrawToCanvas( ACanvas: TCanvas ); end; { TStyleSheetCanvas2D } TStyleSheetCanvas2D = class ( TStyleSheet ) function CreateWidgetContext( ARect: TRectF; ACaption: String ): TWidgetContext; override; end; { TWidgetContextCanvas2D } TWidgetContextCanvas2D = class ( TWidgetContext, IDrawToCanvas ) private FOffScreen: TBGRABitmap; function GetCanvas: TBGRACanvas2D; public procedure UpdateRect(ARect: TRectF); override; function CreateRect( ARect: TRectF ): TGeometryRect; override; function CreateEllipse( ARect: TRectF ): TGeometryEllipse; override; function CreateCircle( ACenter: TVec2; ARadius: Float ): TGeometryCircle; override; function CreateText( ACaption: String ): TGeometryText; override; procedure DrawToCanvas(ACanvas: TCanvas); property Canvas: TBGRACanvas2D read GetCanvas; end; { TGeometryRectCanvas2D } TGeometryRectCanvas2D = class ( TGeometryRect ) public procedure PassGeometry; override; end; { TGeometryCircleCanvas2D } TGeometryCircleCanvas2D = class ( TGeometryCircle ) public procedure PassGeometry; override; end; { TGeometryEllipseCanvas2D } TGeometryEllipseCanvas2D = class ( TGeometryEllipse ) public procedure PassGeometry; override; end; { TGeometryPathCanvas2D } TGeometryPathCanvas2D = class ( TGeometryPath ) public procedure PassGeometry; override; end; { TGeometryTextCanvas2D } TGeometryTextCanvas2D = class ( TGeometryText ) public procedure UpdateCanvasSettings; procedure PassGeometry; override; procedure UpdateGeometry; override; end; { TRendererFillColorBGRA } TRendererFillColorBGRA = class ( TRendererFillColor ) procedure SetupPenBrush(ACanvas: TBGRACanvas2D); {procedure RenderPoints( ACanvas: TObject; Points: TVec2List ); override; procedure RenderBezier( ACanvas: TObject; Points: TVec2List ); override; procedure RenderCircle( ACanvas: TObject; Position: TVec2; Radius: Float ); override; procedure RenderEllipse(ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2 ); override; procedure RenderRectangle( ACanvas: TObject; TopLeft: TVec2; BottomRight:TVec2 ); override; procedure RenderText(ACanvas: TObject; APosition: TVec2; ACaption: String); override;} procedure RenderGeometry(AGeometry: TGeometry); override; end; { TRendererStrokeColorBGRA } TRendererStrokeColorBGRA = class ( TRendererStrokeColor ) procedure SetupPenBrush(ACanvas: TBGRACanvas2D); {procedure RenderPoints( ACanvas: TObject; Points: TVec2List ); override; procedure RenderBezier( ACanvas: TObject; Points: TVec2List ); override; procedure RenderCircle( ACanvas: TObject; Position: TVec2; Radius: Float ); override; procedure RenderEllipse( ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2 ); override; procedure RenderRectangle( ACanvas: TObject; TopLeft: TVec2; BottomRight:TVec2 ); override; procedure RenderText( ACanvas: TObject; APosition: TVec2; ACaption: String); override;} procedure RenderGeometry(AGeometry: TGeometry); override; end; { TRendererTextFillColorBGRA } {TRendererTextFillColorBGRA = class ( TRendererTextFillColor ) procedure SetupFont( ACanvas: TBGRACanvas2D ); procedure RenderText( ACanvas: TObject; APosition: TVec2; ACaption: String); override; end;} implementation { TWidgetContextCanvas2D } function TWidgetContextCanvas2D.GetCanvas: TBGRACanvas2D; begin Result:= FOffScreen.Canvas2D; end; procedure TWidgetContextCanvas2D.UpdateRect(ARect: TRectF); begin inherited UpdateRect(ARect); BGRAReplace( FOffScreen, TBGRABitmap.Create( Rect.WidthI, Rect.HeightI, BGRA( 0, 0, 0, 0 ))); end; function TWidgetContextCanvas2D.CreateRect(ARect: TRectF): TGeometryRect; begin Result:= TGeometryRectCanvas2D.Create( Self ); Result.Left:= ARect.Left; Result.Top:= ARect.Top; Result.Width:= ARect.Width; Result.Height:= ARect.Height; end; function TWidgetContextCanvas2D.CreateEllipse(ARect: TRectF): TGeometryEllipse; begin Result:= TGeometryEllipseCanvas2D.Create( Self ); Result.Left:= ARect.Left; Result.Top:= ARect.Top; Result.Width:= ARect.Width; Result.Height:= ARect.Height; end; function TWidgetContextCanvas2D.CreateCircle(ACenter: TVec2; ARadius: Float ): TGeometryCircle; begin Result:= TGeometryCircleCanvas2D.Create( Self ); Result.CenterX:= ACenter.X; Result.CenterY:= ACenter.Y; Result.Radius:= ARadius; end; function TWidgetContextCanvas2D.CreateText(ACaption: String): TGeometryText; begin Result:= TGeometryTextCanvas2D.Create( Self ); Result.Caption:= ACaption; end; procedure TWidgetContextCanvas2D.DrawToCanvas(ACanvas: TCanvas); begin FOffScreen.Draw( ACanvas, 0, 0, False ); end; { TStyleSheetCanvas2D } function TStyleSheetCanvas2D.CreateWidgetContext(ARect: TRectF; ACaption: String): TWidgetContext; begin Result:= TWidgetContextCanvas2D.Create; Result.UpdateRect( ARect ); Result.Caption:= ACaption; end; { TGeometryCircleCanvas2D } procedure TGeometryCircleCanvas2D.PassGeometry; var C: TBGRACanvas2D; begin C:= ( Context as TWidgetContextCanvas2D ).Canvas; C.beginPath; C.circle( CenterX, CenterY, Radius ); C.closePath; end; { TGeometryEllipseCanvas2D } procedure TGeometryEllipseCanvas2D.PassGeometry; var C: TBGRACanvas2D; begin C:= ( Context as TWidgetContextCanvas2D ).Canvas; C.beginPath; C.ellipse( Left, Top, Width / 2, Height / 2 ); C.closePath; end; { TGeometryPathCanvas2D } procedure TGeometryPathCanvas2D.PassGeometry; begin end; { TGeometryTextCanvas2D } procedure TGeometryTextCanvas2D.UpdateCanvasSettings; var C: TBGRACanvas2D; begin C:= ( Context as TWidgetContextCanvas2D ).Canvas; C.fontName:= FontName; C.fontEmHeight:= FontSize; C.fontName:= FontName; C.fontStyle:= BGRAGraphics.TFontStyles( FontStyle ); end; procedure TGeometryTextCanvas2D.PassGeometry; var C: TBGRACanvas2D; begin C:= ( Context as TWidgetContextCanvas2D ).Canvas; UpdateCanvasSettings; C.beginPath; C.text( Caption, Left, Top ); C.closePath; end; procedure TGeometryTextCanvas2D.UpdateGeometry; var Sz: TCanvas2dTextSize; begin inherited UpdateGeometry; UpdateCanvasSettings; Sz:= ( Context as TWidgetContextCanvas2D ).Canvas.measureText( Caption ); FWidth:= Sz.width; FHeight:= Sz.height; end; { TGeometryRectCanvas2D } procedure TGeometryRectCanvas2D.PassGeometry; var C: TBGRACanvas2D; begin C:= ( Context as TWidgetContextCanvas2D ).Canvas; C.beginPath; C.rect( Left, Top, Width, Height ); C.closePath; end; { TRendererTextFillColorBGRA } { procedure TRendererTextFillColorBGRA.SetupFont(ACanvas: TBGRACanvas2D); begin ACanvas.fontName:= FontName; ACanvas.fontEmHeight:= Size; ACanvas.fontName:= FontName; ACanvas.fontStyle:= BGRAGraphics.TFontStyles( Style ); end; procedure TRendererTextFillColorBGRA.RenderText(ACanvas: TObject; APosition: TVec2; ACaption: String); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupFont( C ); C.fillText( ACaption, APosition.X, APosition.Y ); end; end; } { TRendererStrokeColorBGRA } procedure TRendererStrokeColorBGRA.SetupPenBrush(ACanvas: TBGRACanvas2D); var C: TBGRACanvas2D absolute ACanvas; Cl: TIVec4; begin Cl:= ivec4( Color * 255 ); C.lineWidth:= Density; C.strokeStyle( BGRA( Cl.r, Cl.g, Cl.b, Cl.a )); end; {procedure TRendererStrokeColorBGRA.RenderPoints( ACanvas: TObject; Points: TVec2List ); var C: TBGRACanvas2D absolute ACanvas; i: Integer; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.moveTo( Points[ 0 ].X, Points[ 0 ].Y ); for i:= 1 to Points.Count - 1 do C.lineTo( Points[ i ].X, Points[ i ].Y ); C.closePath; C.stroke; end; end; procedure TRendererStrokeColorBGRA.RenderBezier(ACanvas: TObject; Points: TVec2List); var C: TBGRACanvas2D absolute ACanvas; i: Integer; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.moveTo( Points[ 0 ].X, Points[ 0 ].Y ); for i:= 1 to Points.Count - 1 do C.lineTo( Points[ i ].X, Points[ i ].Y ); C.toSpline( Points[ i ] = Points[ 0 ], ssInside ); C.closePath; C.stroke; end; end; procedure TRendererStrokeColorBGRA.RenderCircle(ACanvas: TObject; Position: TVec2; Radius: Float); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.circle( Position.X, Position.Y, Radius ); C.closePath; C.stroke; end; end; procedure TRendererStrokeColorBGRA.RenderEllipse(ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2); var C: TBGRACanvas2D absolute ACanvas; Ctr: TVec2; WH: TVec2; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; Ctr:= ( TopLeft + BottomRight ) / 2; WH:= ( BottomRight - TopLeft ) / 2; C.ellipse( Ctr.X, Ctr.Y, WH.X, WH.Y ); C.closePath; C.stroke; end; end; procedure TRendererStrokeColorBGRA.RenderRectangle(ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.rect( TopLeft.X, TopLeft.Y, BottomRight.X - TopLeft.X, BottomRight.Y - TopLeft.Y ); C.closePath; C.stroke; end; end; procedure TRendererStrokeColorBGRA.RenderText(ACanvas: TObject; APosition: TVec2; ACaption: String); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.strokeText( ACaption, APosition.X, APosition.Y ); end; end; } procedure TRendererStrokeColorBGRA.RenderGeometry(AGeometry: TGeometry); var C: TBGRACanvas2D; begin C:= ( AGeometry.Context as TWidgetContextCanvas2D ).Canvas; SetupPenBrush( C ); AGeometry.PassGeometry; C.stroke; end; { TRendererFillColorBGRA } procedure TRendererFillColorBGRA.SetupPenBrush(ACanvas: TBGRACanvas2D); var C: TBGRACanvas2D absolute ACanvas; Cl: TIVec4; begin Cl:= ivec4( Color * 255 ); C.fillStyle( BGRA( Cl.r, Cl.g, Cl.b, Cl.a )); // C.font:=; end; { procedure TRendererFillColorBGRA.RenderPoints(ACanvas: TObject; Points: TVec2List); var C: TBGRACanvas2D absolute ACanvas; i: Integer; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.moveTo( Points[ 0 ].X, Points[ 0 ].Y ); for i:= 1 to Points.Count - 1 do C.lineTo( Points[ i ].X, Points[ i ].Y ); C.closePath; C.fill; end; end; procedure TRendererFillColorBGRA.RenderBezier(ACanvas: TObject; Points: TVec2List); var C: TBGRACanvas2D absolute ACanvas; i: Integer; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.moveTo( Points[ 0 ].X, Points[ 0 ].Y ); for i:= 1 to Points.Count - 1 do C.lineTo( Points[ i ].X, Points[ i ].Y ); C.toSpline( Points[ i ] = Points[ 0 ], ssInside ); C.closePath; C.fill; end; end; procedure TRendererFillColorBGRA.RenderCircle(ACanvas: TObject; Position: TVec2; Radius: Float); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.circle( Position.X, Position.Y, Radius ); C.closePath; C.fill; end; end; procedure TRendererFillColorBGRA.RenderEllipse(ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2); var C: TBGRACanvas2D absolute ACanvas; Ctr: TVec2; WH: TVec2; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; Ctr:= ( TopLeft + BottomRight ) / 2; WH:= ( BottomRight - TopLeft ) / 2; C.ellipse( Ctr.X, Ctr.Y, WH.X, WH.Y ); C.closePath; C.fill; end; end; procedure TRendererFillColorBGRA.RenderRectangle(ACanvas: TObject; TopLeft: TVec2; BottomRight: TVec2); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.beginPath; C.rect( TopLeft.X, TopLeft.Y, BottomRight.X - TopLeft.X, BottomRight.Y - TopLeft.Y ); C.closePath; C.fill; end; end; procedure TRendererFillColorBGRA.RenderText(ACanvas: TObject; APosition: TVec2; ACaption: String); var C: TBGRACanvas2D absolute ACanvas; begin if ( ACanvas is TBGRACanvas2D ) then begin SetupPenBrush( ACanvas ); C.fillText( ACaption, APosition.X, APosition.Y ); end; end; } procedure TRendererFillColorBGRA.RenderGeometry(AGeometry: TGeometry); var C: TBGRACanvas2D; begin C:= ( AGeometry.Context as TWidgetContextCanvas2D ).Canvas; SetupPenBrush( C ); AGeometry.PassGeometry; C.fill; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) procedure FormPaint(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure DrawRectangledTri(C: TCanvas; AX, AY, ASizeX, ASizeY, AScale: integer; ATriKind: integer; AColorBG, AColorFill, AColorLine: TColor); var b: TBitmap; p0, p1, p2, p3: TPoint; line1, line2: TPoint; ar: array[0..2] of TPoint; begin b:= TBitmap.Create; try b.SetSize(ASizeX*AScale, ASizeY*AScale); p0:= Point(0, 0); p1:= Point(b.Width, 0); p2:= Point(0, b.Height); p3:= Point(b.Width, b.Height); case ATriKind of 0: begin ar[0]:= p1; ar[1]:= p2; ar[2]:= p3; line1:= p1; line2:= p2; end; 1: begin ar[0]:= p0; ar[1]:= p2; ar[2]:= p3; line1:= p0; line2:= p3; end; 2: begin ar[0]:= p0; ar[1]:= p1; ar[2]:= p3; line1:= p0; line2:= p3; end; 3: begin ar[0]:= p0; ar[1]:= p1; ar[2]:= p2; line1:= p1; line2:= p2; end; end; b.Canvas.Brush.Color:= AColorBG; b.Canvas.Fillrect(0, 0, b.Width, b.Height); b.Canvas.Brush.Color:= AColorFill; b.Canvas.Polygon(ar); b.Canvas.Pen.Color:= AColorLine; b.Canvas.Pen.Width:= AScale; b.Canvas.MoveTo(line1); b.Canvas.LineTo(line2); C.StretchDraw( Rect(AX, AY, AX+ASizeX, AY+ASizeY), b); finally b.Free; end; end; procedure TForm1.FormPaint(Sender: TObject); const cBg = clGray; cFill = clLtGray; cLine = clYellow; begin DrawRectangledTri(Canvas, 0, 0, 40, 100, 5, 0, cBG, cFill, cLine); DrawRectangledTri(Canvas, 50, 0, 40, 100, 5, 1, cBG, cFill, cLine); DrawRectangledTri(Canvas, 0, 110, 40, 100, 5, 2, cBG, cFill, cLine); DrawRectangledTri(Canvas, 50, 110, 40, 100, 5, 3, cBG, cFill, cLine); end; end.
unit ConsoleTools; interface uses {$IFDEF MSWINDOWS} windows, {$ENDIF} commandprocessor, stringx, typex, systemx, sysutils, betterobject; const CC_RED = 12; CC_YELLOW = 14; CC_WHITE = 15; CC_SILVER = 7; CC_GREY = 8; CC_BLUE = 9; CC_GREEN = 10; NLR = '`cF`'+CRLF; type TConsole = class(TBetterObject) private {$IFDEF MSWINDOWS} FHandle: THandle; {$ENDIF} twiddleframe: ni; FForeGroundColorNumber: nativeint; FBAckGroundColorNumber: nativeint; procedure SetBackGroundColorNumber(const Value: nativeint); procedure SetForeGroundColorNumber(const Value: nativeint); protected public AutoCRLF: boolean; {$IFDEF MSWINDOWS} property Handle: THandle read FHandle; {$ENDIF} procedure Init;override; procedure SetTextAttribute(iAttr: nativeint); procedure Write(sString: string); procedure WriteLn(sString: string); procedure WhiteSpace(linecount: ni = 4); procedure Append(sString: string); property ForeGroundColorNumber: nativeint read FForeGroundColorNumber write SetForeGroundColorNumber; property BackGroundColorNumber: nativeint read FBAckGroundColorNumber write SetBackGroundColorNumber; procedure Twiddle; procedure WriteEx(sExpression: string; sEsc: char = '`'); procedure WriteOk(bOk: boolean); procedure WatchCommand(c: TCommand); end; procedure WatchCommandInConsole(c: TCommand); procedure ClearScreen; implementation function TextBar(pct: single): string; begin result := '..........'; for var t := 0 to (round((pct*100)/10))-1 do begin result[t+low(result)] := '#'; end; result := '['+result+']'; end; procedure WatchCommandInConsole(c: TCommand); var s: string; iPrevWriteSize: ni; begin iPrevWriteSize := 0; while not c.WaitFor(250) do begin if assigned(c.Thread) then begin c.Lock; try s := zcopy(c.Thread.GetSignalDebug+' '+floatprecision(c.PercentComplete*100,0)+'% '+TextBar(c.PercentComplete)+c.Status,0,70)+CR; Write(stringx.StringRepeat(' ', iPrevWriteSize)+#13); Write(s); iPrevWriteSize := length(s); finally c.unlock; end; end; end; Write(stringx.StringRepeat(' ', iPrevWriteSize)+#13); s := floatprecision(c.PercentComplete*100,0)+'% '+ zcopy(c.Status,0,70)+CR; Write(s); end; procedure TConsole.Append(sString: string); begin {$IFDEF CONSOLE} system.Write(sString); {$ENDIF} end; procedure TConsole.Init; begin inherited; {$IFDEF MSWINDOWS} Fhandle := GetStdHandle(STD_OUTPUT_HANDLE); {$ENDIF} AutoCRLF := true; end; procedure TConsole.SetBackGroundColorNumber(const Value: nativeint); begin {$IFDEF CONSOLE} FBAckGroundColorNumber := Value; {$IFDEF MSWINDOWS} SetConsoleTextAttribute(handle, ((FBAckGroundColorNumber and $f) shl 4) or (FForeGroundColorNumber and $f)); {$ENDIF} {$ENDIF} end; procedure TConsole.SetForeGroundColorNumber(const Value: nativeint); begin {$IFDEF CONSOLE} FForeGroundColorNumber := Value; {$IFDEF MSWINDOWS} SetConsoleTextAttribute(handle, ((FBAckGroundColorNumber and $f) shl 4) or (FForeGroundColorNumber and $f)); {$ENDIF} {$ENDIF} end; procedure TConsole.SetTextAttribute(iAttr: nativeint); begin {$IFDEF CONSOLE} {$IFDEF MSWINDOWS} windows.SetConsoleTextAttribute(handle, iAttr); {$ENDIF} {$ENDIF} end; procedure TConsole.Twiddle; begin twiddleframe := (twiddleframe+1) and 15; case twiddleframe of 0: WriteEx('`cE`[`cF`*`c7`*`c8`* `cE`]'+CR); 1: WriteEx('`cE`[`c7`*`cF`* `cE`]'+CR); 2: WriteEx('`cE`[`c8`*`c7`*`cF`* `cE`]'+CR); 3: WriteEx('`cE`[ `c8`*`c7`*`cF`* `cE`]'+CR); 4: WriteEx('`cE`[ `c8`*`c7`*`cF`* `cE`]'+CR); 5: WriteEx('`cE`[ `c8`*`c7`*`cF`* `cE`]'+CR); 6: WriteEx('`cE`[ `c8`*`c7`*`cF`* `cE`]'+CR); 7: WriteEx('`cE`[ `c8`*`c7`*`cF`* `cE`]'+CR); 8: WriteEx('`cE`[ `c8`*`c7`*`cF`*`cE`]'+CR); 9: WriteEx('`cE`[ `cF`*`c7`*`cE`]'+CR); 10: WriteEx('`cE`[ `cF`*`c7`*`c8`*`cE`]'+CR); 11: WriteEx('`cE`[ `cF`*`c7`*`c8`* `cE`]'+CR); 12: WriteEx('`cE`[ `cF`*`c7`*`c8`* `cE`]'+CR); 13: WriteEx('`cE`[ `cF`*`c7`*`c8`* `cE`]'+CR); 14: WriteEx('`cE`[ `cF`*`c7`*`c8`* `cE`]'+CR); 15: WriteEx('`cE`[ `cF`*`c7`*`c8`* `cE`]'+CR); end; end; procedure TConsole.WatchCommand(c: TCommand); begin WAtchCommandInConsole(c); end; procedure TConsole.WhiteSpace(linecount: ni); begin for var t := 1 to linecount do WriteEx(NLR); end; procedure TConsole.Write(sString: string); begin {$IFDEF CONSOLE} if AutoCRLF then system.Writeln(sString) else system.Write(sString); {$ENDIF} end; procedure TConsole.WriteEx(sExpression: string; sEsc: char = '`'); begin var slh := ParseStringH(sExpression, sESC); for var t := 0 to slh.o.count-1 do begin var sSection: string := slh.o[t]; if (t and 1) = 0 then begin Append(slh.o[t]); end else begin if length(sSection) < 1 then Append(sEsc) else begin var cmd := lowercase(sSection[low(sSection)]); if cmd = 'c' then begin var clr := lowercase(sSection[high(sSection)]); var iclr := strtoint('$'+clr); SetTextAttribute(iclr); end; if cmd = 'n' then begin Append('CRLF'); end; end; end; end; end; procedure TConsole.WriteLn(sString: string); begin {$IFDEF CONSOLE} system.Writeln(sSTring); {$ENDIF} end; procedure TConsole.WriteOk(bOK: boolean); begin if bOK then WriteEx('`cA`Ok!`cF`'+CRLF) else WriteEx('`cC`FAIL!`cF`'+CRLF); end; procedure ClearScreen; {$IFNDEF MSWINDOWS} begin raise ECritical.create('unimplemented'); //TODO -cunimplemented: unimplemented block end; {$ELSE} var stdout: THandle; csbi: TConsoleScreenBufferInfo; ConsoleSize: DWORD; NumWritten: DWORD; Origin: TCoord; begin stdout := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(stdout<>INVALID_HANDLE_VALUE); Win32Check(GetConsoleScreenBufferInfo(stdout, csbi)); ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y; Origin.X := 0; Origin.Y := 0; Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, NumWritten)); Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin, NumWritten)); Win32Check(SetConsoleCursorPosition(stdout, Origin)); end; {$ENDIF} end.
unit uScene; interface uses Types, Graphics, // Own units UCommon, uResFont, uGraph, uHint; type TSceneEnum = (scNone, scMenu, scAbout, scSellect, scName, scRace, scLoad, scGame, scDialog, scTrade, scInv, scStat, scHero, scQuest, scSkill, scHelp, scFrame, scCraft, scGold); TMouseBtn = (mbLeft, mbRight, mbMiddle, mbDblLeft); TSceneCustom = class(THODObject) public procedure Draw(); virtual; function Click(Button: TMouseBtn): Boolean; virtual; function Keys(var Key: Word): Boolean; virtual; function MouseMove(X, Y: Integer): Boolean; virtual; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; virtual; function Enum(): TSceneEnum; virtual; function KeyPress(var Key: Char): Boolean; virtual; procedure Added(); virtual; procedure Removed(); virtual; end; TSceneManager = class(THODObject) private FScenes: TObjList; Owning: array[TSceneEnum] of Boolean; function GetScene(Index: TSceneEnum): TSceneCustom; public //** Конструктор. constructor Create(); destructor Destroy(); override; procedure AddScene(Scene: TSceneCustom; Own: Boolean = False); procedure SetScene(Scene: TSceneCustom; Own: Boolean = False); function IsScene(SceneEnum: TSceneEnum): Boolean; procedure Clear(); function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; virtual; procedure DeleteScene(SceneEnum: TSceneEnum; NeedRedraw: Boolean = True); property Scenes[Index: TSceneEnum]: TSceneCustom read GetScene; function Click(Button: TMouseBtn): Boolean; function MouseMove(X, Y: Integer): Boolean; procedure Draw(); function Keys(var Key: Word): Boolean; overload; function Keys(var Key: Char): Boolean; overload; end; TFrameScenePos = (spLeft, spRight, spFull); TSceneFrame = class(TSceneCustom) private FImage: TBitmap; FClose: TBitmap; FIsLoad: Boolean; FBack: TBitmap; FGraph: TGraph; FScenePos: TFrameScenePos; FResFont: TResFont; FHint: THint; procedure SetResFont(const Value: TResFont); procedure SetHint(const Value: THint); function GetOrigin: TPoint; public HintBack: TBitmap; property Hint: THint read FHint write SetHint; property Graph: TGraph read FGraph write FGraph; property Back: TBitmap read FBack write FBack; property ResFont: TResFont read FResFont write SetResFont; procedure Refresh(); procedure Close(); //** Конструктор. constructor Create(AScenePos: TFrameScenePos); destructor Destroy; override; procedure Draw(); override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; function Enum(): TSceneEnum; override; property ScenePos: TFrameScenePos read FScenePos; property Origin: TPoint read GetOrigin; end; const SceneCount = Ord(High(TSceneEnum)) + 1; function SceneManager(): TSceneManager; function IsLeftFrame: Boolean; function IsRightFrame: Boolean; implementation uses Windows, SysUtils, uMain, uGUIBorder, uSCR, uUtils, uSounds, uIni, uGUI, uSceneStat, uSceneChar, uSceneQuest, uSceneSkill, uSceneHelp, uSceneCraft, uSceneInv, uMusicMenu; var TheSceneManager: TSceneManager; { TCustomScene } procedure TSceneCustom.Added; begin end; function TSceneCustom.Click(Button: TMouseBtn): Boolean; begin Result := False; end; procedure TSceneCustom.Draw; begin end; function TSceneCustom.Enum: TSceneEnum; begin Result := scNone; end; function TSceneCustom.KeyPress(var Key: Char): Boolean; begin Result := False; end; function TSceneCustom.Keys(var Key: Word): Boolean; begin Result := False; end; function TSceneCustom.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; begin Result := False; end; function TSceneCustom.MouseMove(X, Y: Integer): Boolean; begin Result := False; end; procedure TSceneCustom.Removed; begin end; function SceneManager(): TSceneManager; begin Result := TheSceneManager; end; { TSceneManager } procedure TSceneManager.AddScene(Scene: TSceneCustom; Own: Boolean = False); begin if Scenes[Scene.Enum] <> nil then DeleteScene(Scene.Enum); FScenes[Ord(Scene.Enum)] := Scene; Owning[Scene.Enum] := Own; Scene.Added(); SceneManager.Draw(); end; constructor TSceneManager.Create; begin FScenes := TObjList.Create(False); FScenes.Count := SceneCount; end; procedure TSceneManager.DeleteScene(SceneEnum: TSceneEnum; NeedRedraw: Boolean = True); begin if Assigned(FScenes[Ord(SceneEnum)]) then (FScenes[Ord(SceneEnum)] as TSceneCustom).Removed(); if Owning[SceneEnum] then Scenes[SceneEnum].Free; FScenes[Ord(SceneEnum)] := nil; Owning[SceneEnum] := False; if NeedRedraw then SceneManager.Draw(); end; destructor TSceneManager.Destroy; begin Clear(); FreeAndNil(FScenes); inherited; end; procedure TSceneManager.Draw; var i: TSceneEnum; begin for i := Low(TSceneEnum) to High(TSceneEnum) do if Scenes[i] <> nil then Scenes[i].Draw(); fMain.Display(); MusicMenu.SetVolume(Sound.Volume); if IsMenu then MusicMenu.Play else MusicMenu.Stop; end; procedure TSceneManager.Clear(); var i: TSceneEnum; begin for i := Low(TSceneEnum) to High(TSceneEnum) do DeleteScene(i, False); end; function TSceneManager.GetScene(Index: TSceneEnum): TSceneCustom; begin Result := TSceneCustom(FScenes[Ord(Index)]); end; function TSceneManager.Keys(var Key: Word): Boolean; var i: TSceneEnum; sc: TSceneFrame; DontAdd: Boolean; begin if Key in [ord('A'), ord('C'), ord('S'), ord('Q'), ord('I'), ord('H')] then begin case Key of ord('A'): sc := SceneSkill; ord('C'): sc := SceneChar; ord('S'): sc := SceneStat; ord('Q'): sc := SceneQuest; ord('I'): sc := SceneInv; ord('H'): begin sc := SceneHelp; IsHelp := False; end; end; DontAdd := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if (Scenes[i] <> nil) and (Scenes[i] is TSceneFrame) then begin if Scenes[i] = sc then DontAdd := True; if TSceneFrame(Scenes[i]).ScenePos in [sc.ScenePos, spFull] then SceneManager.DeleteScene(i); end; if Scenes[scRace] <> nil then DontAdd := true; if not DontAdd then SceneManager.AddScene(sc); Exit; end; Result := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if not Result and (Scenes[i] <> nil) then Result := Result or Scenes[i].Keys(Key); end; procedure TSceneManager.SetScene(Scene: TSceneCustom; Own: Boolean = False); begin Clear; AddScene(Scene, Own); end; function TSceneManager.Keys(var Key: Char): Boolean; var i: TSceneEnum; begin Result := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if not Result and (Scenes[i] <> nil) then Result := Result or Scenes[i].KeyPress(Key); end; function TSceneManager.Click(Button: TMouseBtn): Boolean; var i: TSceneEnum; begin Result := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if not Result and (Scenes[i] <> nil) then Result := Result or Scenes[i].Click(Button); end; function TSceneManager.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; var i: TSceneEnum; begin Result := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if not Result and (Scenes[i] <> nil) then Result := Result or Scenes[i].MouseDown(Button, X, Y); end; function TSceneManager.IsScene(SceneEnum: TSceneEnum): Boolean; begin Result := (Scenes[SceneEnum] <> nil); end; function TSceneManager.MouseMove(X, Y: Integer): Boolean; var i: TSceneEnum; begin Result := False; for i := Low(TSceneEnum) to High(TSceneEnum) do if not Result and (Scenes[i] <> nil) then Result := Result or Scenes[i].MouseMove(X, Y); end; function IsLeftFrame: Boolean; begin Result := SceneManager.IsScene(scStat) or SceneManager.IsScene(scHero) or SceneManager.IsScene(scQuest) end; function IsRightFrame: Boolean; begin Result := SceneManager.IsScene(scInv) or SceneManager.IsScene(scSkill) end; { TFrameScene } function TSceneFrame.Click(Button: TMouseBtn): Boolean; var IsHandled: Boolean; begin Result := False; IsHandled := False; case FScenePos of spLeft : if IsMouseInRect(368, 528, 392, 552) then IsHandled := True; spRight : if IsMouseInRect(408, 528, 432, 552) then IsHandled := True; spFull : if IsMouseInRect(765, 528, 789, 552) then IsHandled := True; end; if IsHandled then begin Result := True; Close; end; end; procedure TSceneFrame.Draw; begin Back.Assign(FImage); case FScenePos of spLeft : Back.Canvas.Draw(368, 528, FClose); spRight : Back.Canvas.Draw(8, 528, FClose); spFull : Back.Canvas.Draw(765, 528, FClose); end; Refresh; end; procedure TSceneFrame.Close; begin SceneManager.Clear; SCR.Hint := nil; fMain.RefreshBox; Sound.PlayClick(); end; constructor TSceneFrame.Create(AScenePos: TFrameScenePos); begin FIsLoad := False; FScenePos := AScenePos; FResFont := TResFont.Create; FResFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); FGraph := TGraph.Create(Path + 'Data\Images\GUI\'); FImage := Graphics.TBitmap.Create; FGraph.LoadImage('BG.bmp', FImage); FImage.Height := 566; if (FScenePos = spFull) then begin FImage.Width := 800; FImage.Canvas.Draw(400, 0, FImage); end; GUIBorder.Make(FImage); FClose := Graphics.TBitmap.Create; FBack := Graphics.TBitmap.Create; with FBack.Canvas do begin Font.Name := ResFont.FontName; Font.Size := 14; Font.Color := $006CB1C5; Brush.Style := bsClear; end; FGraph.LoadImage('Close.png', FClose); HintBack := Graphics.TBitmap.Create; HintBack.Assign(FImage); Hint := THint.Create; end; destructor TSceneFrame.Destroy; begin FreeAndNil(FBack); FreeAndNil(FGraph); FreeAndNil(FClose); FreeAndNil(FImage); FreeAndNil(HintBack); Hint.Free; inherited; end; function TSceneFrame.Enum: TSceneEnum; begin Result := scFrame; end; function TSceneFrame.GetOrigin: TPoint; begin if scenepos = spRight then Result := Point(400, 0) else Result := Point(0, 0); end; function TSceneFrame.Keys(var Key: Word): Boolean; begin Result := True; case Key of 27: Close; end; end; procedure TSceneFrame.Refresh; begin case FScenePos of spLeft : begin if IsMouseInRect(368, 528, 392, 552) then Hint.ShowString(368, 528, 24, 'Закрыть', True, Origin, HintBack); SCR.BG.Canvas.Draw(0, 0, Back); end; spRight : begin if IsMouseInRect(408, 528, 432, 552) then Hint.ShowString(0, 528, 24, 'Закрыть', True, Origin, HintBack); SCR.BG.Canvas.Draw(400, 0, Back); end; spFull : begin if IsMouseInRect(765, 528, 789, 552) and not IsMenu then Hint.ShowString(765, 528, 24, 'Закрыть', True, Origin, HintBack); SCR.BG.Canvas.Draw(0, 0, Back); end; end; end; procedure TSceneFrame.SetResFont(const Value: TResFont); begin FResFont := Value; end; procedure TSceneFrame.SetHint(const Value: THint); begin FHint := Value; end; initialization TheSceneManager := TSceneManager.Create(); finalization FreeAndNil(TheSceneManager); end.
unit upmgThreadEmailSender; interface uses Classes, Windows, umailSendMail; type TpmgThreadEmailSender = class(TThread) private FMailSender : TmailSendEmail; FsMailAviso : string; FnIntervalo : integer; FnIntervaloContador : integer; FsListaEmails : TStringList; function ServicoAtivo : boolean; procedure CalcHoraNovaExecucao; protected procedure Execute; override; procedure OnBeforeSend(Sender: TObject); procedure OnAfterSend(Sender: TObject); public constructor Create(CreateSuspended: Boolean); reintroduce; destructor Destroy; override; end; implementation uses upmgDMemailSender, upmgEmailSenderConfig, umpgConstantes, SysUtils, upmgConstantes, umailEmails, DateUtils, umpgSendMail, umailContas, DB, IdExplicitTLSClientServerBase; { TpmgThreadEmailSender } procedure TpmgThreadEmailSender.CalcHoraNovaExecucao; begin if (FnIntervalo > 0) then FnIntervaloContador := FnIntervalo * 60 {segundos} * 60 {minutos} else Terminate; end; constructor TpmgThreadEmailSender.Create(CreateSuspended: Boolean); begin inherited; FMailSender := TmailSendEmail.Create(fpmgDMemailSender.ZConnection); FMailSender.OnBeforeSend := OnBeforeSend; FMailSender.OnAfterSend := OnAfterSend; FreeOnTerminate := True; FsMailAviso := STRING_INDEFINIDO; FnIntervalo := NUMERO_INDEFINIDO; FnIntervaloContador := NUMERO_INDEFINIDO; FsListaEmails := TStringList.Create; end; destructor TpmgThreadEmailSender.Destroy; begin FMailSender.Free; FsListaEmails.Free; inherited; end; procedure TpmgThreadEmailSender.Execute; var emailEmails : TemailEmails; function VerificaData : boolean; begin if (emailEmails.FieldByName('NUDIASPERIODICIDADE').AsInteger > 0) then result := (DaySpan( emailEmails.FieldByName('DTULTENVIO').AsDateTime, Now) > emailEmails.FieldByName('NUDIASPERIODICIDADE').AsInteger) else result := false; end; procedure SendMailAviso; var oSend : TmpgSendMail; oContas : TemailContas; begin oContas := TemailContas.Create(nil); oSend := TmpgSendMail.Create; try oContas.Connection := fpmgDMemailSender.ZConnection; oContas.Select := 'SelectConsulta'; oContas.ParamByName('USUARIO').AsString := FsMailAviso; oContas.Open; if not(oContas.IsEmpty) then begin oSend.FromList.Address := oContas.FieldByName('USUARIO').AsString; oSend.FromList.Name := 'Personal Manager'; oSend.Message.Subject := 'EmailSender'; oSend.Message.ContentType := 'text/plain'; oSend.Message.Body := FsListaEmails.Text; oSend.Message.Date := Now; oSend.Server.Host := oContas.FieldByName('SERVIDOR').AsString; oSend.Server.Port := oContas.FieldByName('NUPORTA').AsInteger; oSend.Server.UserName := oContas.FieldByName('USUARIO').AsString; oSend.Server.UserPws := oContas.FieldByName('SENHA').AsString; oSend.UseTLS := TIdUseTLS(oContas.FieldByName('NUTSL').AsInteger); oSend.ToList.Address := FsMailAviso; oSend.SendMail; end; finally oSend.Free; oContas.Free; end; end; begin inherited; if (ServicoAtivo) then while not Terminated do begin if (FnIntervaloContador = 0) or (FnIntervaloContador = NUMERO_INDEFINIDO) then begin emailEmails := TemailEmails.Create(nil); try emailEmails.Select := 'SelectEnvioAtivos'; emailEmails.Connection := fpmgDMemailSender.ZConnection; emailEmails.Open; while not emailEmails.Eof do begin if (VerificaData) then try FMailSender.CreateMsg(True, emailEmails.FieldByName('CDEMAIL').AsInteger); except On E: Exception do FsListaEmails.Add(emailEmails.FieldByName('EMAIL').AsString + ' - Erro: ' + E.Message); end; emailEmails.Next; end; if (FsListaEmails.Count > 0) then begin SendMailAviso; FsListaEmails.Clear; end; finally emailEmails.Free; end; CalcHoraNovaExecucao; end; Sleep(1000); Dec(FnIntervaloContador); end; end; procedure TpmgThreadEmailSender.OnAfterSend(Sender: TObject); begin with TmailSendEmail(Sender) do FsListaEmails.Add(ToNome + ' <' + ToEmail + '> - ' + ToCargo + ': ' + ToEmpresa + ' [' + Assunto + ']'); end; procedure TpmgThreadEmailSender.OnBeforeSend(Sender: TObject); begin end; function TpmgThreadEmailSender.ServicoAtivo: boolean; var epmgConfig : TepmgEmailSenderConfig; begin epmgConfig := TepmgEmailSenderConfig.Create(nil); try FnIntervalo := NUMERO_INDEFINIDO; FsMailAviso := STRING_INDEFINIDO; epmgConfig.Select := 'SelectPadrao'; epmgConfig.Open; while not epmgConfig.Eof do begin if (UpperCase(epmgConfig.FieldByName('CDCONFIG').AsString) = smailCONFIG_EMAIL_AVISO) then FsMailAviso := epmgConfig.FieldByName('VLCONFIG1').AsString else if (UpperCase(epmgConfig.FieldByName('CDCONFIG').AsString) = smailCONFIG_INTERVALO) then FnIntervalo := epmgConfig.FieldByName('VLCONFIG1').AsInteger; epmgConfig.Next; end; result := (FnIntervalo > 0); finally epmgConfig.Free; end; end; end.
unit uClienteCRUD; interface uses uCliente, FireDAC.Comp.Client; type TClienteCRUD = class(TCliente) private FConexao : TFDConnection; FCliente : TFDQuery; FpsCidadeDescricao: String; procedure pcdInsertCliente; procedure pcdUpdateCliente; procedure pcdParametrosCliente; function fncRetornaCodCidade(psCidade: String): Integer; procedure SetpsCidadeDescricao(const Value: String); public constructor Create(poConexao: TFDConnection); overload; destructor Destroy; override; procedure pcdGravarCliente; procedure pcdExluirCliente; function fncConsultaClientes: TFDQuery; published property psCidadeDescricao : String read FpsCidadeDescricao write SetpsCidadeDescricao; end; implementation uses System.SysUtils; { TClienteCRUD } constructor TClienteCRUD.Create(poConexao: TFDConnection); begin FConexao := poConexao; FCliente := TFDQuery.Create(nil); FCliente.Close; FCliente.Connection := FConexao; end; destructor TClienteCRUD.Destroy; begin inherited; end; function TClienteCRUD.fncRetornaCodCidade(psCidade: String): Integer; var vloCidade : TFDQuery; begin Result := 1; vloCidade := TFDQuery.Create(nil); try vloCidade.Close; vloCidade.Connection := FConexao; vloCidade.SQL.Clear; vloCidade.SQL.Add('SELECT CID_CODIGO FROM CIDADE WHERE CID_DESCRICAO = :CIDADE'); vloCidade.ParamByName('CIDADE').AsString := psCidade; vloCidade.Open(); if not vloCidade.IsEmpty then Result := vloCidade.FieldByName('CID_CODIGO').AsInteger; finally FreeAndNil(vloCidade); end; end; function TClienteCRUD.fncConsultaClientes: TFDQuery; begin FCliente.SQL.Clear; FCliente.SQL.Add('SELECT CLI_CODIGO, CLI_RAZAO, CLI_TELEFONE, CLI_TIPOPESSOA,'); FCliente.SQL.Add(' CLI_CNPJCPF, CLI_RETAGUARDA, CLI_PDV, CLI_EMAIL,'); FCliente.SQL.Add(' CLI_ENDERECO, CLI_NUMERO, CLI_CIDADE, CID_DESCRICAO,'); FCliente.SQL.Add(' CLI_ESTADO, CLI_CEP, CLI_IE, CLI_REVENDA, CLI_BAIRRO,'); FCliente.SQL.Add(' CLI_DATACADASTRO, CLI_TIPOLICENCA'); FCliente.SQL.Add('FROM CLIENTE'); FCliente.SQL.Add('INNER JOIN CIDADE ON (CLI_CIDADE = CID_CODIGO)'); if CLI_CODIGO <> 0 then begin FCliente.SQL.Add('WHERE CLI_CODIGO = :CODIGO'); FCliente.ParamByName('CODIGO').AsInteger := CLI_CODIGO; end; FCliente.Open(); Result := FCliente; end; procedure TClienteCRUD.pcdExluirCliente; begin try FCliente.SQL.Clear; FCliente.SQL.Add('DELETE FROM CLIENTE WHERE CLI_CODIGO = :CODIGO'); FCliente.ParamByName('CODIGO').AsInteger := CLI_CODIGO; FCliente.ExecSQL; except on E:Exception do begin raise Exception.Create('Erro ao excluir cliente com a mensagem: '+ E.Message); end; end; end; procedure TClienteCRUD.pcdGravarCliente; begin FCliente.SQL.Clear; FCliente.SQL.Add('SELECT CLI_CODIGO FROM CLIENTE WHERE CLI_CODIGO = :CODIGO'); FCliente.ParamByName('CODIGO').AsInteger := CLI_CODIGO; FCliente.Open(); CLI_CIDADE := fncRetornaCodCidade(FpsCidadeDescricao); try if FCliente.IsEmpty then pcdInsertCliente else pcdUpdateCliente; pcdParametrosCliente; except on E:Exception do begin raise Exception.Create('Erro ao inserir cliente com a mensagem: '+ E.Message); end; end; end; procedure TClienteCRUD.pcdInsertCliente; begin FCliente.SQL.Clear; FCliente.SQL.Add('INSERT INTO CLIENTE (CLI_CODIGO, CLI_RAZAO, CLI_TELEFONE, CLI_TIPOPESSOA, CLI_CNPJCPF,'); FCliente.SQL.Add(' CLI_RETAGUARDA, CLI_PDV, CLI_EMAIL, CLI_ENDERECO, CLI_NUMERO,'); FCliente.SQL.Add(' CLI_CIDADE, CLI_ESTADO, CLI_CEP, CLI_IE, CLI_REVENDA, CLI_BAIRRO,'); FCliente.SQL.Add(' CLI_DATACADASTRO, CLI_TIPOLICENCA)'); FCliente.SQL.Add('VALUES (:CLI_CODIGO, :CLI_RAZAO, :CLI_TELEFONE, :CLI_TIPOPESSOA, :CLI_CNPJCPF,'); FCliente.SQL.Add(' :CLI_RETAGUARDA, :CLI_PDV, :CLI_EMAIL, :CLI_ENDERECO, :CLI_NUMERO,'); FCliente.SQL.Add(' :CLI_CIDADE, :CLI_ESTADO, :CLI_CEP, :CLI_IE, :CLI_REVENDA, :CLI_BAIRRO,'); FCliente.SQL.Add(' :CLI_DATACADASTRO, :CLI_TIPOLICENCA)'); end; procedure TClienteCRUD.pcdUpdateCliente; begin FCliente.SQL.Clear; FCliente.SQL.Add('UPDATE CLIENTE SET CLI_RAZAO = :CLI_RAZAO,'); FCliente.SQL.Add(' CLI_TELEFONE = :CLI_TELEFONE,'); FCliente.SQL.Add(' CLI_TIPOPESSOA = :CLI_TIPOPESSOA,'); FCliente.SQL.Add(' CLI_CNPJCPF = :CLI_CNPJCPF,'); FCliente.SQL.Add(' CLI_RETAGUARDA = :CLI_RETAGUARDA,'); FCliente.SQL.Add(' CLI_PDV = :CLI_PDV,'); FCliente.SQL.Add(' CLI_EMAIL = :CLI_EMAIL,'); FCliente.SQL.Add(' CLI_ENDERECO = :CLI_ENDERECO,'); FCliente.SQL.Add(' CLI_NUMERO = :CLI_NUMERO,'); FCliente.SQL.Add(' CLI_CIDADE = :CLI_CIDADE,'); FCliente.SQL.Add(' CLI_ESTADO = :CLI_ESTADO,'); FCliente.SQL.Add(' CLI_CEP = :CLI_CEP,'); FCliente.SQL.Add(' CLI_IE = :CLI_IE,'); FCliente.SQL.Add(' CLI_REVENDA = :CLI_REVENDA,'); FCliente.SQL.Add(' CLI_BAIRRO = :CLI_BAIRRO,'); FCliente.SQL.Add(' CLI_DATACADASTRO = :CLI_DATACADASTRO,'); FCliente.SQL.Add(' CLI_TIPOLICENCA = :CLI_TIPOLICENCA'); FCliente.SQL.Add('WHERE CLI_CODIGO = :CLI_CODIGO'); end; procedure TClienteCRUD.SetpsCidadeDescricao(const Value: String); begin FpsCidadeDescricao := Value; end; procedure TClienteCRUD.pcdParametrosCliente; begin FCliente.ParamByName('CLI_CODIGO').AsInteger := CLI_CODIGO; FCliente.ParamByName('CLI_RAZAO').AsString := CLI_RAZAO; FCliente.ParamByName('CLI_TELEFONE').AsString := CLI_TELEFONE; FCliente.ParamByName('CLI_TIPOPESSOA').AsString := CLI_TIPOPESSOA; FCliente.ParamByName('CLI_CNPJCPF').AsString := CLI_CNPJCPF; FCliente.ParamByName('CLI_RETAGUARDA').AsInteger := CLI_RETAGUARDA; FCliente.ParamByName('CLI_PDV').AsInteger := CLI_PDV; FCliente.ParamByName('CLI_EMAIL').AsString := CLI_EMAIL; FCliente.ParamByName('CLI_ENDERECO').AsString := CLI_ENDERECO; FCliente.ParamByName('CLI_NUMERO').AsString := CLI_NUMERO; FCliente.ParamByName('CLI_CIDADE').AsInteger := CLI_CIDADE; FCliente.ParamByName('CLI_ESTADO').AsString := CLI_ESTADO; FCliente.ParamByName('CLI_CEP').AsString := CLI_CEP; FCliente.ParamByName('CLI_IE').AsString := CLI_IE; FCliente.ParamByName('CLI_REVENDA').AsInteger := CLI_REVENDA; FCliente.ParamByName('CLI_BAIRRO').AsString := CLI_BAIRRO; FCliente.ParamByName('CLI_DATACADASTRO').AsString := FormatDateTime('mm/dd/yyyy', CLI_DATACADASTRO); FCliente.ParamByName('CLI_TIPOLICENCA').AsString := CLI_TIPOLICENCA; FCliente.ExecSQL; end; end.
unit kyugo_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,ay_8910,rom_engine, pal_engine,sound_engine,timer_engine; function iniciar_kyugo_hw:boolean; implementation const repulse_rom:array[0..2] of tipo_roms=( (n:'repulse.b5';l:$2000;p:0;crc:$fb2b7c9d),(n:'repulse.b6';l:$2000;p:$2000;crc:$99129918), (n:'7.j4';l:$2000;p:$4000;crc:$57a8e900)); repulse_snd:array[0..3] of tipo_roms=( (n:'1.f2';l:$2000;p:0;crc:$c485c621),(n:'2.h2';l:$2000;p:$2000;crc:$b3c6a886), (n:'3.j2';l:$2000;p:$4000;crc:$197e314c),(n:'repulse.b4';l:$2000;p:$6000;crc:$86b267f3)); repulse_char:tipo_roms=(n:'repulse.a11';l:$1000;p:0;crc:$8e1de90a); repulse_tiles:array[0..2] of tipo_roms=( (n:'15.9h';l:$2000;p:0;crc:$c9213469),(n:'16.10h';l:$2000;p:$2000;crc:$7de5d39e), (n:'17.11h';l:$2000;p:$4000;crc:$0ba5f72c)); repulse_sprites:array[0..5] of tipo_roms=( (n:'8.6a';l:$4000;p:0;crc:$0e9f757e),(n:'9.7a';l:$4000;p:$4000;crc:$f7d2e650), (n:'10.8a';l:$4000;p:$8000;crc:$e717baf4),(n:'11.9a';l:$4000;p:$c000;crc:$04b2250b), (n:'12.10a';l:$4000;p:$10000;crc:$d110e140),(n:'13.11a';l:$4000;p:$14000;crc:$8fdc713c)); repulse_prom:array[0..2] of tipo_roms=( (n:'b.1j';l:$100;p:0;crc:$3ea35431),(n:'g.1h';l:$100;p:$100;crc:$acd7a69e), (n:'r.1f';l:$100;p:$200;crc:$b7f48b41)); srdmission_rom:array[0..1] of tipo_roms=( (n:'5.t2';l:$4000;p:0;crc:$a682b48c),(n:'7.t3';l:$4000;p:$4000;crc:$1719c58c)); srdmission_snd:array[0..1] of tipo_roms=( (n:'1.t7';l:$4000;p:0;crc:$dc48595e),(n:'3.t8';l:$4000;p:$4000;crc:$216be1e8)); srdmission_char:tipo_roms=(n:'15.4a';l:$1000;p:0;crc:$4961f7fd); srdmission_tiles:array[0..2] of tipo_roms=( (n:'17.9h';l:$2000;p:0;crc:$41211458),(n:'18.10h';l:$2000;p:$2000;crc:$740eccd4), (n:'16.11h';l:$2000;p:$4000;crc:$c1f4a5db)); srdmission_sprites:array[0..5] of tipo_roms=( (n:'14.6a';l:$4000;p:0;crc:$3d4c0447),(n:'13.7a';l:$4000;p:$4000;crc:$22414a67), (n:'12.8a';l:$4000;p:$8000;crc:$61e34283),(n:'11.9a';l:$4000;p:$c000;crc:$bbbaffef), (n:'10.10a';l:$4000;p:$10000;crc:$de564f97),(n:'9.11a';l:$4000;p:$14000;crc:$890dc815)); srdmission_prom:array[0..3] of tipo_roms=( (n:'mr.1j';l:$100;p:0;crc:$110a436e),(n:'mg.1h';l:$100;p:$100;crc:$0fbfd9f0), (n:'mb.1f';l:$100;p:$200;crc:$a342890c),(n:'m2.5j';l:$20;p:$300;crc:$190a55ad)); airwolf_rom:tipo_roms=(n:'b.2s';l:$8000;p:0;crc:$8c993cce); airwolf_snd:tipo_roms=(n:'a.7s';l:$8000;p:0;crc:$a3c7af5c); airwolf_char:tipo_roms=(n:'f.4a';l:$1000;p:0;crc:$4df44ce9); airwolf_tiles:array[0..2] of tipo_roms=( (n:'09h_14.bin';l:$2000;p:0;crc:$25e57e1f),(n:'10h_13.bin';l:$2000;p:$2000;crc:$cf0de5e9), (n:'11h_12.bin';l:$2000;p:$4000;crc:$4050c048)); airwolf_sprites:array[0..2] of tipo_roms=( (n:'e.6a';l:$8000;p:0;crc:$e8fbc7d2),(n:'d.8a';l:$8000;p:$8000;crc:$c5d4156b), (n:'c.10a';l:$8000;p:$10000;crc:$de91dfb1)); airwolf_prom:array[0..3] of tipo_roms=( (n:'01j.bin';l:$100;p:0;crc:$6a94b2a3),(n:'01h.bin';l:$100;p:$100;crc:$ec0923d3), (n:'01f.bin';l:$100;p:$200;crc:$ade97052),(n:'74s288-2.bin';l:$20;p:$300;crc:$190a55ad)); var scroll_x:word; scroll_y,fg_color,bg_pal_bank:byte; nmi_enable:boolean; color_codes:array[0..$1f] of byte; procedure update_video_kyugo_hw; var f,nchar:word; atrib,x,y,color:byte; procedure draw_sprites; var n,y:byte; offs,color,sx,sy,nchar,atrib:word; begin for n:=0 to (12*2)-1 do begin offs:=(n mod 12) shl 1+64*(n div 12); sx:=memoria[$9029+offs]+256*(memoria[$9829+offs] and 1); sy:=255-memoria[$a028+offs]+2; color:=(memoria[$a029+offs] and $1f) shl 3; for y:=0 to 15 do begin nchar:=memoria[$9028+offs+128*y]; atrib:=memoria[$9828+offs+128*y]; nchar:=nchar or ((atrib and $01) shl 9) or ((atrib and $02) shl 7); put_gfx_sprite(nchar,color,(atrib and 8)<>0,(atrib and 4)<>0,2); actualiza_gfx_sprite(sx,sy+16*y,3,2); end; end; end; begin for f:=0 to $7ff do begin //background if gfx[1].buffer[f] then begin x:=f mod 64; y:=f div 64; atrib:=memoria[$8800+f]; nchar:=memoria[$8000+f]+((atrib and $03) shl 8); color:=((atrib shr 4) or bg_pal_bank) shl 3; put_gfx_flip(x*8,y*8,nchar,color,2,1,(atrib and $4)<>0,(atrib and $8)<>0); gfx[1].buffer[f]:=false; end; //foreground if gfx[0].buffer[f] then begin x:=f mod 64; y:=f div 64; nchar:=memoria[$9000+f]; put_gfx_trans(x*8,y*8,nchar,2*color_codes[nchar shr 3]+fg_color,1,0); gfx[0].buffer[f]:=false; end; end; scroll_x_y(2,3,scroll_x+32,scroll_y); draw_sprites; actualiza_trozo(0,0,256,512,1,0,0,256,512,3); actualiza_trozo_final(0,16,288,224,3); end; procedure eventos_kyugo_hw; begin if event.arcade then begin //system if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); //P1 if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); //P2 if arcade_input.left[0] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.right[0] then marcade.in2:=(marcade.in2 or $2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.up[0] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.down[0] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); if arcade_input.but0[0] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.but1[0] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); end; end; procedure kyugo_hw_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if f=239 then begin if nmi_enable then z80_0.change_nmi(PULSE_LINE); update_video_kyugo_hw; end; end; eventos_kyugo_hw; video_sync; end; end; function kyugo_getbyte(direccion:word):byte; begin case direccion of 0..$a7ff,$f000..$f7ff:kyugo_getbyte:=memoria[direccion]; end; end; procedure kyugo_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$8fff:if memoria[direccion]<>valor then begin gfx[1].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $9000..$97ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $9800..$9fff:memoria[direccion]:=valor or $f0; $a000..$a7ff,$f000..$f7ff:memoria[direccion]:=valor; $a800:scroll_x:=(scroll_x and $100) or valor; $b000:begin scroll_x:=(scroll_x and $ff) or ((valor and $1) shl 8); if fg_color<>((valor and $20) shr 3) then begin fg_color:=(valor and $20) shr 3; fillchar(gfx[0].buffer[0],$800,1); end; if bg_pal_bank<>((valor and $40) shr 2) then begin bg_pal_bank:=(valor and $40) shr 2; fillchar(gfx[1].buffer[0],$800,1); end; end; $b800:scroll_y:=valor; end; end; procedure kyugo_outbyte(puerto:word;valor:byte); begin case (puerto and $7) of 0:nmi_enable:=(valor and 1)<>0; 1:main_screen.flip_main_screen:=(valor<>0); 2:if (valor<>0) then z80_1.change_halt(CLEAR_LINE) else z80_1.change_halt(ASSERT_LINE); end; end; //Sound function snd_kyugo_hw_getbyte(direccion:word):byte; begin case direccion of 0..$7fff:snd_kyugo_hw_getbyte:=mem_snd[direccion]; $a000..$a7ff:snd_kyugo_hw_getbyte:=memoria[direccion+$5000]; $c000:snd_kyugo_hw_getbyte:=marcade.in2; $c040:snd_kyugo_hw_getbyte:=marcade.in1; $c080:snd_kyugo_hw_getbyte:=marcade.in0; end; end; procedure snd_kyugo_hw_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $a000..$a7ff:memoria[direccion+$5000]:=valor; end; end; function snd_kyugo_inbyte(puerto:word):byte; begin if (puerto and $ff)=2 then snd_kyugo_inbyte:=ay8910_0.read; end; procedure snd_kyugo_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $00:ay8910_0.Control(valor); $01:ay8910_0.write(valor); $40:ay8910_1.Control(valor); $41:ay8910_1.write(valor); end; end; function kyugo_porta_r:byte; begin kyugo_porta_r:=marcade.dswa; end; function kyugo_portb_r:byte; begin kyugo_portb_r:=marcade.dswb; end; procedure kyugo_snd_irq; begin z80_1.change_irq(HOLD_LINE); end; procedure kyugo_snd_update; begin ay8910_0.update; ay8910_1.update; end; //SRD Mission function srdmission_getbyte(direccion:word):byte; begin case direccion of 0..$a7ff,$e000..$e7ff:srdmission_getbyte:=memoria[direccion]; end; end; procedure srdmission_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$8fff:if memoria[direccion]<>valor then begin gfx[1].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $9000..$97ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $9800..$9fff:memoria[direccion]:=valor or $f0; $a000..$a7ff,$e000..$e7ff:memoria[direccion]:=valor; $a800:scroll_x:=(scroll_x and $100) or valor; $b000:begin scroll_x:=(scroll_x and $ff) or ((valor and $1) shl 8); if fg_color<>((valor and $20) shr 5) then begin fg_color:=(valor and $20) shr 5; fillchar(gfx[0].buffer[0],$800,1); end; if bg_pal_bank<>((valor and $40) shr 6) then begin bg_pal_bank:=(valor and $40) shr 6; fillchar(gfx[1].buffer[0],$800,1); end; end; $b800:scroll_y:=valor; end; end; function snd_srdmission_hw_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$8800..$8fff:snd_srdmission_hw_getbyte:=mem_snd[direccion]; $8000..$87ff:snd_srdmission_hw_getbyte:=memoria[direccion+$6000]; $f400:snd_srdmission_hw_getbyte:=marcade.in0; $f401:snd_srdmission_hw_getbyte:=marcade.in1; $f402:snd_srdmission_hw_getbyte:=marcade.in2; end; end; procedure snd_srdmission_hw_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:memoria[direccion+$6000]:=valor; $8800..$8fff:mem_snd[direccion]:=valor; end; end; function snd_srdmission_inbyte(puerto:word):byte; begin if (puerto and $ff)=$82 then snd_srdmission_inbyte:=ay8910_0.read; end; procedure snd_srdmission_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $80:ay8910_0.Control(valor); $81:ay8910_0.write(valor); $84:ay8910_1.Control(valor); $85:ay8910_1.write(valor); end; end; //Main procedure reset_kyugo_hw; begin z80_0.reset; z80_1.reset; AY8910_0.reset; AY8910_1.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; scroll_x:=0; scroll_y:=0; fg_color:=0; bg_pal_bank:=0; nmi_enable:=false; z80_1.change_halt(ASSERT_LINE); end; function iniciar_kyugo_hw:boolean; var memoria_temp,memoria_temp2:array[0..$17fff] of byte; colores:tpaleta; f,bit0,bit1,bit2,bit3:byte; const pc_x:array[0..7] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3); ps_x:array[0..15] of dword=(0,1,2,3,4,5,6,7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8); procedure convert_chars; begin init_gfx(0,8,8,$100); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8*2,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false); end; procedure convert_tiles; begin init_gfx(1,8,8,$400); gfx_set_desc_data(3,0,8*8,0,$400*8*8,$400*8*8*2); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); end; procedure convert_sprites; begin init_gfx(2,16,16,$400); gfx[2].trans[0]:=true; gfx_set_desc_data(3,0,16*16,0,$400*16*16,$400*16*16*2); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,false); end; begin llamadas_maquina.bucle_general:=kyugo_hw_principal; llamadas_maquina.reset:=reset_kyugo_hw; iniciar_kyugo_hw:=false; iniciar_audio(false); screen_init(1,512,256,true); screen_init(2,512,256); screen_mod_scroll(2,512,512,511,256,256,255); screen_init(3,512,256,false,true); if ((main_vars.tipo_maquina=128) or (main_vars.tipo_maquina=330)) then main_screen.rot90_screen:=true; iniciar_video(288,224); //Main CPU z80_0:=cpu_z80.create(3072000,256); z80_0.change_io_calls(nil,kyugo_outbyte); //Sound CPU z80_1:=cpu_z80.create(3072000,256); z80_1.init_sound(kyugo_snd_update); timers.init(z80_1.numero_cpu,3072000/(60*4),kyugo_snd_irq,nil,true); //Sound Chip ay8910_0:=ay8910_chip.create(1536000,AY8910,0.3); ay8910_0.change_io_calls(kyugo_porta_r,kyugo_portb_r,nil,nil); ay8910_1:=ay8910_chip.create(1536000,AY8910,0.3); case main_vars.tipo_maquina of 128:begin //repulse //cargar roms z80_0.change_ram_calls(kyugo_getbyte,kyugo_putbyte); if not(roms_load(@memoria,repulse_rom)) then exit; //cargar roms snd z80_1.change_ram_calls(snd_kyugo_hw_getbyte,snd_kyugo_hw_putbyte); z80_1.change_io_calls(snd_kyugo_inbyte,snd_kyugo_outbyte); if not(roms_load(@mem_snd,repulse_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,repulse_char)) then exit; convert_chars; //convertir tiles if not(roms_load(@memoria_temp,repulse_tiles)) then exit; convert_tiles; //convertir sprites if not(roms_load(@memoria_temp,repulse_sprites)) then exit; convert_sprites; //paleta if not(roms_load(@memoria_temp,repulse_prom)) then exit; fillchar(color_codes,$20,0); marcade.dswa:=$bf; marcade.dswb:=$bf; end; 330:begin //SRD Mission //cargar roms z80_0.change_ram_calls(srdmission_getbyte,srdmission_putbyte); if not(roms_load(@memoria,srdmission_rom)) then exit; //cargar roms snd z80_1.change_ram_calls(snd_srdmission_hw_getbyte,snd_srdmission_hw_putbyte); z80_1.change_io_calls(snd_srdmission_inbyte,snd_srdmission_outbyte); if not(roms_load(@mem_snd,srdmission_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,srdmission_char)) then exit; convert_chars; //convertir tiles if not(roms_load(@memoria_temp,srdmission_tiles)) then exit; convert_tiles; //convertir sprites if not(roms_load(@memoria_temp,srdmission_sprites)) then exit; convert_sprites; //paleta if not(roms_load(@memoria_temp,srdmission_prom)) then exit; fillchar(color_codes,$20,0); copymemory(@color_codes,@memoria_temp[$300],$20); marcade.dswa:=$bf; marcade.dswb:=$ff; end; 331:begin //Airwolf //cargar roms z80_0.change_ram_calls(srdmission_getbyte,srdmission_putbyte); if not(roms_load(@memoria,airwolf_rom)) then exit; //cargar roms snd z80_1.change_ram_calls(snd_srdmission_hw_getbyte,snd_srdmission_hw_putbyte); z80_1.change_io_calls(snd_srdmission_inbyte,snd_srdmission_outbyte); if not(roms_load(@mem_snd,airwolf_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,airwolf_char)) then exit; convert_chars; //convertir tiles if not(roms_load(@memoria_temp,airwolf_tiles)) then exit; convert_tiles; //convertir sprites if not(roms_load(@memoria_temp2,airwolf_sprites)) then exit; copymemory(@memoria_temp[0],@memoria_temp2[0],$2000); copymemory(@memoria_temp[$4000],@memoria_temp2[$2000],$2000); copymemory(@memoria_temp[$2000],@memoria_temp2[$4000],$2000); copymemory(@memoria_temp[$6000],@memoria_temp2[$6000],$2000); copymemory(@memoria_temp[$8000],@memoria_temp2[$8000],$2000); copymemory(@memoria_temp[$c000],@memoria_temp2[$a000],$2000); copymemory(@memoria_temp[$a000],@memoria_temp2[$c000],$2000); copymemory(@memoria_temp[$e000],@memoria_temp2[$e000],$2000); copymemory(@memoria_temp[$10000],@memoria_temp2[$10000],$2000); copymemory(@memoria_temp[$14000],@memoria_temp2[$12000],$2000); copymemory(@memoria_temp[$12000],@memoria_temp2[$14000],$2000); copymemory(@memoria_temp[$16000],@memoria_temp2[$16000],$2000); convert_sprites; //paleta if not(roms_load(@memoria_temp,airwolf_prom)) then exit; fillchar(color_codes,$20,0); copymemory(@color_codes,@memoria_temp[$300],$20); marcade.dswa:=$bf; marcade.dswb:=$ff; end; end; for f:=0 to $ff do begin bit0:=(memoria_temp[f] shr 0) and 1; bit1:=(memoria_temp[f] shr 1) and 1; bit2:=(memoria_temp[f] shr 2) and 1; bit3:=(memoria_temp[f] shr 3) and 1; colores[f].r:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; bit0:=(memoria_temp[f+$100] shr 0) and 1; bit1:=(memoria_temp[f+$100] shr 1) and 1; bit2:=(memoria_temp[f+$100] shr 2) and 1; bit3:=(memoria_temp[f+$100] shr 3) and 1; colores[f].g:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; bit0:=(memoria_temp[f+$200] shr 0) and 1; bit1:=(memoria_temp[f+$200] shr 1) and 1; bit2:=(memoria_temp[f+$200] shr 2) and 1; bit3:=(memoria_temp[f+$200] shr 3) and 1; colores[f].b:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; end; set_pal(colores,$100); reset_kyugo_hw; iniciar_kyugo_hw:=true; end; end.
unit MainFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; //结构体 TPerson = record //必须是一个指定长度的字符串 Name: string[20]; Age: Integer; end; var Form1: TForm1; const SOURCE_FILE = 'D:\Test\demo1.txt'; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var //读取文本文档的类型 DataSourceFile: TextFile; begin try //将磁盘上的文件跟我们的变量进行关联 AssignFile(DataSourceFile, SOURCE_FILE); //打开文件 Rewrite(DataSourceFile); //向文档中写入数据 Writeln(DataSourceFile, 'HelloWorld'); finally //关闭文件:1、把内存中数据写入到磁盘!2、释放资源 CloseFile(DataSourceFile); end; end; procedure TForm1.Button2Click(Sender: TObject); var //读取文本文档的类型 DataSourceFile: TextFile; var Content: string; begin try //将磁盘上的文件跟我们的变量进行关联 AssignFile(DataSourceFile, SOURCE_FILE); //以读的方式打开文件 Reset(DataSourceFile); //读取文本数据 Readln(DataSourceFile, Content); Form1.Caption := Form1.Caption + ',' + Content; finally //关闭文件:1、把内存中数据写入到磁盘!2、释放资源 CloseFile(DataSourceFile); end; end; procedure TForm1.Button3Click(Sender: TObject); var Person: TPerson; var PersonFile: file of TPerson; begin try //关联文件和变量 AssignFile(PersonFile, SOURCE_FILE); //以写的方式打开文件 Rewrite(PersonFile); //构造结构体的数据 Person.Name := '萧蔷'; Person.Age := 30; //将结构体的数据写入文件 Write(PersonFile, Person); // ShowMessage('记录数:' + IntToStr(FileSize(PersonFile)) + ',当前的文件指针位置:' + IntToStr(FilePos(PersonFile))); //构造结构体的数据 Person.Name := '林志玲'; Person.Age := 30; //将结构体的数据写入文件 Write(PersonFile, Person); ShowMessage('记录数:' + IntToStr(FileSize(PersonFile)) + ',当前的文件指针位置:' + IntToStr(FilePos(PersonFile))); finally CloseFile(PersonFile); end; end; procedure TForm1.Button4Click(Sender: TObject); var Person: TPerson; var PersonFile: file of TPerson; begin try //关联文件和变量 AssignFile(PersonFile, SOURCE_FILE); //以写的方式打开文件 Reset(PersonFile); //改变文件指针位置,文件指针的索引是从0开始 Seek(PersonFile, 1); //将结构体的数据写入文件 read(PersonFile, Person); Memo1.Clear; Memo1.Lines.Add(Person.Name); Memo1.Lines.Add(Person.Age.ToString); finally CloseFile(PersonFile); end; end; end.
unit MapIsoHandler; interface uses Windows, VoyagerInterfaces, VoyagerServerInterfaces, Classes, Controls, FiveTypes, MapIsoView, Config, ExtCtrls; type TMetaMapIsoHandler = class( TInterfacedObject, IMetaURLHandler ) private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TMapIsoHandler = class( TInterfacedObject, IURLHandler ) private constructor Create; destructor Destroy; override; private fControl : TMapIsoViewer; private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; fClientView : IClientView; fConfigHolder : IConfigHolder; fActionButton : TMouseButton; fActionShift : TShiftState; fObjectId : integer; fStatusEnabled : boolean; fIdleTextTimer : TTimer; fSelSoundId : string; fClickSoundId : string; fChatSoundId : string; fLastObj : TObjId; private procedure threadedGetObjStatusText( const parms : array of const ); procedure syncGetObjStatusText( const parms : array of const ); procedure threadedGetContextText( const parms : array of const ); procedure syncGetContextText( const parms : array of const ); procedure threadedPlaySelectionSound( const parms : array of const ); procedure treadedUnfocusObject( const parms : array of const ); private procedure ShowContextText; private procedure OnObjectSelected( ObjId : TObjId; i, j : integer ); procedure OnFacilityBuild( i, j: integer; const FacClass : string; visclass : integer ); procedure OnFacilityBuildAbort; procedure OnCircuitBuild( const CircuitSegments : TSegmentReport; CKind, Cost : integer ); procedure OnCircuitEditChange( cost : integer; var allowed : boolean ); procedure OnCircuitBuildAbort; procedure OnRegionChange( Sender : TObject; const Origin, Size : TPoint ); procedure OnSmallMapClick( Sender : TObject; i, j : integer ); //procedure OnSuperGran( Sender : TObject ); procedure OnMouseUp( Sender : TObject; Button : TMouseButton; Shift : TShiftState; x, y : integer); procedure OnMouseDown( Sender : TObject; Button : TMouseButton; Shift : TShiftState; x, y : integer); procedure OnToolPressed( ToolId : integer ); function OnMouseOnObject( SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnMouseOnObjectRetCode; function OnObjectClicked( SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnObjectClickedRetCode; procedure OnIdleTextChange( Sender : TObject ); procedure OnAreaSelection( imin, jmin, imax, jmax : integer; value : single ); private procedure threadedBuildFacility( const parms : array of const ); procedure syncBuildFacility( const parms : array of const ); procedure syncCreateDummyFacility( const parms : array of const ); procedure threadedCircuitBuild( const parms : array of const ); procedure syncCircuitBuild( const parms : array of const ); procedure syncCreateDummyCircuits( const parms : array of const ); procedure threadedDefineZone( const parms : array of const ); //procedure syncInvalidateSurface( const parms : array of const ); procedure threadedWipeCircuit( const parms : array of const ); procedure threadedConnect( const parms : array of const ); procedure syncConnect( const parms : array of const ); private //fDoGran : boolean; fQWOn : boolean; fLastFacCount : integer; private procedure ShowQuickWeb; procedure HideQuickWeb; procedure ClearStatusLine; procedure LoadCursors; end; const tidURLHandler_MapIsoHandler = 'MapIsoView'; tidSound_Selection = 'select.wav'; tidSound_Click = 'click.wav'; tidSound_Chat = 'system.wav'; const htmlAction_Build = 'BUILD'; htmlAction_BuildRoad = 'BUILDROAD'; htmlAction_BuildRailroad = 'BUILDRAILROAD'; htmlAction_DemolishRoad = 'DEMOLISHROAD'; htmlAction_PickOnMap = 'PICKONMAP'; htmlAction_Select = 'SELECT'; htmlAction_MoveTo = 'MOVETO'; htmlAction_DefineZone = 'DEFINEZONE'; htmlParm_FacilityClass = 'FacilityClass'; htmlParm_VisualClassId = 'VisualClassId'; htmlParm_FacilityXPos = 'x'; htmlParm_FacilityYPos = 'y'; htmlParm_ZoneId = 'ZoneId'; const crConnect = 100; implementation uses Events, ServerCnxHandler, SysUtils, MathUtils, Threads, MapTypes, FocusTypes, URLParser, SoundLib, LanderTypes, Protocol, Forms, VisualClassesHandler, GameTypes, Map, Graphics, ChatListHandler, FiveControl, HintBox, ServerCnxEvents, MapTestDlg, MessageBox, Literals; type PSegmentReport = ^TSegmentReport; const clPositiveMoney = clWhite; clNegativeMoney = clRed; const sidDestroyRoad = 1; sidPickOnMap = 2; // TMetaMapIsoHandler function TMetaMapIsoHandler.getName : string; begin result := tidURLHandler_MapIsoHandler; end; function TMetaMapIsoHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TMetaMapIsoHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaMapIsoHandler.Instantiate : IURLHandler; begin result := TMapIsoHandler.Create; end; // TMapIsoHandler type TLocalFiveControl = class(TFiveControl); constructor TMapIsoHandler.Create; procedure RegisterSelectionKinds; begin fControl.MapView.RegisterSelectionKind(sidDestroyRoad, crConnect, OnMouseOnObject, OnObjectClicked); fControl.MapView.RegisterSelectionKind(sidPickOnMap, crConnect, OnMouseOnObject, OnObjectClicked); end; begin inherited; fControl := TMapIsoViewer.Create( nil ); fControl.MapView.OnFacilityBuild := OnFacilityBuild; fControl.MapView.OnFacilityBuildAbort := OnFacilityBuildAbort; fControl.MapView.OnCircuitBuild := OnCircuitBuild; fControl.MapView.OnCircuitChange := OnCircuitEditChange; fControl.MapView.OnCircuitBuildAbort := OnCircuitBuildAbort; fControl.MapView.OnRegionChange := OnRegionChange; fControl.MapView.OnAreaSelected := OnAreaSelection; fLastFacCount := -1; fStatusEnabled := true; fIdleTextTimer := TTimer.Create( nil ); fIdleTextTimer.Interval := 20000; fIdleTextTimer.OnTimer := OnIdleTextChange; RegisterSelectionKinds; end; destructor TMapIsoHandler.Destroy; begin // fConfigHolder.WriteInteger( false, fClientView.getUserName, 'lastX', fControl.MapView.Origin ); // fConfigHolder.WriteInteger( false, fClientView.getUserName, 'lastX', fClientView.getWorldXSize div 2 ); if fSelSoundId <> '' then SoundLib.UnloadSound( fSelSoundId ); if fClickSoundId <> '' then SoundLib.UnloadSound( fClickSoundId ); if fChatSoundId <> '' then SoundLib.UnloadSound( fChatSoundId ); fIdleTextTimer.Enabled := false; // fControl.Free; fIdleTextTimer.Free; inherited; end; function TMapIsoHandler.HandleURL( URL : TURL ) : TURLHandlingResult; const ZoneColors : array[0..7] of TColor = ($00595959, clMaroon, clTeal, $00BBFFC0, $0043A34F, $001E4823, $0088D9D7, $00D87449); function DefineZone( URL : TURL ) : TURLHandlingResult; var ZoneId : integer; begin ZoneId := StrToInt(GetParmValue( URL, htmlParm_ZoneId )); fControl.ShowSurface( 1 ); fControl.MapView.StartAreaSelection( ZoneId, ZoneColors[ZoneId], [axWater] ); result := urlHandled; end; function Build( URL : TURL ) : TURLHandlingResult; var FacClass : string; FacVisualClass : integer; begin FacClass := GetParmValue( URL, htmlParm_FacilityClass ); FacVisualClass := StrToInt( GetParmValue( URL, htmlParm_VisualClassId )); fControl.ShowSurface( 1 ); fControl.MapView.StartFacilityBuild( FacClass, FacVisualClass ); result := urlHandled; end; function MoveTo( URL : TURL; select : boolean ) : TURLHandlingResult; var strX, strY : string; x, y : integer; begin strX := GetParmValue( URL, htmlParm_FacilityXPos ); strY := GetParmValue( URL, htmlParm_FacilityYPos ); if (strX <> '') and (strY <> '') then begin x := StrToInt( strX ); y := StrToInt( strY ); if (x <> 0) or (y <> 0) then if select then fControl.MapView.MoveAndSelect( y, x ) else fControl.MapView.MoveTo( y, x ); end; result := urlHandled; end; function BuildRoad : TURLHandlingResult; begin fStatusEnabled := false; fControl.MapView.StartCircuitBuild( cirRoads, 20000000 ); result := urlHandled; end; function BuildRailroad : TURLHandlingResult; begin fStatusEnabled := false; fControl.MapView.StartCircuitBuild( cirRailroads, 20000000 ); result := urlHandled; end; function DemolishRoad : TURLHandlingResult; begin //fControl.MapView.StartSelection( sidDestroyRoad ); fControl.MapView.StartAreaSelection( -1, clWhite, [] ); result := urlHandled; end; function PickOnMap : TURLHandlingResult; begin fStatusEnabled := false; fControl.SecondaryText.Caption := GetLiteral('Literal214'); fControl.HintText.Caption := GetLiteral('Literal215'); fControl.MapView.StartSelection( sidPickOnMap ); result := urlHandled; end; var action : string; begin fControl.MapView.AbortCurrentSelection; result := fControl.MapView.HandleURL( URL ); action := GetURLAction( URL ); if action = htmlAction_Build then result := Build( URL ) else if action = htmlAction_Select then result := MoveTo( URL, true ) else if action = htmlAction_MoveTo then result := MoveTo( URL, false ) else if action = htmlAction_BuildRoad then result := BuildRoad else if action = htmlAction_BuildRailroad then result := BuildRailroad else if action = htmlAction_DemolishRoad then result := DemolishRoad else if action = htmlAction_PickOnMap then result := PickOnMap else if action = htmlAction_DefineZone then result := DefineZone( URL ); end; function TMapIsoHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var RefreshTycoon : TRefreshTycoonInfo absolute info; RefreshDate : TRefreshDateInfo absolute info; RefreshSeason : TRefreshSeasonInfo absolute info; RefreshAreaInfo : TRefreshAreaInfo absolute info; EndOfPeriod : TEndOfPeriodInfo absolute info; TycoonRetired : TTycoonRetiredInfo absolute info; ChatMsg : TChatMsgInfo absolute info; NotifyCompanionship : TNotifyCompanionshipInfo absolute info; SetCompany : TSetCompanyInfo absolute info; RefreshObject : TRefreshObjectInfo absolute info; UserListChange : TUserListChangeInfo absolute info; MoveTo : TMoveToInfo absolute info; ChatOverMap : boolean absolute info; KeyCommand : word absolute info; enabled : boolean absolute info; volume : single absolute info; hideshowdata : THideShowFacilityData absolute info; SelectionInfo : TGetSelectionInfo; // startX, startY : integer; procedure InitMapViewOptions; begin with fControl do begin MapView.SoundsEnabled := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'EnableSounds', true); MapView.GlassBuildings := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'UseTransparency', true); MapView.AnimateBuildings := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'AnimateBuildings', true); MapView.CarsEnabled := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'ShowCars', true); MapView.PlanesEnabled := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'ShowPlanes', true); MapView.TranspOverlays := fConfigHolder.ReadBoolean(false, fClientView.getUserName, 'TransparentOverlays', true); MapView.SoundsVolume := StrToFloat(fConfigHolder.ReadString(false, fClientView.getUserName, 'SoundFxVolume', '1')); end; end; begin result := fControl.MapView.HandleEvent( EventId, info ); case EventId of evnHandlerExposed : begin if fControl.MapView.Parent = nil then begin LoadCursors; fControl.MapView.Parent := fControl; fControl.MapView.ImageSuit := fClientView.getSeason; fControl.OnResize( self ); // startX := fConfigHolder.ReadInteger( false, fClientView.getUserName, 'lastX', fClientView.getWorldXSize div 2 ); // startY := fConfigHolder.ReadInteger( false, fClientView.getUserName, 'lastX', fClientView.getWorldXSize div 2 ); // fControl.MapView.MoveTo( startY, startX ); //fControl.Date.Caption := FormatDateTime( 'mmmm d, yyyy', RefreshDate.Date ); fControl.SmallMap.OnSelect := OnSmallMapClick; (* fControl.UserName.Caption := fClientView.getUserName; if fClientView.getCompanyId <> 0 then fControl.Money.Caption := FormatMoney( fClientView.getMoney ) else fControl.Money.Caption := ''; fControl.SuperGran.OnClick := OnSuperGran; *) fControl.MapView.OnObjectSelected := OnObjectSelected; fControl.MapView.OnMouseUp := OnMouseUp; fControl.MapView.OnMouseDown := OnMouseDown; fControl.OnToolPressed := OnToolPressed; fControl.InitSmallMap; fClientView.ClientAware; fControl.InitLinks; end; fControl.SetChasedUser( fClientView.getChasedUser ); fIdleTextTimer.Enabled := true; InitMapViewOptions; end; evnHandlerUnexposed : begin fIdleTextTimer.Enabled := false; end; //fControl.MapView.Parent := nil; evnSetCompany : begin fControl.ClientView := fClientView; fControl.InitLinks; end; evnRefreshArea : begin //fControl.MapView.Focus.QueryUpdate( false ); with RefreshAreaInfo.Area do fControl.MapView.RefreshRegion( Top, Left, Bottom, Right ); end; evnEndOfPeriod :; evnTycoonRetired :; { evnChatMsg : begin Fork( threadedPlaySelectionSound, priHigher, [fChatSoundId] ); end; } evnMoveTo : fControl.MapView.MoveTo( MoveTo.Pos.y, MoveTo.Pos.x ); evnUserChaseStarted : fControl.SetChasedUser( fClientView.getChasedUser ); evnUserChaseAborted : fControl.SetChasedUser( '' ); evnRefreshObject : if RefreshObject.KindOfChange <> fchDestruction then begin SelectionInfo.id := msgGetSelectionInfo; SelectionInfo.Result := false; fControl.MapView.Focus.Dispatch(SelectionInfo); if SelectionInfo.Result and (SelectionInfo.Selection.id = RefreshObject.ObjId) then Fork( threadedGetObjStatusText, priNormal, [RefreshObject.ObjId] ); end else begin HideQuickWeb; fControl.Settings.Enabled := false; end; evnChatOverMap : fControl.SetMsgComposerVisibility( ChatOverMap ); evnKeyCommand : case KeyCommand of keyCmdESC : begin fControl.MapView.AbortFacilityBuild; fControl.MapView.AbortCircuitBuild; fControl.MapView.AbortCurrentSelection; end; keyCmdKeyN :; keyCmdKeyS :; keyCmdKeyW :; keyCmdKeyE :; keyCmdKeyNE :; keyCmdKeySE :; keyCmdKeySW :; keyCmdKeyNW :; keySetSeason0 : fControl.MapView.ImageSuit := 0; keySetSeason1 : fControl.MapView.ImageSuit := 1; keySetSeason2 : fControl.MapView.ImageSuit := 2; keySetSeason3 : fControl.MapView.ImageSuit := 3; end; evnRefreshSeason : fControl.MapView.ImageSuit := RefreshSeason.Season; evnRefreshTycoon : if fLastFacCount <> RefreshTycoon.FacCount then begin if fLastFacCount <> -1 then fControl.InitLinks; fLastFacCount := RefreshTycoon.FacCount; end; evnGlassBuildings : fControl.MapView.GlassBuildings := enabled; evnAnimateBuildings : fControl.MapView.AnimateBuildings := enabled; evnShowCars : fControl.MapView.CarsEnabled := enabled; evnShowPlanes : fControl.MapView.PlanesEnabled := enabled; evnTranspOverlays : fControl.MapView.TranspOverlays := enabled; evnSoundsEnabled : fControl.MapView.SoundsEnabled := enabled; evnSetSoundVolume : fControl.MapView.SoundsVolume := volume; evnHideShowFacility : if hideshowdata.show then fControl.MapView.ShowFacilities([hideshowdata.facid]) else fControl.MapView.HideFacilities([hideshowdata.facid]); evnShowAllFacilities : fControl.MapView.ShowFacilities([0..255]); evnHideAllFacilities : fControl.Mapview.HideFacilities([0..255]); else exit; end; result := evnHandled; end; function TMapIsoHandler.getControl : TControl; begin result := fControl; end; procedure TMapIsoHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); var CachePath : string; begin fMasterURLHandler := URLHandler; URLHandler.HandleEvent( evnAnswerClientView, fClientView ); URLHandler.HandleEvent( evnAnswerConfigHolder, fConfigHolder ); fControl.MasterURLHandler := URLHandler; fControl.ClientView := fClientView; fControl.MapView.setMasterURLHandler( URLHandler ); fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); fSelSoundId := CachePath + 'Sound\' + tidSound_Selection; if not SoundLib.LoadSoundFromFile( fSelSoundId ) then fSelSoundId := ''; fClickSoundId := CachePath + 'Sound\' + tidSound_Click; if not SoundLib.LoadSoundFromFile( fClickSoundId ) then fClickSoundId := ''; { fChatSoundId := CachePath + 'Sound\' + tidSound_Chat; if not SoundLib.LoadSoundFromFile( fChatSoundId ) then fChatSoundId := ''; } end; procedure TMapIsoHandler.threadedGetObjStatusText( const parms : array of const ); var ObjId : TObjId absolute parms[0].vInteger; s1, s2 : string; ErrorCode : TErrorCode; begin if fStatusEnabled then begin s1 := fClientView.ObjectStatusText( sttSecondary, ObjId, ErrorCode ); s2 := fClientView.ObjectStatusText( sttHint, ObjId, ErrorCode ); Threads.Join( syncGetObjStatusText, [s1, s2] ); end; end; procedure TMapIsoHandler.syncGetObjStatusText( const parms : array of const ); var text1 : string; text2 : string; begin text1 := parms[0].vPChar; text2 := parms[1].vPChar; if text1 <> '' then begin fControl.SecondaryText.Caption := text1; fIdleTextTimer.Enabled := false; end else begin ShowContextText; fIdleTextTimer.Enabled := true; end; fControl.SecondaryText.Hint := fControl.SecondaryText.Caption; if text2 <> '' then fControl.HintText.Caption := text2 else fControl.HintText.Caption := GetLiteral('Literal216'); fControl.HintText.Hint := fControl.HintText.Caption; end; procedure TMapIsoHandler.threadedGetContextText( const parms : array of const ); var text : string; begin text := fClientView.ContextText; Join( syncGetContextText, [text] ); end; procedure TMapIsoHandler.syncGetContextText( const parms : array of const ); var text : string absolute parms[0].vPChar; begin if fIdleTextTimer.Enabled then fControl.SecondaryText.Caption := text; end; procedure TMapIsoHandler.threadedPlaySelectionSound( const parms : array of const ); var SoundId : string absolute parms[0].vPChar; begin SoundLib.PlaySound( SoundId, 0, false, 1, 1, 0 ); end; procedure TMapIsoHandler.treadedUnfocusObject( const parms : array of const ); var ObjId : integer absolute parms[0].vInteger; useless : TErrorCode; begin fClientView.UnfocusObject( fLastObj, useless ); end; procedure TMapIsoHandler.ShowContextText; begin Fork( threadedGetContextText, priLower, [0] ); end; procedure TMapIsoHandler.OnObjectSelected( ObjId : TObjId; i, j : integer ); begin if fControl.SmallMap <> nil then fControl.SmallMap.Selection := Point(j, i); fObjectId := ObjId; fControl.SetCurrObj( ObjId, j, i ); Fork( threadedGetObjStatusText, priNormal, [ObjId] ); if ObjId <> 0 then begin Fork( threadedPlaySelectionSound, priHigher, [fSelSoundId] ); fControl.Settings.Enabled := true; if fQWOn or (fActionButton = mbRight) then ShowQuickWeb; end else begin HideQuickWeb; fControl.Settings.Enabled := false; Fork( treadedUnfocusObject, priNormal, [fLastObj] ); end; fLastObj := ObjId; end; { procedure TMapIsoHandler.OnFacilityBuild(i, j: integer; const FacClass : string); var ErrorCode : TErrorCode; begin fStatusEnabled := true; fControl.MapView.Cursor := crDefault; fClientView.NewFacility( FacClass, fClientView.getCompanyId, j, i, ErrorCode ); case ErrorCode of NOERROR : ; ERROR_ZoneMissmatch : Application.MessageBox( 'The Mayor of the city doesn''t allow a building of this type ' + 'on this location. Please note that the zone of this location (indicated by color) has ' + 'to match with the zone type of the facility you intended to build. Buildings zone type ' + 'are shown besides the facility icon on the Build Panel.', 'CONSTRUCTION REQUEST REJECTED', MB_ICONWARNING or MB_OK ); ERROR_AreaNotClear : Application.MessageBox( 'You cannot build there. Area not clear.', 'CONSTRUCTION REQUEST REJECTED', MB_ICONWARNING or MB_OK ); else Application.MessageBox( 'Cannot build facility here.', 'Error', MB_ICONERROR or MB_OK ); end; end; } procedure TMapIsoHandler.OnFacilityBuild(i, j : integer; const facclass : string; visclass : integer); begin fStatusEnabled := true; fControl.MapView.Cursor := crDefault; Fork( threadedBuildFacility, priNormal, [i, j, facclass, visclass] ); end; procedure TMapIsoHandler.OnFacilityBuildAbort; begin fStatusEnabled := true; fControl.MapView.Cursor := crDefault; end; { procedure TMapIsoHandler.OnCircuitBuild( const CircuitSegments : TSegmentReport; CKind, Cost : integer ); var SegIdx : integer; ErrorCode : TErrorCode; begin ClearStatusLine; fControl.MapView.Cursor := crDefault; SegIdx := 0; ErrorCode := NOERROR; with CircuitSegments do while (SegIdx < SegmentCount) and (ErrorCode = NOERROR) do begin fClientView.CreateCircuitSeg( CKind, fClientView.getTycoonId, Segments[SegIdx].x1, Segments[SegIdx].y1, Segments[SegIdx].x2, Segments[SegIdx].y2, cost, ErrorCode ); inc( SegIdx ); end; end; } procedure TMapIsoHandler.OnCircuitBuild( const CircuitSegments : TSegmentReport; CKind, Cost : integer ); var pSegReport : PSegmentReport; begin ClearStatusLine; fControl.MapView.Cursor := crDefault; new( pSegReport ); pSegReport.SegmentCount := CircuitSegments.SegmentCount; getmem( pSegReport.Segments, pSegReport.SegmentCount*sizeof(pSegReport.Segments[0]) ); move( CircuitSegments.Segments[0], pSegReport.Segments[0], pSegReport.SegmentCount*sizeof(pSegReport.Segments[0]) ); Fork( threadedCircuitBuild, priNormal, [pSegReport, CKind, Cost] ); end; procedure TMapIsoHandler.OnCircuitEditChange( cost : integer; var allowed : boolean ); begin fControl.SecondaryText.Caption := GetFormattedLiteral('Literal217', [FormatMoney( cost )]); fControl.HintText.Caption := GetLiteral('Literal218'); end; procedure TMapIsoHandler.OnCircuitBuildAbort; begin ClearStatusLine; fControl.MapView.Cursor := crDefault; end; procedure TMapIsoHandler.OnRegionChange(Sender : TObject; const Origin, Size : TPoint); begin if fControl.SmallMap <> nil then fControl.SmallMap.SetArea(Origin, Size, 2 shl TLocalFiveControl(fControl.MapView).GetZoomLevel); end; procedure TMapIsoHandler.OnSmallMapClick(Sender : TObject; i, j : integer); begin fControl.MapView.MoveTo(i, j); end; (* procedure TMapIsoHandler.OnSuperGran( Sender : TObject ); var i : integer; s : string; x, y : integer; report : TObjectReport; ObjId : TObjId; ErrorCode : TErrorCode; begin fDoGran := not fDoGran; i := 0; while not fDoGran do begin inc( i ); fControl.SuperGran.Caption := IntToStr(i); x := random(500); y := random(500); report := fClientView.ObjectsInArea( x, y, random(500 - x), random(500 - y), ErrorCode ); if report.ObjectCount > 0 then begin x := report.Objects[0].x; y := report.Objects[0].y; ObjId := fClientView.ObjectAt( x, y, ErrorCode ); s := fClientView.ObjectStatusText( sttMain, ObjId, ErrorCode ); if s <> '' then fClientView.SayThis( '', '<SUPERGRAN> ' + s, ErrorCode ); s := fClientView.ObjectStatusText( sttSecondary, ObjId, ErrorCode ); if s <> '' then fClientView.SayThis( '', '<SUPERGRAN> ' + s, ErrorCode ); end; fClientView.DisposeObjectReport( report ); Application.ProcessMessages; end; fControl.SuperGran.Caption := 'Call Super Gran'; end; *) procedure TMapIsoHandler.OnMouseUp( Sender : TObject; Button : TMouseButton; Shift : TShiftState; x, y : integer); begin fActionShift := Shift; fActionButton := Button; end; procedure TMapIsoHandler.OnMouseDown( Sender : TObject; Button : TMouseButton; Shift : TShiftState; x, y : integer); begin Fork( threadedPlaySelectionSound, priHigher, [fClickSoundId] ); end; procedure TMapIsoHandler.OnToolPressed( ToolId : integer ); begin fControl.MapView.AbortCurrentSelection; case ToolId of idQuickWeb : if not fQWOn then ShowQuickWeb else HideQuickWeb; { idShowMap : begin SurfaceViewer.ClientView := fClientView; SurfaceViewer.Show; end; } idVisOpt : begin fStatusEnabled := false; fControl.SecondaryText.Caption := GetLiteral('Literal219'); fControl.HintText.Caption := GetLiteral('Literal220'); fControl.MapView.StartSelection( sidPickOnMap ); end; end; end; function TMapIsoHandler.OnMouseOnObject( SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnMouseOnObjectRetCode; begin case SelId of sidDestroyRoad : if ObjInfo.objkind = okRoad then result := mooCanSelect else result := mooCannotSelect; sidPickOnMap : if ObjInfo.objkind = okBuilding then result := mooCanSelect else result := mooCannotSelect; else result := mooCannotSelect; end; end; function TMapIsoHandler.OnObjectClicked( SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnObjectClickedRetCode; var ErrorCode : TErrorCode; SelectionInfo : TGetSelectionInfo; { FacId : TObjId; report : string; } begin Fork( threadedPlaySelectionSound, priHigher, [fClickSoundId] ); case SelId of sidDestroyRoad : if ObjInfo.objkind = okRoad then begin fClientView.BreakCircuitAt( cirRoads, fClientView.getTycoonId, ObjInfo.c, ObjInfo.r, ErrorCode ); result := ocAbort; case ErrorCode of NOERROR : result := ocGoOn; ERROR_AccessDenied : ShowMsgBox( GetLiteral('Literal221'), GetLiteral('Literal222'), 0, true, false ); else ShowMsgBox( GetLiteral('Literal223'), GetLiteral('Literal224'), 0, true, false ); end; end else result := ocAbort; sidPickOnMap : if ObjInfo.objkind = okBuilding then begin //result := ocAbort; SelectionInfo.id := msgGetSelectionInfo; SelectionInfo.Result := false; fControl.MapView.Focus.Dispatch( SelectionInfo ); Fork( threadedConnect, priNormal, [SelectionInfo.Selection.id, ObjInfo.c, ObjInfo.r] ); result := ocGoOn; end else result := ocAbort; else result := ocAbort; end; if result = ocAbort then ClearStatusLine; end; procedure TMapIsoHandler.OnIdleTextChange( Sender : TObject ); begin if fStatusEnabled then ShowContextText; end; { procedure TMapIsoHandler.OnAreaSelection( imin, jmin, imax, jmax : integer; value : single ); var ErrorCode : TErrorCode; begin fClientView.DefineZone( fClientView.getTycoonUId, round(value), jmin, imin, jmax, imax, ErrorCode ); if not fControl.MapOptionsPanel.Visible then fControl.MapBtn.Click; fControl.Tabs.CurrentTab := 1; end; } procedure TMapIsoHandler.OnAreaSelection( imin, jmin, imax, jmax : integer; value : single ); begin if value >= 0 then begin if not fControl.MapOptionsPanel.Visible then fControl.MapBtn.Click; //fControl.Tabs.CurrentTab := 1; Fork( threadedDefineZone, priNormal, [jmin, imin, jmax, imax, round(value)] ); end else Fork( threadedWipeCircuit, priNormal, [jmin, imin, jmax, imax] ); end; procedure TMapIsoHandler.threadedBuildFacility( const parms : array of const ); var ErrorCode : TErrorCode; i, j : integer; facclass : string; visclass : integer; begin try i := parms[0].vInteger; j := parms[1].vInteger; facclass := parms[2].vPChar; visclass := parms[3].vInteger; Join( syncCreateDummyFacility, [i, j, visclass] ); fClientView.NewFacility( facclass, fClientView.getCompanyId, j, i, ErrorCode ); Join( syncBuildFacility, [ErrorCode, i, j, visclass] ); except end; end; procedure TMapIsoHandler.syncBuildFacility( const parms : array of const ); var ErrorCode : integer absolute parms[0].vInteger; begin fControl.MapView.RemoveDummyFacility( parms[1].VInteger, parms[2].VInteger, parms[3].VInteger, ErrorCode <> NOERROR ); case ErrorCode of NOERROR : ; ERROR_ZoneMissmatch : ShowMsgBox( GetLiteral('Literal225'), GetLiteral('Literal226'), 0, true, false ); ERROR_AreaNotClear : ShowMsgBox( GetLiteral('Literal230'), GetLiteral('Literal231'), 0, true, false ); ERROR_TooManyFacilities : ShowMsgBox( GetLiteral('Literal232'), GetLiteral('Literal233'), 0, true, false ); else ShowMsgBox( GetLiteral('Literal234'), GetLiteral('Literal235'), 0, true, false ); end; end; procedure TMapIsoHandler.syncCreateDummyFacility( const parms : array of const ); begin fControl.MapView.CreateDummyFacility( parms[0].VInteger, parms[1].VInteger, parms[2].VInteger ); end; procedure TMapIsoHandler.threadedCircuitBuild( const parms : array of const ); var CircuitSegments : PSegmentReport; CKind, Cost : integer; SegIdx : integer; ErrorCode : TErrorCode; begin try CircuitSegments := PSegmentReport(parms[0].vPointer); CKind := parms[1].vInteger; Cost := parms[2].vInteger; SegIdx := 0; ErrorCode := NOERROR; Join( syncCreateDummyCircuits, [CircuitSegments, CKind] ); with CircuitSegments^ do while (SegIdx < SegmentCount) and (ErrorCode = NOERROR) do begin fClientView.CreateCircuitSeg( CKind, fClientView.getTycoonId, Segments[SegIdx].x1, Segments[SegIdx].y1, Segments[SegIdx].x2, Segments[SegIdx].y2, cost div SegmentCount, ErrorCode ); inc( SegIdx ); end; Join( syncCircuitBuild, [CircuitSegments, CKind] ); except end; end; procedure TMapIsoHandler.syncCircuitBuild( const parms : array of const ); var CircuitSegments : PSegmentReport absolute parms[0].VPointer; CKind : integer; i : integer; begin CKind := parms[1].vInteger; with CircuitSegments^ do for i := 0 to pred(SegmentCount) do fControl.MapView.RemoveDummyCircuitSeg( CKind, Segments[i].x1, Segments[i].y1, Segments[i].x2, Segments[i].y2 ); end; procedure TMapIsoHandler.syncCreateDummyCircuits( const parms : array of const ); var CircuitSegments : PSegmentReport absolute parms[0].VPointer; CKind : integer; begin CKind := parms[1].vInteger; fControl.MapView.CreateDummyCircuitSegs( CKind, CircuitSegments^ ); end; procedure TMapIsoHandler.threadedDefineZone( const parms : array of const ); var imin, jmin, imax, jmax : integer; value : integer; ErrorCode : TErrorCode; begin jmin := parms[0].vInteger; imin := parms[1].vInteger; jmax := parms[2].vInteger; imax := parms[3].vInteger; value := parms[4].VInteger; fClientView.DefineZone( fClientView.getTycoonUId, value, jmin, imin, jmax, imax, ErrorCode ); //Join( syncInvalidateSurface, [0] ); end; { procedure TMapIsoHandler.syncInvalidateSurface( const parms : array of const ); begin fControl.MapView.InvalidateCurrentSurface; end; } procedure TMapIsoHandler.threadedWipeCircuit( const parms : array of const ); var imin, jmin, imax, jmax : integer; ErrorCode : TErrorCode; begin jmin := parms[0].vInteger; imin := parms[1].vInteger; jmax := parms[2].vInteger; imax := parms[3].vInteger; fClientView.WipeCircuit( cirRoads, fClientView.getTycoonId, jmin, imin, jmax, imax, ErrorCode ); end; procedure TMapIsoHandler.threadedConnect( const parms : array of const ); var SelectedId : integer; x, y : integer; ErrorCode : TErrorCode; FacId : integer; report : string; begin try SelectedId := parms[0].vInteger; x := parms[1].vInteger; y := parms[2].vInteger; FacId := fClientView.ObjectAt( x, y, ErrorCode ); if ErrorCode = NOERROR then begin report := fClientView.ConnectFacilities( SelectedId, FacId, ErrorCode ); Join( syncConnect, [report, ErrorCode] ); end except end; end; procedure TMapIsoHandler.syncConnect( const parms : array of const ); var report : string; ErrorCode : TErrorCode; begin report := parms[0].vPChar; ErrorCode := parms[1].vInteger; case ErrorCode of NOERROR : if report <> '' then begin HintBoxWindow.HintText := report; HintBoxWindow.Show; end else ShowMsgBox( GetLiteral('Literal236'), GetLiteral('Literal237'), 0, true, false ); else ShowMsgBox( GetLiteral('Literal238'), GetLiteral('Literal239'), 0, true, false ); end; end; { fFrameSet.HandleURL( '?frame_Action=Create&frame_Id=ObjectInspector&frame_Class=ObjectInspector&frame_Align=bottom' ); procedure TMapIsoHandler.ShowQuickWeb; var PageName : string; PagePath : string; URL : string; SelectionInfo : TGetSelectionInfo; begin if fObjectId <> 0 then begin SelectionInfo.id := msgGetSelectionInfo; SelectionInfo.Result := false; fControl.MapView.Focus.Dispatch(SelectionInfo); assert(SelectionInfo.Result); with SelectionInfo.Selection do begin PagePath := VisualClassesHandler.ReadString( ClassId, 'Paths', 'Voyager', 'Visual/Voyager/IsoMap/', fMasterURLHandler ); PageName := VisualClassesHandler.ReadString( ClassId, 'VoyagerActions', 'QuickWeb', 'UnknownEdit.asp', fMasterURLHandler ); URL := fClientView.getWorldURL + PagePath + PageName + '?x=' + IntToStr(c) + '&y=' + IntToStr(r) + '&ClassId=' + IntToStr(Id) + '&SecurityId=' + fClientView.getSecurityId + '&WorldName=' + fClientView.getWorldName + '&DAAddr=' + fClientView.getDAAddr + '&DAPort=' + IntToStr(fClientView.getDAPort); fControl.ShowURLInQuickWeb( URL ); end end else fControl.HideQuickWeb; end; } procedure TMapIsoHandler.ShowQuickWeb; var URL : string; SelectionInfo : TGetSelectionInfo; begin if fObjectId <> 0 then begin SelectionInfo.id := msgGetSelectionInfo; SelectionInfo.Result := false; fControl.MapView.Focus.Dispatch(SelectionInfo); assert(SelectionInfo.Result); with SelectionInfo.Selection do begin URL := '?frame_Action=ShowObject' + '&frame_Id=ObjectInspector' + '&frame_Class=ObjectInspector' + //'&frame_Height=30%' + '&frame_Align=bottom' + '&x=' + IntToStr(c) + '&y=' + IntToStr(r) + '&ObjectId=' + IntToStr(SelectionInfo.Selection.id) + '&ClassId=' + IntToStr(ClassId); fMasterURLHandler.HandleURL( URL ); end; fQWOn := true; //fControl.Settings.Text := 'HIDE'; fControl.Settings.Selected := true; end else HideQuickWeb; end; procedure TMapIsoHandler.HideQuickWeb; begin fQWOn := false; fMasterURLHandler.HandleURL( '?frame_Id=ObjectInspector&frame_Close=yes' ); //fControl.Settings.Text := 'SETTINGS'; fControl.Settings.Selected := false; end; procedure TMapIsoHandler.ClearStatusLine; begin fStatusEnabled := true; fControl.SecondaryText.Caption := GetLiteral('Literal240'); fControl.HintText.Caption := GetLiteral('Literal241'); end; procedure TMapIsoHandler.LoadCursors; var CachePath : string; cursor : HCURSOR; begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); cursor := LoadCursorFromFile( pchar(CachePath + 'Cursors\Connect.cur') ); Screen.Cursors[crConnect] := cursor; cursor := LoadCursorFromFile( pchar(CachePath + 'Cursors\Forbiden.cur') ); Screen.Cursors[crNo] := cursor; cursor := LoadCursorFromFile( pchar(CachePath + 'Cursors\Handpnt.cur') ); Screen.Cursors[crHandPoint] := cursor; end; end.
unit ToolsAPITools; interface uses ToolsAPI; function GetActiveFormEditor: IOTAFormEditor; implementation function GetActiveFormEditor; var otaModule: IOTAModule; otaEditor: IOTAEditor; iModule: Integer; begin Result := nil; otaModule := (BorlandIDEServices as IOTAModuleServices).CurrentModule; if otaModule <> nil then begin for iModule := 0 to otaModule.GetModuleFileCount - 1 do begin otaEditor := otaModule.GetModuleFileEditor(iModule); otaEditor.QueryInterface(IOTAFormEditor, Result); if Result <> nil then break; end; end; end; end.
{DEPENDENCY: indylaz_runtime, see readme.txt} unit httpswebserver; {$mode objfpc}{$H+} interface uses SysUtils, Classes, EventLog, LCLIntf, //Indy10.6.2.5494 IdBaseComponent, IdComponent, IdContext,IdSocketHandle, IdGlobal, IdGlobalProtocols, IdCustomHTTPServer, IdHTTPServer, //OpenSSL-1.0.2l-i386-win32 IdSSL, IdSSLOpenSSL; type THTTPWebServer = object private FLogFile: string; FServerActive: boolean; MimeTable: TIdMimeTable; Server: TIdHTTPServer; Log: TEventLog; OpenSSL: TIdServerIOHandlerSSLOpenSSL; function GetMimeType(aFile: String): String; procedure FreeObjects; procedure ServerStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); procedure ServerException(AContext: TIdContext; AException: Exception); procedure ServerConnect(AContext: TIdContext); procedure ServerDisconnect(AContext: TIdContext); procedure ServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure OpenSSLGetPassword(var Password: String); protected public property LogFile: string read FLogFile write FLogFile; property ServerActive: boolean read FServerActive write FServerActive; procedure Start; procedure Stop; end; const GIP='127.0.0.1'; GPORT='443'; GROOT='.\HOME'; GLOG=''; VERBOSE=false; //verbose = log client connect/disconnect messages GCertFile = 'DEMO_Server.crt.pem'; GKeyFile = 'DEMO_Server.key.pem'; GRootCertFile = 'DEMO_RootCA.crt.pem'; GPassword = 'demo'; GCipherList = 'TLSv1.2:!NULL'; implementation procedure THTTPWebServer.Start; var Binding: TIdSocketHandle; msg: string; begin if ServerActive then Exit; MimeTable:=TIdMimeTable.Create(true); //load from system OS if LogFile='' then LogFile:=IncludeTrailingPathDelimiter(GROOT)+'server.log'; Log:=TEventLog.Create(Nil); Log.FileName:= LogFile; Log.LogType := ltFile; //optional ltSystem; Log.Active := true; OpenSSL:=TIdServerIOHandlerSSLOpenSSL.Create; with OpenSSL do begin SSLOptions.SSLVersions := [sslvTLSv1_2]; OnGetPassword := @OpenSSLGetPassword; end; Server:=TIdHTTPServer.Create; with Server do begin; OnStatus := @ServerStatus; OnConnect := @ServerConnect; OnDisconnect := @ServerDisconnect; OnException := @ServerException; OnCommandGet := @ServerCommandGet; Scheduler := nil; //use default Thread Scheduler MaxConnections := 10; KeepAlive := True; IOHandler := OpenSSL; end; Server.Bindings.Clear; try Server.DefaultPort := StrToInt(GPORT); Binding := Server.Bindings.Add; Binding.IP := GIP; Binding.Port := StrToInt(GPORT); with OpenSSL.SSLOptions do begin CertFile := GCertFile; KeyFile := GKeyFile; RootCertFile := GRootCertFile; CipherList := GCipherList; end; Server.Active := true; ServerActive := Server.Active; Log.Info('Server Start'); Log.Info('Bound to: ' + GIP + ' on port ' + GPORT); Log.Info('Doc Root: ' + GROOT); Log.Info('Log File: ' + LogFile); //verify default scheduler active: Log.Debug('ImplicitScheduler='+BoolToStr(Server.ImplicitScheduler,true)); except on E : Exception do begin Log.Error('Server not started'); Log.Error(E.Message); FreeObjects; end; end; end; procedure THTTPWebServer.Stop; begin if not ServerActive then Exit; Server.Active := false; ServerActive := Server.Active; Server.Bindings.Clear; Log.Info('Server stop'); FreeObjects; end; procedure THTTPWebServer.ServerStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); begin Log.Info('Status: '+AStatusText); end; procedure THTTPWebServer.ServerException(AContext: TIdContext; AException: Exception); begin Log.Warning('Exception: ' + AException.Message); end; procedure THTTPWebServer.ServerConnect(AContext: TIdContext); begin if VERBOSE then Log.Info('Client Connect ip: ' + AContext.Connection.Socket.Binding.PeerIP); end; procedure THTTPWebServer.ServerDisconnect(AContext: TIdContext); begin if VERBOSE then Log.Info('Client Disconnect ip: ' + AContext.Connection.Socket.Binding.PeerIP); end; function THTTPWebServer.GetMimeType(aFile: String): String; begin Result := MimeTable.GetFileMimeType(aFile) end; procedure THTTPWebServer.FreeObjects; begin Server.Free; MimeTable.Free; Log.Free; OpenSSL.Free; end; procedure THTTPWebServer.OpenSSLGetPassword(var Password: String); begin Password := GPassword; end; procedure THTTPWebServer.ServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LocalDoc : String; begin LocalDoc:=ARequestInfo.Document; //Log.Debug('ARequestInfo.Document=[' + ARequestInfo.Document + ']'); If (Length(LocalDoc)>0) and (LocalDoc[1]='/') then Delete(LocalDoc,1,1); If (Length(LocalDoc)=0) then LocalDoc:='index.html'; LocalDoc:=IncludeTrailingPathDelimiter(GROOT)+LocalDoc; DoDirSeparators(LocalDoc); Log.Debug('Serving: ' + LocalDoc + ' to ' + ARequestInfo.Host); if ARequestInfo.Command='POST' then begin Log.Debug('Command=' + ARequestInfo.Command + LineEnding + 'Params='+ARequestInfo.Params.Text + LineEnding + 'UnparsedParams='+ARequestInfo.UnparsedParams); LocalDoc := IncludeTrailingPathDelimiter(GROOT) + 'welcome.html'; end; if FileExists(LocalDoc) then begin AResponseInfo.ResponseNo := 200; AResponseInfo.ContentType := GetMimeType(LocalDoc); AResponseInfo.ContentStream := TFileStream.Create(LocalDoc, fmOpenRead + fmShareDenyWrite); end else begin AResponseInfo.ResponseNo := 404; // Not found AResponseInfo.ContentText := ''; end; end; end.
unit main; interface uses Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DBCtrls, Menus, ExtCtrls, StdCtrls, Buttons; type { TMainForm } TMainForm = class(TForm) Label1: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Panel3: TPanel; Image1: TImage; procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); private { Private declarations } FDirectory: string; FLoadedFile: string; FFileNames: TStrings; FFilePos: integer; procedure ShowNext(); procedure ShowPrevious(); procedure ShowFirst(); procedure ShowLast(); procedure OpenDirectory(); procedure LoadPicture(const filename: string); procedure RenameImage(); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses functions; procedure TMainForm.OpenDirectory(); procedure HideHelp(); begin Label1.Visible := false; Label10.Visible := false; Label2.Visible := false; Label3.Visible := false; Label4.Visible := false; Label5.Visible := false; Label6.Visible := false; Label7.Visible := false; Label8.Visible := false; Label9.Visible := false; Label11.Visible := false; Label12.Visible := false; end; var chosenDirectory: string; options : TSelectDirOpts; begin options := []; if SelectDirectory(chosenDirectory, options, 1) then begin FreeAndNil(FFileNames); FFileNames := GetImageFiles(chosenDirectory); if FFileNames.count = 0 then Showmessage('No image files found') else begin HideHelp(); FDirectory := chosenDirectory; FFilePos := -1; ShowNext(); end; end; end; procedure TMainForm.ShowNext(); begin if FDirectory = '' then exit; Inc(FFilePos); if FFilePos >= FFileNames.Count then FFilePos := FFileNames.Count - 1; if FFilePos >= 0 then LoadPicture(FFileNames[FFilePos]); end; procedure TMainForm.ShowPrevious(); begin if FDirectory = '' then exit; Dec(FFilePos); if FFilePos < 0 then FFilePos := 0; if FFilePos < FFileNames.Count then LoadPicture(FFileNames[FFilePos]); end; procedure TMainForm.ShowFirst(); begin FFilePos := 0; if FFilePos < FFileNames.Count then LoadPicture(FFileNames[FFilePos]); end; procedure TMainForm.ShowLast(); begin FFilePos := FFileNames.Count - 1; if FFilePos >= 0 then LoadPicture(FFileNames[FFilePos]); end; procedure TMainForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var shf: boolean; const LEFT_KEY = 37; RIGHT_KEY = 39; UP_KEY = 38; DOWN_KEY = 40; O_KEY = 79; ESC_KEY = 27; R_KEY = 82; begin shf := ssShift in Shift; // ShowMessage(IntToStr(key)); if (Key = LEFT_KEY) then ShowPrevious else if (Key = RIGHT_KEY) then ShowNext else if (Key = DOWN_KEY) then ShowFirst else if (Key = UP_KEY) then ShowLast else if (Key = O_KEY) and shf then OpenDirectory() else if (Key = R_KEY) and shf then RenameImage() else if (Key = ESC_KEY ) then Close(); { if ssAlt in Shift then ShowMessage('ALT'); if ssShift in Shift then ShowMessage('SHIFT'); if ssCtrl in Shift then ShowMessage('STRG'); if ssAltGr in Shift then ShowMessage('ALT GR'); if ssLeft in Shift then ShowMessage('Left Mouse Key'); if ssRight in Shift then ShowMessage('Right Mouse Key'); if ssMiddle in Shift then ShowMessage('Middle Mouse Key'); // if ssDoubleClick in Shift then ShowMessage('Double Click'); } end; procedure TMainForm.LoadPicture(const filename: string); var maxWidth, maxHeight: integer; scaleWidth, scaleHeight, scale: double; path: string; begin path := CombinePath(FDirectory, filename); Image1.Picture.LoadFromFile(path); FLoadedFile := filename; maxWidth := Minimum(Screen.Width, Image1.Picture.Width); maxHeight := Minimum(Screen.Height, Image1.Picture.Height); scaleWidth := maxWidth/Image1.Picture.Width; scaleHeight := maxHeight/Image1.Picture.Height; scale := Minimum(scaleWidth, scaleHeight); Width := Trunc(scale * Image1.Picture.Width); Height := Trunc(scale * Image1.Picture.Height); Caption := path; end; procedure TMainForm.RenameImage(); var newfilename, oldPath, newPath: string; begin if FLoadedFile = '' then exit; newfilename := FLoadedFile; if InputQuery('Change filename', 'New filename', newfilename) then begin oldPath := CombinePath(FDirectory, FLoadedFile); newPath := CombinePath(FDirectory, newfilename); if RenameFile(oldPath, newPath) then begin FFileNames[FFilePos] := newfilename; LoadPicture(FFileNames[FFilePos]); end else ShowMessage('Error renaming file'); end; end; procedure TMainForm.FormCreate(Sender: TObject); begin FFileNames := nil; end; end.
inherited dmProtDoc: TdmProtDoc OldCreateOrder = True inherited qryManutencao: TIBCQuery KeyFields = 'ID_DOC' KeyGenerator = 'GEN_PROTDOC' GeneratorMode = gmInsert SQLInsert.Strings = ( 'INSERT INTO STWPROTDOC' ' (ID_DOC, ID_PROT, CGC, SERIE, NOTA)' 'VALUES' ' (:ID_DOC, :ID_PROT, :CGC, :SERIE, :NOTA)') SQLDelete.Strings = ( 'DELETE FROM STWPROTDOC' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLUpdate.Strings = ( 'UPDATE STWPROTDOC' 'SET' ' ID_DOC = :ID_DOC, ID_PROT = :ID_PROT, CGC = :CGC, SERIE = :SER' + 'IE, NOTA = :NOTA' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLRefresh.Strings = ( 'SELECT ID_DOC, ID_PROT, CGC, SERIE, NOTA FROM STWPROTDOC' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLLock.Strings = ( 'SELECT NULL FROM STWPROTDOC' 'WHERE' 'ID_DOC = :Old_ID_DOC' 'FOR UPDATE WITH LOCK') SQLRecCount.Strings = ( 'SELECT COUNT(*) FROM (' 'SELECT 1 AS C FROM STWPROTDOC' '' ') q') SQL.Strings = ( 'SELECT' ' DOC.ID_DOC,' ' DOC.ID_PROT,' ' DOC.CGC,' ' DOC.SERIE,' ' DOC.NOTA,' ' NF.EMISSAO,' ' NF.ENTREGA' 'FROM STWPROTDOC DOC' 'LEFT JOIN STWOPETNOTA NF ' 'ON DOC.CGC = NF.CGC AND' ' DOC.SERIE = NF.SERIE_2 AND' ' DOC.NOTA = NF.N_FISCAL') IndexFieldNames = 'ID_DOC' object qryManutencaoID_DOC: TIntegerField FieldName = 'ID_DOC' Required = True end object qryManutencaoID_PROT: TIntegerField FieldName = 'ID_PROT' end object qryManutencaoCGC: TStringField FieldName = 'CGC' Size = 18 end object qryManutencaoSERIE: TStringField FieldName = 'SERIE' Size = 3 end object qryManutencaoNOTA: TFloatField FieldName = 'NOTA' end object qryManutencaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' ReadOnly = True end object qryManutencaoENTREGA: TDateTimeField FieldName = 'ENTREGA' ReadOnly = True end end inherited qryLocalizacao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWPROTDOC' ' (ID_DOC, ID_PROT, CGC, SERIE, NOTA)' 'VALUES' ' (:ID_DOC, :ID_PROT, :CGC, :SERIE, :NOTA)') SQLDelete.Strings = ( 'DELETE FROM STWPROTDOC' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLUpdate.Strings = ( 'UPDATE STWPROTDOC' 'SET' ' ID_DOC = :ID_DOC, ID_PROT = :ID_PROT, CGC = :CGC, SERIE = :SER' + 'IE, NOTA = :NOTA' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLRefresh.Strings = ( 'SELECT ID_DOC, ID_PROT, CGC, SERIE, NOTA FROM STWPROTDOC' 'WHERE' ' ID_DOC = :ID_DOC') SQLLock.Strings = ( 'SELECT NULL FROM STWPROTDOC' 'WHERE' 'ID_DOC = :Old_ID_DOC' 'FOR UPDATE WITH LOCK') SQLRecCount.Strings = ( 'SELECT COUNT(*) FROM (' 'SELECT 1 AS C FROM STWPROTDOC' '' ') q') SQL.Strings = ( 'SELECT' ' DOC.ID_DOC,' ' DOC.ID_PROT,' ' DOC.CGC,' ' DOC.SERIE,' ' DOC.NOTA,' ' NF.EMISSAO,' ' NF.ENTREGA' 'FROM STWPROTDOC DOC' 'LEFT JOIN STWOPETNOTA NF ' 'ON DOC.CGC = NF.CGC AND' ' DOC.SERIE = NF.SERIE_2 AND' ' DOC.NOTA = NF.N_FISCAL') object qryLocalizacaoID_DOC: TIntegerField FieldName = 'ID_DOC' Required = True end object qryLocalizacaoID_PROT: TIntegerField FieldName = 'ID_PROT' end object qryLocalizacaoCGC: TStringField FieldName = 'CGC' Size = 18 end object qryLocalizacaoSERIE: TStringField FieldName = 'SERIE' Size = 3 end object qryLocalizacaoNOTA: TFloatField FieldName = 'NOTA' end object qryLocalizacaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' ReadOnly = True end object qryLocalizacaoENTREGA: TDateTimeField FieldName = 'ENTREGA' ReadOnly = True end end object qryProtDoc: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWPROTDOC' ' (ID_DOC, ID_PROT, CGC, SERIE, NOTA)' 'VALUES' ' (:ID_DOC, :ID_PROT, :CGC, :SERIE, :NOTA)') SQLDelete.Strings = ( 'DELETE FROM STWPROTDOC' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLUpdate.Strings = ( 'UPDATE STWPROTDOC' 'SET' ' ID_DOC = :ID_DOC, ID_PROT = :ID_PROT, CGC = :CGC, SERIE = :SER' + 'IE, NOTA = :NOTA' 'WHERE' ' ID_DOC = :Old_ID_DOC') SQLRefresh.Strings = ( 'SELECT ID_DOC, ID_PROT, CGC, SERIE, NOTA FROM STWPROTDOC' 'WHERE' ' ID_DOC = :ID_DOC') SQLLock.Strings = ( 'SELECT NULL FROM STWPROTDOC' 'WHERE' 'ID_DOC = :Old_ID_DOC' 'FOR UPDATE WITH LOCK') SQLRecCount.Strings = ( 'SELECT COUNT(*) FROM (' 'SELECT 1 AS C FROM STWPROTDOC' '' ') q') SQL.Strings = ( 'SELECT' ' DOC.ID_DOC,' ' DOC.ID_PROT,' ' DOC.CGC,' ' DOC.SERIE,' ' DOC.NOTA,' ' NF.EMISSAO,' ' NF.ENTREGA' 'FROM STWPROTDOC DOC' 'LEFT JOIN STWOPETNOTA NF ' 'ON DOC.CGC = NF.CGC AND' ' DOC.SERIE = NF.SERIE_2 AND' ' DOC.NOTA = NF.N_FISCAL') AutoCommit = False Left = 96 Top = 168 object qryProtDocID_DOC: TIntegerField FieldName = 'ID_DOC' Required = True end object qryProtDocID_PROT: TIntegerField FieldName = 'ID_PROT' end object qryProtDocCGC: TStringField FieldName = 'CGC' Size = 18 end object qryProtDocSERIE: TStringField FieldName = 'SERIE' Size = 3 end object qryProtDocNOTA: TFloatField FieldName = 'NOTA' end object qryProtDocEMISSAO: TDateTimeField FieldName = 'EMISSAO' ProviderFlags = [] end object qryProtDocENTREGA: TDateTimeField FieldName = 'ENTREGA' ProviderFlags = [] end end end
//////////////////////////////////////////////////////////////////////////////// // Errors.pas // MTB communication library // Error codes definiton // (c) Jan Horacek (jan.horacek@kmz-brno.cz), //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2016 Jan Horacek 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. } { DESCRIPTION: This file defines library error codes. } unit Errors; interface const MTB_GENERAL_EXCEPTION = 1000; MTB_FT_EXCEPTION = 1001; // device is always closed when this exception happens MTB_FILE_CANNOT_ACCESS = 1010; MTB_FILE_DEVICE_OPENED = 1011; MTB_MODULE_INVALID_ADDR = 1100; MTB_MODULE_FAILED = 1102; MTB_PORT_INVALID_NUMBER = 1103; MTB_MODULE_UNKNOWN_TYPE = 1104; MTB_INVALID_SPEED = 1105; MTB_INVALID_SCOM_CODE = 1106; MTB_INVALID_MODULES_COUNT = 1107; MTB_INPUT_NOT_YET_SCANNED = 1108; MTB_ALREADY_OPENNED = 2001; MTB_CANNOT_OPEN_PORT = 2002; MTB_FIRMWARE_TOO_LOW = 2003; MTB_DEVICE_DISCONNECTED = 2004; MTB_SCANNING_NOT_FINISHED = 2010; MTB_NOT_OPENED = 2011; MTB_ALREADY_STARTED = 2012; MTB_OPENING_NOT_FINISHED = 2021; MTB_NO_MODULES = 2025; MTB_NOT_STARTED = 2031; MTB_INVALID_PACKET = 3100; MTB_MODULE_NOT_ANSWERED_CMD = 3101; MTB_MODULE_NOT_ANSWERED_CMD_GIVING_UP = 3102; MTB_MODULE_OUT_SUM_ERROR = 3106; MTB_MODULE_OUT_SUM_ERROR_GIVING_UP = 3107; MTB_MODULE_IN_SUM_ERROR = 3108; MTB_MODULE_IN_SUM_ERROR_GIVING_UP = 3109; MTB_MODULE_NOT_RESPONDED_FB = 3121; MTB_MODULE_NOT_RESPONDED_FB_GIVING_UP = 3122; MTB_MODULE_IN_FB_SUM_ERROR = 3126; MTB_MODULE_IN_FB_SUM_ERROR_GIVING_UP = 3127; MTB_MODULE_OUT_FB_SUM_ERROR = 3128; MTB_MODULE_OUT_FB_SUM_ERROR_GIVING_UP = 3129; MTB_MODULE_INVALID_FB_SUM = 3125; MTB_MODULE_NOT_RESPONDING_PWR_ON = 3131; MTB_MODULE_PWR_ON_IN_SUM_ERROR = 3136; MTB_MODULE_PWR_ON_IN_SUM_ERROR_GIVING_UP = 3137; MTB_MODULE_PWR_ON_OUT_SUM_ERROR = 3138; MTB_MODULE_PWR_ON_OUT_SUM_ERROR_GIVING_UP = 3139; MTB_MODULE_FAIL = 3141; MTB_MODULE_RESTORED = 3142; MTB_MODULE_INVALID_DATA = 3145; MTB_MODULE_REWIND_IN_SUM_ERROR = 3162; MTB_MODULE_REWIND_OUT_SUM_ERROR = 3163; MTB_MODULE_SCAN_IN_SUM_ERROR = 3166; MTB_MODULE_SCAN_IN_SUM_ERROR_GIVING_UP = 3167; MTB_MODULE_SCAN_OUT_SUM_ERROR = 3168; MTB_MODULE_SCAN_OUT_SUM_ERROR_GIVING_UP = 3169; MTB_MODULE_SC_IN_SUM_ERROR = 3176; MTB_MODULE_SC_IN_SUM_ERROR_GIVING_UP = 3177; MTB_MODULE_SC_OUT_SUM_ERROR = 3178; MTB_MODULE_SC_OUT_SUM_ERROR_GIVING_UP = 3179; MTB_UNSUPPORTED_API_VERSION = 4000; implementation 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 FB4D.OAuth; interface uses System.Classes, System.SysUtils, System.Types, System.JSON, System.JSON.Types, REST.Types, JOSE.Types.Bytes, JOSE.Context, JOSE.Core.JWT, FB4D.Interfaces; type TTokenJWT = class(TInterfacedObject, ITokenJWT) private fContext: TJOSEContext; function GetPublicKey(const Id: string): TJOSEBytes; public constructor Create(const OAuthToken: string); destructor Destroy; override; function VerifySignature: boolean; function GetHeader: TJWTHeader; function GetClaims: TJWTClaims; end; implementation uses System.Generics.Collections, JOSE.Core.JWS, JOSE.Signing.RSA, FB4D.Request; { TTokenJWT } constructor TTokenJWT.Create(const OAuthToken: string); var CompactToken: TJOSEBytes; begin CompactToken.AsString := OAuthToken; fContext := TJOSEContext.Create(CompactToken, TJWTClaims); CompactToken.Clear; end; destructor TTokenJWT.Destroy; begin fContext.Free; inherited; end; function TTokenJWT.GetPublicKey(const Id: string): TJOSEBytes; const GOOGLE_x509 = 'https://www.googleapis.com/robot/v1/metadata/x509'; SToken = 'securetoken@system.gserviceaccount.com'; var ARequest: TFirebaseRequest; AResponse: IFirebaseResponse; JSONObj: TJSONObject; c: integer; begin result.Empty; ARequest := TFirebaseRequest.Create(GOOGLE_x509, 'GetPublicKey'); JSONObj := nil; try AResponse := ARequest.SendRequestSynchronous([SToken], rmGet, nil, nil, tmNoToken); JSONObj := TJSONObject.ParseJSONValue(AResponse.ContentAsString) as TJSONObject; for c := 0 to JSONObj.Count-1 do if SameText(JSONObj.Pairs[c].JsonString.Value, Id) then result.AsString := JSONObj.Pairs[c].JsonValue.Value; if result.IsEmpty then raise ETokenJWT.Create('kid not found: ' + Id); finally JSONObj.Free; AResponse := nil; ARequest.Free; end; end; function TTokenJWT.GetClaims: TJWTClaims; begin result := fContext.GetClaims; end; function TTokenJWT.GetHeader: TJWTHeader; begin result := fContext.GetHeader; end; function TTokenJWT.VerifySignature: boolean; var PublicKey: TJOSEBytes; jws: TJWS; begin jws := fContext.GetJOSEObject<TJWS>; PublicKey := GetPublicKey(GetHeader.JSON.GetValue('kid').Value); {$IFDEF IOS} result := false; // Unfortunately, this function is no longer available for iOS platform // For details check the following discussions // https://github.com/SchneiderInfosystems/FB4D/discussions/163 // https://github.com/paolo-rossi/delphi-jose-jwt/issues/51 {$ELSE} jws.SetKeyFromCert(PublicKey); result := jws.VerifySignature; {$ENDIF} end; end.
unit m_listbox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TMariaeListBox } TMariaeListBox = class(TListBox) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public constructor Create(MOwner: TComponent); override; procedure EditingDone; override; procedure OnEditingDone; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_listbox_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeListBox]); end; { TMariaeListBox } procedure TMariaeListBox.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; constructor TMariaeListBox.Create(MOwner: TComponent); begin inherited Create(MOwner); Self.MultiSelect := True; end; procedure TMariaeListBox.EditingDone; begin inherited EditingDone; Self.SetChanged(True); end; procedure TMariaeListBox.OnEditingDone; begin Self.SetChanged(True); end; procedure TMariaeListBox.ResetChanged; begin Self.SetChanged(False); end; end.
unit FFSSplitter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, FFSTypes; type TFFSSplitter = class(TSplitter) private FFieldsColorScheme: TFieldsColorScheme; procedure SetFieldsColorScheme(const Value: TFieldsColorScheme); procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } property FieldsColorScheme:TFieldsColorScheme read FFieldsColorScheme write SetFieldsColorScheme; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Controls', [TFFSSplitter]); end; { TFFSSplitter } procedure TFFSSplitter.MsgFFSColorChange(var Msg: TMessage); begin color := FFSColor[FFieldsColorScheme]; end; procedure TFFSSplitter.SetFieldsColorScheme(const Value: TFieldsColorScheme); begin FFieldsColorScheme := Value; color := FFSColor[FFieldsColorScheme]; end; end.
Unit udmBloqueioLote; interface uses SysUtils, Classes, InvokeRegistry, Midas, SOAPMidas, SOAPDm, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Phys.ODBCBase, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TRetorno = class(TRemotable) private FID: UnicodeString; FSucesso: UnicodeString; FMensagem: UnicodeString; published property id: UnicodeString read FID write FID; property sucesso: UnicodeString read FSucesso write FSucesso; property mensagem: UnicodeString read FMensagem write FMensagem; end; IdmBloqueioLote = interface(IInvokable) ['{192F05A7-37AF-4EEB-9DDB-604CA1E6BF01}'] function envioLaudoXML(const arquivo: WideString): TRetorno; stdcall; end; TdmBloqueioLote = class(TSoapDataModule, IdmBloqueioLote, IAppServerSOAP, IAppServer) FDConnection: TFDConnection; qryTeste: TFDQuery; MSSQLDriverLink: TFDPhysMSSQLDriverLink; stpGeraBloqueioLote: TFDStoredProc; stpGeraBloqueioLoteItens: TFDStoredProc; stpGeraBloqueioLotecd_bloqueio_lote: TIntegerField; stpGeraEmailBloqueio: TFDStoredProc; procedure SoapDataModuleDestroy(Sender: TObject); private public function envioLaudoXML(const arquivo: WideString): TRetorno; stdcall; end; implementation uses Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc; {$R *.DFM} procedure TdmBloqueioLoteCreateInstance(out obj: TObject); begin obj := TdmBloqueioLote.Create(nil); end; function TdmBloqueioLote.envioLaudoXML(const arquivo: WideString): TRetorno; var lxml, lxmlRetorno, lxmlRetornoErro : IXMLDocument; lNodeIdentificacao, lNodeInspecao, lNodeItens, lNodeItem, lNodeRetorno, lNodeRetornoErro : IXMLNode; i, x : integer; lValido : Boolean; cd_bloqueio : Integer; nm_oper, id, nm_laudo : String; listaLPN : TStringList; begin lValido := True; Result := TRetorno.Create; listaLPN := TStringList.Create; //------------------------------------------------------------- //-->> Valida o XML de Entrada //------------------------------------------------------------- try lxml := NewXMLDocument; lxml.XML.Text := arquivo; lxml.Active := True; except on E:Exception do begin lValido := False; Result.id := '0'; Result.sucesso := 'N'; Result.mensagem := '(MSGWMS) Operação não Realizada - Erro na estrutura do XML! ' + E.Message; end; end; if lValido then begin //------------------------------------------------------------- //-->> Grava os Dados //------------------------------------------------------------- try with stpGeraBloqueioLote do begin Close; //-->> Guarda o node da Identificação lNodeIdentificacao := lxml.DocumentElement.ChildNodes['IDENTIFICACAO']; ParamByName('@cd_parametro').AsInteger := 1; ParamByName('@cd_bloqueio_lote').AsInteger := 0; ParamByName('@dt_bloqueio_lote').AsString := ''; ParamByName('@hr_bloqueio_lote').AsString := ''; ParamByName('@nm_identificador').AsString := lNodeIdentificacao.ChildNodes['IDENTIFICADOR'].Text; if lNodeIdentificacao.ChildNodes['REQUISITANTE'].Text <> '' then ParamByName('@cd_requisitante').AsInteger := StrToIntDef(lNodeIdentificacao.ChildNodes['REQUISITANTE'].Text,0); ParamByName('@nm_cnpj_requisitante').AsString := lNodeIdentificacao.ChildNodes['CNPJ_REQUISITANTE'].Text; if lNodeIdentificacao.ChildNodes['DESTINO'].Text <> '' then ParamByName('@cd_destino').AsInteger := StrToIntDef(lNodeIdentificacao.ChildNodes['DESTINO'].Text,0); ParamByName('@nm_cnpj_destino').AsString := lNodeIdentificacao.ChildNodes['CNPJ_DESTINO'].Text; ParamByName('@nm_xsd_validacao').AsString := lNodeIdentificacao.ChildNodes['XSDVALIDACAO'].Text; //-->> Guarda o node da Inspeção lNodeInspecao := lxml.DocumentElement.ChildNodes['DADOSXML'].ChildNodes['INSPECAO']; if lNodeInspecao.ChildNodes['CENTRO_ORIGEM'].Text <> '' then ParamByName('@cd_centro_origem').AsInteger := StrToIntDef(lNodeInspecao.ChildNodes['CENTRO_ORIGEM'].Text,0); //-->> Guarda o node de Itens lNodeItens := lNodeInspecao.ChildNodes['ITENS']; nm_oper := lNodeItens.Attributes['IDENT_OPER']; nm_laudo := lNodeItens.Attributes['NUM_LAUDO_BLOQUEIO']; ParamByName('@nm_ident_oper').AsString := nm_oper; ParamByName('@nm_laudo_bloqueio').AsString := nm_laudo; //-->> Salva o XML ParamByName('@ds_arquivo_xml').AsMemo := lxml.XML.Text; //--> Executa a Procedure apenas na Add cd_bloqueio := 0; if nm_oper = 'add' then begin Open; cd_bloqueio := stpGeraBloqueioLotecd_bloqueio_lote.AsInteger; end; end; with stpGeraBloqueioLoteItens do begin listaLPN.Clear; for i := 0 to lNodeItens.ChildNodes.Count - 1 do begin Close; //-->> Guarda o node do Item lNodeItem := lNodeItens.ChildNodes.Get(i); ParamByName('@cd_parametro').AsInteger := 3; ParamByName('@cd_bloqueio_lote').AsInteger := cd_bloqueio; ParamByName('@cd_item_bloqueio_lote').AsInteger := 0; ParamByName('@nm_ident_oper').AsString := nm_oper; if lNodeItem.ChildNodes['COD_BLOQUEIO_WEB'].Text <> '' then ParamByName('@cd_bloqueio_web').AsInteger := StrToIntDef(lNodeItem.ChildNodes['COD_BLOQUEIO_WEB'].Text,0); ParamByName('@nm_sku').AsString := lNodeItem.ChildNodes['SKU'].Text; ParamByName('@nm_descricao').AsString := lNodeItem.ChildNodes['DESCRICAO'].Text; ParamByName('@nm_categoria').AsString := lNodeItem.ChildNodes['CATEGORIA'].Text; ParamByName('@nm_divisao').AsString := lNodeItem.ChildNodes['DIVISAO'].Text; ParamByName('@dt_fabricacao').AsString := lNodeItem.ChildNodes['DH_FABRICACAO'].Text; ParamByName('@dt_vencimento').AsString := lNodeItem.ChildNodes['DH_VENCIMENTO'].Text; if lNodeItem.ChildNodes['QTD_CAIXAS'].Text <> '' then ParamByName('@qt_caixa').AsInteger := StrToIntDef(lNodeItem.ChildNodes['QTD_CAIXAS'].Text,0); if lNodeItem.ChildNodes['QTD_PRODUTOS'].Text <> '' then ParamByName('@qt_produto').AsInteger := StrToIntDef(lNodeItem.ChildNodes['QTD_PRODUTOS'].Text,0); ParamByName('@nm_cod_lpn').AsString := lNodeItem.ChildNodes['COD_LPN'].Text; ParamByName('@dt_bloqueio').AsString := lNodeItem.ChildNodes['DH_BLOQUEIO'].Text; ParamByName('@nm_codigo_motivo').AsString := lNodeItem.ChildNodes['CODIGO_MOTIVO'].Text; ParamByName('@nm_descricao_motivo').AsString := lNodeItem.ChildNodes['DESCRICAO_MOTIVO'].Text; ParamByName('@nm_solicitante_motivo').AsString := lNodeItem.ChildNodes['SOLICITANTE_BLOQUEIO'].Text; ParamByName('@nm_laudo_bloqueio').AsString := nm_laudo; ExecProc; end; end; except on E:Exception do begin lValido := false; lValido := False; Result.id := '0'; Result.sucesso := 'N'; Result.mensagem := '(MSGWMS) Operação não Realizada - Erro na gravação dos Dados! ' + E.Message; end; end; end; if lValido then begin //------------------------------------------------------------- //-->> Retorno de Sucesso //------------------------------------------------------------- id := ''; if cd_bloqueio = 0 then id := '1' else id := IntToStr(cd_bloqueio); Result.id := id; Result.sucesso := 'S'; Result.mensagem := '(MSGWMS) Operação Realizada com Sucesso!'; //------------------------------------------------------------- //-->> Envio de Email try with stpGeraEmailBloqueio do begin Close; if nm_oper = 'add' then begin ParamByName('@cd_parametro').AsInteger := 1; ParamByName('@cd_bloqueio').AsInteger := cd_bloqueio; end else if nm_oper = 'des' then ParamByName('@cd_parametro').AsInteger := 2 else if nm_oper = 'enc' then ParamByName('@cd_parametro').AsInteger := 3; ParamByName('@cd_bloqueio').AsInteger := cd_bloqueio; ExecProc; Close; end; except end; end; end; procedure TdmBloqueioLote.SoapDataModuleDestroy(Sender: TObject); begin FDConnection.Connected := False; end; initialization InvRegistry.RegisterInvokableClass(TdmBloqueioLote, TdmBloqueioLoteCreateInstance); InvRegistry.RegisterInterface(TypeInfo(IdmBloqueioLote)); end.
unit ufrmKartuAP; 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 TfrmKartuAP = class(TfrmDefaultLaporan) cbbCustomer: TcxExtLookupComboBox; lblCustomer: TLabel; pnlfOOTER: TPanel; lblTotal: TLabel; edtOTAL: TcxCurrencyEdit; lblNoAP: TLabel; edNoAP: TcxTextEdit; procedure ActionRefreshExecute(Sender: TObject); procedure FormCreate(Sender: TObject); private FCDSS: TFDJSONDataSets; function GetNoAP: string; procedure InisialisasiCBBSupplier; { Private declarations } public procedure CetakSlip; override; { Public declarations } end; var frmKartuAP: TfrmKartuAP; implementation {$R *.dfm} procedure TfrmKartuAP.ActionRefreshExecute(Sender: TObject); var dTotal: Double; lSupplier: TSupplier; lDS: TClientDataSet; lCabang: TCabang; begin inherited; if VarIsNull(cbbCabang.EditValue) then begin TAppUtils.Warning('Cabang Belum Dipilih'); Exit; end; if VarIsNull(cbbCustomer.EditValue) then begin TAppUtils.Warning('Supplier Belum Dipilih'); Exit; end; lSupplier := TSupplier.CreateID(cbbCustomer.EditValue); lCabang := TCabang.CreateID(cbbCabang.EditValue); FCDSS := ClientDataModule.ServerLaporanClient.LaporanKarAP(dtpAwal.Date, dtpAkhir.Date,lSupplier, lCabang, GetNoAP); lDS := TDBUtils.DSToCDS(TDataSet(TFDJSONDataSetsReader.GetListValue(FCDSS, 1)), Self); cxGridDBTableOverview.SetDataset(lDS, True); cxGridDBTableOverview.ApplyBestFit(); cxGridDBTableOverview.SetVisibleColumns(['urutan','PERIODEAWAL','PERIODEAKHIR','CABANG','SUPPLIER'], 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 TfrmKartuAP.CetakSlip; var lSupplier: TSupplier; lCabang: TCabang; begin inherited; lSupplier := TSupplier.CreateID(cbbCustomer.EditValue); lCabang := TCabang.CreateID(cbbCabang.EditValue); FCDSS := ClientDataModule.ServerLaporanClient.LaporanKarAP(dtpAwal.Date, dtpAkhir.Date,lSupplier, lCabang, GetNoAP); with dmReport do begin AddReportVariable('UserCetak', UserAplikasi.UserName); AddReportVariable('NoBukti', GetNoAP); ExecuteReport( 'Reports/Lap_KarAP' , FCDSS ); end; end; procedure TfrmKartuAP.FormCreate(Sender: TObject); begin inherited; InisialisasiCBBSupplier; cbbCabang.EditValue := ClientDataModule.Cabang.ID; end; function TfrmKartuAP.GetNoAP: string; begin if Trim(edNoAP.Text) = '' then Result := 'XXX' else Result := Trim(edNoAP.Text); end; procedure TfrmKartuAP.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.
unit IdHeaderCoderBase; interface {$i IdCompilerDefines.inc} uses Classes, IdGlobal, IdException; type TIdHeaderDecodingNeededEvent = procedure(const ACharSet: String; const AData: TIdBytes; var VResult: String; var VHandled: Boolean) of object; TIdHeaderEncodingNeededEvent = procedure(const ACharSet, AData: String; var VResult: TIdBytes; var VHandled: Boolean) of object; TIdHeaderCoder = class(TObject) public class function Decode(const ACharSet: String; const AData: TIdBytes): String; virtual; class function Encode(const ACharSet, AData: String): TIdBytes; virtual; class function CanHandle(const ACharSet: String): Boolean; virtual; end; TIdHeaderCoderClass = class of TIdHeaderCoder; EIdHeaderEncodeError = class(EIdException); var GHeaderEncodingNeeded: TIdHeaderEncodingNeededEvent = nil; GHeaderDecodingNeeded: TIdHeaderDecodingNeededEvent = nil; function HeaderCoderByCharSet(const ACharSet: String): TIdHeaderCoderClass; function DecodeHeaderData(const ACharSet: String; const AData: TIdBytes; var VResult: String): Boolean; function EncodeHeaderData(const ACharSet, AData: String): TIdBytes; procedure RegisterHeaderCoder(const ACoder: TIdHeaderCoderClass); procedure UnregisterHeaderCoder(const ACoder: TIdHeaderCoderClass); implementation uses {$IFDEF VCL_XE3_OR_ABOVE} System.Types, {$ENDIF} SysUtils, IdResourceStringsProtocols; type TIdHeaderCoderList = class(TList) public function ByCharSet(const ACharSet: String): TIdHeaderCoderClass; end; var GHeaderCoderList: TIdHeaderCoderList = nil; { TIdHeaderCoder } class function TIdHeaderCoder.Decode(const ACharSet: String; const AData: TIdBytes): String; begin Result := ''; end; class function TIdHeaderCoder.Encode(const ACharSet, AData: String): TIdBytes; begin Result := nil; end; class function TIdHeaderCoder.CanHandle(const ACharSet: String): Boolean; begin Result := False; end; { TIdHeaderCoderList } function TIdHeaderCoderList.ByCharSet(const ACharSet: string): TIdHeaderCoderClass; var I: Integer; LCoder: TIdHeaderCoderClass; begin Result := nil; // loop backwards so that user-defined coders can override native coders for I := Count-1 downto 0 do begin LCoder := TIdHeaderCoderClass(Items[I]); if LCoder.CanHandle(ACharSet) then begin Result := LCoder; Exit; end; end; end; function HeaderCoderByCharSet(const ACharSet: String): TIdHeaderCoderClass; begin if Assigned(GHeaderCoderList) then begin Result := GHeaderCoderList.ByCharSet(ACharSet); end else begin Result := nil; end; end; function DecodeHeaderData(const ACharSet: String; const AData: TIdBytes; var VResult: String): Boolean; var LCoder: TIdHeaderCoderClass; begin LCoder := HeaderCoderByCharSet(ACharSet); if LCoder <> nil then begin VResult := LCoder.Decode(ACharSet, AData); Result := True; end else begin VResult := ''; Result := False; if Assigned(GHeaderDecodingNeeded) then begin GHeaderDecodingNeeded(ACharSet, AData, VResult, Result); end; { RLebeau: TODO - enable this? if not LDecoded then begin raise EIdHeaderDecodeError.Create(RSHeaderDecodeError, [ACharSet]); end; } end; end; function EncodeHeaderData(const ACharSet, AData: String): TIdBytes; var LCoder: TIdHeaderCoderClass; LEncoded: Boolean; begin LCoder := HeaderCoderByCharSet(ACharSet); if LCoder <> nil then begin Result := LCoder.Encode(ACharSet, AData); end else begin Result := nil; LEncoded := False; if Assigned(GHeaderEncodingNeeded) then begin GHeaderEncodingNeeded(ACharSet, AData, Result, LEncoded); end; if not LEncoded then begin raise EIdHeaderEncodeError.CreateFmt(RSHeaderEncodeError, [ACharSet]); end; end; end; procedure RegisterHeaderCoder(const ACoder: TIdHeaderCoderClass); begin if Assigned(ACoder) and Assigned(GHeaderCoderList) and (GHeaderCoderList.IndexOf(TObject(ACoder)) = -1) then begin GHeaderCoderList.Add(TObject(ACoder)); end; end; procedure UnregisterHeaderCoder(const ACoder: TIdHeaderCoderClass); begin if Assigned(GHeaderCoderList) then begin GHeaderCoderList.Remove(TObject(ACoder)); end; end; initialization GHeaderCoderList := TIdHeaderCoderList.Create; finalization FreeAndNil(GHeaderCoderList); end.
{**************************************************************************\ * * Module Name: PMHELP.H * * OS/2 Information Presentation Facility (IPF) for providing Help * * Copyright (c) International Business Machines Corporation 1989, 1990 * ***************************************************************************** } {| Version: 1.00 | Original translation: Peter Sawatzki (ps) | Contributing: | Peter Sawatzki ps | | change history: | Date: Ver: Author: | 11/11/93 1.00 ps original translation by ps } Unit PmHelp; Interface Uses Os2Def; Type {****************************************************************************} { HelpSubTable entry structure } {****************************************************************************} HELPSUBTABLE = Integer; pHELPSUBTABLE = ^HELPSUBTABLE; {****************************************************************************} { HelpTable entry structure } {****************************************************************************} HELPTABLE = Record idAppWindow: USHORT; phstHelpSubTable: pHELPSUBTABLE; idExtPanel: USHORT End; pHELPTABLE = ^HELPTABLE; {****************************************************************************} { IPF Initialization Structure used on the } { WinCreateHelpInstance() call. } {****************************************************************************} HELPINIT = Record cb: USHORT; ulReturnCode: ULONG; pszTutorialName: pSZ; phtHelpTable: pHELPTABLE; hmodHelpTableModule, hmodAccelActionBarModule: HMODULE; idAccelTable, idActionBar: USHORT; pszHelpWindowTitle:pSZ; usShowPanelId: USHORT; pszHelpLibraryName: pSZ End; pHELPINIT = HELPINIT; Const {****************************************************************************} { Search parent chain indicator for HM_SET_ACTIVE_WINDOW message. } {****************************************************************************} HWND_PARENT = HWND(0); {****************************************************************************} { Constants used to define whether user wants to display panel using } { panel number or panel name. } {****************************************************************************} HM_RESOURCEID = 0; HM_PANELNAME = 1; HMPANELTYPE_NUMBER = 0; HMPANELTYPE_NAME = 1; {****************************************************************************} { Constants used to define how the panel IDs are displayed on } { help panels. } {****************************************************************************} CMIC_HIDE_PANEL_ID = $0000; CMIC_SHOW_PANEL_ID = $0001; CMIC_TOGGLE_PANEL_ID = $0002; {****************************************************************************} { Window Help function declarations. } {****************************************************************************} Function WinDestroyHelpInstance(hwndHelpInstance: HWND): BOOL; Function WinCreateHelpInstance(_hab: HAB; phinitHMInitStructure: PHELPINIT): HWND; Function WinAssociateHelpInstance(hwndHelpInstance, hwndApp: HWND): BOOL; Function WinQueryHelpInstance(hwndApp: HWND): HWND; Function WinLoadHelpTable (hwndHelpInstance: HWND; idHelpTable: USHORT; Module: HMODULE): BOOL; Function WinCreateHelpTable (hwndHelpInstance: HWND; phtHelpTable: PHELPTABLE): BOOL; Const {****************************************************************************} { IPF message base. } {****************************************************************************} HM_MSG_BASE = $0220; {****************************************************************************} { Messages applications can send to the IPF. } {****************************************************************************} HM_DISMISS_WINDOW = HM_MSG_BASE+$0001; HM_DISPLAY_HELP = HM_MSG_BASE+$0002; HM_EXT_HELP = HM_MSG_BASE+$0003; HM_SET_ACTIVE_WINDOW = HM_MSG_BASE+$0004; HM_LOAD_HELP_TABLE = HM_MSG_BASE+$0005; HM_CREATE_HELP_TABLE = HM_MSG_BASE+$0006; HM_SET_HELP_WINDOW_TITLE = HM_MSG_BASE+$0007; HM_SET_SHOW_PANEL_ID = HM_MSG_BASE+$0008; HM_REPLACE_HELP_FOR_HELP = HM_MSG_BASE+$0009; HM_HELP_INDEX = HM_MSG_BASE+$000a; HM_HELP_CONTENTS = HM_MSG_BASE+$000b; HM_KEYS_HELP = HM_MSG_BASE+$000c; HM_SET_HELP_LIBRARY_NAME = HM_MSG_BASE+$000d; {****************************************************************************} { Messages the IPF sends to the applications active window } { as defined by the IPF. } {****************************************************************************} HM_ERROR = HM_MSG_BASE+$000e; HM_HELPSUBITEM_NOT_FOUND = HM_MSG_BASE+$000f; HM_QUERY_KEYS_HELP = HM_MSG_BASE+$0010; HM_TUTORIAL = HM_MSG_BASE+$0011; HM_EXT_HELP_UNDEFINED = HM_MSG_BASE+$0012; HM_ACTIONBAR_COMMAND = HM_MSG_BASE+$0013; HM_INFORM = HM_MSG_BASE+$0014; {****************************************************************************} { HMERR_NO_FRAME_WND_IN_CHAIN - There is no frame window in the } { window chain from which to find or set the associated help } { instance. } {****************************************************************************} HMERR_NO_FRAME_WND_IN_CHAIN = $00001001; {****************************************************************************} { HMERR_INVALID_ASSOC_APP_WND - The application window handle } { specified on the WinAssociateHelpInstance() call is not a valid } { window handle. } {****************************************************************************} HMERR_INVALID_ASSOC_APP_WND = $00001002; {****************************************************************************} { HMERR_INVALID_ASSOC_HELP_INST - The help instance handle specified } { on the WinAssociateHelpInstance() call is not a valid } { window handle. } {****************************************************************************} HMERR_INVALID_ASSOC_HELP_INST = $00001003; {****************************************************************************} { HMERR_INVALID_DESTROY_HELP_INST - The window handle specified } { as the help instance to destroy is not of the help instance class. } {****************************************************************************} HMERR_INVALID_DESTROY_HELP_INST = $00001004; {****************************************************************************} { HMERR_NO_HELP_INST_IN_CHAIN - The parent or owner chain of the } { application window specified does not have a help instance } { associated with it. } {****************************************************************************} HMERR_NO_HELP_INST_IN_CHAIN = $00001005; {****************************************************************************} { HMERR_INVALID_HELP_INSTANCE_HDL - The handle specified to be a } { help instance does not have the class name of a IPF } { help instance. } {****************************************************************************} HMERR_INVALID_HELP_INSTANCE_HDL = $00001006; {****************************************************************************} { HMERR_INVALID_QUERY_APP_WND - The application window specified on } { a WinQueryHelpInstance() call is not a valid window handle. } {****************************************************************************} HMERR_INVALID_QUERY_APP_WND = $00001007; {****************************************************************************} { HMERR_HELP_INST_CALLED_INVALID - The handle of the help instance } { specified on an API call to the IPF does not have the } { class name of an IPF help instance. } {****************************************************************************} HMERR_HELP_INST_CALLED_INVALID = $00001008; HMERR_HELPTABLE_UNDEFINE = $00001009; HMERR_HELP_INSTANCE_UNDEFINE = $0000100a; HMERR_HELPITEM_NOT_FOUND = $0000100b; HMERR_INVALID_HELPSUBITEM_SIZE = $0000100c; HMERR_HELPSUBITEM_NOT_FOUND = $0000100d; {****************************************************************************} { HMERR_INDEX_NOT_FOUND - No index in library file. } {****************************************************************************} HMERR_INDEX_NOT_FOUND = $00002001; {****************************************************************************} { HMERR_CONTENT_NOT_FOUND - Library file does not have any contents. } {****************************************************************************} HMERR_CONTENT_NOT_FOUND = $00002002; {****************************************************************************} { HMERR_OPEN_LIB_FILE - Cannot open library file. } {****************************************************************************} HMERR_OPEN_LIB_FILE = $00002003; {****************************************************************************} { HMERR_READ_LIB_FILE - Cannot read library file. } {****************************************************************************} HMERR_READ_LIB_FILE = $00002004; {****************************************************************************} { HMERR_CLOSE_LIB_FILE - Cannot close library file. } {****************************************************************************} HMERR_CLOSE_LIB_FILE = $00002005; {****************************************************************************} { HMERR_INVALID_LIB_FILE - Improper library file provided. } {****************************************************************************} HMERR_INVALID_LIB_FILE = $00002006; {****************************************************************************} { HMERR_NO_MEMORY - Unable to allocate the requested amount of memory. } {****************************************************************************} HMERR_NO_MEMORY = $00002007; {****************************************************************************} { HMERR_ALLOCATE_SEGMENT - Unable } { to allocate a segment of memory for memory allocation requested } { from the IPF. } {****************************************************************************} HMERR_ALLOCATE_SEGMENT = $00002008; {****************************************************************************} { HMERR_FREE_MEMORY - Unable to free allocated memory. } {****************************************************************************} HMERR_FREE_MEMORY = $00002009; {****************************************************************************} { HMERR_PANEL_NOT_FOUND - Unable } { to find a help panel requested to IPF. } {****************************************************************************} HMERR_PANEL_NOT_FOUND = $00002010; {****************************************************************************} { HMERR_DATABASE_NOT_OPEN - Unable to read the unopened database. } {****************************************************************************} HMERR_DATABASE_NOT_OPEN = $00002011; Implementation Function WinCreateHelpInstance; External 'HELPMGR' Index 1; Function WinDestroyHelpInstance; External 'HELPMGR' Index 2; Function WinQueryHelpInstance; External 'HELPMGR' Index 3; Function WinAssociateHelpInstance; External 'HELPMGR' Index 4; Function WinLoadHelpTable; External 'HELPMGR' Index 5; Function WinCreateHelpTable; External 'HELPMGR' Index 6; End.
unit DzListHeaderCustom; interface uses Vcl.Forms, Vcl.StdCtrls, Vcl.Controls, Vcl.ExtCtrls, Vcl.CheckLst, System.Classes, Vcl.Buttons, // DzListHeader, System.Types; type TFrmListHeaderCustom = class(TForm) BtnAll: TSpeedButton; BtnNone: TSpeedButton; BtnSwap: TSpeedButton; BtnDefOrder: TSpeedButton; L: TCheckListBox; BoxBtns: TPanel; BtnOK: TButton; BtnCancel: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure LDragDrop(Sender, Source: TObject; X, Y: Integer); procedure LDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure LDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure BtnAllClick(Sender: TObject); procedure BtnNoneClick(Sender: TObject); procedure BtnSwapClick(Sender: TObject); procedure BtnDefOrderClick(Sender: TObject); procedure BtnOKClick(Sender: TObject); private LH: TDzListHeader; DropIndex: Integer; procedure Load; procedure AddCol(C: TDzListHeaderCol); end; procedure DoListHeaderCustomizeDlg(LH: TDzListHeader); implementation {$R *.dfm} procedure DoListHeaderCustomizeDlg; var F: TFrmListHeaderCustom; begin F := TFrmListHeaderCustom.Create(Application); F.LH := LH; F.ShowModal; F.Free; end; // procedure TFrmListHeaderCustom.FormCreate(Sender: TObject); begin L.Anchors := [akLeft,akRight,akTop,akBottom]; BoxBtns.Anchors := [akBottom]; DropIndex := -1; end; procedure TFrmListHeaderCustom.FormShow(Sender: TObject); begin Load; end; procedure TFrmListHeaderCustom.AddCol(C: TDzListHeaderCol); var A: String; I: Integer; begin A := C.CaptionEx; if A='' then A := C.Caption; I := L.Items.AddObject(A, C); L.Checked[I] := C.Visible; end; procedure TFrmListHeaderCustom.Load; var C: TDzListHeaderCol; begin for C in LH.Columns do begin if C.Customizable then AddCol(C); end; end; procedure TFrmListHeaderCustom.BtnOKClick(Sender: TObject); var I: Integer; C: TDzListHeaderCol; begin LH.Columns.BeginUpdate; try for I := 0 to L.Count-1 do begin C := TDzListHeaderCol(L.Items.Objects[I]); C.Index := I; C.Visible := L.Checked[I]; end; finally LH.Columns.EndUpdate; end; ModalResult := mrOk; end; procedure TFrmListHeaderCustom.BtnDefOrderClick(Sender: TObject); var I: Integer; C: TDzListHeaderCol; begin L.Clear; for I := 0 to LH.Columns.Count-1 do begin C := LH.Columns.FindItemID(I); if C.Customizable then AddCol(C); end; end; procedure TFrmListHeaderCustom.LDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var OldIndex: Integer; begin if L.ItemIndex=-1 then begin Accept := False; Exit; end; OldIndex := DropIndex; DropIndex := L.ItemAtPos(Point(X,Y), False); if DropIndex=L.Count then Dec(DropIndex); if OldIndex<>DropIndex then L.Invalidate; end; procedure TFrmListHeaderCustom.LDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin L.Canvas.FillRect(Rect); if (Index=DropIndex) and (Index<>L.ItemIndex) then begin if L.ItemIndex>Index then L.Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Top+1) else L.Canvas.Rectangle(Rect.Left, Rect.Bottom, Rect.Right, Rect.Bottom-1) end; L.Canvas.TextOut(Rect.Left+2, Rect.Top+2, L.Items[Index]); end; procedure TFrmListHeaderCustom.LDragDrop(Sender, Source: TObject; X, Y: Integer); begin if DropIndex<>L.ItemIndex then begin L.Items.Move(L.ItemIndex, DropIndex); L.ItemIndex := DropIndex; //L.Invalidate; end; DropIndex := -1; end; procedure TFrmListHeaderCustom.BtnAllClick(Sender: TObject); begin L.CheckAll(cbChecked); end; procedure TFrmListHeaderCustom.BtnNoneClick(Sender: TObject); begin L.CheckAll(cbUnchecked); end; procedure TFrmListHeaderCustom.BtnSwapClick(Sender: TObject); var I: Integer; begin for I := 0 to L.Count-1 do L.Checked[I] := not L.Checked[I]; end; end.
unit alcuAutoAnnoExportTaskPrim; // Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuAutoAnnoExportTaskPrim.pas" // Стереотип: "SimpleClass" // Элемент модели: "TalcuAutoAnnoExportTaskPrim" MUID: (53F59F27018A) {$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc} interface {$If Defined(ServerTasks)} uses l3IntfUses , alcuExport , evdTasksHelpers , k2Base ; type TalcuAutoAnnoExportTaskPrim = class(TalcuExport) protected function pm_GetStartDate: TDateTime; procedure pm_SetStartDate(aValue: TDateTime); function pm_GetEndDate: TDateTime; procedure pm_SetEndDate(aValue: TDateTime); function pm_GetBelongsIDList: BelongsIDListHelper; {$If NOT Defined(Nemesis)} function GetDescription: AnsiString; override; {$IfEnd} // NOT Defined(Nemesis) public class function GetTaggedDataType: Tk2Type; override; public property StartDate: TDateTime read pm_GetStartDate write pm_SetStartDate; property EndDate: TDateTime read pm_GetEndDate write pm_SetEndDate; property BelongsIDList: BelongsIDListHelper read pm_GetBelongsIDList; end;//TalcuAutoAnnoExportTaskPrim {$IfEnd} // Defined(ServerTasks) implementation {$If Defined(ServerTasks)} uses l3ImplUses , AutoAnnoExportTask_Const //#UC START# *53F59F27018Aimpl_uses* //#UC END# *53F59F27018Aimpl_uses* ; function TalcuAutoAnnoExportTaskPrim.pm_GetStartDate: TDateTime; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.DateTimeA[k2_attrStartDate]); end;//TalcuAutoAnnoExportTaskPrim.pm_GetStartDate procedure TalcuAutoAnnoExportTaskPrim.pm_SetStartDate(aValue: TDateTime); begin TaggedData.DateTimeW[k2_attrStartDate, nil] := (aValue); end;//TalcuAutoAnnoExportTaskPrim.pm_SetStartDate function TalcuAutoAnnoExportTaskPrim.pm_GetEndDate: TDateTime; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.DateTimeA[k2_attrEndDate]); end;//TalcuAutoAnnoExportTaskPrim.pm_GetEndDate procedure TalcuAutoAnnoExportTaskPrim.pm_SetEndDate(aValue: TDateTime); begin TaggedData.DateTimeW[k2_attrEndDate, nil] := (aValue); end;//TalcuAutoAnnoExportTaskPrim.pm_SetEndDate function TalcuAutoAnnoExportTaskPrim.pm_GetBelongsIDList: BelongsIDListHelper; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := TBelongsIDListHelper.Make(TaggedData.cAtom(k2_attrBelongsIDList)); end;//TalcuAutoAnnoExportTaskPrim.pm_GetBelongsIDList {$If NOT Defined(Nemesis)} function TalcuAutoAnnoExportTaskPrim.GetDescription: AnsiString; //#UC START# *53FB28170339_53F59F27018A_var* //#UC END# *53FB28170339_53F59F27018A_var* begin //#UC START# *53FB28170339_53F59F27018A_impl* Result := 'Экспорт аннотаций для дельты'; //#UC END# *53FB28170339_53F59F27018A_impl* end;//TalcuAutoAnnoExportTaskPrim.GetDescription {$IfEnd} // NOT Defined(Nemesis) class function TalcuAutoAnnoExportTaskPrim.GetTaggedDataType: Tk2Type; begin Result := k2_typAutoAnnoExportTask; end;//TalcuAutoAnnoExportTaskPrim.GetTaggedDataType {$IfEnd} // Defined(ServerTasks) end.
unit command_tree_lib; interface type TCommandTree=class(TAbstractCommandContainer) //дерево для undo/redo с многими ветвями private fRoot,fCurrent,fIterator: TAbstractTreeCommand; procedure RecursiveCompare(t1,t2: TabstractTreeCommand;var same,plus,minus: Integer); procedure RecursiveMerge(t1,t2: TAbstractTreeCommand); procedure Assimilate(t: TAbstractTreeCommand); protected function FindExistingCommand(command: TAbstractTreeCommand;position: TAbstractTreeCommand): boolean; public constructor Create(AOwner: TComponent); override; procedure Clear; override; function CheckForExistingCommand(command: TAbstractCommand): boolean; override; function UndoEnabled: Boolean; override; function RedoEnabled: Boolean; override; procedure Add(command: TAbstractCommand); override; procedure Undo; override; procedure Redo; override; procedure JumpToBranch(command: TAbstractCommand); override; function IsEmpty: Boolean; override; function CurrentExecutedCommand: TAbstractCommand; override; function PrevCommand: TAbstractCommand; override; function NextCommand: TAbstractCommand; override; //для построения списков undo/redo procedure CompareWith(tree: TCommandTree;var same,plus,minus: Integer); procedure MergeWith(tree: TCommandTree); published property Root: TAbstractTreeCommand read fRoot write fRoot; property Current: TAbstractTreeCommand read fCurrent write fCurrent; end; //спасено из abstractDocument: последовательность создания пустого дерева (* Root:=TBranchCommand.Create(UndoTree); Current:=Root; Root.ActiveBranch:=true; *) implementation (* TCommandTree *) constructor TCommandTree.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TCommandTree.Clear; begin fRoot:=nil; fCurrent:=nil; end; function TCommandTree.isEmpty: Boolean; begin Result:=Root.Next=nil; end; function TCommandTree.FindExistingCommand(command: TAbstractTreeCommand;position: TAbstractTreeCommand): boolean; begin if position=nil then Result:=false else if position.EqualsByAnyOtherName(command) then begin JumpToBranch(position); Result:=true; end else if (position is TInfoCommand) then Result:=FindExistingCommand(command,position.Next) or FindExistingCommand(command,position.Branch) else Result:=false; end; function TCommandTree.CheckForExistingCommand(command: TAbstractCommand): boolean; begin //может, код действительно станет более читаемым, если здоровенный, здоровенный //add разделить на 2 части //поиск в глубину, сначала идем прямо по курсу if current is TInfoCommand then Result:=FindExistingCommand(command as TAbstractTreeCommand,current) else Result:=FindExistingCommand(command as TAbstractTreeCommand,current.Next) or FindExistingCommand(command as TAbstractTreeCommand,current.Branch); end; procedure TCommandTree.Add(command: TAbstractCommand); var treecom: TAbstractTreeCommand; begin while (current.Next<>nil) and (current.Next is TInfoCommand) do begin current.ActiveBranch:=true; current:=current.Next; end; if (current.Next<>nil) then begin //придется отпочковать целую ветвь //убедимся, что прокрутили все уже отпочкованные ветви //чаще всего этот цикл не будет выполняться ни разу current.ActiveBranch:=true; current.TurnLeft:=true; while (current.Branch<>nil) do begin current.ActiveBranch:=true; current.TurnLeft:=true; current:=current.Branch; end; //создаем новую ветвь current.Branch:=TBranchCommand.Create(self); current.Branch.Prev:=current; //делаем ее текущей current:=current.Branch; current.ActiveBranch:=true; current.TurnLeft:=false; end; //теперь заведомо концевой узел, просто добавляем новый элемент treecom:=command as TAbstractTreeCommand; treecom.ensureCorrectName(treecom.Name,self); insertComponent(treecom); current.Next:=treecom; treecom.ActiveBranch:=true; treecom.TurnLeft:=false; treecom.Prev:=current; current:=treecom; end; procedure TCommandTree.Undo; begin (Owner as TAbstractDocument).fCriticalSection.Acquire; //проверка UndoEnabled гарантирует, что вызов undo будет произведен //когда его можно сделать if current.Undo then begin current.ActiveBranch:=false; current:=current.Prev; while (current is TInfoCommand) and (current.prev<>nil) do begin current.ActiveBranch:=false; current:=current.Prev; end; if (current is THashedCommand) then THashingThread.Create(THashedCommand(current),true) else BeginHashEvent.SetEvent; end else Raise Exception.Create('Undo command failed'); (Owner as TAbstractDocument).fCriticalSection.Leave; WaitForHashEvent; end; procedure TCommandTree.Redo; begin (owner as TAbstractDocument).fCriticalSection.Acquire; //проверка RedoEnabled гарантирует, что вызов undo будет произведен //когда его можно сделать repeat if current.TurnLeft then current:=current.Branch else current:=current.Next; current.ActiveBranch:=true; until (not (current is TInfoCommand)); if not current.Execute then Raise Exception.Create('Redo command failed'); if (current is THashedCommand) then THashingThread.Create(THashedCommand(current),false) else BeginHashEvent.SetEvent; (owner as TAbstractDocument).fCriticalSection.Leave; WaitForHashEvent; end; procedure TCommandTree.JumpToBranch(command: TAbstractCommand); var b: TAbstractTreeCommand; begin (owner as TAbstractDocument).fCriticalSection.Acquire; //самая веселая команда //нужно перейти на произвольное состояние //первым делом, надо проторить путь от command до активного пути if command=nil then command:=root; b:=command as TAbstractTreeCommand; while not b.ActiveBranch do begin b.ActiveBranch:=true; b.Prev.TurnLeft:=(b.Prev.Branch=b); b:=b.Prev; end; //теперь b - это точка ветвления //если command стояла выше по активной ветви, чем current, то b=current //пойдем от текущего положения до b, по пути отменяя все операции while current<>b do begin assert(Assigned(current),'jump to branch current=nil'); if not current.Undo then Raise Exception.Create('Undo command failed'); // if (current is THashedCommand) then THashingThread.Create(THashedCommand(current),true); current.ActiveBranch:=false; current:=current.Prev; while (current is TInfoCommand) and (current<>b) do begin current.ActiveBranch:=false; current:=current.Prev; end; end; //все, сомкнулись. Теперь дотопаем от b до command while current<>command do begin while current.TurnLeft and (current<>command) do current:=current.Branch; if current<>command then begin current:=current.Next; if not current.Execute then Exception.Create('Redo command failed'); end; end; (owner as TAbstractDocument).fCriticalSection.Leave; end; function TCommandTree.UndoEnabled: Boolean; var t: TAbstractTreeCommand; begin t:=current; while (t is TInfoCommand) and (t.Prev<>nil) do t:=t.Prev; Result:=(t.Prev<>nil); end; function TCommandTree.RedoEnabled: Boolean; var t: TAbstractTreeCommand; begin t:=current; repeat if t.TurnLeft then t:=t.Branch else t:=t.Next; until (t=nil) or (not (t is TInfoCommand)); Result:=Assigned(t); end; function TCommandTree.CurrentExecutedCommand: TAbstractCommand; begin //здесь мы игнорируем инфокоманды и инициализируем итератор fIterator:=current; while Assigned(fIterator) and (fIterator is TInfoCommand) do fIterator:=fIterator.Prev; Result:=fIterator; if fIterator=nil then fIterator:=root; end; function TCommandTree.PrevCommand: TAbstractCommand; begin if Assigned(fIterator) then begin fIterator:=fIterator.Prev; while Assigned(fIterator) and (fIterator is TInfoCommand) do fIterator:=fIterator.Prev; Result:=fIterator; end else Result:=nil; end; function TCommandTree.NextCommand: TAbstractCommand; begin if Assigned(fIterator) then begin repeat if fIterator.TurnLeft then fIterator:=fIterator.Branch else fIterator:=fIterator.Next; until (fIterator=nil) or (not (fIterator is TInfoCommand)); Result:=fIterator; end else Result:=nil; end; procedure TCommandTree.RecursiveCompare(t1,t2: TAbstractTreeCommand;var same,plus,minus: Integer); begin if t1=nil then begin if t2<>nil then begin //у второго дерева оказалась ветвь, которой нет у нас inc(plus); RecursiveCompare(nil,t2.Next,same,plus,minus); RecursiveCompare(nil,t2.Branch,same,plus,minus); end end else begin if t2=nil then begin //у нас есть ветвь, которой нет у второго дерева inc(minus); RecursiveCompare(t1.Next,nil,same,plus,minus); RecursiveCompare(t1.Branch,nil,same,plus,minus); end else begin //ветвь есть у обеих, но одинаковы ли команды? if t1.EqualsByAnyOtherName(t2) then begin inc(same); RecursiveCompare(t1.Next,t2.Next,same,plus,minus); RecursiveCompare(t1.Branch,t2.Branch,same,plus,minus); end else begin inc(plus); inc(minus); RecursiveCompare(t1.Next,nil,same,plus,minus); RecursiveCompare(t1.Branch,nil,same,plus,minus); RecursiveCompare(nil,t2.Next,same,plus,minus); RecursiveCompare(nil,t2.Branch,same,plus,minus); end; end; end; end; procedure TCommandTree.CompareWith(tree: TCommandTree;var same,plus,minus: Integer); var backup1,backup2: TAbstractCommand; begin backup1:=current; backup2:=tree.Current; //чтобы все команды вернулись в исходное (невыполненное) состояние JumpToBranch(root); tree.JumpToBranch(tree.Root); //начальная установка, корень за совпадение не считаем same:=0; plus:=0; minus:=0; RecursiveCompare(root.Next,tree.Root.Next,same,plus,minus); RecursiveCompare(root.Branch,tree.Root.Branch,same,plus,minus); JumpToBranch(backup1); tree.JumpToBranch(backup2); end; procedure TCommandTree.MergeWith(tree: TCommandTree); var backup1: TAbstractCommand; begin //добавляем ветви, которых у нас не было. //второе дерево в сущности можно "пустить на мясо", //то есть выкусывам из него ветви и присоединяем к нам. backup1:=current; JumpToBranch(root); tree.JumpToBranch(tree.root); RecursiveMerge(root,tree.Root); JumpToBranch(backup1); //а дереву 2 незачем прыгать, оно скоро уничтожится end; procedure TCommandTree.RecursiveMerge(t1,t2: TAbstractTreeCommand); var iterator: TAbstractTreeCommand; begin if t1.Next=nil then begin if t2.Next<>nil then begin //перецепляем //повтора не будет, ведь t1 вообще концевой t1.Next:=t2.Next; t1.Next.Prev:=t1; //меняем владельца Assimilate(t2.Next); //осталось посмотреть, может еще и ветвь есть? if t2.Branch<>nil then begin //t1 был концевой, повторов быть не может t1.Branch:=t2.Branch; t1.Branch.Prev:=t1; assimilate(t2.Branch); end; end; end else if t2.Next<>nil then begin if t1.Next.EqualsByAnyOtherName(t2.Next) then RecursiveMerge(t1.Next,t2.Next) else begin //раз не совпадают, нужно эту "неведомую" ветвь прицепить сбоку //но не будем торопиться, сначала проверим branch iterator:=t1; while iterator.Branch<>nil do iterator:=iterator.Branch; iterator.Branch:=TBranchCommand.Create(self); iterator.Branch.Prev:=iterator; iterator:=iterator.Branch; iterator.Next:=t2.Next; iterator.Next.Prev:=iterator; //перецепили одну команду, теперь нужно перетянуть к себе все хвосты assimilate(t2.Next); end; //и еще посмотрим, может и ветвь есть? //если у t2 нет ветвей, то и незачем париться if t2.Branch<>nil then begin if (t1.Branch<>nil) and (t1.Branch.EqualsByAnyOtherName(t2.Branch)) then RecursiveMerge(t1.Branch,t2.Branch) else begin iterator:=t1; while iterator.Branch<>nil do iterator:=iterator.Branch; iterator.Branch:=t2.Branch; iterator.Branch.Prev:=iterator; Assimilate(t2.Branch); end; end; end; end; procedure TCommandTree.Assimilate(t: TAbstractTreeCommand); begin t.Owner.RemoveComponent(t); InsertComponent(t); if Assigned(t.Next) then Assimilate(t.Next); if Assigned(t.Branch) then Assimilate(t.Branch); end; end.
unit ObjCToPas; { * This file is part of ObjCParser tool * Copyright (C) 2008-2009 by Dmitry Boyarintsev under the GNU LGPL * license version 2.0 or 2.1. You should have received a copy of the * LGPL license along with at http://www.gnu.org/ } // the unit contains (should contain) ObjC to Pascal convertion utility routines // todo: move all ObjCParserUtils functions here. interface {$ifdef fpc}{$mode delphi}{$h+}{$endif} uses SysUtils, ObjCParserTypes; const ObjCDefaultParamDelim = '_'; type TCProcessor = class(TObject) public procedure ProcessTree(Root: TEntity); virtual; abstract; end; function ObjCToPasMethodName(mtd: TClassMethodDef; CutLastDelims: Boolean = false; ParamDelim: AnsiChar = ObjCDefaultParamDelim): AnsiString; function IsPascalReserved(const s: AnsiString): Boolean; implementation function ObjCToPasMethodName(mtd: TClassMethodDef; CutLastDelims: Boolean; ParamDelim: AnsiChar): AnsiString; var i : Integer; obj : TObject; begin Result := mtd._Name; for i := 0 to mtd.Items.Count - 1 do begin obj := mtd.Items[i]; if not Assigned(obj) then Continue; if obj is TParamDescr then begin Result := Result + TParamDescr(obj)._Descr; end else if obj is TObjCParameterDef then Result := Result + ParamDelim; end; if CutLastDelims then begin i := length(Result); while (i > 0) and (Result[i] = ParamDelim) do dec(i); Result := Copy(Result, 1, i); end; end; // 'result' is considered reserved word! function IsPascalReserved(const s: AnsiString): Boolean; var ls : AnsiString; begin //todo: a hash table should be used! Result := false; if s = '' then Exit; ls := AnsiLowerCase(s); case ls[1] of 'a': Result := (ls = 'absolute') or (ls = 'abstract') or (ls = 'and') or (ls = 'array') or (ls = 'as') or (ls= 'asm') or (ls = 'assembler'); 'b': Result := (ls = 'begin') or (ls = 'break'); 'c': Result := (ls = 'cdecl') or (ls = 'class') or (ls = 'const') or (ls = 'constructor') or (ls = 'continue') or (ls = 'cppclass'); 'd': Result := (ls = 'deprecated') or (ls = 'destructor') or (ls = 'div') or (ls = 'do') or (ls = 'downto'); 'e': Result := (ls = 'else') or (ls = 'end') or (ls = 'except') or (ls = 'exit') or (ls = 'export') or (ls = 'exports') or (ls = 'external'); 'f': Result := (ls = 'fail') or (ls = 'false') or (ls = 'far') or (ls = 'file') or (ls = 'finally') or (ls = 'for') or (ls = 'forward') or (ls = 'function'); 'g': Result := (ls = 'goto'); 'i': Result := (ls = 'if') or (ls = 'implementation') or (ls = 'in') or (ls = 'index') or (ls = 'inherited') or (ls = 'initialization') or (ls = 'inline') or (ls = 'interface') or (ls = 'interrupt') or (ls = 'is'); 'l': Result := (ls = 'label') or (ls = 'library'); 'm': Result := (ls = 'mod'); 'n': Result := {(ls = 'name') or} (ls = 'near') or (ls = 'nil') or (ls = 'not'); 'o': Result := (ls = 'object') or (ls = 'of') or (ls = 'on') or (ls = 'operator') or (ls = 'or') or (ls = 'otherwise'); 'p': Result := (ls = 'packed') or (ls = 'popstack') or (ls = 'private') or (ls = 'procedure') or (ls = 'program') or (ls = 'property') or (ls = 'protected') or (ls = 'public'); 'r': Result := (ls = 'raise') or (ls = 'record') or (ls = 'reintroduce') or (ls = 'repeat') or (ls = 'result'); 's': Result := (ls = 'self') or (ls = 'set') or (ls = 'shl') or (ls = 'shr') or (ls = 'stdcall') or (ls = 'string'); 't': Result := (ls = 'then') or (ls = 'to') or (ls = 'true') or (ls = 'try') or (ls = 'type'); 'u': Result := (ls = 'unimplemented') or (ls = 'unit') or (ls = 'until') or (ls = 'uses'); 'v': Result := (ls = 'var') or (ls = 'virtual'); 'w': Result := (ls = 'while') or (ls = 'with'); 'x': Result := (ls = 'xor'); end; end; end.
{ TRedisWire: Redis.pas Copyright 2014 Stijn Sanders Made available under terms described in file "LICENSE" https://github.com/stijnsanders/TRedisWire } unit Redis; interface uses SysUtils, Sockets; type TRedisWire=class(TObject) private FSocket:TTcpClient; FTimeoutMS:cardinal; procedure SetTimeoutMS(const Value: cardinal); public constructor Create(const Host:string;Port:integer=6379); destructor Destroy; override; function Cmd(const CmdStr: WideString):OleVariant; overload; function Cmd(const CmdStr: UTF8String):OleVariant; overload; function Cmd(const Args:array of OleVariant):OleVariant; overload; function Get_(const Key:WideString):OleVariant; procedure Set_(const Key:WideString; Value:OleVariant); function Incr(const Key:WideString):integer; function Decr(const Key:WideString):integer; function IncrBy(const Key:WideString;By:integer):integer; function DecrBy(const Key:WideString;By:integer):integer; property TimeoutMS:cardinal read FTimeoutMS write SetTimeoutMS; property Values[const Key: WideString]:OleVariant read Get_ write Set_; default; end; ERedisError=class(Exception); implementation uses Variants, WinSock, Classes; { TRedisWire } constructor TRedisWire.Create(const Host: string; Port: integer); begin inherited Create; FSocket:=TTcpClient.Create(nil); //FSocket.BlockMode:=bmBlocking; FSocket.RemoteHost:=Host; FSocket.RemotePort:=IntToStr(Port); //FSocket.Open;//see check FTimeoutMS:=10000;//default end; destructor TRedisWire.Destroy; begin FSocket.Free; inherited; end; function TRedisWire.Cmd(const CmdStr: WideString): OleVariant; begin Result:=Cmd(UTF8Encode(CmdStr)); end; function TRedisWire.Cmd(const CmdStr: UTF8String): OleVariant; var Data:UTF8String; DataLength,DataIndex,DataLast,DataNext,ArrayLength,ArrayIndex:integer; InArray:boolean; function ReadInt:integer; var i:integer; neg:boolean; begin Result:=0; neg:=false;//default inc(DataIndex); if (DataIndex<=DataLength) then case Data[DataIndex] of '-': begin neg:=true; inc(DataIndex); end; '+':inc(DataIndex); end; while (DataIndex<=DataLength) and (Data[DataIndex]<>#13) do begin while (DataIndex<=DataLength) and (Data[DataIndex]<>#13) do begin Result:=Result*10+(byte(Data[DataIndex]) and $0F); inc(DataIndex); end; if (DataIndex>DataLength) then begin if DataLast<>1 then begin DataLength:=DataLength-DataLast+1; Data:=Copy(Data,DataLast,DataLength); DataLast:=1; end; SetLength(Data,DataLength+$10000); i:=FSocket.ReceiveBuf(Data[DataLength+1],$10000); if (i=-1) then raise ERedisError.Create(SysErrorMessage(WSAGetLastError)); inc(DataLength,i); end; end; inc(DataIndex,2);//#13#10 if neg then Result:=-Result; end; var i:integer; begin //check connection if not FSocket.Connected then begin FSocket.Connect; //TODO: failover server list? DataIndex:=1; setsockopt(FSocket.Handle,IPPROTO_TCP,TCP_NODELAY,@DataIndex,4); setsockopt(FSocket.Handle,SOL_SOCKET,SO_RCVTIMEO,PAnsiChar(@FTimeoutMS),4); end; //send command Data:=CmdStr; DataLength:=Length(Data); //TODO: check Copy(Data,DataLength-1,2)=#13#10? if FSocket.SendBuf(Data[1],DataLength)<>DataLength then raise ERedisError.Create(SysErrorMessage(WSAGetLastError)); //get a first block SetLength(Data,$10000); DataLength:=FSocket.ReceiveBuf(Data[1],$10000); if (DataLength=-1) or (DataLength=0) then raise ERedisError.Create(SysErrorMessage(WSAGetLastError)); //SetLength(Data,DataLength); InArray:=false; ArrayIndex:=0; DataIndex:=1; DataLast:=1; while (DataIndex<=DataLength) do begin DataLast:=DataIndex; case Data[DataIndex] of '-'://error raise ERedisError.Create( Copy(Data,DataIndex+1,DataLength-DataIndex-2)); '+'://message begin if InArray then raise ERedisError.Create('Unexpected message in array'); Result:=Data='+OK'#13#10;//boolean? DataIndex:=DataLength+1; end; '*'://array begin if InArray then raise ERedisError.Create('Unexpected nested array'); InArray:=true; ArrayIndex:=0; ArrayLength:=ReadInt; //TODO: detect array type? Result:=VarArrayCreate([0,ArrayLength-1],varVariant); end; ':'://integer if InArray then begin Result[ArrayIndex]:=ReadInt; inc(ArrayIndex); end else Result:=ReadInt; '$'://dump string if (DataIndex+3<DataLength) and (Data[DataIndex+1]='-') and (Data[DataIndex+2]='1') then begin if InArray then begin Result[ArrayIndex]:=Null; inc(ArrayIndex); end else Result:=Null; inc(DataIndex,5); end else begin DataNext:=ReadInt; if (DataLast<>1) and (DataIndex+DataNext>DataLength) then begin DataLength:=DataLength-DataLast+1; Data:=Copy(Data,DataLast,DataLength); DataLast:=1; end; while DataIndex+DataNext>DataLength do begin SetLength(Data,DataLength+$10000); i:=FSocket.ReceiveBuf(Data[DataLength+1],$10000); if (i=-1) then raise ERedisError.Create(SysErrorMessage(WSAGetLastError)); inc(DataLength,i); end; //TODO: variant type convertors? if InArray then begin Result[ArrayIndex]:=Copy(Data,DataIndex,DataLength); inc(ArrayIndex); end else Result:=Copy(Data,DataIndex,DataLength); inc(DataIndex,DataLength); inc(DataIndex,2);//#13#10 end; else raise ERedisError.Create('Unknown response type: '+Data); end; //if InArray and (ArrayIndex<ArrayLength)... end; end; procedure TRedisWire.SetTimeoutMS(const Value: cardinal); begin FTimeoutMS:=Value; if FSocket.Connected then setsockopt(FSocket.Handle,SOL_SOCKET,SO_RCVTIMEO,PAnsiChar(@FTimeoutMS),4); end; function TRedisWire.Get_(const Key: WideString): OleVariant; begin Result:=Cmd('GET '+Key+#13#10); end; procedure TRedisWire.Set_(const Key: WideString; Value: OleVariant); begin //TODO: encode value Cmd('SET '+Key+' "'+VarToWideStr(Value)+'"'#13#10); end; function TRedisWire.Cmd(const Args: array of OleVariant): OleVariant; var s,t:WideString; i:integer; vt:word; begin s:='*'+IntToStr(Length(Args))+#13#10; for i:=0 to Length(Args)-1 do begin vt:=VarType(Args[i]); if (vt and varArray)<>0 then raise ERedisError.Create('#'+IntToStr(i)+': Nested arrays not supported'); case vt and varTypeMask of varEmpty,varNull: s:=s+'$-1'#13#10; {//see https://github.com/antirez/redis/issues/1709 varSmallint,varInteger, varShortInt,varByte,varWord,varLongWord,varInt64: s:=s+':'+VarToWideStr(Args[i])+#13#10; } else begin t:=VarToWideStr(Args[i]); s:=s+'$'+IntToStr(Length(t))+#13#10+t+#13#10; end; //else raise ERedisError.Create('#'+IntToStr(i)+': Variant type not supported'); end; end; Result:=Cmd(s); end; function TRedisWire.Incr(const Key: WideString): integer; begin Result:=Cmd('incr '+Key+#13#10); end; function TRedisWire.Decr(const Key: WideString): integer; begin Result:=Cmd('decr '+Key+#13#10); end; function TRedisWire.IncrBy(const Key: WideString; By: integer): integer; begin Result:=Cmd('incr '+Key+' '+IntToStr(By)+#13#10); end; function TRedisWire.DecrBy(const Key: WideString; By: integer): integer; begin Result:=Cmd('decr '+Key+' '+IntToStr(By)+#13#10); 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 ClpBerTaggedObjectParser; {$I ..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpIProxiedInterface, ClpIAsn1StreamParser, ClpIBerTaggedObjectParser, ClpIAsn1TaggedObjectParser; resourcestring SUnConstructedTag = 'Explicit Tags Must be Constructed (see X.690 8.14.2)'; SParsingError = '%s'; type TBerTaggedObjectParser = class(TInterfacedObject, IAsn1TaggedObjectParser, IAsn1Convertible, IBerTaggedObjectParser) strict private var F_constructed: Boolean; F_tagNumber: Int32; F_parser: IAsn1StreamParser; function GetIsConstructed: Boolean; inline; function GetTagNo: Int32; inline; public constructor Create(constructed: Boolean; tagNumber: Int32; const parser: IAsn1StreamParser); destructor Destroy; override; function GetObjectParser(tag: Int32; isExplicit: Boolean) : IAsn1Convertible; inline; function ToAsn1Object(): IAsn1Object; property IsConstructed: Boolean read GetIsConstructed; property TagNo: Int32 read GetTagNo; end; implementation { TBerTaggedObjectParser } constructor TBerTaggedObjectParser.Create(constructed: Boolean; tagNumber: Int32; const parser: IAsn1StreamParser); begin F_constructed := constructed; F_tagNumber := tagNumber; F_parser := parser; end; destructor TBerTaggedObjectParser.Destroy; begin F_parser := Nil; inherited Destroy; end; function TBerTaggedObjectParser.GetIsConstructed: Boolean; begin result := F_constructed; end; function TBerTaggedObjectParser.GetObjectParser(tag: Int32; isExplicit: Boolean) : IAsn1Convertible; begin if (isExplicit) then begin if (not F_constructed) then begin raise EIOCryptoLibException.CreateRes(@SUnConstructedTag); end; result := F_parser.ReadObject(); Exit; end; result := F_parser.ReadImplicit(F_constructed, tag); end; function TBerTaggedObjectParser.GetTagNo: Int32; begin result := F_tagNumber; end; function TBerTaggedObjectParser.ToAsn1Object: IAsn1Object; begin try result := F_parser.ReadTaggedObject(F_constructed, F_tagNumber); except on e: EIOCryptoLibException do begin raise EAsn1ParsingCryptoLibException.CreateResFmt(@SParsingError, [e.Message]); end; end; end; end.
const arraySize = 10; const minRandomNumber = -9; const maxRandomNumber = 9; type integerArrayType = array [1..arraySize] of integer; procedure viewArray(arr: integerArrayType; size: integer); begin write('['); for var index := 1 to size - 1 do begin write(arr[index] + ', '); end; writeln(arr[size] + ']'); end; function generateRandomArray(): integerArrayType; begin var generatedArray: integerArrayType; for var index := 1 to arraySize do begin generatedArray[index] := Random(minRandomNumber, maxRandomNumber); end; Result := generatedArray; end; var filteredArraySize: integer := 0; function getIncompatibleWithNatural(integerArray: integerArrayType; naturalNumber: integer): integerArrayType; begin var filteredArray: integerArrayType; var currentIndex: integer := 0; for var index := 1 to arraySize do begin if integerArray[index] mod naturalNumber <> 0 then begin currentIndex := currentIndex + 1; filteredArray[currentIndex] := integerArray[index]; end; end; filteredArraySize := currentIndex; Result := filteredArray; end; function sortArray(integerArray: integerArrayType; size: integer): integerArrayType; begin var sortedArray: integerArrayType; for var index := 1 to size do begin sortedArray[index] := integerArray[index]; end; for var i := 1 to size - 1 do begin for var j := 1 to size - i do begin if sortedArray[j] < sortedArray[j + 1] then begin var nextElement: integer := sortedArray[j + 1]; var currentElement: integer := sortedArray[j]; sortedArray[j + 1] := currentElement; sortedArray[j] := nextElement; end; end; end; Result := sortedArray; end; begin var naturalNumber: integer; write('Enter natural number: '); readln(naturalNumber); var generatedArray: integerArrayType := generateRandomArray(); var filteredArray: integerArrayType := getIncompatibleWithNatural(generatedArray, naturalNumber); var sortedArray: integerArrayType := sortArray(filteredArray, filteredArraySize); write('Generated array: '); viewArray(generatedArray, arraySize); write('Filtered array: '); viewArray(filteredArray, filteredArraySize); write('Sorted array: '); viewArray(sortedArray, filteredArraySize); end.
unit OrderUnit; interface uses REST.Json.Types, Classes, SysUtils, System.Generics.Collections, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit, JSONDictionaryIntermediateObjectUnit; type /// <summary> /// Json schema for an Order class, which is used for keeping client order information at certain address. /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Order.dtd /// </remarks> TOrder = class(TGenericParameters) private [JSONName('order_id')] [Nullable] FId: NullableInteger; [JSONName('address_1')] FAddress1: String; [JSONName('address_2')] [Nullable] FAddress2: NullableString; [JSONName('address_alias')] FAddressAlias: String; [JSONName('cached_lat')] FCachedLatitude: double; [JSONName('cached_lng')] FCachedLongitude: double; [JSONName('curbside_lat')] [Nullable] FCurbsideLatitude: NullableDouble; [JSONName('curbside_lng')] [Nullable] FCurbsideLongitude: NullableDouble; [JSONName('address_city')] [Nullable] FAddressCity: NullableString; [JSONName('address_state_id')] [Nullable] FAddressStateId: NullableString; [JSONName('address_country_id')] [Nullable] FAddressCountryId: NullableString; [JSONName('address_zip')] [Nullable] FAddressZIP: NullableString; [JSONName('order_status_id')] [Nullable] FOrderStatusId: NullableString; [JSONName('member_id')] [Nullable] FMemberId: NullableString; [JSONName('EXT_FIELD_first_name')] [Nullable] FFirstName: NullableString; [JSONName('EXT_FIELD_last_name')] [Nullable] FLastName: NullableString; [JSONName('EXT_FIELD_email')] [Nullable] FEmail: NullableString; [JSONName('EXT_FIELD_phone')] [Nullable] FPhone: NullableString; [JSONName('EXT_FIELD_custom_data')] [NullableObject(TDictionaryStringIntermediateObject)] FCustomData: NullableObject; [JSONName('day_scheduled_for_YYMMDD')] [Nullable] FScheduleDate: NullableString; [JSONName('created_timestamp')] [Nullable] FCreatedTimestamp: NullableInteger; [JSONMarshalled(False)] FFormatSettings: TFormatSettings; function GetScheduleDate: TDate; procedure SetScheduleDate(const Value: TDate); public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; override; constructor Create(Address: String; AddressAlias: String; Latitude, Longitude: double); reintroduce; overload; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Order Id /// </summary> property Id: NullableInteger read FId write FId; /// <summary> /// Address 1 field /// </summary> property Address1: String read FAddress1 write FAddress1; /// <summary> /// Address 2 field /// </summary> property Address2: NullableString read FAddress2 write FAddress2; /// <summary> /// Address Alias. /// </summary> property AddressAlias: String read FAddressAlias write FAddressAlias; /// <summary> /// Geo latitude /// </summary> property CachedLatitude: double read FCachedLatitude write FCachedLatitude; /// <summary> /// Geo longitude /// </summary> property CachedLongitude: double read FCachedLongitude write FCachedLongitude; /// <summary> /// Generate optimal routes and driving directions to this curbside latitude /// </summary> property CurbsideLatitude: NullableDouble read FCurbsideLatitude write FCurbsideLatitude; /// <summary> /// Generate optimal routes and driving directions to the curbside langitude /// </summary> property CurbsideLongitude: NullableDouble read FCurbsideLongitude write FCurbsideLongitude; /// <summary> /// Address City /// </summary> property AddressCity: NullableString read FAddressCity write FAddressCity; /// <summary> /// Address state ID /// </summary> property AddressStateId: NullableString read FAddressStateId write FAddressStateId; /// <summary> /// Address country ID /// </summary> property AddressCountryId: NullableString read FAddressCountryId write FAddressCountryId; /// <summary> /// Address ZIP /// </summary> property AddressZIP: NullableString read FAddressZIP write FAddressZIP; /// <summary> /// Order status ID /// </summary> property OrderStatusId: NullableString read FOrderStatusId write FOrderStatusId; /// <summary> /// The id of the member inside the route4me system /// </summary> property MemberId: NullableString read FMemberId write FMemberId; /// <summary> /// First name /// </summary> property FirstName: NullableString read FFirstName write FFirstName; /// <summary> /// Last name /// </summary> property LastName: NullableString read FLastName write FLastName; /// <summary> /// Email /// </summary> property Email: NullableString read FEmail write FEmail; /// <summary> /// Phone number /// </summary> property Phone: NullableString read FPhone write FPhone; /// <summary> /// ScheduleDate /// </summary> property ScheduleDate: TDate read GetScheduleDate write SetScheduleDate; /// <summary> /// Timestamp of an order creation. /// </summary> property CreatedTimestamp: NullableInteger read FCreatedTimestamp write FCreatedTimestamp; /// <summary> /// Custom data /// </summary> property CustomData: NullableObject read FCustomData; procedure AddCustomField(Key: String; Value: String); end; TOrderArray = TArray<TOrder>; TOrderList = TObjectList<TOrder>; implementation { TOrder } constructor TOrder.Create; begin Inherited; FFormatSettings := TFormatSettings.Create; FFormatSettings.ShortDateFormat := 'yyyy-mm-dd'; FFormatSettings.DateSeparator := '-'; FAddress1 := EmptyStr; FAddressAlias := EmptyStr; FCachedLatitude := Double.NaN; FCachedLongitude := Double.NaN; FId := NullableInteger.Null; FAddress2 := NullableString.Null; FCurbsideLatitude := NullableDouble.Null; FCurbsideLongitude := NullableDouble.Null; FAddressCity := NullableString.Null; FAddressStateId := NullableString.Null; FAddressCountryId := NullableString.Null; FAddressZIP := NullableString.Null; FOrderStatusId := NullableString.Null; FMemberId := NullableString.Null; FFirstName := NullableString.Null; FLastName := NullableString.Null; FEmail := NullableString.Null; FPhone := NullableString.Null; FScheduleDate := NullableString.Null; FCreatedTimestamp := NullableInteger.Null; FCustomData := NullableObject.Null; end; procedure TOrder.AddCustomField(Key, Value: String); var Dic: TDictionaryStringIntermediateObject; begin if (FCustomData.IsNull) then FCustomData := TDictionaryStringIntermediateObject.Create(); Dic := FCustomData.Value as TDictionaryStringIntermediateObject; Dic.Add(Key, Value); end; constructor TOrder.Create(Address, AddressAlias: String; Latitude, Longitude: double); begin Create; FAddress1 := Address; FAddressAlias := AddressAlias; FCachedLatitude := Latitude; FCachedLongitude := Longitude; end; destructor TOrder.Destroy; begin FCustomData.Free; inherited; end; function TOrder.Equals(Obj: TObject): Boolean; var Other: TOrder; begin Result := False; if not (Obj is TOrder) then Exit; Other := TOrder(Obj); Result := (FId = Other.FId) and (FAddress1 = Other.FAddress1) and (FAddress2 = Other.FAddress2) and (FAddressAlias = Other.FAddressAlias) and (FMemberId = Other.FMemberId) and (FCachedLatitude = Other.FCachedLatitude) and (FCachedLongitude = Other.FCachedLongitude) and (FCurbsideLatitude = Other.FCurbsideLatitude) and (FCurbsideLongitude = Other.FCurbsideLongitude) and (FAddressCity = Other.FAddressCity) and (FAddressStateId = Other.FAddressStateId) and (FAddressCountryId = Other.FAddressCountryId) and (FAddressZIP = Other.FAddressZIP) and (FOrderStatusId = Other.FOrderStatusId) and (FMemberId = Other.FMemberId) and (FFirstName = Other.FFirstName) and (FLastName = Other.FLastName) and (FEmail = Other.FEmail) and (FPhone = Other.FPhone) and (FScheduleDate = Other.FScheduleDate) and (FCreatedTimestamp = Other.FCreatedTimestamp) and (FCustomData = Other.FCustomData); end; function TOrder.GetScheduleDate: TDate; begin if FScheduleDate.IsNotNull then Result := StrToDate(FScheduleDate.Value, FFormatSettings) else Result := 0; end; procedure TOrder.SetScheduleDate(const Value: TDate); begin if (Value = 0) then FScheduleDate := NullableString.Null else FScheduleDate := DateToStr(Value, FFormatSettings); end; end.
unit TTSTITMFLAGSTABLE; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSTITMFLAGSRecord = record PLenderNum: String[4]; PCifFlag: String[1]; PLoanCif: String[20]; PCollNum: Integer; PTrackCode: String[8]; PSubNum: Integer; POrigSpFlags: String[9]; End; TTTSTITMFLAGSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSTITMFLAGSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSTITMFlags = (TTSTITMFLAGSPrimaryKey); TTTSTITMFLAGSTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCifFlag: TStringField; FDFLoanCif: TStringField; FDFCollNum: TIntegerField; FDFTrackCode: TStringField; FDFSubNum: TIntegerField; FDFOrigSpFlags: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanCif(const Value: String); function GetPLoanCif:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPSubNum(const Value: Integer); function GetPSubNum:Integer; procedure SetPOrigSpFlags(const Value: String); function GetPOrigSpFlags:String; procedure SetEnumIndex(Value: TEITTSTITMFLAGS); function GetEnumIndex: TEITTSTITMFLAGS; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSTITMFLAGSRecord; procedure StoreDataBuffer(ABuffer:TTTSTITMFLAGSRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCifFlag: TStringField read FDFCifFlag; property DFLoanCif: TStringField read FDFLoanCif; property DFCollNum: TIntegerField read FDFCollNum; property DFTrackCode: TStringField read FDFTrackCode; property DFSubNum: TIntegerField read FDFSubNum; property DFOrigSpFlags: TStringField read FDFOrigSpFlags; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanCif: String read GetPLoanCif write SetPLoanCif; property PCollNum: Integer read GetPCollNum write SetPCollNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PSubNum: Integer read GetPSubNum write SetPSubNum; property POrigSpFlags: String read GetPOrigSpFlags write SetPOrigSpFlags; published property Active write SetActive; property EnumIndex: TEITTSTITMFLAGS read GetEnumIndex write SetEnumIndex; end; { TTTSTITMFLAGSTable } procedure Register; implementation procedure TTTSTITMFLAGSTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanCif := CreateField( 'LoanCif' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFSubNum := CreateField( 'SubNum' ) as TIntegerField; FDFOrigSpFlags := CreateField( 'OrigSpFlags' ) as TStringField; end; { TTTSTITMFLAGSTable.CreateFields } procedure TTTSTITMFLAGSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSTITMFLAGSTable.SetActive } procedure TTTSTITMFLAGSTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSTITMFLAGSTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSTITMFLAGSTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSTITMFLAGSTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSTITMFLAGSTable.SetPLoanCif(const Value: String); begin DFLoanCif.Value := Value; end; function TTTSTITMFLAGSTable.GetPLoanCif:String; begin result := DFLoanCif.Value; end; procedure TTTSTITMFLAGSTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSTITMFLAGSTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSTITMFLAGSTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSTITMFLAGSTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSTITMFLAGSTable.SetPSubNum(const Value: Integer); begin DFSubNum.Value := Value; end; function TTTSTITMFLAGSTable.GetPSubNum:Integer; begin result := DFSubNum.Value; end; procedure TTTSTITMFLAGSTable.SetPOrigSpFlags(const Value: String); begin DFOrigSpFlags.Value := Value; end; function TTTSTITMFLAGSTable.GetPOrigSpFlags:String; begin result := DFOrigSpFlags.Value; end; procedure TTTSTITMFLAGSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CifFlag, String, 1, N'); Add('LoanCif, String, 20, N'); Add('CollNum, Integer, 0, N'); Add('TrackCode, String, 8, N'); Add('SubNum, Integer, 0, N'); Add('OrigSpFlags, String, 9, N'); end; end; procedure TTTSTITMFLAGSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CifFlag;LoanCif;CollNum;TrackCode;SubNum, Y, Y, N, N'); end; end; procedure TTTSTITMFLAGSTable.SetEnumIndex(Value: TEITTSTITMFLAGS); begin case Value of TTSTITMFLAGSPrimaryKey : IndexName := ''; end; end; function TTTSTITMFLAGSTable.GetDataBuffer:TTTSTITMFLAGSRecord; var buf: TTTSTITMFLAGSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCifFlag := DFCifFlag.Value; buf.PLoanCif := DFLoanCif.Value; buf.PCollNum := DFCollNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PSubNum := DFSubNum.Value; buf.POrigSpFlags := DFOrigSpFlags.Value; result := buf; end; procedure TTTSTITMFLAGSTable.StoreDataBuffer(ABuffer:TTTSTITMFLAGSRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanCif.Value := ABuffer.PLoanCif; DFCollNum.Value := ABuffer.PCollNum; DFTrackCode.Value := ABuffer.PTrackCode; DFSubNum.Value := ABuffer.PSubNum; DFOrigSpFlags.Value := ABuffer.POrigSpFlags; end; function TTTSTITMFLAGSTable.GetEnumIndex: TEITTSTITMFLAGS; var iname : string; begin result := TTSTITMFLAGSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSTITMFLAGSPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TTTSTITMFLAGSTable, TTTSTITMFLAGSBuffer ] ); end; { Register } function TTTSTITMFLAGSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..7] of string = ('LENDERNUM','CIFFLAG','LOANCIF','COLLNUM','TRACKCODE','SUBNUM' ,'ORIGSPFLAGS'); 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 TTTSTITMFLAGSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftInteger; 7 : result := ftString; end; end; function TTTSTITMFLAGSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCifFlag; 3 : result := @Data.PLoanCif; 4 : result := @Data.PCollNum; 5 : result := @Data.PTrackCode; 6 : result := @Data.PSubNum; 7 : result := @Data.POrigSpFlags; end; end; end.
unit UPickerDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBitmapSelector, FMX.TMSCustomSelector, FMX.TMSColorSelector, FMX.TMSBitmapPicker, FMX.TMSBaseControl, FMX.TMSCustomPicker, FMX.TMSColorPicker, FMX.Objects, System.UIConsts, FMX.TMSFontSizePicker, FMX.TMSFontNamePicker, FMX.Layouts, FMX.Memo; type TForm5 = class(TForm) GroupBox1: TGroupBox; TMSFMXBitmapPicker1: TTMSFMXBitmapPicker; Label1: TLabel; Panel1: TPanel; Image1: TImage; Label2: TLabel; GroupBox2: TGroupBox; TMSFMXColorPicker1: TTMSFMXColorPicker; Label3: TLabel; Panel2: TPanel; Rectangle1: TRectangle; Label4: TLabel; GroupBox3: TGroupBox; TMSFMXBitmapSelector1: TTMSFMXBitmapSelector; lblSample: TLabel; GroupBox4: TGroupBox; TMSFMXColorSelector1: TTMSFMXColorSelector; Label5: TLabel; Panel3: TPanel; Rectangle2: TRectangle; GroupBox5: TGroupBox; TMSFMXBitmapSelector2: TTMSFMXBitmapSelector; GroupBox6: TGroupBox; Memo1: TMemo; TMSFMXFontNamePicker1: TTMSFMXFontNamePicker; TMSFMXFontSizePicker1: TTMSFMXFontSizePicker; procedure TMSFMXBitmapPicker1ItemSelected(Sender: TObject; AItemIndex: Integer); procedure TMSFMXColorPicker1ItemSelected(Sender: TObject; AItemIndex: Integer); procedure TMSFMXBitmapSelector1ItemSelected(Sender: TObject; AItemIndex: Integer); procedure TMSFMXColorSelector1ItemClick(Sender: TObject; AItemIndex: Integer); procedure TMSFMXColorSelector1ItemSelected(Sender: TObject; AItemIndex: Integer); procedure TMSFMXBitmapSelector2ItemAfterDrawContent(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItemIndex: Integer); procedure FormCreate(Sender: TObject); procedure TMSFMXFontNamePicker1FontNameSelected(Sender: TObject; AFontName: string); procedure TMSFMXFontSizePicker1FontSizeSelected(Sender: TObject; AFontSize: Single); private { Private declarations } public { Public declarations } end; var Form5: TForm5; implementation {$R *.fmx} procedure TForm5.FormCreate(Sender: TObject); begin TMSFMXFontSizePicker1.SelectedFontSize := Memo1.Font.Size; TMSFMXFontNamePicker1.SelectedFontName := Memo1.Font.Family; end; procedure TForm5.TMSFMXBitmapPicker1ItemSelected(Sender: TObject; AItemIndex: Integer); begin image1.Bitmap.Assign(TMSFMXBitmapPicker1.SelectedBitmap); end; procedure TForm5.TMSFMXBitmapSelector1ItemSelected(Sender: TObject; AItemIndex: Integer); begin case AItemIndex of 0: lblSample.TextAlign := TTextAlign.taLeading; 1: lblSample.TextAlign := TTextAlign.taCenter; 2: lblSample.TextAlign := TTextAlign.taTrailing; end; end; procedure TForm5.TMSFMXBitmapSelector2ItemAfterDrawContent(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItemIndex: Integer); var pt: TPathData; begin case TMSFMXBitmapSelector2.Items[AItemIndex].State of isHover: InflateRect(ARect,-4, -4); isDown,isSelected: begin InflateRect(ARect,-4, -4); ACanvas.Stroke.Thickness := 2; ACanvas.Stroke.Color := claBlack; end; isNormal: InflateRect(ARect,-8, -8); end; ARect := RectF(Int(ARect.Left)+ 0.5, Int(ARect.Top) + 0.5, Int(ARect.Right) +0.5, Int(ARect.Bottom) + 0.5); case AItemIndex of 0: begin ACanvas.Fill.Color := claBlue; ACanvas.FillEllipse(ARect,1); ACanvas.DrawEllipse(ARect,1); end; 1: begin ACanvas.Fill.Color := claGreen; ACanvas.FillRect(ARect,0,0,AllCorners,1); ACanvas.DrawRect(ARect,0,0,AllCorners,1); end; 2: begin pt := TPathData.Create; pt.MoveTo(PointF(ARect.Left + ARect.Width / 2, ARect.Top)); pt.LineTo(PointF(ARect.Left + ARect.Width , ARect.Bottom)); pt.LineTo(PointF(ARect.Left , ARect.Bottom)); pt.ClosePath; //pt.LineTo(Point(ARect.Left + ARect.Width div 2, ARect.Top)); ACanvas.Fill.Color := claRed; ACanvas.FillPath(pt,1); ACanvas.DrawPath(pt,1); pt.Free; end; end; end; procedure TForm5.TMSFMXColorPicker1ItemSelected(Sender: TObject; AItemIndex: Integer); begin Rectangle1.Fill.Color := TMSFMXColorPicker1.SelectedColor; end; procedure TForm5.TMSFMXColorSelector1ItemClick(Sender: TObject; AItemIndex: Integer); begin if AItemIndex = TMSFMXColorSelector1.Items.Count - 1 then begin ShowMessage('Pick a custom color here'); TMSFMXColorSelector1.Items[AItemIndex].Color := claRed; Rectangle2.Fill.Color := claRed; end; end; procedure TForm5.TMSFMXColorSelector1ItemSelected(Sender: TObject; AItemIndex: Integer); begin Rectangle2.Fill.Color := TMSFMXColorSelector1.SelectedColor; end; procedure TForm5.TMSFMXFontNamePicker1FontNameSelected(Sender: TObject; AFontName: string); begin Memo1.Font.Family := AFontName; end; procedure TForm5.TMSFMXFontSizePicker1FontSizeSelected(Sender: TObject; AFontSize: Single); begin Memo1.Font.Size := AFontSize; end; end.
{ 一个简单的BitSet,类似于C++ 使用动态实现,请及时Destroy 支持操作:单位设置,and、or、xor、not FPC5719 2018.11 } {$MODE OBJFPC} unit bitset; interface type TBitSet=class private data:^byte; len:longint; public constructor Create; constructor Create(l:longint); destructor Destroy;override; procedure SetBit(pos:longint;val:boolean); function GetBit(pos:longint):boolean; property Value[x:longint]:boolean read GetBit write SetBit; procedure Print; end; operator and(a,b:TBitSet) res:TBitSet; operator or(a,b:TBitSet) res:TBitSet; operator xor(a,b:TBitSet) res:TBitSet; operator not(a:TBitSet) res:TBitSet; implementation uses math; constructor TBitSet.Create; begin len:=0; data:=NIL; end; constructor TBitSet.Create(l:longint); begin len:=l; data:=GetMem(len); fillchar(data^,len,0); end; destructor TBitSet.Destroy; begin FreeMem(data); end; procedure TBitSet.SetBit(pos:longint;val:boolean); var t1,t2:longint; begin t1:=pos div 8; t2:=pos mod 8; if (t1>len)or(t1=len)and(t2>0) then exit; if val then data[t1]:=data[t1] or (1 shl t2) else data[t1]:=data[t1] and not (1 shl t2); end; function TBitSet.GetBit(pos:longint):boolean; var t1,t2:longint; begin t1:=pos div 8; t2:=pos mod 8; if (t1>len)or(t1=len)and(t2>0) then exit(false); exit((data[t1] and (1 shl t2))>0); end; procedure TBitset.Print; var i:longint; begin for i:=0 to len*8-1 do write(Value[i]:6); writeln; end; operator and(a,b:TBitSet) res:TBitSet; var i,mx:longint; begin mx:=max(a.len,b.len); res:=TBitSet.Create(mx); for i:=0 to mx*8-1 do res.Value[i]:=a.Value[i] and b.Value[i]; end; operator or(a,b:TBitSet) res:TBitSet; var i,mx:longint; begin mx:=max(a.len,b.len); res:=TBitSet.Create(mx); for i:=0 to mx*8-1 do res.Value[i]:=a.Value[i] or b.Value[i]; end; operator xor(a,b:TBitSet) res:TBitSet; var i,mx:longint; begin mx:=max(a.len,b.len); res:=TBitSet.Create(mx); for i:=0 to mx*8-1 do res.Value[i]:=a.Value[i] xor b.Value[i]; end; operator not(a:TBitSet) res:TBitSet; var i:longint; begin res:=TBitSet.Create(a.len); for i:=0 to a.len*8-1 do res.Value[i]:=not a.Value[i]; end; end.
unit ce_tools; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, process, menus, ce_common, ce_writableComponent, ce_interfaces, ce_observer, ce_inspectors; type TCEToolItem = class(TCollectionItem) private fProcess: TCheckedAsyncProcess; fExecutable: TCEFilename; fWorkingDir: TCEPathname; fShowWin: TShowWindowOptions; fOpts: TProcessOptions; fParameters: TStringList; fToolAlias: string; fQueryParams: boolean; fClearMessages: boolean; fChainBefore: TStringList; fChainAfter: TStringList; fShortcut: TShortcut; fMsgs: ICEMessagesDisplay; procedure setParameters(aValue: TStringList); procedure setChainBefore(aValue: TStringList); procedure setChainAfter(aValue: TStringList); procedure processOutput(sender: TObject); procedure execute; published property toolAlias: string read fToolAlias write fToolAlias; property options: TProcessOptions read fOpts write fOpts; property executable: TCEFilename read fExecutable write fExecutable; property workingDirectory: TCEPathname read fWorkingDir write fWorkingDir; property parameters: TStringList read fParameters write setParameters; property showWindows: TShowWindowOptions read fShowWin write fShowWin; property queryParameters: boolean read fQueryParams write fQueryParams; property clearMessages: boolean read fClearMessages write fClearMessages; property chainBefore: TStringList read fChainBefore write setchainBefore; property chainAfter: TStringList read fChainAfter write setChainAfter; property shortcut: TShortcut read fShortcut write fShortcut; public constructor create(ACollection: TCollection); override; destructor destroy; override; procedure assign(Source: TPersistent); override; end; TCETools = class(TWritableLfmTextComponent, ICEMainMenuProvider, ICEEditableShortcut) private fTools: TCollection; fShctCount: Integer; function getTool(index: Integer): TCEToolItem; procedure setTools(const aValue: TCollection); // procedure menuDeclare(item: TMenuItem); procedure menuUpdate(item: TMenuItem); procedure executeToolFromMenu(sender: TObject); // function scedWantFirst: boolean; function scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; procedure scedSendItem(const category, identifier: string; aShortcut: TShortcut); published property tools: TCollection read fTools write setTools; public constructor create(aOwner: TComponent); override; destructor destroy; override; // function addTool: TCEToolItem; procedure executeTool(aTool: TCEToolItem); overload; procedure executeTool(aToolIndex: Integer); overload; property tool[index: integer]: TCEToolItem read getTool; default; end; //TODO-crefactor: either set the tools as a service of merge the tools collection& tool editor in a single unit. var CustomTools: TCETools; implementation uses ce_symstring, dialogs; const toolsFname = 'tools.txt'; {$REGION TCEToolItem -----------------------------------------------------------} constructor TCEToolItem.create(ACollection: TCollection); begin inherited; fToolAlias := format('<tool %d>', [ID]); fParameters := TStringList.create; fChainBefore := TStringList.Create; fChainAfter := TStringList.Create; end; destructor TCEToolItem.destroy; begin fParameters.Free; fChainAfter.Free; fChainBefore.Free; killProcess(fProcess); inherited; end; procedure TCEToolItem.assign(Source: TPersistent); var tool: TCEToolItem; begin if Source is TCEToolItem then begin tool := TCEToolItem(Source); // toolAlias := tool.toolAlias; chainAfter.Assign(tool.chainAfter); chainBefore.Assign(tool.chainBefore); queryParameters := tool.queryParameters; clearMessages := tool.clearMessages; fOpts := tool.fOpts; parameters.Assign(tool.parameters); executable := tool.executable; workingDirectory := tool.workingDirectory; end else inherited; end; procedure TCEToolItem.setParameters(aValue: TStringList); begin fParameters.Assign(aValue); end; procedure TCEToolItem.setChainBefore(aValue: TStringList); var i: Integer; begin fChainBefore.Assign(aValue); i := fChainBefore.IndexOf(fToolAlias); if i <> -1 then fChainBefore.Delete(i); end; procedure TCEToolItem.setChainAfter(aValue: TStringList); var i: Integer; begin fChainAfter.Assign(aValue); i := fChainAfter.IndexOf(fToolAlias); if i <> -1 then fChainAfter.Delete(i); end; procedure TCEToolItem.execute; var i: Integer; prms: string; begin killProcess(fProcess); // if fClearMessages then getMessageDisplay(fMsgs).clearByContext(amcMisc); // fProcess := TCheckedAsyncProcess.Create(nil); fProcess.OnReadData:= @processOutput; fProcess.OnTerminate:= @processOutput; fProcess.Options := fOpts; fProcess.Executable := symbolExpander.get(fExecutable); fProcess.ShowWindow := fShowWin; fProcess.CurrentDirectory := symbolExpander.get(fWorkingDir); if fQueryParams then begin prms := ''; if InputQuery('Parameters', '', prms) then if prms <> '' then fProcess.Parameters.DelimitedText := symbolExpander.get(prms); end; for i:= 0 to fParameters.Count-1 do fProcess.Parameters.AddText(symbolExpander.get(fParameters.Strings[i])); fProcess.Execute; end; procedure TCEToolItem.processOutput(sender: TObject); var lst: TStringList; str: string; begin getMessageDisplay(fMsgs); lst := TStringList.Create; try processOutputToStrings(fProcess, lst); for str in lst do fMsgs.message(str, nil, amcMisc, amkAuto); finally lst.Free; end; end; {$ENDREGION --------------------------------------------------------------------} {$REGION Standard Comp/Obj -----------------------------------------------------} constructor TCETools.create(aOwner: TComponent); var fname: string; begin inherited; fTools := TCollection.Create(TCEToolItem); fname := getCoeditDocPath + toolsFname; if fileExists(fname) then loadFromFile(fname); // EntitiesConnector.addObserver(self); end; destructor TCETools.destroy; begin EntitiesConnector.removeObserver(self); // forceDirectory(getCoeditDocPath); saveToFile(getCoeditDocPath + toolsFname); fTools.Free; inherited; end; {$ENDREGION} {$REGION ICEMainMenuProvider ---------------------------------------------------} procedure TCETools.executeToolFromMenu(sender: TObject); begin executeTool(TCEToolItem(TMenuItem(sender).tag)); end; procedure TCETools.menuDeclare(item: TMenuItem); var i: Integer; itm: TMenuItem; colitm: TCEToolItem; begin if tools.Count = 0 then exit; // item.Caption := 'Custom tools'; item.Clear; for i := 0 to tools.Count-1 do begin colitm := tool[i]; // itm := TMenuItem.Create(item); itm.ShortCut:= colitm.shortcut; itm.Caption := colitm.toolAlias; itm.tag := ptrInt(colitm); itm.onClick := @executeToolFromMenu; item.add(itm); end; end; procedure TCETools.menuUpdate(item: TMenuItem); var i: Integer; colitm: TCEToolItem; mnuitm: TMenuItem; begin if item = nil then exit; if item.Count <> tools.Count then menuDeclare(item) else for i:= 0 to tools.Count-1 do begin colitm := tool[i]; mnuitm := item.Items[i]; // if mnuitm.Tag <> ptrInt(colitm) then mnuitm.Tag := ptrInt(colitm); if mnuitm.Caption <> colitm.toolAlias then mnuitm.Caption := colitm.toolAlias; if mnuitm.shortcut <> colitm.shortcut then mnuitm.shortcut := colitm.shortcut; end; end; {$ENDREGION} {$REGION ICEEditableShortcut ---------------------------------------------------} function TCETools.scedWantFirst: boolean; begin result := fTools.Count > 0; fShctCount := 0; end; function TCETools.scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; begin category := 'Tools'; identifier:= tool[fShctCount].toolAlias; aShortcut := tool[fShctCount].shortcut; // fShctCount += 1; result := fShctCount < fTools.Count; end; procedure TCETools.scedSendItem(const category, identifier: string; aShortcut: TShortcut); var i: Integer; begin if category <> 'Tools' then exit; // for i := 0 to tools.Count-1 do if tool[i].toolAlias = identifier then begin tool[i].shortcut := aShortcut; break; end; end; {$ENDREGION} {$REGION Tools things ----------------------------------------------------------} procedure TCETools.setTools(const aValue: TCollection); begin fTools.Assign(aValue); end; function TCETools.getTool(index: Integer): TCEToolItem; begin result := TCEToolItem(fTools.Items[index]); end; function TCETools.addTool: TCEToolItem; begin result := TCEToolItem(fTools.Add); end; procedure TCETools.executeTool(aTool: TCEToolItem); var nme: string; chained: TCollectionItem; begin if aTool = nil then exit; if not exeInSysPath(aTool.executable) then if (aTool.chainAfter.Count = 0) and (aTool.chainBefore.Count = 0) then exit; for nme in aTool.chainBefore do for chained in fTools do if TCEToolItem(chained).toolAlias = nme then if TCEToolItem(chained).toolAlias <> aTool.toolAlias then TCEToolItem(chained).execute; if exeInSysPath(aTool.executable) then aTool.execute; for nme in aTool.chainAfter do for chained in fTools do if TCEToolItem(chained).toolAlias = nme then if TCEToolItem(chained).toolAlias <> aTool.toolAlias then TCEToolItem(chained).execute; end; procedure TCETools.executeTool(aToolIndex: Integer); begin if aToolIndex < 0 then exit; if aToolIndex > fTools.Count-1 then exit; // executeTool(tool[aToolIndex]); end; {$ENDREGION} initialization RegisterClasses([TCEToolItem, TCETools]); CustomTools := TCETools.create(nil); finalization CustomTools.Free; end.
unit VTEditors; {$mode delphi} {$H+} // Utility unit for the advanced Virtual Treeview demo application which contains the implementation of edit link // interfaces used in other samples of the demo. interface uses LCLIntf,LCLType, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VirtualTrees, ExtDlgs, Buttons, ExtCtrls, ComCtrls, MaskEdit, LResources, EditBtn; type // Describes the type of value a property tree node stores in its data property. TValueType = ( vtNone, vtString, vtPickString, vtNumber, vtPickNumber, vtMemo, vtDate ); type // Node data record for the the document properties treeview. TPropertyData = record ValueType: TValueType; Value : String; // This value can actually be a date or a number too. Changed : Boolean; end; PPropertyData = ^TPropertyData; // Our own edit link to implement several different node editors. { TPropertyEditLink } TPropertyEditLink = class(TInterfacedObject, IVTEditLink) private FEdit: TWinControl; // One of the property editor classes. FTree: TVirtualStringTree; // A back reference to the tree calling. FNode: PVirtualNode; // The node being edited. FColumn: Integer; // The column of the node being edited. FOldEditProc: TWndMethod; // Used to capture some important messages // regardless of the type of edit control we use. FListItems : TStringList; // One of the property editor classes. protected procedure EditWindowProc(var Message: TMessage); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public constructor Create; destructor Destroy; override; function BeginEdit: Boolean; stdcall; function CancelEdit: Boolean; stdcall; function EndEdit: Boolean; stdcall; function GetBounds: TRect; stdcall; function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall; procedure ProcessMessage(var Message: TMessage); stdcall; procedure SetBounds(R: TRect); stdcall; end; type TPropertyTextKind = ( ptkText, ptkHint ); TGridData = record ValueType: array[0..3] of TValueType; // one for each column Value : array[0..3] of Variant; Changed : Boolean; end; PGridData = ^TGridData; // Our own edit link to implement several different node editors. TGridEditLink = class(TPropertyEditLink, IVTEditLink) public function EndEdit: Boolean; stdcall; function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall; end; function ShowForm( afc : TFormClass; iLeft : integer = -1; iTop : integer = -1 ) : TForm; function FindAppForm ( afc : TFormClass ) : TForm; procedure ConvertToHighColor(ImageList: TImageList); implementation //uses // CommCtrl; (* uses PropertiesDemo, GridDemo; *) {--------------------------------------------------------------- utility functions ---------------------------------------------------------------} function ShowForm( afc : TFormClass; iLeft : integer = -1; iTop : integer = -1 ) : TForm; begin Result := FindAppForm( afc ); if Result = nil then begin Result := afc.Create(Application); if (iLeft <> -1) then Result.left := iLeft; if (iTop <> -1) then Result.top := iTop ; end; Result.Show; end; function FindAppForm ( afc : TFormClass ) : TForm; var i : integer; begin Result := nil; for i := Screen.FormCount-1 downto 0 do begin if (Screen.Forms[i] is afc) then begin Result := Screen.Forms[i]; break; end; end; end; procedure ConvertToHighColor(ImageList: TImageList); // To show smooth images we have to convert the image list from 16 colors to high color. var IL: TImageList; begin //todo: properly implement // Have to create a temporary copy of the given list, because the list is cleared on handle creation. { IL := TImageList.Create(nil); IL.Assign(ImageList); //with ImageList do // Handle := ImageList_Create(Width, Height, ILC_COLOR16 or ILC_MASK, Count, AllocBy); ImageList.Assign(IL); IL.Free; } end; (*------------------------------------------------------------------- TPropertyEditLink -------------------------------------------------------------------*) // This implementation is used in VST3 to make a connection beween the tree // and the actual edit window which might be a simple edit, a combobox or a memo etc. constructor TPropertyEditLink.Create; begin inherited; FListItems := TStringList.Create; // One of the property editor classes. end; destructor TPropertyEditLink.Destroy; begin FEdit.Parent := nil; FEdit.Free; FListItems.Free; inherited; end; function TPropertyEditLink.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; var Data: PPropertyData; begin Result := True; FTree := Tree as TVirtualStringTree; FNode := Node; FColumn := Column; // determine what edit type actually is needed FEdit.Free; FEdit := nil; Data := FTree.GetNodeData(Node); case Data.ValueType of vtString: begin FEdit := TEdit.Create(nil); with FEdit as TEdit do begin Visible := False; Parent := Tree; Text := Data.Value; BorderStyle := bsNone; OnKeyDown := EditKeyDown; end; end; vtPickString: begin FEdit := TComboBox.Create(nil); with FEdit as TComboBox do begin //BorderStyle := bsNone; Visible := False; Parent := Tree; Text := Data.Value; Items.Add(Text); Items.Add('Standard'); Items.Add('Additional'); Items.Add('Win32'); OnKeyDown := EditKeyDown; end; end; vtNumber: begin FEdit := TMaskEdit.Create(nil); with FEdit as TMaskEdit do begin BorderStyle := bsNone; Visible := False; Parent := Tree; EditMask := '9999'; Text := Data.Value; OnKeyDown := EditKeyDown; end; end; vtPickNumber: begin FEdit := TComboBox.Create(nil); with FEdit as TComboBox do begin //BorderStyle := bsNone; Visible := False; Parent := Tree; Text := Data.Value; OnKeyDown := EditKeyDown; end; end; vtMemo: begin FEdit := TComboBox.Create(nil); // In reality this should be a drop down memo but this requires a special control. with FEdit as TComboBox do begin //BorderStyle := bsNone; Visible := False; Parent := Tree; Text := Data.Value; Items.Add(Data.Value); OnKeyDown := EditKeyDown; end; end; vtDate: begin FEdit := TDateEdit.Create(nil); with FEdit as TDateEdit do begin //BorderStyle := bsNone; Visible := False; Parent := Tree; { CalColors.MonthBackColor := clWindow; CalColors.TextColor := clBlack; CalColors.TitleBackColor := clBtnShadow; CalColors.TitleTextColor := clBlack; CalColors.TrailingTextColor := clBtnFace; } Date := StrToDate(Data.Value); OnKeyDown := EditKeyDown; end; end; else Result := False; end; end; procedure TPropertyEditLink.EditWindowProc(var Message: TMessage); // Here we can capture messages for keeping track of focus changes. begin case Message.Msg of WM_KILLFOCUS: if FEdit is TDateEdit then begin //todo { // When the user clicks on a dropped down calender we also get // the kill focus message. if not TDateTimePicker(FEdit).DroppedDown then} FTree.EndEditNode; end else FTree.EndEditNode; else FOldEditProc(Message); end; end; function TPropertyEditLink.BeginEdit: Boolean; begin Result := True; FEdit.Show; FEdit.SetFocus; // Set a window procedure hook (aka subclassing) to get notified about important messages. FOldEditProc := FEdit.WindowProc; FEdit.WindowProc := EditWindowProc; end; function TPropertyEditLink.CancelEdit: Boolean; begin Result := True; // Restore the edit's window proc. FEdit.WindowProc := FOldEditProc; FEdit.Hide; end; function TPropertyEditLink.EndEdit: Boolean; var Data: PPropertyData; Buffer: array[0..1024] of Char; S: String; P: TPoint; Dummy: Integer; begin // Check if the place the user click on yields another node as the one we // are currently editing. If not then do not stop editing. GetCursorPos(P); P := FTree.ScreenToClient(P); Result := FTree.GetNodeAt(P.X, P.Y, True, Dummy) <> FNode; if Result then begin // restore the edit's window proc FEdit.WindowProc := FOldEditProc; Data := FTree.GetNodeData(FNode); //original { if FEdit is TComboBox then S := TComboBox(FEdit).Text else begin GetWindowText(FEdit.Handle, Buffer, 1024); S := Buffer; end; } //lcl case Data.ValueType of vtString: S:= TEdit(FEdit).Text; vtPickString, vtMemo: S:= TComboBox(FEdit).Text; vtNumber: S:= TMaskEdit(FEdit).Text; vtDate: S:= TDateEdit(FEdit).Text; else S:='BUG - Error getting value'; end; if S <> Data.Value then begin Data.Value := S; Data.Changed := True; FTree.InvalidateNode(FNode); end; FEdit.Hide; end; end; procedure TPropertyEditLink.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var CanAdvance: Boolean; begin case Key of VK_RETURN, VK_UP, VK_DOWN: begin // Consider special cases before finishing edit mode. CanAdvance := Shift = []; if FEdit is TComboBox then CanAdvance := CanAdvance and not TComboBox(FEdit).DroppedDown; //todo //if FEdit is TDateEdit then // CanAdvance := CanAdvance and not TDateEdit(FEdit).DroppedDown; if CanAdvance then begin FTree.EndEditNode; with FTree do begin if Key = VK_UP then FocusedNode := GetPreviousVisible(FocusedNode) else FocusedNode := GetNextVisible(FocusedNode); Selected[FocusedNode] := True; end; Key := 0; end; end; end; end; procedure TPropertyEditLink.ProcessMessage(var Message: TMessage); begin FEdit.WindowProc(Message); end; function TPropertyEditLink.GetBounds: TRect; begin Result := FEdit.BoundsRect; end; procedure TPropertyEditLink.SetBounds(R: TRect); var Dummy: Integer; begin // Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn) // we have to set the edit's width explicitly to the width of the column. FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right); FEdit.BoundsRect := R; end; (*------------------------------------------------------------------- TGridEditLink -------------------------------------------------------------------*) function TGridEditLink.EndEdit: Boolean; var Data: PGridData; Buffer: array[0..1024] of Char; S: String; I: Integer; begin Result := True; // Restore the edit's window proc. FEdit.WindowProc := FOldEditProc; Data := FTree.GetNodeData(FNode); if FEdit is TComboBox then begin S := TComboBox(FEdit).Text; if S <> Data.Value[FColumn - 1] then begin Data.Value[FColumn - 1] := S; Data.Changed := True; end; end else if FEdit is TMaskEdit then begin I := StrToInt(Trim(TMaskEdit(FEdit).EditText)); if I <> Data.Value[FColumn - 1] then begin Data.Value[FColumn - 1] := I; Data.Changed := True; end; end else if FEdit is TCustomEdit then begin S := TCustomEdit(FEdit).Text; if S <> Data.Value[FColumn - 1] then begin Data.Value[FColumn - 1] := S; Data.Changed := True; end; { GetWindowText(FEdit.Handle, Buffer, 1024); S := Buffer; if S <> Data.Value[FColumn - 1] then begin Data.Value[FColumn - 1] := S; Data.Changed := True; end; } end; if Data.Changed then FTree.InvalidateNode(FNode); FEdit.Hide; end; function TGridEditLink.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; var Data: PGridData; //todo: fpc does not accept variant to TTransLateString TempText: String; begin Result := True; FTree := Tree as TVirtualStringTree; FNode := Node; FColumn := Column; // Determine what edit type actually is needed. FEdit.Free; FEdit := nil; Data := FTree.GetNodeData(Node); case Data.ValueType[FColumn - 1] of vtString: begin FEdit := TEdit.Create(nil); with FEdit as TEdit do begin Visible := False; Parent := Tree; TempText:= Data.Value[FColumn - 1]; Text := TempText; OnKeyDown := EditKeyDown; end; end; vtPickString: begin FEdit := TComboBox.Create(nil); with FEdit as TComboBox do begin Visible := False; Parent := Tree; TempText:= Data.Value[FColumn - 1]; Text := TempText; // Here you would usually do a lookup somewhere to get // values for the combobox. We only add some dummy values. case FColumn of 2: begin Items.Add('John'); Items.Add('Mike'); Items.Add('Barney'); Items.Add('Tim'); end; 3: begin Items.Add('Doe'); Items.Add('Lischke'); Items.Add('Miller'); Items.Add('Smith'); end; end; OnKeyDown := EditKeyDown; end; end; vtNumber: begin FEdit := TMaskEdit.Create(nil); with FEdit as TMaskEdit do begin Visible := False; Parent := Tree; EditMask := '9999;0; '; TempText:= Data.Value[FColumn - 1]; Text := TempText; OnKeyDown := EditKeyDown; end; end; vtPickNumber: begin FEdit := TComboBox.Create(nil); with FEdit as TComboBox do begin Visible := False; Parent := Tree; TempText:= Data.Value[FColumn - 1]; Text := TempText; OnKeyDown := EditKeyDown; end; end; vtMemo: begin FEdit := TComboBox.Create(nil); // In reality this should be a drop down memo but this requires // a special control. with FEdit as TComboBox do begin Visible := False; Parent := Tree; TempText:= Data.Value[FColumn - 1]; Text := TempText; Items.Add(Data.Value[FColumn - 1]); OnKeyDown := EditKeyDown; end; end; vtDate: begin FEdit := TDateEdit.Create(nil); with FEdit as TDateEdit do begin Visible := False; Parent := Tree; { CalColors.MonthBackColor := clWindow; CalColors.TextColor := clBlack; CalColors.TitleBackColor := clBtnShadow; CalColors.TitleTextColor := clBlack; CalColors.TrailingTextColor := clBtnFace; } Date := StrToDate(Data.Value[FColumn - 1]); OnKeyDown := EditKeyDown; end; end; else Result := False; end; end; end.
{!DOCTOPIC}{ Type » TPointArray } {!DOCREF} { @method: function TPointArray.Len(): Int32; @desc: Returns the length of the TPA. Same as `Length(TPA)` } function TPointArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TPointArray.IsEmpty(): Boolean; @desc: Returns True if the TPA is empty. Same as `Length(TPA) = 0` } function TPointArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TPointArray.Append(const PT:TPoint); @desc: Add another TP to the TPA } {$IFNDEF SRL6} procedure TPointArray.Append(const PT:TPoint); {$ELSE} procedure TPointArray.Append(const PT:TPoint); override; {$ENDIF} var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := PT; end; {!DOCREF} { @method: procedure TPointArray.Insert(idx:Int32; Value:TPoint); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure TPointArray.Insert(idx:Int32; Value:TPoint); var l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(TPoint)); Self[idx] := value; end; {!DOCREF} { @method: procedure TPointArray.Del(idx:Int32); @desc: Removes the element at the given index `idx` } procedure TPointArray.Del(idx:Int32); var i,l:Int32; begin l := Length(Self); if (l <= idx) or (idx < 0) then Exit(); if (L-1 <> idx) then MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(TPoint)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TPointArray.Remove(Value:TPoint); @desc: Removes the first element from left which is equal to `Value` } procedure TPointArray.Remove(Value:TPoint); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TPointArray.Pop(): TPoint; @desc: Removes and returns the last item in the array } function TPointArray.Pop(): TPoint; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TPointArray.PopLeft(): TPoint; @desc: Removes and returns the first item in the array } function TPointArray.PopLeft(): TPoint; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(TPoint)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TPointArray.Slice(Start,Stop: Int32; Step:Int32=1): TPointArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to c'step' past items. You can give it negative start, and stop, then it will wrap around based on length(..) If `Start >= Stop`, and `Step <= -1` it will result in reversed output. [note]Don't pass positive `Step`, combined with `Start > Stop`, that is undefined[/note] } function TPointArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TPointArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure TPointArray.Extend(Arr:TPointArray); @desc: Extends the TPA with a TPA `Arr` } procedure TPointArray.Extend(Arr:TPointArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(TPoint)); end; {!DOCREF} { @method: function TPointArray.Find(Value:TPoint): Int32; @desc: Searces for the given value and returns the first position from the left. } function TPointArray.Find(Value:TPoint): Int32; begin if Self.Len() = 0 then Exit(-1); Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TPointArray.Find(Sequence:TPointArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TPointArray.Find(Sequence:TPointArray): Int32; overload; begin if Self.Len() = 0 then Exit(-1); Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TPointArray.FindAll(Value:TPoint): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TPointArray.FindAll(Value:TPoint): TIntArray; begin if Self.Len() = 0 then Exit(); Result := exp_FindAll(Self,[Value]); end; {!DOCREF} { @method: function TPointArray.FindAll(Sequence:TPointArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TPointArray.FindAll(Sequence:TPointArray): TIntArray; overload; begin if Self.Len() = 0 then Exit(); Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TPointArray.Contains(Pt:TPoint): Boolean; @desc: Checks if the TPA contains the given TPoint `PT` } function TPointArray.Contains(Pt:TPoint): Boolean; begin Result := Self.Find(PT) <> -1; end; {!DOCREF} { @method: function TPointArray.Count(Pt:TPoint): Boolean; @desc: Checks if the TPA contains the given TPoint `PT` } function TPointArray.Count(Pt:TPoint): Boolean; begin Result := Length(Self.FindAll(PT)); end; {!DOCREF} { @method: function TPointArray.Sorted(Key:TSortKey=sort_Default): TPointArray; @desc: Sorts a copy of the TPA Supported keys: `sort_Default, sort_Magnitude, sort_ByRow, sort_ByColumn, sort_ByX, sort_ByY` } function TPointArray.Sorted(Key:TSortKey=sort_Default): TPointArray; begin Result := Self.Slice(); case Key of sort_Default, sort_Magnitude: se.SortTPA(Result); sort_ByRow: se.SortTPAByRow(Result); sort_ByColumn: se.SortTPAByColumn(Result); sort_ByX: se.SortTPAByX(Result); sort_ByY: se.SortTPAByY(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function TPointArray.Sorted(From:TPoint): TPointArray; overload; @desc: Sorts a copy of the TPA from .. } function TPointArray.Sorted(From:TPoint): TPointArray; overload; begin Result := Self.Slice(); se.SortTPAFrom(Result, From) end; {!DOCREF} { @method: procedure TPointArray.Sort(Key:TSortKey=sort_Default); @desc: Sorts the TPA Supported keys: c'sort_Default, sort_Magnitude, sort_ByRow, sort_ByColumn, sort_ByX, sort_ByY' } procedure TPointArray.Sort(Key:TSortKey=sort_Default); begin case Key of sort_Default, sort_Magnitude: se.SortTPA(Self); sort_ByRow: se.SortTPAByRow(Self); sort_ByColumn: se.SortTPAByColumn(Self); sort_ByX: se.SortTPAByX(Self); sort_ByY: se.SortTPAByY(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: procedure TPointArray.Sort(From:TPoint); overload; @desc: Sorts the TPA from .. } procedure TPointArray.Sort(From:TPoint); overload; begin se.SortTPAFrom(Self, From) end; {!DOCREF} { @method: procedure TPointArray.Reverse(); @desc: Reverses the TPA } procedure TPointArray.Reverse(); begin Self := Self.Slice(,,-1); end; {!DOCREF} { @method: function TPointArray.Reversed(): TPointArray; @desc: Returns a reversed copy of the TPA } function TPointArray.Reversed(): TPointArray; begin Result := Self.Slice(,,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================} {!DOCREF} { @method: function TPointArray.Combine(TPA:TPointArray): TPointArray; @desc: Combines two TPAs and returns the resulting TPA } {$IFNDEF SRL6} function TPointArray.Combine(TPA:TPointArray): TPointArray; {$ELSE} function TPointArray._Combine(TPA:TPointArray): TPointArray; {$ENDIF} begin Result := se.UniteTPA(Self, TPA, False); end; {!DOCREF} { @method: function TPointArray.Bounds(): TBox; @desc: Returns the squared minimum bounding box covering the TPA } function TPointArray.Bounds(): TBox; begin Result := GetTPABounds(Self); end; {!DOCREF} { @method: function TPointArray.BoundingBox(): TPointArray; @desc: Returns the minimum bounding recatangle covering the TPA (four TPoint) } function TPointArray.BoundingBox(): TPointArray; begin Result := se.TPABBox(Self); end; {!DOCREF} { @method: function TPointArray.ConvexHull(): TPointArray; @desc: Returns the convex hull of the points } function TPointArray.ConvexHull(): TPointArray; begin Result := se.ConvexHull(Self); end; {!DOCREF} { @method: function TPointArray.Invert(): TPointArra @desc: Inverts the TPA based on the bounds of the TPA, so each point within the bounds, but not in the TPA is returned } {$IFNDEF SRL6} function TPointArray.Invert(): TPointArray; {$ELSE} function TPointArray._Invert(): TPointArray; {$ENDIF} begin Result := se.InvertTPA(self); end; {!DOCREF} { @method: function TPointArray.Cluster(Dist:Int32; Eightway:Boolean=True): T2DPointArray; @desc: Clusters the TPA in to groups separated by a given minimum distance } {$IFNDEF SRL6} function TPointArray.Cluster(Dist:Int32; Eightway:Boolean=True): T2DPointArray; {$ELSE} function TPointArray.Cluster(Dist:Int32; Eightway:Boolean): T2DPointArray; overload; {$ENDIF} begin Result := se.ClusterTPA(Self, dist, eightway); end; {!DOCREF} { @method: function TPointArray.ClusterEx(Distx, Disty:Int32; Eightway:Boolean=True): T2DPointArray; @desc: Clusters the TPA in to groups separated by a given minimum distance horizontally, and vertiacally } function TPointArray.ClusterEx(Distx, Disty:Int32; Eightway:Boolean=True): T2DPointArray; begin Result := se.ClusterTPAEx(Self, distx,disty, eightway); end; {!DOCREF} { @method: function TPointArray.Partition(Width, Height:Int32): T2DPointArray; @desc: Splits the TPA in to boxes of the given size } function TPointArray.Partition(Width, Height:Int32): T2DPointArray; begin se.TPAPartition(Self, Width, Height); end; {!DOCREF} { @method: function TPointArray.Mean(): TPoint; @desc: Returns the geometric mean of the TPA } function TPointArray.Mean(): TPoint; begin Result := MiddleTPA(Self); end; {!DOCREF} { @method: function TPointArray.Center(Method:TCenterAlgo): TPoint; @desc: Returns the center of the TPA, defined by the given method } function TPointArray.Center(Method:TCenterAlgo): TPoint; begin Result := se.TPACenter(Self, method, False); end; {!DOCREF} { @method: function TPointArray.Rotate(Angle:Extended): TPointArray; @desc: Rotates the TPA [note][b]Not[/b] the same as RotatePoints in Simba![/note] } {$IFNDEF SRL6} function TPointArray.Rotate(Angle:Extended): TPointArray; {$ELSE} function TPointArray._Rotate(Angle:Extended): TPointArray; {$ENDIF} begin Result := se.RotateTPA(Self, Angle); end; {!DOCREF} { @method: function TPointArray.RotatePts(Angle:Extended; CX,CY: Int32): TPointArray; @desc: Rotates the TPA, but each point is threated "induvidually" [note]The same as RotatePoints in Simba![/note] } function TPointArray.RotatePts(Angle:Extended; CX,CY: Int32): TPointArray; begin Result := RotatePoints(Self, Angle, CX,CY); end; {!DOCREF} { @method: procedure TPointArray.Offset(OffX,OffY: Int32); @desc: offsets each point in the TPA, both horizontally, and vertically by the given amount } {$IFNDEF SRL6} procedure TPointArray.Offset(OffX,OffY: Int32); {$ELSE} procedure TPointArray.Offset(OffX,OffY: Int32); overload; {$ENDIF} begin OffsetTPA(Self, Point(OffX, OffY)); end; {!DOCREF} { @method: function TPointArray.Sum(): TPoint; @desc: Adds up the array and returns the sum from each axis } function TPointArray.Sum(): TPoint; begin Result := se.SumTPA(Self); end;
unit AddressBookContactActionsUnit; interface uses System.Generics.Collections, SysUtils, AddressBookContactUnit, AddressBookParametersUnit, IConnectionUnit, BaseActionUnit, SettingsUnit, CommonTypesUnit, EnumsUnit; type TAddressBookContactActions = class(TBaseAction) private public /// <summary> /// ADD a location to a userís address book. /// </summary> function Add(Contact: TAddressBookContact; out ErrorString: String): TAddressBookContact; /// <summary> /// UPDATE existing address book location parameters. /// </summary> function Update(Contact: TAddressBookContact; out ErrorString: String): TAddressBookContact; /// <summary> /// REMOVE specified location from an address book. /// </summary> function Remove(AddressId: integer; out ErrorString: String): boolean; overload; /// <summary> /// REMOVE locations from an address book. /// </summary> function Remove(AddressIds: TArray<integer>; out ErrorString: String): boolean; overload; /// <summary> /// GET all locations from a userís address book. /// </summary> function Get(Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; overload; /// <summary> /// GET locations from an address book by a specified list of locations IDs. /// </summary> function Get(AddressesIds: TArray<integer>; out ErrorString: String): TAddressBookContactList; overload; /// <summary> /// GET an address book location by containing specified text in any field. /// </summary> function Find(Query: String; Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; overload; /// <summary> /// GET specified fields from an address book by containing specified text in any field. /// </summary> function Find(Query: String; Fields: TArray<String>; Limit, Offset: integer; out Total: integer; out ErrorString: String): T2DimensionalStringArray; overload; /// <summary> /// Display locations included in the routes. /// </summary> function Find(DisplayLocations: TDisplayLocations; Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; overload; end; implementation uses RemoveAddressBookContactsRequestUnit, AddressBookContactFindResponseUnit, StatusResponseUnit, GetAddressBookContactsResponseUnit, GenericParametersUnit; function TAddressBookContactActions.Remove(AddressId: integer; out ErrorString: String): boolean; begin Result := Remove([AddressId], ErrorString); end; function TAddressBookContactActions.Add(Contact: TAddressBookContact; out ErrorString: String): TAddressBookContact; begin Result := FConnection.Post(TSettings.EndPoints.AddressBook, Contact, TAddressBookContact, ErrorString) as TAddressBookContact; end; function TAddressBookContactActions.Get(Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; var Response: TGetAddressBookContactsResponse; Request: TGenericParameters; i: integer; begin Result := TAddressBookContactList.Create; Request := TGenericParameters.Create; try Request.AddParameter('limit', IntToStr(Limit)); Request.AddParameter('offset', IntToStr(Offset)); Response := FConnection.Get(TSettings.EndPoints.AddressBook, Request, TGetAddressBookContactsResponse, ErrorString) as TGetAddressBookContactsResponse; try if (Response <> nil) then begin for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); Total := Response.Total; end; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TAddressBookContactActions.Find(Query: String; Fields: TArray<String>; Limit, Offset: integer; out Total: integer; out ErrorString: String): T2DimensionalStringArray; var Response: TAddressBookContactFindResponse; Request: TGenericParameters; i: integer; FieldsStr: String; begin SetLength(Result, 0); Request := TGenericParameters.Create; try Request.AddParameter('limit', IntToStr(Limit)); Request.AddParameter('offset', IntToStr(Offset)); Request.AddParameter('query', Query); FieldsStr := EmptyStr; for i := 0 to Length(Fields) - 1 do begin if (i > 0) then FieldsStr := FieldsStr + ','; FieldsStr := FieldsStr + Fields[i]; end; Request.AddParameter('fields', FieldsStr); Response := FConnection.Get(TSettings.EndPoints.AddressBook, Request, TAddressBookContactFindResponse, ErrorString) as TAddressBookContactFindResponse; try if (Response <> nil) then begin Result := Response.Results; Total := Response.Total; end; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TAddressBookContactActions.Find(DisplayLocations: TDisplayLocations; Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; var Response: TGetAddressBookContactsResponse; Request: TGenericParameters; i: integer; begin Result := TAddressBookContactList.Create; Request := TGenericParameters.Create; try Request.AddParameter('limit', IntToStr(Limit)); Request.AddParameter('offset', IntToStr(Offset)); Request.AddParameter('display', TDisplayLocationsDescription[DisplayLocations]); Response := FConnection.Get(TSettings.EndPoints.AddressBook, Request, TGetAddressBookContactsResponse, ErrorString) as TGetAddressBookContactsResponse; try if (Response <> nil) then begin for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); Total := Response.Total; end; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TAddressBookContactActions.Get(AddressesIds: TArray<integer>; out ErrorString: String): TAddressBookContactList; var Response: TGetAddressBookContactsResponse; Request: TGenericParameters; i: integer; Ids: String; begin Result := TAddressBookContactList.Create; Request := TGenericParameters.Create; try Ids := EmptyStr; if Length(AddressesIds) = 1 then Ids := '1,' + IntToStr(AddressesIds[0]) else for i := 0 to Length(AddressesIds) - 1 do begin if (i > 0) then Ids := Ids + ','; Ids := Ids + IntToStr(AddressesIds[i]); end; Request.AddParameter('address_id', Ids); Response := FConnection.Get(TSettings.EndPoints.AddressBook, Request, TGetAddressBookContactsResponse, ErrorString) as TGetAddressBookContactsResponse; try if (Response <> nil) then for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TAddressBookContactActions.Remove(AddressIds: TArray<integer>; out ErrorString: String): boolean; var Request: TRemoveAddressBookContactsRequest; Response: TStatusResponse; begin Request := TRemoveAddressBookContactsRequest.Create(); try Request.AddressIds := AddressIds; Response := FConnection.Delete(TSettings.EndPoints.AddressBook, Request, TStatusResponse, ErrorString) as TStatusResponse; try Result := (Response <> nil) and (Response.Status); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TAddressBookContactActions.Update( Contact: TAddressBookContact; out ErrorString: String): TAddressBookContact; begin Result := FConnection.Put(TSettings.EndPoints.AddressBook, Contact, TAddressBookContact, ErrorString) as TAddressBookContact; end; function TAddressBookContactActions.Find(Query: String; Limit, Offset: integer; out Total: integer; out ErrorString: String): TAddressBookContactList; var Response: TGetAddressBookContactsResponse; Request: TGenericParameters; i: integer; begin Result := TAddressBookContactList.Create; Request := TGenericParameters.Create; try Request.AddParameter('limit', IntToStr(Limit)); Request.AddParameter('offset', IntToStr(Offset)); Request.AddParameter('query', Query); Response := FConnection.Get(TSettings.EndPoints.AddressBook, Request, TGetAddressBookContactsResponse, ErrorString) as TGetAddressBookContactsResponse; try if (Response <> nil) then begin for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); Total := Response.Total; end; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; end.
unit GetRequest; interface uses IdHTTP , DownloadObj , classes , sysUtils ; type TGetRequest=class private FHttp: TIdHTTP; FDownload: TDownload; FResponseCode: integer; FErrorMessage: string; procedure iniResponse; published property http: TIdHTTP read FHttp write FHttp; property download: TDownload read FDownload write FDownload; property responseCode: integer read FResponseCode write FResponseCode; property errorMessage: string read FErrorMessage write FErrorMessage; public constructor Create; overload; constructor Create(const aHttp: TIdHTTP; const aDownload: TDownload); overload; destructor Destroy; override; function Execute(const aFileStream: TFileStream): boolean; end; implementation { TGetRequest } constructor TGetRequest.Create; begin http := nil; download := nil; iniResponse; end; constructor TGetRequest.Create(const aHttp: TIdHTTP; const aDownload: TDownload); begin http := aHttp; download := aDownload; iniResponse; end; destructor TGetRequest.Destroy; begin inherited; end; function TGetRequest.Execute(const aFileStream: TFileStream): boolean; var vUrl: string; begin result := false; iniResponse; if assigned(FHttp) and assigned(FDownload) then begin vUrl := format('%s/%s/%s',[FDownload.url, FDownload.name, FDownload.extension]); try FHTTP.Get(vUrl, aFileStream); result := true; except on E: EIDHttpProtocolException do begin errorMessage := format('Error encountered during GET: code %d , message %s', [E.ErrorCode, E.Message]); end; on E: Exception do errorMessage := format('Error encountered during GET: %s', [E.Message]); end; responseCode := FHttp.ResponseCode; end; end; procedure TGetRequest.iniResponse; begin responseCode := 0; errorMessage := ''; end; end.
unit uWebSocket; {$mode objfpc}{$H+} { Copyright (c) 2018, pjde JQuery, JQuery Mobile (c) 2010-2012 The JQuery Foundation All rights reserved. } interface uses Classes, Winsock2, uLog; const // web socket decoding stages rsNone = 0; rsHeader = 1; rsExtraLength = 2; rsMask = 3; rsPayload = 4; // web socket op codes opContinuation = $0; opText = $1; opBinary = $2; // 3 - 7 reseerved for further non-control frames opClose = $8; opPing = $9; opPong = $a; // b - f reserved for further control frames WSPort = 10200; ny : array[boolean] of string = ('NO', 'YES'); type TWSThread = class; TWSServer = class; TWSMsgEvent = procedure (aThread : TWSThread; aMsg : TMemoryStream) of object; TWSTextEvent = procedure (aThread : TWSThread; aText : string) of object; TWSCloseEvent = procedure (aThread : TWSThread; aCode : integer; aText : string) of object; TWSClientEvent = procedure (aThread : TWSThread) of object; TMsgEvent = procedure (Sender : TObject; s : string) of object; { TWSThread } TWSThread = class (TWinsock2TCPServerThread) private FVersion : string; FOrigin : string; FClientKey, FServerKey : string; FProtocol : string; FUpgraded : boolean; FHandShake : boolean; FRxStage : integer; FNeed : integer; FPayloadLength : integer; FOpCode : integer; FFinal : Boolean; FMasked : Boolean; FMask : array [0..3] of byte; FRxStream : TMemoryStream; FRxPacket : TMemoryStream; FOwner : TWSServer; public ID : string; constructor Create (aServer : TWinsock2TCPServer); destructor Destroy; override; procedure SendString (s : string); overload; procedure SendString (s: TMemoryStream); overload; function EncodeLength (len : integer) : string; procedure SendPing (s : string); procedure SendPong (s : string); procedure SendClose (Code : integer; aReason : string = ''); end; TWSServer = class (TWinsock2TCPListener) private FPort : integer; FAutoPong : boolean; FOnText : TWSMsgEvent; FOnPing, FOnPong : TWSTextEvent; FOnClose : TWSCloseEvent; FOnNewClient, FOnFinishClient : TWSClientEvent; protected procedure DoCreateThread (aServer : TWinsock2TCPServer; var aThread : TWinsock2TCPServerThread); procedure DoConnect (aThread : TWinsock2TCPServerThread); override; procedure DoDisconnect (aThread : TWinsock2TCPServerThread); override; function DoExecute (aThread : TWinsock2TCPServerThread) : Boolean; override; public constructor Create; destructor Destroy; override; procedure Start; procedure Stop; published property Port : integer read FPort write FPort; property AutoPong : boolean read FAutoPong write FAutoPong; property OnText : TWSMsgEvent read FOnText write FOnText; property OnPing : TWSTextEvent read FOnPing write FOnPing; property OnPong : TWSTextEvent read FOnPong write FOnPong; property OnClose : TWSCloseEvent read FOnClose write FOnClose; property OnNewClient : TWSClientEvent read FOnNewClient write FOnNewClient; property OnFinishClient : TWSClientEvent read FOnFinishClient write FOnFinishClient; end; function GetKey (aKey : string) : string; // get server key from client's key implementation uses Crypto, SysUtils; const SpecGUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; CRLF = #13#10; function Base64Encode (Input : string) : string; var Final : string; Count : Integer; Len : Integer; const Base64Out: array [0..64] of Char = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '='); begin Final := ''; Count := 1; Len := Length (Input); while Count <= Len do begin Final := Final + Base64Out[(Byte (Input[Count]) and $FC) shr 2]; if (Count + 1) <= Len then begin Final := Final + Base64Out[((Byte (Input[Count]) and $03) shl 4) + ((Byte (Input[Count + 1]) and $F0) shr 4)]; if (Count+2) <= Len then begin Final := Final + Base64Out[((Byte (Input[Count + 1]) and $0F) shl 2) + ((Byte (Input[Count + 2]) and $C0) shr 6)]; Final := Final + Base64Out[(Byte (Input[Count + 2]) and $3F)]; end else begin Final := Final + Base64Out[(Byte (Input[Count + 1]) and $0F) shl 2]; Final := Final + '='; end end else begin Final := Final + Base64Out[(Byte (Input[Count]) and $03) shl 4]; Final := Final + '=='; end; Count := Count + 3; end; Result := Final; end; function GetKey (aKey : string) : string; // get server key from client's key var Tmp, Hash : string; Context: TSHA1Context; Digest: TSHA1Digest; i : integer; begin Tmp := aKey + SpecGUID; SHA1Init (Context); SHA1Update (Context, @Tmp[1], length (Tmp)); SHA1Final (Context, Digest); Hash := ''; for i := 0 to 19 do Hash := Hash + Char (Digest[i]); Result := Base64Encode (Hash); end; { TWSThread - Implements the Web Sockets RFC Protocol } constructor TWSThread.Create (aServer : TWinsock2TCPServer); var i : integer; begin inherited Create (aServer); ID := ''; FVersion := ''; FOrigin := ''; FClientKey := ''; FServerKey := ''; FProtocol := ''; FHandShake := true; FUpgraded := false; FRxStage := rsNone; FMasked := false; for i := 0 to 3 do FMask[i] := 0; FRxStream := TMemoryStream.Create; FRxPacket := TMemoryStream.Create; end; destructor TWSThread.Destroy; begin FRxStream.Free; FRxPacket.Free; inherited; end; procedure TWSThread.SendClose (Code : integer; aReason : string); var aRes : string; begin Code := Code mod $10000; aRes := AnsiChar ($80 or opClose) + EncodeLength (2 + length (aReason)); // fin + opClose + no mask + payload length aRes := aRes + AnsiChar (Code mod $100) + AnsiChar (Code div $100) + aReason; Server.WriteData (@aRes[1], length (aRes)); end; procedure TWSThread.SendPing (s: string); var aRes : AnsiString; begin aRes := AnsiChar ($80 or opPing) + EncodeLength (length (s)); aRes := aRes + s; Server.WriteData (@aRes[1], length (aRes)); end; procedure TWSThread.SendPong (s: string); var aRes : string; begin aRes := AnsiChar ($80 or opPong) + EncodeLength (length (s)); aRes := aRes + s; Server.WriteData (@aRes[1], length (aRes)); end; procedure TWSThread.SendString (s: string); var aRes : string; begin aRes := AnsiChar ($80 or opText) + EncodeLength (length (s)); aRes := aRes + s; Server.WriteData (@aRes[1], length (aRes)); end; procedure TWSThread.SendString (s: TMemoryStream); var aRes : string; begin aRes := AnsiChar ($80 or opText) + EncodeLength (s.Size); SetLength (aRes, s.Size + 2); Move (s.Memory^, aRes[3], s.Size); Server.WriteData (@aRes[1], length (aRes)); end; function TWSThread.EncodeLength (len : integer): string; var // 64K maximum i : integer; lenmask, lendiv : uint64; begin if len > $ffff then begin Result := ''; lenmask := uint64 ($ff00000000000000); lendiv := $100000000000000; for i := 7 downto 0 do begin Result := Result + Char ((len and lenmask) div lendiv); lenmask := lenmask div $100; lendiv := lendiv div $100; end; end else if len > 125 then // following 2 bytes as length begin Result := Char ($7e) + Char (len div $100) + Char (len mod $100); end else Result := Char (len); // thats all end; { TWSServer } { procedure TWSServer.ClientDisconnected (Sender: TObject; Client: TWSocketClient; Error: Word); begin Mon ('WebSocket Client Disconnected.'); if Assigned (FOnFinishClient) then FOnFinishClient (Self, TWSClient (Client)); end; } constructor TWSServer.Create; begin inherited Create; FAutoPong := true; BoundPort := WSPort; OnCreateThread := @DoCreateThread; // Log ('WS Server Created ... ready on ' + LocalAddress); end; destructor TWSServer.Destroy; begin Stop; inherited Destroy; end; function TWSServer.DoExecute (aThread: TWinsock2TCPServerThread): Boolean; var aWSThread : TWSThread; x, y : integer; ba : array [0..1024] of byte; b : byte; c : integer; d, closed : boolean; lines : TStringList; tmp, tmp2 : string; p : int64; Response : string; procedure DoOutput (opCode : integer); var s : string; y : integer; begin with aWSThread do begin if FOpCode in [opPing, opPong, opClose] then begin FRxPacket.Seek (0, soFromBeginning); SetLength (s, FRxPacket.Size); FRxPacket.Read (s[1], FRxPacket.Size); end else s := ''; case FOpCode of opText : if Assigned (FOwner.FOnText) then FOwner.FOnText (aWSThread, FRxPacket); opBinary : begin SendClose (1002, 'Binary not supported.'); // check Result := false; end; opPing : begin if FOwner.FAutoPong then SendPong (s); if Assigned (FOwner.FOnPing) then FOwner.FOnPing (aWSThread, s); end; opPong : if Assigned (FOwner.FOnPong) then FOwner.FOnPong (aWSThread, s); opClose : if length (s) >= 2 then begin y := ord (s[2]) + $100 * ord (s[1]); s := Copy (s, 3, Length (s) - 2); // Log ('Close Code ' + y.ToString + ' Reason ' + s); if Assigned (FOwner.FOnClose) then FOwner.FOnClose (aWSThread, y, s); Result := false; end; end; FRxPacket.Clear; end; end; begin Result := inherited DoExecute (aThread); if not Result then exit; aWSThread := TWSThread (aThread); c := 1024; closed := false; d := aThread.Server.ReadAvailable (@ba[0], 1023, c, closed); //Log ('c ' + c.ToString + ' closed ' + ny[closed] + ' d ' + ny[d]); if closed or not d then Result := false; if (c = 0) or closed then exit; SetLength (tmp, c); Move (ba[0], tmp[1], c); //Log ('read ' + inttostr (c)); with aWSThread do begin if not FUpgraded then begin lines := TStringList.Create; x := Pos (CRLF, tmp); while x > 0 do begin lines.Add (Copy (tmp, 1, x - 1)); tmp := Copy (tmp, x + 2, length (tmp) - x); x := Pos (CRLF, tmp); end; if Length (tmp) > 0 then lines.Add (tmp); for x := 0 to lines.Count - 1 do begin y := Pos (': ', lines[x]); if y > 0 then begin tmp := Copy (lines[x], 1, y - 1); tmp2 := Copy (lines[x], y + 2, length (lines[x]) - y); if tmp = 'Sec-WebSocket-Key' then begin FClientKey := tmp2; FServerKey := GetKey (FClientKey); end else if tmp = 'Sec-WebSocket-Version' then FVersion := tmp2 else if tmp = 'Sec-WebSocket-Origin' then FOrigin := tmp2 else if tmp = 'Sec-WebSocket-Protocol' then FProtocol := tmp2; end; end; lines.Free; if (length (FServerKey) > 0) then begin Response := 'HTTP/1.1 101 Switching Protocols' + CRLF + 'Upgrade: websocket' + CRLF + 'Connection: Upgrade' + CRLF + 'Sec-WebSocket-Accept: ' + FServerKey + CRLF + 'Sec-WebSocket-Origin: ' + FOrigin + CRLF + 'Sec-WebSocket-Protocol: ' + FProtocol + CRLF + CRLF; Server.WriteData (@Response[1], length (Response)); FUpgraded := true; FRxStage := rsHeader; // expect new massage FNeed := 2; // mimimum needed is 2 bytes if Assigned (FOnNewClient) then FOnNewClient (aWSThread); end; end else begin p := FRxStream.Position; FRxStream.Seek (0, soFromEnd); FRxStream.Write (tmp[1], length (tmp)); FRxStream.Seek (p, soFromBeginning); while (FRxStream.Size - FRxStream.Position) >= FNeed do begin case FRxStage of rsHeader : begin // need to implement continuation FRxStream.Read (b, 1); FOpCode := b and $0f; FFinal := (b and $80) > 0; // ignore rsvs for now FRxStream.Read (b, 1); FMasked := (b and $80) > 0; FPayLoadLength := b and $7f; if FPayLoadLength = 0 then begin if FMasked then begin FNeed := 4; FRxStage := rsMask; end else begin DoOutput (FOpCode); FNeed := 2; FRxStage := rsHeader; end; end else if FPayloadLength <= 125 then // final length begin if FMasked then begin FNeed := 4; FRxStage := rsMask; end else begin FNeed := FPayLoadLength; FRxStage := rsPayload; end; end else if FPayLoadLength = 126 then begin FRxStage := rsExtraLength; FNeed := 2; end else if FPayLoadLength = 127 then begin FRxStage := rsExtraLength; FNeed := 8; end end; rsExtraLength : begin FPayLoadLength := 0; for x := 1 to FNeed do begin FRxStream.Read (b, 1); FPayLoadLength := (FPayLoadLength * $100) + b; end; if FMasked then begin FNeed := 4; FRxStage := rsMask; end else begin FRxStage := rsPayload; FNeed := FPayLoadLength; end; end; rsMask : begin FRxStream.Read (FMask, 4); if FPayLoadLength = 0 then begin DoOutput (FOpCode); FRxStage := rsHeader; FNeed := 2; end else begin FRxStage := rsPayload; FNeed := FPayLoadLength; end; end; rsPayload : begin SetLength (Tmp, FPayLoadLength); FRxStream.Read (Tmp[1], length (Tmp)); if FOpCode <> opContinuation then FRxPacket.Clear; FRxPacket.Seek (0, soFromEnd); for x := 1 to length (Tmp) do begin b := ord (Tmp[x]) xor FMask[(x - 1) mod 4]; FRxPacket.Write (b, 1); end; if FFinal then DoOutput (FOpCode); FRxStage := rsHeader; FNeed := 2; end; else FRxStream.Read (b, 1); // avoid infinite loop end; // case end; // while if FRxStream.Position = FRxStream.Size then FRxStream.Clear; end; end; end; procedure TWSServer.Start; begin try BoundPort := FPort; Active := true; Log ('Web Sockets Listening.'); except Log ('Web Sockets Listening Error.'); end; end; procedure TWSServer.Stop; begin Active := false; end; procedure TWSServer.DoCreateThread (aServer: TWinsock2TCPServer; var aThread: TWinsock2TCPServerThread); begin // Log ('Web Socket Thread Created'); aThread := TWSThread.Create (aServer); TWSThread (aThread).FOwner := Self; end; procedure TWSServer.DoConnect (aThread: TWinsock2TCPServerThread); begin inherited DoConnect (aThread); // Log ('Web Socket Connected'); end; procedure TWSServer.DoDisconnect (aThread: TWinsock2TCPServerThread); begin inherited DoDisconnect (aThread); // Log ('Web Socket Disconnected'); if Assigned (FOnFinishClient) then FOnFinishClient (TWSThread (aThread)); end; end.
function isPrime(n: LongInt): Boolean; var i: LongInt; begin isPrime := (n = 2) or (n = 3) or not ((n mod 2 = 0) or (n mod 3 = 0)); i := 5; while i <= (n div 2 + 1) do begin if n mod i = 0 then isPrime := false; if n mod (i + 2) = 0 then isPrime := false; i += 6; end; end; var i: LongInt; begin for i := 1 to 10000 do if isPrime(i) then begin Write('found a prime number: '); WriteLn(i); end; end.
unit Model.Departamentos; interface type TDepartamentos = class private FCodigo: System.Integer; FDEscricao: System.string; FLog: System.string; public property Codigo: System.Integer read FCodigo write FCodigo; property Descricao: System.string read FDescricao write FDescricao; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFCodigo: System.Integer; pFDescricao: System.string; pFLog: System.string); overload; end; implementation constructor TDepartamentos.Create; begin inherited Create; end; constructor TDepartamentos.Create(pFCodigo: Integer; pFDescricao: string; pFLog: string); begin FCodigo := pFCodigo; FDescricao := pFDescricao; FLog := pFLog; 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 ClpIGlvTypeBParameters; {$I ..\Include\CryptoLib.inc} interface uses ClpBigInteger, ClpCryptoLibTypes; type IGlvTypeBParameters = interface(IInterface) ['{089AC2AB-15A1-47F5-BED0-C09EA77BECB9}'] function GetBeta: TBigInteger; function GetBits: Int32; function GetG1: TBigInteger; function GetG2: TBigInteger; function GetLambda: TBigInteger; function GetV1: TCryptoLibGenericArray<TBigInteger>; function GetV2: TCryptoLibGenericArray<TBigInteger>; property beta: TBigInteger read GetBeta; property lambda: TBigInteger read GetLambda; property v1: TCryptoLibGenericArray<TBigInteger> read GetV1; property v2: TCryptoLibGenericArray<TBigInteger> read GetV2; property g1: TBigInteger read GetG1; property g2: TBigInteger read GetG2; property bits: Int32 read GetBits; end; implementation end.